text
stringlengths
46
74.6k
--- id: data-availability title: Rollup Data Availability --- Utilizing NEAR as storage data availability with a focus on lowering rollup DA fees. - [Blob Store Contract](#blob-store-contract): A contract that provides the store for arbitrary DA blobs. - [Light Client](#light-client): A trustless off-chain light client for NEAR with DA-enabled features. - [RPC Client](#da-rpc): The defacto client for submitting data blobs to NEAR. - [Integrations](#integrations): Proof of concept works for integrating with L2 rollups. :::tip For the latest information, please check the [Near DA](https://github.com/near/rollup-data-availability/) repository. ::: --- ## System Context This outlines the system components that we build and how it interacts with external components. Red lines denote external flow of commitments. White lines denote flow of blob data. :::note `Fisherman` is just an example how a rollup can work with the light client in the initial stage of DA, until we implement a more non-interactive approach, such as KZG. ::: ```mermaid C4Context title NEAR Data Availability System Context Enterprise_Boundary(b1, "Ethereum") { System_Ext(SystemEth, "Ethereum") System_Boundary(b2, "Rollup") { System_Ext(SystemRollup, "Rollup", "Derives blocks, execute transactions, posts commitments & sequence data") System(SystemNearDa, "NEAR DA Client", "Submits/Gets blob data, creates commitments") } BiRel(SystemRollup, SystemEth, "Posts sequences, proofs of execution, DA frame references") BiRel(SystemRollup, SystemNearDa, "Post batches, retrieves commitments") Rel(fisherman, SystemEth, "Looks for commitments, posts results") } Enterprise_Boundary(b0, "NEAR") { System(SystemLc, "Light Client", "Syncs headers, provides inclusion proofs") System(SystemNear, "NEAR Protocol", "NEAR validators, archival nodes") Rel(SystemLc, SystemNear, "Syncs headers") Rel(SystemNearDa, SystemNear, "Submits/Gets blob") %% This doesn't exist yet %% System(SystemDas, "Data Availability Sampling", "Data redundancy, retrieval, sample responses") %% BiRel(SystemDas, SystemLc, "Commitments") } Person_Ext(fisherman, "Fisherman") Rel(fisherman, SystemLc, "Requests inclusion proofs, validates inclusion proofs") UpdateRelStyle(fisherman, SystemEth, $offsetY="-10" $lineColor="red") UpdateRelStyle(fisherman, SystemLc, $offsetY="-10", $lineColor="red") UpdateRelStyle(SystemRollup, SystemEth, $offsetY="-30", $lineColor="white") UpdateElementStyle(fisherman, $bgColor="grey", $borderColor="red") UpdateRelStyle(SystemRollup, SystemNearDa, $offsetX="-200", $lineColor="white", $textColor="white") UpdateRelStyle(SystemNearDa, SystemNear, $textColor="white", $lineColor="white", $offsetY="10") UpdateRelStyle(SystemNearLc, SystemNear, $offsetX="30") ``` --- ## [Blob Store Contract](https://github.com/near/rollup-data-availability/tree/main/contracts/blob-store) The [blob store contract](https://github.com/near/rollup-data-availability/tree/main/contracts/blob-store) provides the store for arbitrary DA blobs. In practice, these "blobs" are sequencing data from rollups, but they can be any data. NEAR blockchain state storage is pretty cheap. At the time of writing, 100KiB is a flat fee of 1NEAR. To limit the costs of NEAR storage even more, we don't store the blob data in the blockchain state. It works by taking advantage of NEAR consensus around receipts. When a chunk producer processes a receipt, there is consensus around the receipt. However, once the chunk has been processed and included in the block, the receipt is no longer required for consensus and can be pruned. The pruning time is at least 3 NEAR epochs, where each epoch is 12 Hours; in practice, this is around five epochs. Once the receipt has been pruned, it is the responsibility of archival nodes to retain the transaction data, and we can even get the data from indexers. We can validate that the blob was retrieved from ecosystem actors in the format submitted by checking the blob commitment. The blob commitment currently needs to be more efficient and will be improved, but it benefits us because anybody can build this with limited expertise and tooling. It is created by taking a blob, chunking it into 256-byte pieces, and creating a Merkle tree, where each leaf is a Sha-256 hash of the shard. The root of the Merkle tree is the blob commitment, which is provided as [transaction_id ++ commitment] to the L1 contract, which is 64 bytes. What this means: - Consensus is provided around the submission of a blob by NEAR validators - The function input data is stored by full nodes for at least three days - Archival nodes can store the data for longer - We don't occupy consensus with more data than needs to be - Indexers can also be used, and this Data is currently indexed by all significant explorers in NEAR - The commitment is available for a long time, and the commitment is straightforward to create --- ## [Light Client](https://github.com/near/rollup-data-availability/tree/main/) A trustless off-chain light client for NEAR with DA-enabled features, Such as KZG commitments, Reed-Solomon erasure coding & storage connectors. The light client provides easy access to transaction and receipt inclusion proofs within a block or chunk. This is useful for checking any dubious blobs which may not have been submitted or validating that a blob has been submitted to NEAR. A blob submission can be verified by: - Taking the NEAR transaction ID from Ethereum for the blob commitment. - Ask the light client for an inclusion proof for the transaction ID or the receipt ID if you're feeling specific; this will give you a Merkle inclusion proof for the transaction/receipt. - Once you have the inclusion proof, you can ask the light client to verify the proof for you, or advanced users can manually verify it themselves. - Armed with this knowledge, rollup providers can have advanced integration with light clients and build proving systems around it. In the future, we will provide extensions to light clients such that non-interactive proofs can be supplied for blob commitments and other data availability features. It's also possible that the light client may be on-chain for the header syncing and inclusion proof verification, but this is a low priority right now. --- ## DA RPC This client is the defacto client for submitting blobs to NEAR. These crates allow a client to interact with the blob store. It can be treated as a "black box", where blobs go in, and `[transaction_id ++ commitment]` emerges. There are multiple versions: - The [`da-rpc` crate](https://github.com/near/rollup-data-availability/tree/main/crates/da-rpc) is the rust client, which anyone can use if they prefer rust in their application. The responsibility of this client is to provide a simple interface for interacting with NEAR DA. - The [`da-rpc-sys` crate](https://github.com/near/rollup-data-availability/tree/main/crates/da-rpc-sys) is the FFI client binding for use by non-rust applications. This calls through to `da-rpc` to interact with the blob store, with some additional black box functionality for dealing with pointers wrangling and such. - The [`da-rpc-go` package](https://github.com/near/rollup-data-availability/tree/main/gopkg/da-rpc) is the go client bindings for use by non-rust applications, and this calls through to `da-rpc-sys`, which provides another application-level layer for easy interaction with the bindings. :::info See also [the diagram](https://github.com/near/rollup-data-availability/blob/main/docs/da_rpc_client.md) ::: --- ## Integrations We have developed some proof of concept works for integrating with L2 rollups: - [CDK Stack](https://github.com/firatNEAR/cdk-validium-node/tree/near): We have integrated with the Polygon CDK stack. Using the Sequence Sender for submissions to NEAR. - [Optimism](https://github.com/near/optimism): We have integrated with the Optimism OP stack. Using the `Batcher` for submissions to NEAR and the proposer for submitting NEAR commitment data to Ethereum. - [Arbitrum Nitro](https://github.com/near/nitro): We have integrated a small plugin into the DAC daserver. This is much like our http sidecar and provides a very modular integration into NEAR DA whilst supporting arbitrum DACs. :::info In the future, the `Arbitrum Nitro` integration will likely be the easiest way to support NEAR DA as it acts as an independent sidecar which can be scaled as needed. This also means that the DAC can opt-in and out of NEAR DA, lowering their infrastructure burden. With this approach, the DAC committee members just need to have a "dumb" signing service, with the store backed by NEAR. :::
A personal message from Marieke Flament NEAR FOUNDATION September 21, 2023 All good things come to an end – and after a wild (very wild!) two years as CEO of NEAR Foundation, I have decided to step down and leave space for the next evolution of the NEAR Foundation, which will be led by Chris Donovan. I will continue my NEAR journey as an active and committed NEAR Foundation Council member, an advisor to Chris, a huge ecosystem advocate and hopefully a proud member of the NEAR Digital Collective (shameless plug – vote for me!). I am excited to continue having an impact and to continue contributing to NEAR. I am very proud of what has been achieved by the NEAR Foundation team for the ecosystem in an incredibly challenging environment. Two years ago, I had never heard of NEAR. Upon doing a bit of research and after several conversations it became clear that NEAR had a tremendous potential – fantastic tech, a diverse and vibrant community and a world of open possibilities, and so I joined. I also took on the role because I believe that we can create a better internet through an Open Web, and help tackle some of our world’s biggest challenges by leveraging the incredible tech we have. My strategy has been one of driving mainstream adoption, enabling and empowering grassroot communities and continuing our journey to decentralization. Bringing onboard large web2 players, while nurturing web3 innovators has also been key to our growth. I am extremely proud of what we have achieved together on this quest to bring an open web to the masses to further decentralize the ecosystem and drive mainstream adoption. Here’s a snapshot of what has been achieved so far: over the last two years we’ve signed many critical partnerships – notably SWEAT, Playember, Circle, Ledger, Alibaba, Amazon, Google, KPMG, Cosmose AI, SailGP, The Littles, PipeFlare, Shemaroo, Kakao Games, Inven / Vortex and Netmarble / Marblex in Korea – just to name a few. As those partnerships came on mainnet, user growth went from 50k to 3m Monthly Active Accounts (growing daily!) – 2 out of 3 of the top Dapps on Dappradar are built on NEAR. And more is to come as many of the above partnerships are set to bear fruits in the coming weeks and months. The awareness of NEAR has skyrocketed, putting NEAR on the map as a trusted player, thanks to over 2,000 pieces of press coverage, a Twitter follower growth from 200k to 2m and many very iconic and successful events such as NEARCON and NEARAPAC. True to its mission the NEAR Foundation has helped empower the NEAR ecosystem, by kicking off its governance with the NEAR digital collective (NDC) an industry first for community governance of treasury; as well as setting up NEAR Horizon a unique on-chain platform providing founders the support they need to thrive. All this tremendous progress has been made while protecting our treasury amidst many internal and external crises, leaving us one of the industry’s best funded treasuries ($350m, 330m tokens). Last but not least, I am extremely proud and in awe of the NEAR Foundation’s team – a team of incredible people, which has at its core and heart one goal: to serve. NEAR is in a very strong position – no other ecosystem is as well financed, nor has the decentralized governance that we have. We played the long game, away from FUD and FOMO, and it is starting to pay off. Although I am stepping down from the Foundation as CEO, I look forward to continue making an impact on NEAR and the Foundation, and in my future roles I vow to: Be the voice and advocate for responsible decentralization, strongly rejecting any plans to centralize efforts away from the people. I strongly believe that when brought together people make better, fairer decisions. Protect the ecosystem from any form of self-interest, no matter their origins. Fight against any toxic culture within the NEAR ecosystem – we are in this together and need to support one another. The future is NEAR,
# Runtime crate Runtime crate encapsulates the logic of how transactions and receipts should be handled. If it encounters a smart contract call within a transaction or a receipt it calls `near-vm-runner`, for all other actions, like account creation, it processes them in-place. ## Runtime class The main entry point of the `Runtime` is method `apply`. It applies new singed transactions and incoming receipts for some chunk/shard on top of given trie and the given state root. If the validator accounts update is provided, updates validators accounts. All new signed transactions should be valid and already verified by the chunk producer. If any transaction is invalid, the method returns an `InvalidTxError`. In case of success, the method returns `ApplyResult` that contains the new state root, trie changes, new outgoing receipts, stats for validators (e.g. total rent paid by all the affected accounts), execution outcomes. ### Apply arguments It takes the following arguments: - `trie: Arc<Trie>` - the trie that contains the latest state. - `root: CryptoHash` - the hash of the state root in the trie. - `validator_accounts_update: &Option<ValidatorAccountsUpdate>` - optional field that contains updates for validator accounts. It's provided at the beginning of the epoch or when someone is slashed. - `apply_state: &ApplyState` - contains block index and timestamp, epoch length, gas price and gas limit. - `prev_receipts: &[Receipt]` - the list of incoming receipts, from the previous block. - `transactions: &[SignedTransaction]` - the list of new signed transactions. ### Apply logic The execution consists of the following stages: 1. Snapshot the initial state. 1. Apply validator accounts update, if available. 1. Convert new signed transactions into the receipts. 1. Process receipts. 1. Check that incoming and outgoing balances match. 1. Finalize trie update. 1. Return `ApplyResult`. ## Validator accounts update Validator accounts are accounts that staked some tokens to become a validator. The validator accounts update usually happens when the current chunk is the first chunk of the epoch. It also happens when there is a challenge in the current block with one of the participants belong to the current shard. This update distributes validator rewards, return locked tokens and maybe slashes some accounts out of their stake. ## Signed Transaction conversion New signed transaction transactions are provided by the chunk producer in the chunk. These transactions should be ordered and already validated. Runtime does validation again for the following reasons: - to charge accounts for transactions fees, transfer balances, prepaid gas and account rents; - to create new receipts; - to compute burnt gas; - to validate transactions again, in case the chunk producer was malicious. If the transaction has the the same `signer_id` and `receiver_id`, then the new receipt is added to the list of new local receipts, otherwise it's added to the list of new outgoing receipts. ## Receipt processing Receipts are processed one by one in the following order: 1. Previously delayed receipts from the state. 1. New local receipts. 1. New incoming receipts. After each processed receipt, we compare total gas burnt (so far) with the gas limit. When the total gas burnt reaches or exceeds the gas limit, the processing stops. The remaining receipts are considered delayed and stored into the state. ### Delayed receipts Delayed receipts are stored as a persistent queue in the state. Initially, the first unprocessed index and the next available index are initialized to 0. When a new delayed receipt is added, it's written under the next available index in to the state and the next available index is incremented by 1. When a delayed receipt is processed, it's read from the state using the first unprocessed index and the first unprocessed index is incremented. At the end of the receipt processing, the all remaining local and incoming receipts are considered to be delayed and stored to the state in their respective order. If during receipt processing, we've changed indices, then the delayed receipt indices are stored to the state as well. ### Receipt processing algorithm The receipt processing algorithm is the following: 1. Read indices from the state or initialize with zeros. 1. While the first unprocessed index is less than the next available index do the following 1. If the total burnt gas is at least the gas limit, break. 1. Read the receipt from the first unprocessed index. 1. Remove the receipt from the state. 1. Increment the first unprocessed index. 1. Process the receipt. 1. Add the new burnt gas to the total burnt gas. 1. Remember that the delayed queue indices has changed. 1. Process the new local receipts and then the new incoming receipts - If the total burnt gas is less then the gas limit: 1. Process the receipt. 1. Add the new burnt gas to the total burnt gas. - Else: 1. Store the receipt under the next available index. 1. Increment the next available index. 1. Remember that the delayed queue indices has changed. 1. If the delayed queue indices has changed, store the new indices to the state. ## Balance checker Balance checker computes the total incoming balance and the total outgoing balance. The total incoming balance consists of the following: - Incoming validator rewards from validator accounts update. - Sum of the initial accounts balances for all affected accounts. We compute it using the snapshot of the initial state. - Incoming receipts balances. The prepaid fees and gas multiplied their gas prices with the attached balances from transfers and function calls. Refunds are considered to be free of charge for fees, but still has attached deposits. - Balances for the processed delayed receipts. - Initial balances for the postponed receipts. Postponed receipts are receipts from the previous blocks that were processed, but were not executed. They are action receipts with some expected incoming data. Usually for a callback on top of awaited promise. When the expected data arrives later than the action receipt, then the action receipt is postponed. Note, the data receipts are 0 cost, because they are completely prepaid when issued. The total outgoing balance consists of the following: - Sum of the final accounts balance for all affected accounts. - Outgoing receipts balances. - New delayed receipts. Local and incoming receipts that were not processed this time. - Final balances for the postponed receipts. - Total rent paid by all affected accounts. - Total new validator rewards. It's computed from total gas burnt rewards. - Total balance burnt. In case the balance is burnt for some reason (e.g. account was deleted during the refund), it's accounted there. - Total balance slashed. In case a validator is slashed for some reason, the balance is account here. When you sum up incoming balances and outgoing balances, they should match. If they don't match, we throw an error.
--- title: 3.2 DEX / AMM / Aggregators / Perps description: Specific examples of the DeFi product stack and its layers of complexity --- # 3.2 On DEXs / AMMs / Aggregators / Orderbooks and Perps **“Decentralized finance is, in some views, a category that started off honorable but limited, turned into somewhat of an overcapitalized monster that relied on unsustainable forms of yield farming, and is now in the early stages of setting down into a stable medium, improving security and refocusing on a few applications that are particularly valuable.” ([Vitalik](https://vitalik.eth.limo/general/2022/12/05/excited.html))** Getting into the nitty-gritty of Decentralized Finance (DeFi), centers upon a number of first principles and underlying benefits as compared to existing finance. We will then move into looking at specific examples of the DeFi product stack, in increasing layers of complexity. ## Principles of DeFi: Benefits and Legacy Shortcomings As we explore the following DeFi legos, keep in mind the table of benefits and shortcomings as DeFi compares to the legacy financial system: | DeFi Benefit | Legacy System Shortcoming | | --- | --- | | Efficiency | Slow Settlement Cycles | | Transparency | Liquidity Challenges | | Financial Inclusion | Lack of Assurance Around Underlying Assets | ## _Service Categories of DeFi_ While we will not be zooming in on each of these verticals, to date, these are the primary foci of DeFi: * _Stablecoins. Maintains stable value most usually pegged to a real-world currency or asset such as the US Dollar. (to be discussed below)_ * _Exchanges. Allows for the trading of one digital asset into or for another. (to be discussed below)_ * _Credit / Lending Markets. Creates loans and payment conditions between digital assets utilizing smart contracts to manage the loan and repayment of the assets. (to be discussed in lecture 4 of this module)._ * _Derivatives. Complex financial instruments built on top of existing digital instruments._ (to be discussed below). * _Insurance. Covers a future scenario as programmed in smart contract or agreed upon on-chain, such that if the event happens the protocol pays out to the wronged party_ Dominated by [Nexus Mutual.](https://nexusmutual.io/) And specifically focused on covering smart contract vulnerabilities and exchange. * _Asset Management. On-chain management of funds at scale, including risk mitigation, and time-horizon customization of assets._ Decentralized hedge-fund management, as evident from Enzyme.finance. ## _Incentive Mechanisms Used Across Protocols in DeFi_ As we dive into the different protocols, it is useful to keep in mind the underlying incentives that tend to govern most of the actions of the different network participants: * **Lock Up Yields:** Whereby interest is paid out to users, willing to lock up their value into the protocol, to be used primarily as liquidity or collateral that other traders can make use of on the protocol. * **Liquidation Fees:** When liquidity providers or market makers, are rewarded when undercollateralized loans are liquidated and a proportion of the liquidation value is paid out to the liquidity providers. * **Liquidity Mining:** Users are rewarded from the protocol in question for locking up their value in a liquidity pool, and paid out in the protocol token as an incentive mechanism. In these scenarios, users are rewarded at a fixed rate in tokens from the mother protocol in proportion to the reward fee set for the pool the user is participating in. ## The Network Participants Tend To Revolve Around The Follow Characters * **Programmable Financial Functions:** When the smart contract is designed to execute a specific function, when certain preconditions are fulfilled: Swapping one asset for another, lending out at a certain rate for a collateral deposit, paying out or liquidating on certain market dynamics. * **Liquidity Providers:** Participants that lock up and provide value for the protocol, for certain incentives and time-conditions. * **Users:** Participants who engage with the protocol, by placing their value (assets) in the protocol, and thereby interacting with the smart contract and the liquidity pool. The different use-cases outlined below, all revolve around these central stakeholders. ## Decentralized Exchanges and AMMs An Automated Market Maker (AMM) is a type of algorithm used to enable the trading of assets without the need for a traditional order book. Instead of matching buyers and sellers based on pre-existing orders (as traditional order books do), AMMs use a mathematical formula to determine the price of an asset based on the amount of liquidity in the market. In this sense, a user is not trading against another user, but rather against a protocol’s liquidity pool - that is to say, the algorithm itself. When a user wants to trade an asset, they can do so through the AMM by providing the desired amount and the asset they want to trade for. The AMM will then use its formula to determine the price of the trade and execute it automatically. ![](@site/static/img/bootcamp/mod-em-3.2.1.png) AMM’s invert traditional order books in a number of ways: * They can facilitate trading without the need for a central authority or exchange. This allows for more decentralized and efficient trading of assets. * AMMs can enable the trading of assets that may not have a pre-existing market or liquidity, as the AMM can create a market for them on-the-fly. * AMM’s provide a ‘constant’ liquidity event, for users or investors to reliably sell assets at any point in time - regardless of if there is a counterparty willing to purchase their assets. * NEAR specifically, allows AMM’s to access liquidity across shards, in order to execute trades at optimal prices (for example, a trade on Ref, can pull liquidity from Trisolaris if need be). _The underlying incentive governing AMM’s is known as ‘Yield Farming’ - it specifically refers to the first of the three incentive mechanisms discussed above._ Yield farming refers to the incentive mechanism by which a user is incentivized to participate in a liquidity pool. Users are rewarded, for providing liquidity - usually both pairs of it - into a specific pool. The APY (yield) is set either using the protocols native tokens, or tokens from the projects involved in the pool. In some cases, protocols can make agreements with a suite of tokens to offer a basket of yield to a given user. Importantly, the rates and returns from yield farming vary based upon the total amount of liquidity provided in the pool. In this sense, those who provide liquidity earlier on, stand to earn more. ![](@site/static/img/bootcamp/mod-em-3.2.2.png) The _farming_ element, refers to a user's capacity to harvest rewards, and then promptly move over into another liquidity pool, so as to benefit from a higher APY. Many users will not ‘park’ their liquidity in a single pool for too long - and as a result there is sometimes a challenge in keeping liquidity on a certain protocol (known as sticky liquidity). ## Uniswap and Sushi Swap The first AMM to launch at scale (not counting 0x) was [Uniswap](https://defillama.com/protocol/uniswap). It remains the largest and most successful with 3.5 billion locked as of December 2022 (followed by Pancake Swap on BSC with 2.9 billion). Shortly after Uniswap launched, an anonymous team forked the open-source code of Uniswap, and named it Sushiswap, from which they launched and airdropped the $SUSHI token, which could be locked up to receive fees from the trades of users. This was one of the first times ever, that a massively successful protocol was forked. Shortly after, Uniswap launched its own governance token that did not harvest protocol revenue. The V3 of Uniswap also included a commercial license, which is set to expire in Quarter 2 of 2023. ![](@site/static/img/bootcamp/mod-em-3.2.3.png) While Sushiswap was well positioned to capitalize on the lack of fee sharing on Uniswap, poor management of the protocol by the team, coupled with a lack of committed ‘sticky’ liquidity, ultimately led to its demise. ## _1inch and the Power of Aggregators:_ While many different AMM’s may compete on a single L1, it remains up to the user to decide which AMM may offer them the best deal for their swap. To simplify optionality for users, _aggregators_ are commonly utilized on top of a specific L1 ecosystem to offer users all available options for a specific trading pair - from which a small fee is taken on top. [1inch remains ](https://1inch.io/)the leading aggregator on Ethereum. ## Orderbook DEXs and Perps / Futures Orderbook DEXs refer to decentralized exchanges - that are structured to pair trades, as done normally through a centralized exchange. While orderbook DEX’s still operate off of user-pooled liquidity, the difference between an orderbook and an AMM is as follows: _In an AMM, the user is trading against the contract - and the algorithm programming the swap rates. With an Orderbook, the user is trading against other users - and has the freedom to sell their tokens at higher or lower prices, or with stop loss._ AMM’s predominantly rely upon passive market making - meaning the algorithm is changing, after a trade, and based on the current state of liquidity. Orderbook DEXs rely upon proactive market making - meaning a pair can be set at a higher or lower price, beyond what other users are trading for. Orderbooks in crypto are relatively new innovations due to the high-throughput and low cost requirements that traditional L1s like Ethereum were unable to accommodate for. As Consensys explains: _“Which lets users transparently match their orders with one another on a 'price-time-priority-basis.' In short, the highest bid and the lowest ask converge to represent the current market price, and users have the option to cross this bid-ask spread to immediately execute the order. Given the transparency of this system, users can see market depth in real-time. While these features of a CLOB (central limit Orderbook) are quite powerful, they are difficult to implement within an on-chain system. This difficulty stems primarily from high throughput and low execution cost requirements of an order book. That is, in order for a CLOB to effectively operate on-chain, gas fees must be cheap and transactions must be very fast.”_ ([Consensys](https://consensys.net/blog/cryptoeconomic-research/serum-a-decentralized-on-chain-central-limit-order-book/)) And with a robust orderbook structure - on-chain - and therefore a decentralized, open-source infrastructure, other builders can create further financial primitives on top of any Orderbook, including perpetual futures and token bond markets. Notably orderbook DEXs in crypto include: **Serum on Solana:** [https://docs.projectserum.com/](https://docs.projectserum.com/) **Tonic on NEAR:** [https://tonic.foundation/](https://tonic.foundation/) ## _Perpetuals_ Perpetuals or perps, refers to leveraged positions taken by a user. Unlike traditional futures contracts, which have a fixed expiration date, perpetual futures contracts do not expire. Rather, they are designed to mimic the underlying spot market and allow traders to hold their positions indefinitely. Positions only expire, when a user sells, or they are forceable liquidated due to the price dropping. While usually deemed risky for users, Orderbooks or liquidity providers stand to gain much from poor trading positions. Certain perpetual dApps such as [GMX ](https://gmx.io/#/)or [GNS ](https://gains-network.gitbook.io/docs-home/)allow users to take out up to 20x (sometimes more) leverage on their trades. From a protocol design perspective, the more value that is transacted or leveraged, means that the fees LP’s and stakers stand to gain are also higher - assuming the protocol has been designed in a decentralized manner. On GMX,[ GNP is the single sided liquidity pool](https://itsa-global.medium.com/itsa-defi-insight-gmx-on-chain-perpetuals-and-glp-935bb3168f0a#:~:text=GLP%20is%20a%20single%20sided,protocol%20lose%20and%20vice%20versa.) from which users are able to access fees, and which harvests the upside of liquidations. _The most important takeaway from these advanced financial protocols is twofold: (1) First, they require price matching from orderbook DEXs in order to operate, and (2) They have yet to be stress tested, in ways other crypto products (Terra/Luna) have shown serious vulnerabilities only at a later time._ ## The Common Suspects of Token Utility in DeFi In this initial overview, we are essentially circling between theory and reality, with the intent of driving home the core conceptual logic of decentralized finance: Self-executing code, used as a foundation for liquidity providers, and users to collaboratively service themselves. When it comes to token design, there are typically three common token-economics used. _Note_: Anyone working with such projects, must be attentive to the design of the token and specifically where the revenue is distributed in the protocol. * **Liquidity incentives:** As discussed above, this refers to yields, liquidation fees, and liquidity providing fees. Note that liquidity incentives from a project perspective centers on _emission rates _which must be sustainable in order for the token to maintain its value. * **Governance:** The capacity to vote in new rates, token emissions, revenue sharing designs, or even legal (as for example with Uniswap V3). Best examples to date include Uniswap and 1inch. Neither protocol token does anything more than governance. * **Yield from Fees:** This, as said above in reference to GMX or Sushiswap, is the basis for decentralizing the revenue sharing that a protocol may earn from fees. Token holders ‘stake’ or ‘lock-up’ their tokens, and in return yield fees from the active users of the network. * **Aidrops**: While not an actually token utility, it is very common for DeFi protocols to attract a committed and active userbase in the protocols early days, by guaranteeing a _snapshot_ and future airdrop for the most active users. As it sounds, the protocol team drops tokens to the addresses most actively using the platform. Usually this is done randomly, and it is no different than simply giving away money for free to early users. Suspects of this include 1inch and DYDX. ## _Where is there room for innovation in DeFi?_ As we come to the end of this overview, there are a number of interesting areas whereby we can imagine DeFi to innovate in the coming years. At the top of the list includes the need to better align incentives _sustainably_ between the different stakeholders: * _Long term focused participants and token incentives_ How can we better incentivize sticky liquidity? How can this be done, without over-inflating the token via LP payouts? * _L1 - DeFi Integration for additional incentives._ Is there a way that the block inflation of the L1 ecosystem can be harnessed with a DeFi protocol to offer users rewards such that the DeFi native token can strengthen over time? Are there certain liquidity mechanics that an L1 ecosystem can provide to a DeFi protocol, in order to ensure further liquidity is attracted into the ecosystem? * _[Just in-time liquidity.](https://twitter.com/Crypto_McKenna/status/1599593678976454657?s=20&t=p1N1zudbRDGHZ1Vn2nF3Mw)_ Attempts to strengthen AMMs such that they can offer users quick trade execution at specific prices. However, as demonstrated in [Uniswaps blog](https://uniswap.org/blog/jit-liquidity), this remains a very small amount of trades on AMMs to date. ![](@site/static/img/bootcamp/mod-em-3.2.4.png) * _Risk Management Innovations:_ Through tranching protocols such as [BarnBridge ](https://barnbridge.com/)or [Saffron Finance](https://saffron.finance/), that are able to create delta neutral positions for users or through institutional pools, with improved KYC controls, we are likely to see increasingly complex infrastructures built on top of base-layer DeFi protocols in order to offer improved risk management and legal accommodation.
Women in Web3 Changemakers: Veronica Korzh NEAR FOUNDATION October 10, 2023 “I think balance is the crucial factor,” says Veronica Korzh, the co-founder and CEO of GeekPay, an all-in-one platform to streamline and secure batch payments in digital currencies to gig workers. “It doesn’t really matter if it’s Web2, Web3, Web5 or whatever — equality and diversity in terms of genders, races, religions brings more to the table.” Korzh 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. Korzh, along with nine other outstanding candidates, are showing the industry the change women are bringing about during the advent of the Open Web. Korzh was selected not only for her work at GeekPay, but because of the pivotal role she has played in supporting Ukrainian startups, helping them maintain access to funding and talent during a period where so many have been displaced after Russia’s invasion of Ukraine. Korze is a Partner at SID Venture Partners, the first unique Ukrainian high-technology venture capital firm established by IT experts focusing on investments into early-stage technology startups. In little over a year, it has successfully funded 16 startups across a range of sectors, and recently became the most active venture investor in Ukrainian startups in the last 18 months. A Web3 Journey “My story is quite simple,” says Korzh, who is currently based in Lisbon. “I’ve been in the Ukrainian software business for about 15 years in project management, programme management, and also in product house roles”. Korzh’s journey into Web3 came about after a chance encounter with Illia Polosukhin, one of the co-founders of NEAR Protocol. “I was always fascinated about technology, and blockchain has, for the last 10 years, been one of the most exciting technologies.” This led Korzh to begin investigating what this breakthrough technology was really all about. At first, says Korzh, blockchain was difficult to understand, but there was something intriguing that led Korzh to dive deeper. At the time, Kurzh had been working on a fitness app in Ukraine, but that chance encounter led her to radically rethink the direction of her career. “I moved to blockchain and here starts the most interesting part of my life,” she says. In less than two years, Korzh has helped 16 companies access funding and become the co-founder of her own Web3 company. But the road hasn’t been without its challenges. Since the beginning of the Russian invasion in February 2022, the start-up sector in Ukraine’s bustling tech industry has been displaced. Dozens of companies had to relocate, further west in the country, or to welcoming hubs like Lisbon. This made evaluating companies on their merit more challenging. Since then, Ukraine’s crypto native community has bounced back. Ukraine has managed to raise more than $100 million in cryptocurrency donations through its government-curated Crypto Fund of Ukraine, thanks to natively built projects like UkraineDAO. For Korzh and her colleagues, the journey to find the best startups has, despite the disruption, continued. “The technology is still far away from what we would like to have in terms of the ecosystem.” This has meant assessing which projects should be funded, and which require more work, has been a challenge. But, says Korzh, that’s where women come in. More balance, better results “I think balance is the secret sauce for progress for any business. The more balanced ecosystem you have, in terms of gender, the better your results.” Korzh believes increasing the number of women in Web3 can only help produce better results. “In terms of gender equality, this space is very male,” says Korzh. “It is very hard to find women founders.” This is where awards like the Women in Web3 Changemakers hopes to help showcase the work of women across the space and encourage others to take the plunge. “I think awards can help say: ‘I’m capable enough to start my own company,’ or ‘I’m capable enough to understand how blockchain works.’ It’s an indicator for myself as a female founder to think, okay, maybe I should also try myself, maybe I can build something, maybe I can create an idea that then changes the world.”
--- id: upgrade title: Updating Contracts --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs" import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; NEAR accounts separate their logic (contract's code) from their state (storage), allowing the code to be changed. Contract's can be updated in two ways: 1. **Through tools** such as [NEAR CLI](../../../4.tools/cli.md) or [near-api-js](../../../4.tools/near-api-js/quick-reference.md) (if you hold the account's [full access key](../../../1.concepts/protocol/access-keys.md)). 2. **Programmatically**, by implementing a method that [takes the new code and deploys it](#programmatic-update). --- ## Updating Through Tools Simply re-deploy another contract using your preferred tool, for example, using [NEAR CLI](../../../4.tools/cli.md): <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash # (optional) If you don't have an account, create one near create-account <account-id> --useFaucet # Deploy the contract near deploy <account-id> <wasm-file> ``` </TabItem> <TabItem value="near-cli-rs"> ```bash # (optional) If you don't have an account, create one near account create-account sponsor-by-faucet-service somrnd.testnet autogenerate-new-keypair save-to-keychain network-config testnet create # Deploy the contract near contract deploy <accountId> use-file <route_to_wasm> without-init-call network-config testnet sign-with-keychain send ``` </TabItem> </Tabs> --- ## Programmatic Update A smart contract can also update itself by implementing a method that: 1. Takes the new wasm contract as input 2. Creates a Promise to deploy it on itself <CodeTabs> <Language value="rust" language="rust"> <Github fname="update.rs" url="https://github.com/near-examples/update-migrate-rust/blob/main/self-updates/base/src/update.rs" start="10" end="31" /> </Language> </CodeTabs> #### How to Invoke Such Method? <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash # Load the contract's raw bytes CONTRACT_BYTES=`cat ./path/to/wasm.wasm | base64` # Call the update_contract method near call <contract-account> update_contract "$CONTRACT_BYTES" --base64 --accountId <manager-account> --gas 300000000000000 ``` </TabItem> <TabItem value="near-cli-rs"> ```bash # Call the update_contract method near contract call-function as-transaction <contract-account> update_contract file-args </path/to/wasm.wasm> prepaid-gas '300.0 Tgas' attached-deposit '0 NEAR' sign-as <manager-account> network-config testnet sign-with-keychain send ``` </TabItem> <TabItem value="js" label="🌐 JavaScript"> ```js // Load the contract's raw bytes const code = fs.readFileSync("./path/to/wasm.wasm"); // Call the update_contract method await wallet.callMethod({contractId: guestBook, method: "update_contract", args: code, gas: "300000000000000"}); ``` </TabItem> </Tabs> :::tip DAO Factories This is how DAO factories [update their contracts](https://github.com/near-daos/sputnik-dao-contract/blob/main/sputnikdao-factory2/src/factory_manager.rs#L60) ::: --- ## Migrating the State Since the account's logic (smart contract) is separated from the account's state (storage), **the account's state persists** when re-deploying a contract. Because of this, **adding methods** or **modifying existing ones** will yield **no problems**. However, deploying a contract that **modifies or removes structures** stored in the state will raise an error: `Cannot deserialize the contract state`, in which case you can choose to: 1. Use a different account 2. Rollback to the previous contract code 3. Add a method to migrate the contract's state <hr className="subsection" /> ### The Migration Method If you have no option but to migrate the state, then you need to implement a method that: 1. Reads the current state of the contract 2. Applies different functions to transform it into the new state 3. Returns the new state :::tip DAO Update This is how DAOs [update themselves](https://github.com/near-daos/sputnik-dao-contract/blob/main/sputnikdao2/src/upgrade.rs#L59) ::: <hr className="subsection" /> ### Example: Guest Book Migration Imagine you have a Guest Book where you store messages, and the users can pay for such messages to be "premium". You keep track of the messages and payments using the following state: <CodeTabs> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/update-migrate-rust/blob/main/basic-updates/base/src/lib.rs" start="10" end="21" /> </Language> </CodeTabs> #### Update Contract At some point you realize that you could keep track of the `payments` inside of the `PostedMessage` itself, so you change the contract to: <CodeTabs> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/update-migrate-rust/blob/main/basic-updates/update/src/lib.rs" start="12" end="23" /> </Language> </CodeTabs> #### Incompatible States If you deploy the update into an initialized account the contract will fail to deserialize the account's state, because: 1. There is an extra `payments` vector saved in the state (from the previous contract) 2. The stored `PostedMessages` are missing the `payment` field (as in the previous contract) #### Migrating the State To fix the problem, you need to implement a method that goes through the old state, removes the `payments` vector and adds the information to the `PostedMessages`: <CodeTabs> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/update-migrate-rust/blob/main/basic-updates/update/src/migrate.rs" start="3" end="46" /> </Language> </CodeTabs> Notice that `migrate` is actually an [initialization method](../anatomy/anatomy.md#initialization-method) that **ignores** the existing state (`[#init(ignore_state)]`), thus being able to execute and rewrite the state. :::tip You can follow a migration step by step in the [official migration example](https://github.com/near-examples/update-migrate-rust/tree/main/basic-updates/base) :::
--- sidebar_position: 1 --- # Unit Tests You can unit test abstracted logic implemented by smart contract functions like regular JavaScript functions with any testing library of your liking. A simple example would look as follows: #### Contract ```js @NearBindgen({}) export class Contract { ... doSomething(): string { return callSomeFunction(); } } ``` #### Unit Test File ```js describe('Contract', () => { it('callSomeFunction should work', () => { ... results = callSomeFunction(); // then assert results are what you expect .... }); }); ``` As for testing the smart contract functions themselves, we recommend using [integration tests](./integration-tests.md) instead as they fully replicate the environment on which that logic will run.
SailGP Launches Digital Collectibles Series on NEAR COMMUNITY June 15, 2022 SailGP, one of the world’s fastest-growing sports properties, is launching its first ever digital collectibles range, as part of its multi-year partnership with the NEAR Foundation. The collectibles series sits within the NEAR Foundation’s broader partnership with SailGP to reimagine sport for fans by harnessing Web3 technology. Four digital collections will be released, each based on values shared by SailGP and NEAR. “Collecting sporting memorabilia has always been a key part of fan enjoyment and engagement but now, through our first ever SailGP x NEAR digital collectables, fans will not only be able to own a piece of history but also access unique experiences,” says Daisy Vollans, SailGP head of digital and engagement. SailGP’s first NFT collection The first collection will be focused around SailGP and NEAR’s shared ambition for a more sustainable future. Two of SailGP’s striking F50-inspired Earth Day posters will be turned into NFTs (non-fungible tokens), with 10 editions released of each artwork. In tandem, fans who buy one of these 20 NFTs will be gifted a sustainably made t-shirt adorned with one of the Earth Day artworks. The second collection will be themed around SailGP’s events and local communities and will utilize the locally designed artworks that currently feature in SailGP’s City Collection merchandise. Chicago based designer Justin Van Genderen is the first to feature with his striking design highlighting the sport and speed of the F50 while showcasing the Chicago city skyline. The third collection will be photo-driven and fan-focused, with SailGP’s award winning photography forming the basis of exclusive digital artworks. The collection will champion the action-packed, edge-of-your-seat moments from SailGP’s racing, from capsizes and collisions to neck-and-neck rivalries right up to the finish line. Finally, the fourth collection will act as an entry point for fans into SailGP’s digital collectables. The NEAR X SailGP F50 icon – created to drive engagement on twitter as part of a shared Season 3 #F50 hashflag campaign – will be distributed to anyone who engages with SailGP by attending an event, downloading the NEAR wallet or completing SailGP’s new single sign across SailGP platforms later this year. “When sports leagues like Major League Baseball dove into digital collectibles, they launched with charitable use cases that grabbed the attention of industry-advocates like Tyler Winklevoss. SailGP has taken those inspirations and is elevating them to be core to its fan experience – not just bolting on another commercial opportunity. SailGP’s tech innovations, built on climate-neutral NEAR, are inspiring both global and local communities from their iconic locations, like Navy Pier,” says Chris Ghent, NEAR Foundation global head of brand strategy and partnerships. How to start your NEAR x SailGP journey SailGP’s digital collectables journey will begin in earnest in Chicago with an exclusive exhibition curated by the @imnotArt gallery – Chicago’s first physical NFT gallery. NFTs from all four collections will be on display, while fans will also have the chance to purchase a SailGP NFT for the first time. The 60 NFTs created from SailGP’s Chicago City Collection artwork – which will come a piece of official merchandise – will be available to buy, while a image from entertainment collect will be issued to anyone who creates a NEAR digital wallet across the event weekend or uses the QR code to enter the gallery. After two days at the gallery, the collection will move over to the SailGP Event Village at Navy Pier and be on display in the Ballroom. To stay up to date on SailGP’s partnership with NEAR, sign up for the NEAR newsletter, and be sure to follow the Foundation on social media.
--- sidebar_position: 2 title: "Private Methods" --- # Private Methods ## When Using Callbacks Usually, when a contract has to have a callback for a remote cross-contract call, this callback method should only be called by the contract itself to avoid someone else calling it and changing the state. A common pattern is to have an assertion that validates that the direct caller (predecessor account ID) matches to the contract's account (current account ID). The `({ privateFunction: true })` decorator simplifies this by making it a single line decorator while improving readability. Use this annotation within the designated contract class with the [`NearBindgen({})` decorator](../contract-structure/near-bindgen.md) as follows: ```js @call({ privateFunction: true }) my_method({}) { // ... } ``` Which is equivalent to: ```js @call({}) my_method({}) { if near.currentAccountId() != near.predecessorAccountId() { throw new Error("Method method is private"); } // ... } ``` Now with this annotation, only the account of the contract itself can call this method, either directly or through a promise. ## Writing Internal Methods Not all functions need to be exposed publicly. It may be beneficial to write private methods for helper or utility functions, for instance. There are three approaches to write internal methods: 1. Declare the method without using the `call` or `view` decorators. ```js helperMethod(a, b) { // ... } ``` 2. Using an internal helper function in the module scope. ```javascript // Function that can be called in another JS file function getFirstName(account) { // ... } ``` 3. Importing a helper function or class from another module. Another way of not exporting methods is by having a separate class, that is not marked with `NearBindgen({})`. ```js import { getFirstName } from "./helpers.js"; @NearBindgen({}) export class Contract { // ... } class Helpers { // ... } ```
--- id: token-loss title: Avoiding Token Loss sidebar_label: Avoiding Token Loss --- :::warning Careful! Losing tokens means losing money! ::: Token loss is possible under multiple scenarios. These scenarios can be grouped into a few related classes: 1. Improper key management 2. Refunding deleted accounts 3. Failed function calls in batches --- ## Improper key management Improper key management may lead to token loss. Mitigating such scenarios may be done by issuing backup keys allowing for recovery of accounts whose keys have been lost or deleted. ### Loss of `FullAccess` key A user may lose their private key of a `FullAccess` key pair for an account with no other keys. No one will be able to recover the funds. Funds will remain locked in the account forever. ### Loss of `FunctionCall` access key An account may have its one and only `FunctionCall` access key deleted. No one will be able to recover the funds. Funds will remain locked in the account forever. --- ## Refunding deleted accounts When a refund receipt is issued for an account, if that account no longer exists, the funds will be dispersed among validators proportional to their stake in the current epoch. ### Deleting account with non-existent beneficiary When you delete an account, you must assign a beneficiary. Once deleted, a transfer receipt is generated and sent to the beneficiary account. If the beneficiary account does not exist, a refund receipt will be generated and sent back to the original account. Since the original account has already been deleted, the funds will be dispersed among validators. ### Account with zero balance is garbage-collected, just before it receives refund If an account `A` transfers all of its funds to another account `B` and account `B` does not exist, a refund receipt will be generated for account `A`. During the period of this round trip, account `A` is vulnerable to deletion by garbage collection activities on the network. If account `A` is deleted before the refund receipt arrives, the funds will be dispersed among validators. --- ## Failed function calls in batches :::warning When designing a smart contract, you should always consider the asynchronous nature of NEAR Protocol. ::: If a contract function `f1` calls two (or more) other functions `f2` and `f3`, and at least one of these functions, `f2` and `f3` fails, then tokens will be refunded from the function that failed, but tokens will be appropriately credited to the function(s) which succeed. The successful call's tokens may be considered lost depending on your use case if a single failure in the batch means the whole batch failed.
August in Review: Javascript SDK, NEAR Digital Collective Launch, and NEARCON Updates COMMUNITY August 30, 2022 The summer is drawing to a close but things are really ramping up all around the NEAR ecosystem. The month of August saw the Javascript SDK release, NEAR Digital Collective’s launch, new NEARCON details, and more. Let’s have a peek around the NEAR ecosystem to what’s been surfacing. From NEAR Foundation’s own initiatives, ecosystem projects, and beyond, it’s been a month of building toward the future. Ecosystem Panel: The Future of Gaming and Web3 The August Ecosystem Town Hall tackled one of Web3’s most fun and interesting topics: Gaming. David Morrison, NEAR’s Community Engagement Lead, hosted a panel of seasoned gaming veterans building on NEAR. Guests included Lisa Sterbakov of Armored Kingdom, Aliaksandr “Sasha” Hudzilin from Human Guild, and Vivi Lin of Octopus Network. The discussion ranged widely from how gaming can be a critical force in blockchain mass adoption to future in-game economic models that will better empower players. And there was one common theme amongst the panelists. The best of blockchain gaming is yet to come, as designers and developers strive to build AAA experiences for Web3. Foundation News With NEARCON fast approaching, it’s been all hands on deck at NEAR Foundation. Ticket sales rose throughout the month, and CoinDesk jumped aboard as NEARCON’s Official Media Partner. Elsewhere, the latest installment In the NEAR Future hit Twitter Spaces. Featuring Mintbase CEO Nate Geier, the AMA explored NFTs, digital collectibles, and Web3 marketplaces ahead of NEARCON. The NEAR Javascript SDK was also released this past month, creating a more seamless onboarding experience for Web2 developers looking to transition into Web3. With over 20 million Javascript developers worldwide —making it the most popular coding language—even more dapps will be coming to the NEAR ecosystem in the future. To help spread the word, Pagoda team members attended ETH Toronto on August 8th through 10th, with Austin Baggio and Ben Kurrek hosting a JS SDK workshop. This past month also marked the beginning of some major changes in NEAR ecosystem governance. Following co-founder Illia Polosuhkin’s talk at EthCC in Paris, NEAR Foundation announced that it would assist in creating the NEAR Digital Collective (NDC). The NDC is a new framework and implementation plan for an ecosystem-wide self-governance treasury. Its main purpose will be to further decentralize NEAR’s ecosystem governance by moving decision-making on-chain for a more resilient, fair, and transparent community. Ecosystem News August was also an incredible month for the NEAR ecosystem, led by Sweatcoin’s $13M funding round to further tomorrow’s movement economy. Built on NEAR, Sweatcoin is now the most downloaded health and fitness app in the world. This most recent funding round includes a private token sale to accelerate the Sweat Economy’s migration to Web3. The ecosystem also surpassed 750 projects being built on NEAR. Growth is certainly accelerating, going from 100 projects to 750 in less than a year. At this pace, it wouldn’t be a surprise to break the 1,000-project mark before the holiday season. Amidst this ecosystem growth, Coinbase added NEAR to its roadmap this past month. It was also an eventful month for all things Aurora. The team successfully fended off an attempted hack on the network, halting the attack in only 31 seconds. Aurora has also been included in the latest Brave desktop update as a preloaded chain for all Brave Wallet users. The Aurora Vietnam Community is also now up and running, furthering the Foundation’s goal of fostering a thriving, global ecosystem. There were several key NFT happenings, headlined by Mintbase launching its grants program that will help foster growth by helping NFT projects bootstrap on NEAR. And Playible —an NFT fantasy sports platform built on the NEAR protocol—celebrated its first fantasy sports NFT launch this past month. The first NEAR-native omnichain NFT project was also announced in August, with Real Birds being announced as a grant recipient. In terms of developer tooling, Chainstack announced that the platform will now support NEAR to more easily deploy, run, and manage nodes. WELLDONE Studio also released and presented its wallet and remix IDE plugin for devs looking to build on NEAR. Both Chainstack and WELLDONE demonstrate how the NEAR ecosystem is enhancing the developer experience month over month. NEAR in the Press NEAR co-founder Illia Polosukhin spoke with CoinTelegraph at Korean Blockchain Week (KBW) about the rollout of the JavaScript SDK, emphasizing that the 20 million worldwide JS developers can now foray into blockchain without significant skills re-tooling. Forkast also reported that the NEAR Foundation shortlisted 20 candidates for its first-ever Women in Web3 Changemakers list. Ten winners will be selected via public vote ending on August 29th, conducted on the blockchain using NEAR wallets (more on this below). Marieke Flement, CEO of the NEAR Foundation, was also featured on the Forbes Technology Council where she gave her thoughts on managing the challenges of a decentralized workforce and the “Right to Disconnect.” NEARCON: Apply for Hackathon, Vote for Women in Web3, and Join the Poster Hunt With NEARCON fast approaching, the NEAR Foundation is extremely thankful for all of the hackathon applications received to date. There are still some slots left, but you’ll want to apply as soon as possible via this application page. Selectees will receive free admission to NEARCON, a travel stipend in NEAR tokens, and an invite to the registration party on September 11th with fellow hackathon-ers. Time is also ticking to vote for Women in Web3 Changemakers. You can vote via typeform or through a DAO. Votes will be counted equally but the typeform is a simpler option for those unfamiliar with DAO voting. To vote via DAO, click on the official Satori link, connect an existing NEAR wallet or create a new one. After claiming an NFT, head to the poll on AstroDAO and cast your vote! Finally, stay tuned for more details on the NEAR Poster Hunt in Lisbon. It’ll be like an IRL scavenger hunt mixed with Web3. Posters with QR codes will be scattered around the city, and people will be able to win prizes, collect POAPs, and more. The NEAR Poster Hunt will be one of the most fun and social events at NEARCON. So, keep your eyes peeled for details!
Grassroots Support Initiative Update – September 11, 2023 NEAR FOUNDATION September 11, 2023 As a follow up to the NEAR Foundation’s previous grassroots support post, we wanted to take a moment to share an update on our progress. On September 4th, we closed the form through which projects could request support until the NDC funding mechanism is live. Over the past two weeks, we have spoken to builders across the ecosystem to understand their needs and begin mapping out the different paths forward to ensure they receive the support they need. We have encountered a range of different requests and have been taking a holistic approach to understand the unique needs faced by each project and the resources available to help them achieve their goals moving forward. While financial support is only one part of this, there have been a number of questions about the range of options available, so we wanted to give everyone visibility into the next steps. Projects looking for funding will first explore internal resources including the BD/Ecosystem success team and ad hoc advisory support via a 1-1 call with the Horizon team, as well as by working closely with the MarketingDAO, CreativesDAO, and DevHub. Projects that do not qualify through any of these routes will have the ability to go to an internal review process. To make sure the community voices are heard and involved in the process, members of the Governance Working Group (GWG) have collaborated with NEAR Foundation to define the criteria needed to receive financial support. The criteria the committee will use to make the selections are the following: Is the project built on NEAR and live on mainnet? Is there a current grant already in place? Are there a minimum 100 monthly active users? Does the request cover a maximum of 3 months of runway? This process should be completed within the coming two weeks, at which point the NEAR Foundation will provide a further update. In the meantime, if you have any questions you can always reach us at [email protected].
NEAR and Press Start Team to Level Up Web3 Gaming COMMUNITY December 9, 2022 NEAR Foundation is excited to announce a new partnership with Press Start Capital, a seed stage venture fund focused on full-stack Web3 gaming, metaverse, and entertainment. This follows the Press Start x Orange DAO Web3 Fellowship announced earlier this year. With NEAR, Press Start is looking to identify, fund, and support the leading Web3 builders and creators of what it calls a “new Golden Age of Entertainment.” Press Start Capital will join NEAR’s network of partner funds. In this new partnership, information and industry insights-sharing between NEAR and Press Start will be vital. Press Start will provide investment and mentorship support to Web3 gaming and entertainment projects building on NEAR. Press Start and its portfolio companies will also have access to the Foundation and ecosystem’s vast network of fund partners—a critical piece in building the new era of gaming. Game developers that aren’t committed to a blockchain will have access to priority NEAR support to help build and ship their Web3 gaming apps and products. Marieke Flament, CEO of the NEAR Foundation, said: “This is a fantastic partnership that will help us to attract the very best projects to our protocol. We look forward to leveraging this opportunity by working closely with Press Start to identify and support exceptional talent and to give creators the tools they need to build without limits on NEAR.” Community front and center Both NEAR and Press Start see the future of gaming as being community-driven. The partners are fully aligned in manifesting a world where players take part in the creation and ownership of the games, stories, and assets they cherish. “As crypto eats software and gaming eats culture, we believe now is the time to build a new Golden Age of Entertainment that will unleash a new generation of community-owned games, apps, and IP,” said Steven Chien, co-founder and General Partner at Press Start Capital. “We’re excited to collaborate with NEAR as a mission-aligned partner to support and grow a community of Web3 founders building community-driven products.” With NEAR and Press Start, founders will help founders in a mutual learning environment. The partnership will also include deal flow sharing and community initiatives. Press Start’s collaboration with NEAR partner OrangeDAO, a group of over 1,300 Y Combinator alumni, on a new fellowship is also part of this community-driven strategy. The fellowship featured participants building applications that will empower future Web3 users and communities. Ten fellows completed a ten-week fellowship program designed to help Y Combinator alumni validate, build, and ship their next web3 project. Several fellows had closed a fundraising round and gained acceptance into top tier accelerators by the end of the fellowship program. Web3 gaming on NEAR: fast and infinitely scalable With the new NEAR and Press Start partnership, Web3 gaming developers can take full advantage of NEAR’s sharded, Proof-of-Stake (PoS), layer-one blockchain. Thanks to NEAR’s unique Nightshade sharding implementation, gaming projects will join a dynamic ecosystem of 800+ active projects and over 125 DAOs, building on a protocol that is ever-expanding and decentralizing. Like the other developers, entrepreneurs, and creatives building on NEAR, Web3 gaming devs will have access to the NEAR community’s resources. From Web3 startup platform Pagoda to NEAR Education and other ecosystem players, gaming devs can tap into a vast web of Web3 technology and expertise. Future partnership opportunities NEAR Foundation’s partnership with Press Start will evolve over time, combining the Foundation’s technological know-how with the VC fund’s investment and builder expertise. There is already potential for a co-sponsored accelerator and events centered on Web3 gaming and entertainment.
Decentralized Storage for dApp Developers DEVELOPERS December 8, 2021 While security, speed, and reliable data records are key elements in developing a decentralized app (dApp) in the Web3 ecosystem, the complexity of decentralization is a critical factor that can drive the cost and effort required in deployment. Standard dApp development consists of a Web 2 tech stack for the front-end and state management handled by smart contracts deployed on the blockchain for the back-end. With this hybrid approach, it can be tricky to determine what to store on and off-chain. For example, keeping all of the files for a front-end’s UI on-chain is less efficient and cost-effective when compared to existing SQL or no-SQL solutions. However, there are times when larger data files will need to be stored in a permanent decentralized manner (such as NFTs that contain large images or songs), so the content is always accessible to its owner. As a new developer in the crypto space, your first approach to storing various media files might be to use the same blockchain where the smart contract is being deployed. However, the storage cost for large amounts of binary data on the blockchain can be prohibitive and ultimately not practical. To solve this problem, teams of developers have been working on creating decentralized storage solutions focused on storing large amounts of data at a competitive price. These solutions allow dApp developers to maintain a decentralized infrastructure that secures the availability of your data when needed. Arweave, IPFS, and Sia’s Skynet are three great examples of such projects, and we are excited to share ways you can integrate their platforms into your project. The DevRel team has published a new article on Decentralized Storage Solutions, that gives you a brief introduction to each solution and an integration example so you can quickly try them out and find the optimal solution for your project. At NEAR we are committed to helping create a healthy Web3 ecosystem where everyone can build projects that integrate different technologies, solutions, and networks that fit their needs. We want developers and users to choose which tool is the best for the job and ensure interoperability is maintained. Have any questions, comments, or feedback? Join us on Discord and let us know in the #development channels. We also host daily Office Hours live Monday – Friday 11AM – 12PM PT (6PM – 7PM UTC), where the DevRel team will answer any questions you may have!
```js const accountId = context.accountId ?? props.accountId; const keypomContract = "v2.keypom.near"; const dropSupplyForOwner = Near.view( keypomContract, "get_drop_supply_for_owner", { account_id: accountId } ); const dropsForOwner = Near.view(keypomContract, "get_drops_for_owner", { account_id: accountId, from_index: (dropSupplyForOwner - 1).toString(), }); const dropId = dropsForOwner[dropsForOwner.length - 1].drop_id; ```
--- NEP: 148 Title: Fungible Token Metadata Author: Robert Zaremba <robert-zaremba>, Evgeny Kuzyakov <ek@near.org>, @oysterpack DiscussionsTo: https://github.com/near/NEPs/discussions/148 Status: Final Type: Standards Track Category: Contract Created: 03-Mar-2022 Requires: 141 --- ## Summary An interface for a fungible token's metadata. The goal is to keep the metadata future-proof as well as lightweight. This will be important to dApps needing additional information about an FT's properties, and broadly compatible with other tokens standards such that the [NEAR Rainbow Bridge](https://near.org/blog/eth-near-rainbow-bridge/) can move tokens between chains. ## Motivation Custom fungible tokens play a major role in decentralized applications today. FTs can contain custom properties to differentiate themselves from other tokens or contracts in the ecosystem. In NEAR, many common properties can be stored right on-chain. Other properties are best stored off-chain or in a decentralized storage platform, in order to save on storage costs and allow rapid community experimentation. ## Rationale and alternatives As blockchain technology advances, it becomes increasingly important to provide backwards compatibility and a concept of a spec. This standard encompasses all of these concerns. Prior art: - [EIP-1046](https://eips.ethereum.org/EIPS/eip-1046) - [OpenZeppelin's ERC-721 Metadata standard](https://docs.openzeppelin.com/contracts/2.x/api/token/erc721#ERC721Metadata) also helped, although it's for non-fungible tokens. ## Specification A fungible token smart contract allows for discoverable properties. Some properties can be determined by other contracts on-chain, or return in view method calls. Others can only be determined by an oracle system to be used on-chain, or by a frontend with the ability to access a linked reference file. ### Examples scenario #### Token provides metadata upon deploy and initialization Alice deploys a wBTC fungible token contract. ##### Assumptions - The wBTC token contract is `wbtc`. - Alice's account is `alice`. - The precision ("decimals" in this metadata standard) on wBTC contract is `10^8`. ##### High-level explanation Alice issues a transaction to deploy and initialize the fungible token contract, providing arguments to the initialization function that set metadata fields. ##### Technical calls 1. `alice` deploys a contract and calls `wbtc::new` with all metadata. If this deploy and initialization were done using [NEAR CLI](https://docs.near.org/tools/near-cli) the command would be: ```shell near deploy wbtc --wasmFile res/ft.wasm --initFunction new --initArgs '{ "owner_id": "wbtc", "total_supply": "100000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Wrapped Bitcoin", "symbol": "WBTC", "icon": "data:image/svg+xml,%3C…", "reference": "https://example.com/wbtc.json", "reference_hash": "AK3YRHqKhCJNmKfV6SrutnlWW/icN5J8NUPtKsNXR1M=", "decimals": 8 }}' --accountId alice ``` ## Reference-level explanation A fungible token contract implementing the metadata standard shall contain a function named `ft_metadata`. ```ts function ft_metadata(): FungibleTokenMetadata {} ``` ##### Interface ```ts type FungibleTokenMetadata = { spec: string; name: string; symbol: string; icon: string | null; reference: string | null; reference_hash: string | null; decimals: number; }; ``` An implementing contract MUST include the following fields on-chain - `spec`: a string. Should be `ft-1.0.0` to indicate that a Fungible Token contract adheres to the current versions of this Metadata and the [Fungible Token Core][FT Core] specs. This will allow consumers of the Fungible Token to know if they support the features of a given contract. - `name`: the human-readable name of the token. - `symbol`: the abbreviation, like wETH or AMPL. - `decimals`: used in frontends to show the proper significant digits of a token. This concept is explained well in this [OpenZeppelin post](https://docs.openzeppelin.com/contracts/3.x/erc20#a-note-on-decimals). An implementing contract MAY include the following fields on-chain - `icon`: a small image associated with this token. Must be a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs), to help consumers display it quickly while protecting user data. Recommendation: use [optimized SVG](https://codepen.io/tigt/post/optimizing-svgs-in-data-uris), which can result in high-resolution images with only 100s of bytes of [storage cost](https://docs.near.org/concepts/storage/storage-staking). (Note that these storage costs are incurred to the token owner/deployer, but that querying these icons is a very cheap & cacheable read operation for all consumers of the contract and the RPC nodes that serve the data.) Recommendation: create icons that will work well with both light-mode and dark-mode websites by either using middle-tone color schemes, or by [embedding `media` queries in the SVG](https://timkadlec.com/2013/04/media-queries-within-svg/). - `reference`: a link to a valid JSON file containing various keys offering supplementary details on the token. Example: "/ipfs/QmdmQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm", "https://example.com/token.json", etc. If the information given in this document conflicts with the on-chain attributes, the values in `reference` shall be considered the source of truth. - `reference_hash`: the base64-encoded sha256 hash of the JSON file contained in the `reference` field. This is to guard against off-chain tampering. ## Reference Implementation The `near-contract-standards` cargo package of the [Near Rust SDK](https://github.com/near/near-sdk-rs) contain the following implementations of NEP-148: - [Implementation](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/fungible_token/metadata.rs) ## Drawbacks - It could be argued that `symbol` and even `name` could belong as key/values in the `reference` JSON object. - Enforcement of `icon` to be a data URL rather than a link to an HTTP endpoint that could contain privacy-violating code cannot be done on deploy or update of contract metadata, and must be done on the consumer/app side when displaying token data. - If on-chain icon uses a data URL or is not set but the document given by `reference` contains a privacy-violating `icon` URL, consumers & apps of this data should not naïvely display the `reference` version, but should prefer the safe version. This is technically a violation of the "`reference` setting wins" policy described above. ## Future possibilities - Detailed conventions that may be enforced for versions. - A fleshed out schema for what the `reference` object should contain. ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). [FT Core]: ../specs/Standards/Tokens/FungibleToken/Core.md
NEAR at Collision: Expand into the Open Web with the Blockchain Operating System NEAR FOUNDATION May 24, 2023 NEAR Foundation is excited to announce that NEAR is heading to the 2023 edition of Collision from June 26-29 in Toronto, Ontario. NEAR experts will be at Collision to demonstrate how brands and companies can expand into the open web using the Blockchain Operating System (BOS). The BOS is an industry-first category: a common layer for browsing and discovering open web experiences with any blockchain — all in one browser. Here is what to expect from NEAR at Collision 2023. The BOS and NEAR Horizon at Collision If you saw NEAR’s big announcement out of ETHDenver and Collision, NEAR isn’t just a Layer 1 blockchain. It’s a Blockchain Operating System that makes it easy to use the tools you already know to build apps that engage users, while fostering an open web free from centralized platforms. Also appearing at Collision will be NEAR Horizon — NEAR Foundation’s new Web3 startup support platform. Meet with the Horizon team and get started on the Web3 funding and building journey. NEAR speakers at Collision At Collision, catch a number of exciting NEAR speakers and sessions. Illia Polosukhin – Co-founder, NEAR Protocol; CEO, Pagoda Elad Gil – Investor Kendall Cole – Founder, Proximity Laura Cunningham – General Manager, NEAR Horizon Joyce Yang – Founder, Global Coin Research Steven Chien – Founder, Press Start Capital Paul Hsu – CEO & Founder, Decasonic Stay updated on the complete slate of confirmed speakers at near.org/Collision. NEAR @ Collision NEAR Horizon pitch and networking event NEAR Horizon will be hosting another Pitch and networking event with VC partners the evening of June 27th. Applications to pitch are being accepted now through June 7th.
Overview of Layer 2 approaches: Plasma, State Channels, Side Chains, Roll Ups DEVELOPERS June 20, 2019 With the increasing adoption of blockchains, and still very limited capacity of modern protocols, many so-called Layer 2 protocols emerged, such as State Channels, Side Chains, Plasma and Roll Ups. This blog post dives relatively deeply into the technical details of each approach and their benefits and disadvantages. The core idea behind any Layer 2 solution is that it allows several parties to securely interact in some way without issuing transaction on the main chain (which is the Layer 1), but still to some extent leveraging the security of the main chain as the arbitrator. Different layer 2 solutions have different properties, advantages and disadvantages. The L2 solution that I personally find the most exciting is Roll Ups, which we will cover last. Thanks to Ben Jones (Plasma Group), Tom Close (Magmo), Petr Korolev and Georgios Konstantopoulos for reviewing an early draft of this post. State Channels As a good introductory example of Layer 2 solutions, let’s first consider simple payment channels. Payment channels are one of the most adopted Layer 2 solutions today. Lightning Network, for example, is based on Payment Channels. Payment channels is a specific instantiation of a more generic concept called State Channels. A good overview of the history of the state channels can be found here. State channel is a protocol between a fixed set of participants (often two) that want to transact securely between themselves off-chain, in case of payment channel specifically exchange money. The protocol for the payment channel goes as follows: two participants first both deposit some money, say $10 worth of Bitcoin, on-chain using two on-chain transactions. After the money is deposited, both participants can instantaneously send each other money without interaction with the main chain by sending to each other state updates in a form of [turn_number, amount, signature], for as long as the balances of both participants remain non-negative. Once one of the participants wants to stop using the payment channel, they perform a so-called “exit”: submit the last state update to the main chain, and the latest balances are transferred back to the two parties that initiated the payment channel. The main chain can validate the validity of the state update by verifying signatures and final balances, thus making it impossible to try to exit from an invalid state. The problem with the exits is that the main chain cannot validate that the sequence of the transactions submitted is full, i.e. that no more state updates happened after those that are presented. For example, consider the following scenario: From the state in which Alice has $11 and Bob has $9 Alice sends a state update to Bob that transfers him $7, waits for him to provide her some service for those $7, and then exits with the state update that was before she sent $7 to Bob. The main chain cannot know that an extra State Update existed, and thus sees the exit as valid. The way to get around it is to have some time after the exit was initiated for Bob to challenge the exit, by providing a state update that is signed by Alice, and has a higher turn_number than the one that Alice submitted. In the example above Bob can submit the last state update that transfers $7 to him from Alice during the challenge period, and claim his $16 instead of just $9 in the attempted exit by Alice. While the construction with the exit game is now secure, it presents a major inconvenience: the participants might be forced to wait for a rather long period of time to exit, usually 24 hours, and need to frequently (at least once per exit period) monitor the main chain to make sure their counterparty doesn’t try to exit using some past state. A technique called WatchTowers can be used to delegate watching the network to a 3rd party. Read more about watchtowers here and here. To remove the necessity to wait for the exit timeout if both parties collaborate many implementations have a concept of “collaborative close”, in which participants can sign a “conclusion proof”, and the presence of such a conclusion proof allows the other party to exit without waiting for the challenge period. The payment channel can be generalized to arbitrary state transitions, not just payments, for as long as the main chain can validate the correctness of such transitions. For example, a game of chess can be played using state channels, by players submitting their moves as transactions to each other. Despite the inconveniences listed above, State Channels are widely used today for payments, games and other use cases, due to their immediate finality (once the counterparty confirms the receipt of a state update it is final), no fees except for those paid for the deposit and exit, and relative simplicity of the construction. While the high level definition of the state channels is relatively simple, accounting for all the corner cases, so that no party can illegally take money from the other party, is a relatively complex task. See this whiteboard session with Tom Close from Magmo in which we dive very deeply into the intricacies of building secure state channels. State Channel Networks Another disadvantage of the state channels as described above is that they only exist between two participants. You can have constructions with N of N multisignatures that allow multiple parties maintain a state channel between themselves, but it would be desirable to have a layer 2 solution with properties that State Channels have, that allows parties that do not have a channel open between them directly to still transact. Interestingly, it is possible to construct the state channels in such a way that if Alice has a state channel with Bob, and Bob has a state channel with Carol, then Alice can securely and atomically send money to Carol via Bob. With this an entire network of state channels can be built, allowing a large number of participants to transact with each other, without maintaining a connection between every pair of participants. This is the idea behind the Lightning network. In our whiteboard session with Dan Rabinson on Interledger we dived pretty deep into Lightning Networks design, check it out here. Side Chains The core idea behind a simple side chain is to have a completely separate blockchain, with its own validators and operators, that has bridges to transfer assets to and from the main chain, and optionally snapshots the block headers to the main chain to prevent forks. The snapshots can provide security against forks even when the validators of the side chain collude and try to fork out: On the figure above the side chain produces blocks, and snapshots them to the main chain. The snapshot is just the hash of the block that is stored on the main chain. The fork choice rule on the side chain is such that the chain cannot be canonical if it doesn’t build on top of the latest snapshotted block. On the figure above even if the validators of the side chain collude and try to produce a longer chain A’<-B’<-C’ after producing block A to perform a double spend, if block A was snapshotted to the main chain, the longer chain will be ignored by the side chain participants. If a participant wants to move assets from the main chain to the side chain, they “lock” the assets on the main chain, and provide a proof of the lock on the side chain. To unlock the assets on the main chain, they initiate an exit on the side chain, and provide a proof of the exit once it is included in the side chain block. However, despite the fact that the side chain can leverage the security of the main chain to prevent forks, the validators can still collude and perform a different kind of attack called Invalid State Transition. The idea behind the attack is that the main chain cannot possibly validate all the blocks that the side chain produces (it would invalidate the purpose of the side chain, that is to offload the main chain from validating each transaction), and thus if more than 50% or 66% (depending on the construction) of the validators collude, they can create a completely invalid block that steals money from other participants, snapshot such a block, initiate an exit for the stolen funds and complete it. We wrote a great overview of the invalid state transition problem in the context of sharding here. This problem maps to side chains one to one, in which case side chains would correspond to shards in the overview, and the main chain would correspond to the beacon chain. The article linked above also covers some ways to get around invalid state transitions, but those ways are not implemented in practice today, and most side chains are built with the assumption that more than 50% (or 66% depending on construction) of validators never get corrupted. Plasma Plasma is a construction that enables “non-custodial” sidechains, that is, even if all sidechain (commonly called “plasma chain”) validators collude to conduct any type of adversarial behavior, the assets on the plasma chain are safe, and can be exited to the mainchain. The simplest construction of plasma, commonly referred to as Plasma Cash, only operates with simple non-fungible tokens, and only allows transferring a particular constant amount in each transaction. It operates in the following way: Each block contains a Sparse Merkle Tree that in its leafs contains the change to the ownership of a particular token. For example, on the above figures there are four total tokens in circulation, and in the block B tokens 1, 3 and 4 do not change hands (there’s nil in the leaf), while token 2 now belongs to Alice. If block D then contained a transaction signed by Alice that transfers the block to Bob, then the same token 2 in block D would have the transaction from Alice to Bob. To transfer a token to someone one needs to provide the full history of the token across all the blocks that were produced on the plasma chain since the token was moved to the chain until the transaction. In the example above if Bob wants to transfer the token to Carol, then a transaction (depicted at the bottom) would include one entry per block, with a merkle proof of change of ownership or lack thereof in each block. Plasma chain snapshots the headers of all the blocks to the main chain, and thus Carol can validate that all the merkle proofs correspond to the hashes snapshotted to the main chain, and that the change of ownership in each block is valid. Once such transaction ends up in a block of the plasma chain, the corresponding entry with Carol is written into the merkle tree, and Carol is now the owner. Since it is assumed that the Plasma operator can be corrupted at any moment, the exits cannot be instantaneous (since the hash of the state snapshotted by the plasma operator cannot be trusted), and an exit game is required. Even for such relatively simple construction that we discussed above the exit game is pretty complex. In an episode of Whiteboard Series with Georgios Konstantopoulos from Loom Network, that goes very deep into the technical details of Plasma Cash, he presents the exit game that was used at that point by Loom Network, and we find an example where by withholding the data the operator can either steal tokens from an honest participant, or have an ability to execute a relatively painful grieving attack (see the video starting from 41:40 for the details). Later Dan Robinson proposed a simpler exit game that addressed the issue, but again an example that reorders blocks was found that broke it. Overall, the biggest advantage of Plasma is the security of the tokens that are stored on the plasma chain. An honest participant can be certain that they will be able to withdraw their tokens no matter what of the following events occur: plasma operator creates an invalid state transition (before or after the honest participant received their tokens), plasma operator withholds the produced blocks, plasma operator completely stops producing blocks. In all these scenarios, or in general under any circumstances, the tokens cannot be lost. The disadvantages are the necessity to provide the full history of the token when it is transferred, and the complexity of the exit games (and in general reasoning about them). For more technical details see the episode with Loom Network mentioned above, as well as the episode with Ben Joines from Plasma Group, in which he talks about Plasma CashFlow, a more sophisticated flavor of Plasma Cash that allows transacting in arbitrary denominations. Roll Ups As I mentioned when discussing the side chains, one of the ways to get around the Invalid State Transition problem in side chains is to provide a cryptographic proof of correctness of each state transition. The particular instantiation of this approach presently built by Matter Labs is called Roll Ups, and was initially proposed on ethresear.ch by Barry White Hat here. The Roll Up is effectively a side chain, in the sense that it produces blocks, and snapshots those blocks to the main chain. The operators in the Roll Up, however, are not trusted. Thus it is assumed that at any point the operators can attempt to stop producing blocks, produce an invalid block, withhold data, or attempt some other adversarial behavior. Similar to regular side chains, the operators cannot produce fork that precedes any block snapshotted to the main chain, so once a block on the main chain that contains the snapshot is finalized, so is the block on the Roll Up chain that is snapshotted. To get around the state validity issue, each time the Roll Up operator snapshots the block, they provide a snark of a list of transactions which performs a valid state transition. Consider the example below: There are three blocks on the roll up chain: A, B and C, snapshotted correspondingly to blocks X, Y and Z on the main chain. At each point in time the main chain doesn’t need to store anything besides the last merkle root of the state of the roll up chain. When the block A is snapshotted, a transaction is sent to the main chain that contains: The merkle root h(S2) of the new state S2; Either the full state S2, or all the transactions in the block. A zk-SNARK that attests that there’s a valid series of transactions that move from a state hash of which is equal to h(S1) to a state hash of which is equal to h(S2), and that the applied transactions match the data provided in (2). The transaction verifies that the zk-SNARK is correct, and stores the new merkle root h(S2) on chain. Importantly, it doesn’t store the full content of A in the state, but it naturally is kept in the call data, so can be fetched in the future. The fact that the full block is stored in the call data is somewhat a bottleneck, but it provides a solution to the data availability issue. With the current Matter Labs implementation it takes one minute to compute the snark for a transaction (which can be done in parallel for multiple transactions), each transaction costs 1K gas on-chain, and occupies 9 bytes of call data on the main chain. With this construction the malicious operator cannot do any harm besides going offline: It cannot withhold the data, since the transaction that snapshots a block must have the full block or the full state passed as an argument, and validates that the content is correct, and then such content is persisted in the mainnet calldata. It cannot produce a block with an invalid state transition, since it must submit a zk-SNARK that attests to the correctness of the state transition, and such a zk-SNARK cannot be obtained for an invalid block; It cannot create a fork since the fork choice rule always prefers the chain that contains the last snapshotted block, even if a longer chain exists. While the amount of storage in the call data is not improved significantly with this L2 solution, the amount of the actual writable storage consumed is constant (and is very small), and the gas cost of on-chain verification is only 1k gas/tx, which is 21x lower than an on-chain transaction. Importantly, assuming the Roll Up operators cooperate, the exit is instantaneous, and doesn’t involve an exit game. These properties combined make the Roll Up chains one of the most exciting L2 solutions today. Outro I work on a sharded Layer 1 protocol called Near. There’s a common misconception that sharded Layer 1 protocols compete with Layer 2 as solutions for blockchain scalability. In practice, however, it is not the case, and even when sharded protocols become live, Layer 2 solutions will still be actively used. Designed for specific use cases, Layer 2 will remain cheaper and provide higher throughput, even when Layer 1 blockchains scale significantly better. This write-up is part of an ongoing effort to create high quality technical content about blockchain protocols and related topics. We run a video series in which we talk to the founders and core developers of many protocols, we have episodes withEthereum Serenity,Cosmos,Polkadot,Ontology,QuarkChain and many other protocols. All the episodes are conveniently assembled into a playlist here. Follow me on twitter to get updated when we publish new write-ups and videos.
--- id: state title: Basics --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {WidgetEditor} from "@site/src/components/widget-editor" Borrowing from React, Near Components use hooks such as [**`useState`**](#state) and [**`useEffect`**](#useeffect-hook) to handle the state's logic, and [**props**](#props) to receive parameters. Near Components are stored in the blockchain, for which you will use the `NEAR VM` to [retrieve and execute them in the browser](../../4.web3-apps/integrate-components.md). Using a VM enforces components to be sandboxed, making them very secure since they cannot access your `LocalStorage` or other elements in the page they are incorporated to. However, because of this, components cannot import external libraries. However, they can [**import functions**](#import) from other components. --- ## State To handle the component's state you can use `useState` hook. The `useState` hook returns a tuple of two values: the current state and a function that updates it. <WidgetEditor> ```jsx const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); ``` </WidgetEditor> Each time a state variable is updated, the component will be **re-rendered**. This means that the **whole code will run again**. --- ## Props Each component has access to a local variable named `props` which holds the properties received as input when the component is composed. <WidgetEditor id='2'> ```jsx return <> <p> This component props: {JSON.stringify(props)} </p> <Widget src="influencer.testnet/widget/Greeter" props={{name: "Maria", amount: 2}} /> </> ``` </WidgetEditor> --- ## useEffect Hook The [`useEffect` hook](https://react.dev/learn/synchronizing-with-effects) is used to handle side effects. It will execute each time one of the dependencies changes. <WidgetEditor id='3'> ```jsx const [count, setCount] = useState(0); const [visible, setVisible] = useState(false); useEffect(() => { if(count > 5) setVisible(true); }, [count]); return ( <div> <p>You clicked {count} times</p> <p className="alert alert-danger" hidden={!visible}> You clicked more than 5 times </p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); ``` </WidgetEditor> --- ## Import Components can import functions from other components. This is useful to reuse code and to create libraries of components. <WidgetEditor id='4'> ```jsx const {add, multiply} = VM.require('influencer.testnet/widget/Math'); return <> <p> 2 + 3 = {add(2, 3)} </p> <p> 2 * 3 = {multiply(2, 3)} </p> </> ``` </WidgetEditor> Where the code of the `Math` component is: ```js function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } return { add, multiply }; ```
NEARCON Highlights NEAR FOUNDATION September 12, 2022 NEARCON 2022 is at full tilt here in the gorgeous city of Lisbon, where the NEAR ecosystem is on full display, with over 2,000 people in attendance. With a distinct carnival atmosphere, NEARCON has been a vibrant, interactive showcase of the ecosystem’s diverse and inspiring talent and creativity. Beyond the myriad of engaging talks and projects demos, there have also been parties, an IRL hackathon, food trucks from around the world, and much more NEARCON has also seen a bevy of exciting announcements, including some new ecosystem funds, a major Nightshade sharding milestone, and more. Let’s take a quick look at everything that is new on NEAR from NEARCON. A number of other announcements will be rolling out over the course of NEARCON, so stay tuned for those tomorrow. Switchboard Brings Permissionless Oracle Protocol to NEAR Switchboard Labs launches its permissionless, customizable oracle devnet implementation on NEAR Protocol. The protocol allows developers to build general-purpose data feeds such as price, sports or weather data, opening up a world of new possibilities for developers. Being a permissionless oracle protocol, Switchboard allows a developer to build their own data feed within minutes and have complete customizability, and management over their own feeds. NearPay brings debit cards creating another bridge between crypto and IRL NearPay, the bridge between the fiat and crypto world has taken another step forward in helping users access their crypto wherever they are with the launch of a physical debit card. A virtual card is already working in the EU and the UK, and the physical card is due to start delivery during the autumn. On top of that, the NearPay team has plans to expand into the US and Asia over the next 12 months. Pagoda launches flagship product for dApp developers on NEAR Pagoda, the easiest Web3 startup platform and a major contributor to the NEAR Protocol, announced today the launch of their flagship developer product. The Pagoda Console provides a robust set of integrated tools to streamline the dApp development experience from a single place. Pagoda supercharges existing dApps built on NEAR and accelerates the development of new NEAR dApps. Developers, innovators, and founders are empowered with a comprehensive toolset to build, deploy, improve, manage, test, monitor, analyze and interact with their dApps. Regional Hubs Launch in India and Vietnam At NEARCON, not one but two regional hubs were announced: India and Vietnam. The regional hub in India is dedicated to blockchain talent development and innovation. NEAR’s involvement in the country aims to move the dial towards a sustainable and inclusive approach to blockchain development, and a strong group of potential emerging leaders already exists in the region. In Vietnam, meanwhile, NEAR has partnered with premier venture capital fund GFS Ventures to launch a hub dedicated to ongoing blockchain innovation, education and talent development throughout the region. Vietnam’s digital economy is booming with the pandemic seeing eight million new digital consumers and a doubling of new startups in the country. The nation is actively promoting digital transformation and development and also ranks 5th out of 154 countries in the Global Cryptocurrency Acceptance Index. However, Vietnam tops global rankings when it comes to the percentage of crypto ownership, as one in five of its people (or 20.3 per cent) own crypto. Fayyr Launches First NFT Marketplace on NEAR for Social Impact Organizations Fayyr provides a unique online marketplace for users to support social impact causes and artists at the same time. Artists upload their creations to Fayyr and earmark a percentage of the proceeds support an impact organization of their choosing. Founded by a professor and two students from the University of Waterloo, Fayyr’s vision is to empower global participation in an environment that supports social good using emerging blockchain technology. The team at Fayyr is addressing a gap in the current NFT market by providing a space for charities, non-profits, and social impact organizations to participate in the crypto space through donations from NFT purchases. NEAR to Form Community Working Group on Ecosystem Governance (NDC) NEAR is thrilled to be reaching a new milestone on the road to decentralization by creating a new framework for an ecosystem-wide self-governance treasury called the NEAR Digital Collective (NDC). The purpose of the NDC is to shift decision-making to the blockchain itself, making the NEAR community more resilient, transparent, and fair. This working group will be led and shaped by the NEAR community and will take the next steps necessary to launch and implement the NDC framework. This process, now being launched, aims to serve as a model for the wider Web3 ecosystem for the creation and implementation of truly decentralized, on-chain governance. Sustainable Learn2Earn with “Coinbase Earn” Along with being the world’s leading blockchain for developers, with its low fees, high speeds, and infinite scalability, NEAR has always championed the importance of education and sustainability in its mission toward mass adoption of Web3. Now, in a new, exciting partnership with Coinbase, one of the world’s largest digital currency exchanges, those values will take center stage in Coinbase Earn, a new program aimed at educating users about NEAR and the utility of its native token. The program will be funded through NEAR staking rewards—a first-of-its-kind, sustainable approach to help users learn about the tokenomics of the NEAR ecosystem, and what makes NEAR the best entry point to Web3. Women Make Web3 Inclusion and accessibility are at the heart of NEAR Foundation’s mission. Partnering with Forkast, a global digital media platform focused on Web3, NEAR is thrilled to unveil the winners of the inaugural Women in Web3 Changemakers. In total 1,167 votes were tallied for 180 nominations. Of the nominees, eleven were selected (ten + one tie) and it will be a joy to honor them publicly at NEARCON. Here are the names of the 2022 Changemakers listed in alphabetical order: Amy Soon, Founder, Blu3 DAO Bianca Lopes, Identity Advocate and Investor Deborah Ojengbede, CEO, AFEN Blockchain Erikan Obotetukudo, Founder and General Partner, Audacity Lauren Ingram, Founder, Women of Web3 Medha Parlikar, Co-founder, Casperlabs Oluchi Enebeli, Nigeria’s first female blockchain engineer, founder Web3Ladies Sian Morson, Founder and Editor of TheBlkChain Tammy Kahn, Co-founder and Co-CEO of FYEO Tricia Wang, Co-founder and lead Crypto Research and Design Lab (CRADL) at CISA Wendy Diamond, Web3 Impact Investor, LDP Ventures, CEO/Founder Women’s Entrepreneurship Day Organization (WEDO)/#ChooseWOMEN CEO of NEAR Foundation Marieke Flament said: “Together we can inspire one another, become each other’s role models and level the playing field for the next generation of women.” Selected by public vote, these extraordinary and diverse women hail from all corners of the globe. They are founders, investors, CEOs, engineers, and so much more. “This inaugural list of these incredible eleven Changemakers,” writes Angie Lau, CEO, editor-in-chief, and co-founder of Forkast, “celebrates the trajectory of our collective story. We can’t wait to tell their stories, and share them with the world.” Tether Finds a New Home at NEAR NEAR Foundation is excited to announce a new and important partnership with Tether (“USD₮”). The addition of Tether to NEAR’s rapidly growing ecosystem is a major moment for both parties and will be crucial to an increasing presence in DeFi ecosystems. “We’re excited to launch USD₮ on NEAR, offering its community access to the first, most stable, and trusted stablecoin in the digital token space,” says Paolo Ardoino, CTO at Tether Operations Limited. Marieke Flament, CEO of NEAR Foundation, adds “We look forward to seeing what Tether will achieve with the launch of USD₮ and the vital role it will play in shaping the future of finance and the digital economy.” For more information on how the stablecoin works, head over to Tether. NEAR Foundation announces partnership with Few and Far to grow the NEAR NFT ecosystem Few and Far, the next-generation NFT marketplace built on NEAR Protocol, has been awarded a grant by the NEAR Foundation — and a partnership to significantly increase the advancement of NFTs across the ecosystem. “We are thrilled to support Few and Far’s mission to provide seamless NFT minting solutions and an easy-to-use marketplace for the NEAR ecosystem and beyond,” says Robbie Lim, GM, Partners & International at NEAR. “The NEAR Foundation embraces the digital asset revolution and the importance of laying the foundations for web3 gaming, the metaverse economy, and much more.” Nightshade Sharding Phase 1 is live On NEARCON Day 1, there was some major Nightshade sharding news. Pagoda, the Web3 startup platform and contributor to NEAR Protocol, announced the launch of Sharding Phase 1—a major technical milestone that increases the number of validators, improves decentralization, and bolsters the network’s resilience. This is great news for anyone building or creating on NEAR, the network for creating without limits. Sharding Phase 1 is a significant step toward network decentralization and scaling capacity toward billions of transactions. And it will do this without any disruptions for developers, entrepreneurs, end users, and token holders. This launch is the second part of a four-phase plan to implement Nightshade, a novel sharding design that enables an almost infinitely automated scalable blockchain. Phase 1 follows less than a year from the launch of Phase 0, which marked the very beginning of sharding on the NEAR network. Pagoda said Nightshade’s subsequent phases are expected to be complete in 2023. NEAR and Caerus launch a fund for creators NEAR Foundation also had some exciting news for creators. The Foundation announced a new strategic partnership with Caerus, a recently launched investment firm, to help revolutionize how Web3 intersects with culture and entertainment. The partnership will see the creation of a $100M venture capital fund to support the development of next-generation platforms, marketplaces, and apps that showcase a range of creators, talent, IP owners and their communities. The Venture Lab, the partnership’s first investment, will be an incubator for creators and IP owners to build and launch projects. “We’re yet to imagine the plethora of use cases for how Web3 technologies will change how culture is experienced, entertainment is consumed, and value is distributed,” said Nathan Pillai, an executive at IMG/Endeavor. “And that was the genesis of Caerus: to be a catalyst for innovation that unleash projects in sport, music, film, TV, fashion, art and gaming which offer greater equity for all.” Stay tuned for more updates tomorrow!
```js Near.call([ { contractName: ftContract, methodName: "ft_transfer", args: { receiver_id: keypomContract, amount: "1", }, deposit: "1", gas: "300000000000000", }, ]); ```
NFT Marketplace for Hip Hop Heads Launches on NEAR CASE STUDIES June 19, 2021 Hey NEAR and Hip Hop Heads! Get ready for our first consumer-facing NFT pop-up shop! This project sprang from the mind of Ed Young, one of the co-founders of the bible of hip-hop: The Source Magazine. He had this crazy idea, our team thought it was rad, and so we built it with him. What did we build? An epic collection of hip hop icons that you can own: Hip Hop Heads. The Hip Hop Heads First Edition NFT Collection is a tribute to the history and culture of hip hop, 47 years after its inception in the Bronx, New York City. The collection features 103 animated portraits of famous figures from Hip Hop created by André LeRoy Davis for “The Last Word” feature of The Source over the last few decades. The marketplace auction is officially live! Check out the entire collection at nft.hiphop. Every day from now, Juneteenth, until July 25, one new edition of each Hip-Hop Head will be added to the auction. Each Hip-Hop Head will start with a reserve price and the current bid is bonded with the item until it is outbid or the auction closes. If a bid is returned, fans can immediately use the returned credits to bid again. Here’s the best part: cash rules everything around me. Fans can purchase these NFTs with a credit card. The marketplace offers an easier way to buy NFTs than ever before: no complicated onboarding, no passing through an exchange, just a simple, familiar purchasing experience made possible on NEAR. Check out the auction flow in the graphic below. And at the end of the auction on day 37, each winning buyer’s NFTs will display right in their NEAR wallet. Boom. It’s radical. Another cool part: NFT royalties on NEAR are written right into the NFT code, which means that any secondary sales will automatically distribute royalties back to the creators, even if the NFT moves into different marketplaces. This is uniquely possible on NEAR thanks to the protocol’s contract-level NFT standard. On-chain, programmable royalties at the smart contract level put creative and financial power back in the hands of artists, and when you buy a NEAR NFT, you can be certain that the creators you love will continue to benefit from their work. A percentage of the royalties from the Hip Hop Heads NFT auctions and secondary sales will be gifted in perpetuity to the artists depicted or to their estates by Ed Young and André LeRoy Davis. I’m so pumped to announce this launch. This carries a lot of personal weight for me. I remember the very first time I listened to “Enter the Wu-Tang (36 Chambers).” Hip hop never let me go after that. It’s funny in some ways; imagine an angsty, small-town white kid, chasing his older brother and his surfer punk friends to the beach and singing every word to “C.R.E.A.M.” But in other ways, this was destined to happen because of the work of Ed Young at The Source. Hip hop has been a force pushing culture for almost 50 years, and now it is bridging into what’s been a somewhat fringe technology for the last five. This remix of crypto and hip hop is the first of what I’m sure will be many: a brand-new blend of culture and technology is now becoming possible. We built this for people – fans – who know the feeling. Hip hop is so much more than music, and if you want to truly own a piece of its history, you should get on this! Try it out, start bidding, and let us know what you think. You only have 36 chambers…I mean days.
NEAR in May: 10m Wallets Surpassed, SailGP Hits the Waves, and More COMMUNITY May 27, 2022 May marked a month of milestones for the NEAR Foundation and ecosystem. While there was turbulence in the crypto markets, NEAR continued to forge ahead in onboarding new users, improving its technology, and developing partnerships. Community and education were prominent themes this past month, with the first iteration of the IRL NEAR Hacker House commencing in Miami, Florida. Community Talks were also at the forefront, with sessions hosted by the NEAR community on identity and building digital Queer awareness. But things didn’t stop there. From breaking account growth barriers to making headlines with NEAR’s Kenya Regional Hub, here’s everything NEAR that went down in May. NEAR surpasses 10 million wallets The month of May marked a huge milestone for the NEAR ecosystem, as the protocol surpassed the 10 million wallets created mark. Crossing this threshold brings NEAR one step closer to fulfilling the Foundation’s vision of a creating a decentralized world where anyone can create, interact, and thrive. NEAR Hacker House kicks off in Miami From May 18-22, the inaugural NEAR Hacker House took place in one of the new crypto world capitols, Miami. It was a weeklong IRL event with co-working and creation taking place at the Spot Wynwood, jam-packed with technical, social, and community-driven events. The Hacker House was free to all who signed up to attend, with tracks in development, art, and marketing. There was also in-person mentorship and guidance from key industry players in the NEAR ecosystem. Not to mention morning yoga sessions to encourage wellness and after hours social networking events. The goal was to provide participants with a taste of Hacker Houses to come, with plans for others in Europe, Latin America, and Asia in the works. Community Talks workshops and Queer plurality May was also a big month for NEAR Community Talks events and thought leadership. This included a pair of community building workshops with NEAR veterans and a series of talks on Queer diversity in the digital realm. The Community Building 101 workshop with NEAR community veterans took place during two sessions on May 7 and 15. Legedary NEAR builders like Rimberjack and Ozymandius gave a masterclass on starting communities from scratch and leveraging the right resources for success. The latter weeks of May then saw the beginning of NEAR’s Queer Diversity in the Digital Realm talks, with the first two events taking place on May 20 and 27. Gustavo Gustrava from TibiraDAO kicked off the series with a Community Talk on the basics of gender identity, intersectionality, and inclusive language. Gustrava hosted the second session’s panel educating the community on experiences of homophobia and lesbophobia, and will be hosting the final two sessions in June. The Queer Diversity and Community Building 101 events showed the strength of NEAR Community Talks and will generate momentum for further workshops in the coming months. NEAR x SailGP embarks on first race The ground-breaking partnership between SailGP and NEAR lept into action in May. Season 3 of SailGP kicked off on May 14, with Team Australia capturing first place at the Bermuda Gran Prix. As the season progresses, SailGP and NEAR will work towards the goals finalising the outline of the DAO that will eventually take over the management of a sailing team, alongside the release of SailGP NFTs. Once the SailGP DAO is firmly established using NEAR’s AstroDAO framework, fans will get the opportunity to join, own a portion of a team, and actively participate in decision-making and governance activities with real-world, competetive implications. The next phase will involve NFTs capturing previously unavailable SailGP moments and artwork for fans and collectors. NEAR in the News The launch of NEAR’s Kenya Regional Hub was one of the big headlines in May. NEAR partnered with local Kenyan blockchain community Sankore to establish a presence in Nairobi, furthering the NEAR Foundation’s goal of onboarding billions onto the blockchain and empowering individuals to live and prosper as they see fit. “We are thrilled to be working with NEAR to educate and nurture talented individuals to become world-class blockchain developers,” Sankore founder Kevin Imani told Business Insider. “Our dream is to lead the way in blockchain innovations in providing solutions to Africa’s biggest problems. This hub is the next step in turning our shared vision into reality.” Marieke Flament, the CEO of NEAR Foundation, expressed to CoinTelegraph her excitement of the potential avenues and opportunities for the proliferation of blockchain solutions throughout Africa. Flament added that the establishment of the Kenya Regional Hub and partnership with Sankore provides NEAR with the opportunity to discover new talent within the region. And according to the African Eye Report, the Regional Hub is already forging connections with local universities. To date, 77 students have registered for NEAR Certified Developer Workshops, seven in the NEAR Certified Analysts Workshops, and six local students have already been officially certified as NEAR developers. In other news, Tamago, a Web3 streaming music and NFT platform built on NEAR, appeared on Billboard magazine’s website. Tamago announced that it raised a seed round of $1M from investors to help decentralize the music industry. As Billboard reported, Tamago will release exclusive NFTs and music drops from artists Felix Da Housecat, Paramida, and others. CoinTelegraph also reported that Aurora, NEAR’s Ethereum Virtual Machine (EVM), will launch a $90 million fund to foster DeFi innovation on the NEAR Protocol. The fund will be launched in partnership with Proximity Labs in the form of 25 million Aurora tokens transferred from the DAO treasury to Proximity. “Aurora DAO continues its mission to extend the Ethereum economy outside Ethereum blockchain,” said Aurora Labs founder Alex Shevchenko “This grant is a next big step in the development of the Aurora ecosystem and I’m happy that Proximity Labs accompanies us in this journey.” ICYMI May was NFT month for the NEAR Foundation, and towards that end published a 4-part series entitled “NFTs on NEAR.” The series highlighted a variety of NFT voices and experts to go beyond the hype of NFTs, educate on what makes NFT technology so powerful, and explore what the future holds. If you want to learn more about what NFTs really mean, and exciting developments going on within the NEAR NFT ecosystem, be sure to check out May’s NFT month series below: Beyond the Hype A Deep Dive into Paras Why NFT? Where Will NFTs Go Next?
NEAR Foundation and Blumer: Pioneering Web3 Social Networking in Latin America NEAR FOUNDATION July 26, 2023 NEAR Foundation is excited to announce a strategic partnership with Blumer, Colombia’s first Web3 social network. This collaboration signifies a new era in social media where active users are incentivized for their contributions, marking a transformative shift in the user-social platform dynamic. By harnessing the strengths of blockchain technology and integrating them with the vibrant world of social networking, this partnership aims to challenge the status quo, prioritizing user privacy, compensation, and education. It’s a pioneering effort that not only champions user-centric design, but also sets the stage for a more inclusive digital future in Latin America. Blumer: Revolutionizing Social Media through Blockchain Technology Blumer, the first Web3 social network created and developed in Colombia, is an innovative platform that combines the functionality of traditional social networks with the advantages of blockchain technology. What makes Blumer so unique is that users are compensated for time spent on social media, distributing 18% of its advertising revenue back to its community. “At Blumer, we believe in creating a social network for everyone,” says Ernesto Ruiz, Blumer’s CEO. “Our platform is designed to be a space where users can express themselves, connect with friends, and learn about the crypto world. We’re committed to creating a platform that is fun, engaging, and rewarding for everyone involved.” As Ruiz alludes to, Blumer users can monetize their time spent on social media through a variety of activities like consuming advertisements, selling NFTs, and performing crypto transactions. This not only promotes user engagement but emphasizes a novel approach to commercial growth, derived largely from businesses undertaking digital marketing. Blumer isn’t just social media landscape but reshaping the whole digital economy narrative. Its unique approach of monetizing user engagement and activity on social media paves the way for a paradigm shift in user interaction and value creation. Let’s now delve into how this innovative platform aims to advance the adoption of Web3 in Latin America, one educated user at a time. “This partnership is a significant step towards creating a fair and transparent social media ecosystem,” adds Marieke Flament, CEO of NEAR Foundation. “By combining the benefits of blockchain technology with social media, we are set to revolutionize how we interact on social platforms.“ Educating users and advancing Latin American Web3 adoption Blumer also tackles the significant challenges facing cryptocurrency adoption in Latin America — namely, the lack of knowledge, understanding, and real market usability. Through ZVerso, its free crypto education platform, Blumer is empowering users with the knowledge to confidently engage within the Web3 ecosystem. By providing users with essential blockchain education and tools, Blumer is making strides toward democratizing access to Web3 technologies. This proactive educational initiative aligns with a broader vision for a more decentralized, inclusive, and user-centric digital future in Latin America. With an online population of over 54 million people, Latin America and the Caribbean form the fifth-largest global market for social media. South America alone boasts over 30 million users. The NEAR and Blumer partnership provides a unique opportunity to tap into this thriving hub and bolster the adoption of Web3 solutions. “With NEAR’s support, we are confident that we can achieve our vision and create a social network fit to thrive in tomorrow’s landscape,” Ruiz adds. The collaboration between NEAR and Blumer signifies a pivotal stride towards fostering a fair, transparent, and user-centric social media ecosystem. As Blumer forges ahead with innovative advancements in decentralized social networking, the NEAR Foundation and ecosystem give one big “Like” to Blumer’s mission of a user-empowered social network.
--- sidebar_position: 3 sidebar_label: Statistics Dashboard title: RPC Statistics --- :::warning Please be advised that these tools and services will be discontinued soon. ::: Inspect your RPC Usage in the [Statistics Tab](https://console.pagoda.co/apis?tab=statistics): ![](/docs/pagoda/stats1.png) :::info Data defaults to the last 30 days. Currently the statistics page show the usage data across all projects and API keys within an organization set on Pagoda Console. ::: Aggregated key metrics available at the top of the dashboard are - Total Request Volume - Request Success Rate - Total failed request - Average Latency ## Set a Time Period Data is sent with UTC time to the browser and the browser adjusts to the user’s timezon. - Last 15 Minutes is the last complete 15 minutes. This updates every few seconds. - Last 1 Hour is the last fully completed hour; from 00 to 59 minutes and 59 seconds. - Last 24 Hours is the last fully completed 24 consecutive hours. - Last 7 Days is the previous 7 days from the current time. Each data point groups one hour’s worth of data. The most recent hour is partial data for the current hour and updates every few seconds. - Last 30 Days is the previous 30 days from the current time. Each data point groups one hour’s worth of data. The most recent hour is partial data for the current hour and updates every few seconds. ## Requests breakdowns Multiple breakdowns are available in the statistics page ![](/docs/pagoda/stats2.png) Requests can be broken down by - Requests Methods - Requests Status - Aggregated status display breakdown by requests methods We are working to include more detailed breakdown by each requests and more interactive dashboard that enable clickthrough from the charts ## Network Status Check the [Pagoda Status page](https://status.pagoda.co/) for the latest service information across all networks and subscribe to updates based on your service choice and needs. ![](/docs/pagoda/stats3.png)
--- id: basics title: "Basic Instructions" --- # Basic instructions To compile release version of the smart contract you can run a build script (specified in `package.json` for your project as `{ build: near-sdk-js build, ... }`): ```bash npm run build ``` :::info The above `build` command seeks a `index.js` file in `/src` and outputs a `contract.wasm` file in a newly created `/build` folder at the same level as `/src`. For more information, see the [source code for the CLI commands here](https://github.com/near/near-sdk-js/blob/2a51b6c6233c935c7957b91818cfe6f9c3073d71/packages/near-sdk-js/src/cli/cli.ts?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L28-L36). ::: <!-- TODO: custom build commands using CLI -->
Get to Know the BOS: FastAuth for Easy, Web2 Style Onboarding and Account Recovery UNCATEGORIZED May 30, 2023 With the recent launch of the NEAR Blockchain Operating system (BOS) on near.org, came one of the first and most powerful features — FastAuth. With FastAuth, BOS users get a better than Web2-style onboarding experience, allowing them to easily create an account for any app on the BOS without a new password or the need to buy any crypto. And perhaps most powerfully for developers, FastAuth is both the easiest and fastest way to get people to try their new components and apps, yet another reason why developers will want to build on the BOS. This helps dramatically lower the threshold for adoption and opens the door to bringing billions of Web2 users into the Web3 space. To get up to speed on FastAuth, here is a FastAuth primer with some product demo videos. Easy onboarding and email recovery with FastAuth FastAuth gives users the power to quickly and easily create a single account that can be used for any website or app that integrates with the Blockchain Operating System (BOS). This feature makes FastAuth an ideal tool for developers building components on NEAR. With a Web2-style onboarding experience that puts the user experience front and center, users can create a free account using biometrics, phone prompts, and an email address. This means that users can quickly interact with an app but also easily re-authenticate to the app using the same or different devices. Since most users are accustomed to centralized authentication methods like “Sign in with Google”, Web3 account management using seed phrases and wallets have, until now, created a significant barrier to entry for many people. By combining FastAuth with decentralized email recovery, users no longer need to remember seed phrases or install third party wallet applications. Users can recover their accounts through a “Single Sign-on” (SSO) process with the email they used at registration. Account recovery is also decentralized and does not give custodial access to full access keys to any single custodian. It is accomplished through a process called “multi-party computation”. This finally paves a way for mass adoption with an easy, secure, and decentralized account recovery system. With FastAuth, one of the most challenging parts in onboarding users to Web3 no longer exists. Now, users can set up a BOS account quicker than creating a Gmail, Facebook, Tiktok, or Instagram account. And developers can deliver their Web3 components, apps, and experiences more seamlessly than ever. No third-party applications required FastAuth also removes the need to download any third-party applications. Everything just works seamlessly right from the browser on your desktop or mobile device. By creating an easy, user-centric experience, FastAuth makes the open web accessible to everyone right from the get-go and opens the door to mainstream adoption. Anyone developing components on the BOS can leverage this user-friendly experience to quickly and intuitively get their apps in front of users. Create an account without crypto BOS FastAuth has another great trick up its sleeve. Until now, getting started in Web3 and interacting with apps meant acquiring crypto first. With FastAuth, new users can get started right away without having to buy or be gifted crypto. This is a game changer for developers, enterprises, and end-users alike. Through FastAuth’s use of NEAR’s Meta Transactions and Zero Balance Accounts, users can register an account free of charge. Developers can also use this to their advantage as Meta Transactions paired with relayers, which allow them to sponsor initial interactions for new users without needing to purchase $NEAR. This streamlined onboarding experience allows developers to significantly increase conversion rates for people trying their components and apps for the first time. FastAuth also expands an app and website’s audience by making it more accessible to mainstream users. FastAuth creates an easy way for enterprises to integrate Web3 and crypto technology into their business. With just a few lines of code, they can onboard existing users into powerful new community and commerce experiences that are accessible, highly secure , and decentralized. End users can also get started using Web3 apps and experiences in an easy, accessible way. Setting up a secure fully user-owned account now only takes seconds. What’s next for FastAuth While FastAuth is already enabling fast and simple onboarding of mainstream users as well as streamlining component-building for developers on the BOS, a number of other features and upgrades are already in the works: The ability to extend relayers and FastAuth to additional gateways beyond near.org Further MPC decentralization Multi-chain compatibility Two-factor authentication Stay tuned to near.org for new FastAuth features and upgrades, as they are rolled out.
# Epoch All blocks are split into epochs. Within one epoch, the set of validators is fixed, and validator rotation happens at epoch boundaries. Genesis block is in its own epoch. After that, a block is either in its parent's epoch or starts a new epoch if it meets certain conditions. Within one epoch, validator assignment is based on block height: each height has a block producer assigned to it, and each height and shard have a chunk producer. ### End of an epoch A block is defined to be the last block in its epoch if it's the genesis block or if the following conditions are met: - Let `estimated_next_epoch_start = first_block_in_epoch.height + epoch_length` - `block.height + 1 >= estimated_next_epoch_start` - `block.last_finalized_height + 3 >= estimated_next_epoch_start` `epoch_length` is defined in `genesis_config` and has a value of `43200` height delta on mainnet (12 hours at 1 block per second). ### EpochHeight Epochs on one chain can be identified by height, which is defined the following way: - Special epoch that contains genesis block only: undefined - Epoch starting from the block that's after genesis: `0` (NOTE: in current implementation it's `1` due to a bug, so there are two epochs with height `1`) - Following epochs: height of the parent epoch plus one ### Epoch id Every block stores the id of its epoch - `epoch_id`. Epoch id is defined as - For special genesis block epoch it's `0` - For epoch with height `0` it's `0` (NOTE: the first two epochs use the same epoch id) - For epoch with height `1` it's the hash of genesis block - For epoch with height `T+2` it's the hash of the last block in epoch `T` ### End of an epoch - After processing the last block of epoch `T`, `EpochManager` aggregates information from block of the epoch, and computes validator set for epoch `T+2`. This process is described in [EpochManager](EpochManager.md). - After that, the validator set rotates to epoch `T+1`, and the next block is produced by the validator from the new set - Applying the first block of epoch `T+1`, in addition to a normal transition, also applies the per-epoch state transitions: validator rewards, stake unlocks and slashing.
Rapping at Stanford | NEAR Update: May 31, 2019 COMMUNITY May 31, 2019 We kicked things off this week with an epic rap session at Stanford! Last week, we were heads down smashing bugs, crushing code and shipping features. Keep your eye on our twitter – we’re planning our next hackathon – announcement coming very soon. In other news, we’ve shipped economics to our testnet, as well as the new wallet. ?Just for fun ? 4-Leaf Cheddar AKA Lucky Money AKA 4tunate 4tune @PotatoDepaulo dropping some wisdom ahead of tonight’s crypto collectible workshop at Stanford Blockchain Club. Get your sweet cryptocorgis here -only at NEAR ? pic.twitter.com/zVf3KjxbMK — NEAR Protocol (@NEARProtocol) May 31, 2019 COMMUNITY AND EVENTS If you want to see us do more in person and/or online events, just reach out on Discord: near.chat Stanford Blockchain Club workshop We covered how to build NFTs on our protocol. You can find the template for creating a new app here. You can find a completed version of the code and a complete version of Crypto Corgis! Lightning talk for Decentralized Colorado We skyped in to the Decentralized Colorado Lightning Talks night to promote our upcoming virtual dApp workshop in partnership with the Denver crypto community. If you’re in Denver, make sure you mark June 19th in your calendar. Upcoming events Hack.Two (TBA) Denver DIY Crypto Collectible Web Dev Workshop WRITING AND CONTENT We recorded a stack of Whiteboard Series interviews with teams that had flown into New York for Consensus. More videos will be released next week so keep an eye on our YouTube. Whiteboard with Fluence Whiteboard with Spacemesh We’ve released a new post on Developer Experience in Blockchain. Max published Exploring Liveness of Avalanche ENGINEERING HIGHLIGHTS There were 32 PRs in our multiple repos from 5 different authors over the last couple of weeks. As always, the code is completely open source on Github. We’ve been making steady progress on economics and our new model of sharding. Application/Development Layer Wallet Initial support for app-specific keys Send money to another account Cleaned up UI to prepare for release Display token amounts in dashboard and profile pages Account recovery working cross-browser Nearlib Minor error message improvements Support for viewing authorized apps from wallet and revoking access keys. Send tokens Near CLI Make method calls from command line Support setting networkId Configure separate network IDs for starter project config environments NEARStudio Improve templates compatibility with CLI tools Blockchain Layer Stabilizing current nearcore (released and running) Implementation of economics: charging storage rent and transaction fees. Continuing Nightshade development: integration tests, chunk production and network. HOW YOU CAN GET INVOLVED Join us! If you want to work with one of the most talented teams in the world right now to solve incredibly hard problems, check out our careers page for openings. And tell your friends ? Learn more about NEAR in The Beginner’s Guide to NEAR Protocol. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox. Reminder: you can help out significantly by adding your thoughts in our 2-minute Developer Survey. https://upscri.be/633436/
Highlights from NEAR at Davos: Crypto Goes Mainstream COMMUNITY June 2, 2022 Hello, NEAR world. From May 22-26th, the global Web3 community assembled at Davos, Switzerland for the World Economic Forum. Each year, policymakers and industry leaders descend on Davos to discuss the most important issues facing the world. While Web3 wasn’t officially on the WEF agenda, its presence loomed large. This year’s WEF featured insights from the Web3 world on blockchain, crypto, and the Open Web. Several NEAR community members and partners attended WEF to help educate and network with global leaders on Web3 innovation. Here are the highlights from NEAR at Davos. Crypto Main Street WEF effectively split the town of Davos in two. At the invite-only Congress, only the people with the right badges could attend the official forum. On the other, The Promenade”, events were free and open, with a noticeable “come as you are” vibe. While many representatives from governments, big tech firms, and large enterprises appeared at The Promenade, major crypto and Web3 players dominated the space. Along Crypto Main Street, crypto firms spent billions renting out shop fronts for visibility. Players occupying The Promenade included platforms like Polkadot, CasperLabs, Circle, Ripple, and others. Amidst soaring inflation, higher interest rates, and Terra/Luna’s collapse, Web3’s show of long-term commitment was a must. At Davos, questions arose over the sustainability of cryptocurrencies, stablecoins, and decentralized apps, and the community was there to answer them. Crypto Main Street’s biggest draw was “The Sanctuary”—a church space sponsored by Filecoin Foundation. Located just off The Promenade, the venue was a place for all to chill with free Bitcoin pizza slices and local beer, as well as learn from a strategic CNBC venue hosting crypto-related talks. Web3’s appearance at Davos also reaffirmed the obvious: blockchain and digital assets, as well as growing mainstream interest in crypto are shaping the new financial landscape. NEAR talks at The Sanctuary NEAR Foundation CEO Marieke Flament took the stage for the panel titled “Crypto, Quantum and AI: Perspectives on Emerging Tech and Sustainability”. The panel also featured Coinbase founder Michael Casey and Jack Hidary, CEO of Sandbox AI. Flament and the other panel members explored sustainability issues facing powerful blockchain technologies. Flament and the panelists agreed that blockchain sustainability is not just about the environmental impact. Other sustainability concerns include long term usability and relevance in a future defined by quantum computing and artificial intelligence. The panel also talked about the role technologists can play in educating the world about the possibility of blockchain. Attracting more talent to the sector was also a big topic of conversation on the panel. NEAR Co-founder Illia Polosukhin also took The Sanctuary stage for a fireside chat on blockchain as a force for good. In conversation with Gillian Tett, Editor at Large for the Financial Times, Pololukhin spoke about using cryptocurrencies for humanitarian aid. Polouskhin, who is Ukrainian, spoke about how effectively money had been sent via crypto to his home country during the war. A co-founder of Unchain Fund, he explained how the blockchain-based initiative raised millions in crypto to support Ukraine with humanitarian assistance, and how the model can be applied to other charitable causes. Gillian, who is passionate about ESG, sustainability, and “moral money”, seemed genuinely moved by the discussion. After their fireside chat, she stayed on the stage to speak with Polosukhin. There were several other big Web3 stories at Davos. Microsoft and Accentrue announced the Global Collaboration Village, which aims to improve metaverse functionality and engagement. Filecoin Foundation also announced plans to host blockchain nodes in space with defense contractor Lockheed Martin. NEAR in the news from Davos NEAR figures appeared in a variety of Davos press coverage, including interviews with Coindesk, Forkast News, Bloomberg TV, and Reuters. No small task, since many of the journalists at Davos were restricted to official Congress events. Forkast News, a Hong Kong-based crypto news media platform, sat down with Marieke Flament to discuss her takeaways from Davos, as well as her thoughts on the future of blockchain. In a pre-recorded broadcast, she said that crypto is not something that can be ignored. “It’s part of the conversation,” Flament remarked. “It’s open, it’s actually inclusive, and it wants collaboration, and it can help solve some of our biggest challenges.” This interview also aired on Coindesk’s channel, which hosts the Daily Forkast show. (Flament’s segment kicks in at the 4:47 mark.) Flament and Polosukhin also sat down with Reuters to talk Web3 talent and the need for global regulatory action. Their thoughts also appeared in Reuters’ Davos-related article “Get Your Crypto House in Order”. Flament’s views on India’s talent pool were clear: “When you map out where the next generations of developers are and where is the talent and where actually should we go, India pops up very, very high on the map.” Live from Zug, Switzerland on WEF’s final day, Flament made a guest appearance on Bloomberg Surveillance: Early Edition TV Show. (Her spot kicks in at the 1 hour 15-minute mark). Flament spoke on stablecoins, the Terra crisis, and how to tackle similar cases of isolated volatility. Although there were some rumors of weariness among regulators and policymakers at Davos, and skepticism from traditional banks, crypto remained front and center in the minds of Davos delegates. They understood that Web3 is undergoing rapid innovation, and its influence will only continue to grow in the coming years. Sweatcoin’s ‘Walk for Ukraine’ challenge Sweatcoin, the app that allows users to earn by moving, was also at Davos. Featured in the official WEF Davos app, the pioneers in the “movement economy” hosted “The Davos Challenge: Walk for Ukraine”. Sweatcoin encouraged Davos delegates and millions of other app users to track their steps and donate the sweatcoins generated to the Free Ukraine Foundation. The Davos challenge was part of the “Sweatcoin for Good” initiative. In this larger campaign, Sweatcoin invited users, in-app, to donate the sweatcoins they earn with their steps to a variety of charities. To participate in the challenge, users downloaded the free Sweatcoin app (iOs and Android) and started walking. With the foot traffic at Davos, the walking challenge was a great way to put newly minted sweatcoins to good use. Over the course of 7 days, Davos delegates and other Sweatcoin users donated 2,753,102 $SWC to the Free Ukraine Foundation. There were over 60K unique givers and nearly 900K unique visits to the Sweatcoin app during the campaign.
```rust #[payable] pub fn call_with_attached_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise { assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR"); let promise = ext(self.ft_contract.clone()) .with_static_gas(Gas(150*TGAS)) .with_attached_deposit(YOCTO_NEAR) .ft_transfer_call(receiver_id, amount, None, "".to_string()); return promise.then( // Create a promise to callback query_greeting_callback Self::ext(env::current_account_id()) .with_static_gas(Gas(100*TGAS)) .external_call_callback() ) } ```
Community Update: ZEST & Flux on MainNet, Hack the Rainbow, EDU@NEAR COMMUNITY September 1, 2020 Hello citizens of NEARverse! This is NiMA coming to you from a NEARby planet in the Milky Chain … (you can listen to an audio version of this update below, featuring Peter, head of devX at NEAR) Audio Player 00:00 00:00 Use Up/Down Arrow keys to increase or decrease volume. NEAR collective is hard at work to deliver the next phase of our roadmap which will also allow us to onboard thousands of new community members and token holders to the NEAR network. In parallel, our middleware team is working towards bridging NEAR to Ethereum with the Rainbow Bridge 🌈 If you’re curious about the bridge and want to start BUIDLing on top of NEAR we invite you to join Hack the Rainbow 🌈hackathon. Hack the Rainbow is going to be hosted on Gitcoin from Sep 15-30th and will come with a primary prize pool of $50,000 in $NEAR tokens and $DAI. More bounties and incentives will be announced in the coming weeks in collaboration with our community and ecosystem partners! Rainbow Bridge 🌈 101 The Open Web could not be truly open without building bridges and breaking silos. This is why we are launching the Rainbow Bridge which will connect the Ethereum and NEAR blockchains while maintaining the trustless and permissionless nature of both blockchains. In practice this means users and developers of the bridge will only have to make the same security and trust assumptions as they would if their contracts were running on either side of the bridge. They only need to trust the blockchains themselves. Furthermore, the bridge is designed and built to be both rapid and generic. Interactions across the bridge could happen within minutes and seconds in contrast to days or weeks that are commonplace with existing solutions. “Rainbow Bridge is also generic. Any information that is cryptographically provable on NEAR is usable in Ethereum contracts and the other way around.” To dive deeper into the technical architecture of the bridge read this in-depth blog post from Max, Middleware engineering lead at NEAR. The Block also covered the rainbow bridge here. (paywall) NEAR Ecosystem Updates We are excited to welcome more projects launching on NEAR MainNet. Flux, an open scalable platform for prediction markets, is the first protocol to launch on NEAR’s mainnet. The team from VHS have launched their ZEST Play Platform and digital horse racing game ZedRun, the first gaming DApp to launch on NEAR’s mainnet. Scaling Mintbase with NEAR Nate (founder/dev of Mintbase) published a very candid blog post about their journey and thought process around scaling Mintbase and how they landed on NEAR as the best solution! You can read the whole story on Medium, but I wanted to share this paragraph with you about Nate’s love-hate relationship with Solidity & EVM 👀 : “I’m tired of solidity, rust has been a pretty refreshing transition and is insanely good about memory and types ❤️, potentially the EVM (Ethereum Virtual Machine) might not be as attractive to new developers in the future. Sometimes it’s easiest to just start over fresh rather than duck taping solutions.” Engineering Updates: We are implementing implicit account creation to match Ethereum DevX/UX create-near-app v1.2.0 published! This update comes with lots of improvements from one of our active contributors Lucio M. Tato aka LMT 🙏🚀! You can now initialize new NEAR projects using Vue. Head over to the full Guide https://github.com/near/create-near-app near-sdk-rs near-sdk v2.0.0 published — there are several changes to LookupMap, TreeMap and collections; read the whole update https://discordapp.com/channels/490367152054992913/708307442491981849/747871093481537546 near-indexer framework is maturing while near-indexer-for-wallet and near-indexer-for-explorer are evolving Bridge has all major audit findings addressed, only minor findings remain! We launched 6 AssemblyScript bounties 🎉 https://github.com/near/core-contracts-as/projects/1 Rosetta Data API is implemented and Construction API is under design review Edu updates NEAR 101, “NEAR for Web Developers”, recorded 3 times with some changes and improvements along the way. crowdcast.io/e/near-101—v0-1 crowdcast.io/e/near-101—v0-2 crowdcast.io/e/near-101—v0-3 NEAR 102, “NEAR for Ethereum Developers”, in progress with help from community members Educational bounties program designed with 2 sample bounties writtenhere andhere. More to come … Workshop for facilitators invitation shared with community — we are inviting capable community members to deliver existing NEAR 101 content based on studying the recordings (and with our support, mentorship and guidance of course) Looking for YOUR input to our educational priorities. If you have any suggestions, ideas or preferences and would like them to be heard, email Sherif directly at[email protected] or find him on Telegram (amgando) or Discord (Sherif#5201) Our friends from Blockchain at Berkeley did a NEAR white paper deep dive, check out their presentation here: https://youtu.be/9Hdt3JcV5EM Aaron, Vitalpoint AI Guild lead and NEAR community hero, published an in-depth course on his Guild website. The course covers building and issuance of Fungible Tokens on NEAR and shows learners how to add a few additional features on top of the standard implementation. CTA: register for Hack the Rainbow on Gitcoin Here’s a quick break down of prizes: Prizes are 80% $NEAR tokens and 20% DAI (here expressed in $ equivalent) – 20x 500$ for projects using ETH<>NEAR Rainbow Bridge – 1x 5K overall winner – 5x 3K runner ups – 20x 1k top 20 submissions There will be additional bounties and boosted ideas from other hackathon partners. All submissions qualify for the main NEAR prize pool and additionally partner bounties if they qualify. This week we are watching, reading, and listening to … Open Web Collective released several amazing episodes of their podcast. The latest episode is with Sergey Nazarov who is telling us the story behind Chainlink. Truly fascinating OG blockchain journey from circa 2012 to 2020! You can subscribe to the podcast on Spotify or Apple Podcasts . The Open Web Collective invites you to their demo day on Crowdcast! Sign up and join us to see what the projects have been cooking up in the latest cohort! That’s it for this update. See you in the next one!
--- id: gas title: Gas --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The RPC API enables you to query the gas price for a specific block or hash. --- ## Gas Price {#gas-price} > Returns gas price for a specific `block_height` or `block_hash`. > > - Using `[null]` will return the most recent block's gas price. - method: `gas_price` - params: `[block_height]`, `["block_hash"]`, or `[null]` `[block_height]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "gas_price", "params": [17824600] } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.gasPrice(17824600); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=gas_price params:='[17824600]' id=dontcare ``` </TabItem> </Tabs> `["block_hash"]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "gas_price", "params": ["AXa8CHDQSA8RdFCt12rtpFraVq4fDUgJbLPxwbaZcZrj"] } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.gasPrice( "AXa8CHDQSA8RdFCt12rtpFraVq4fDUgJbLPxwbaZcZrj" ); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=gas_price params:='["AXa8CHDQSA8RdFCt12rtpFraVq4fDUgJbLPxwbaZcZrj"]' id=dontcare ``` </TabItem> </Tabs> `[null]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "gas_price", "params": [null] } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.gasPrice(null); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=gas_price params:='[null]' id=dontcare ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "gas_price": "100000000" }, "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 `gas_price` 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_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 an archival node</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> ---
NEAR Funding Updates: Funding Beyond Grants NEAR FOUNDATION October 6, 2022 Welcome to the Funding Team Series that highlights important updates about NEAR Foundation’s Grants program, ecosystem and funding strategy. Part 1 will cover funding beyond Grants, Part 2 will reintroduce NEAR Foundation’s Grant Program, and Part 3 will introduce the Grant Team Handbook, to be published in the coming weeks. The NEAR Funding team is composed of two sub-teams: the Grants team that manages the Grants program and the Strategic Funding team which focuses on equity investments and the external VC network. Part 1 / Funding Beyond Grants 1. NEAR ecosystem funding programs 2. Success stories in the NEAR ecosystem 3. Projects that have raised capital NEAR Foundation has been deeply focused on developing other funding programs within the ecosystem since the start of 2022. Since the creation of Proximity Labs and Aurora and the launch of their own grants program, NEAR Foundation has been redirecting DeFi projects to Proximity and EVM based projects to Aurora. Please note that Proximity’s, Aurora’s, and all other separate grant programs’ decisions are made independent of NEAR Foundation. 1. Ecosystem funding programs A number of grant programs have launched and are ongoing in the NEAR ecosystem including: Human Guild for Gaming projects, CypherPunk Guild for privacy projects, and Mintbase for NFT projects. These grant channels are to be used to expand and decentralize our ecosystem in a more efficient manner. Additionally, to amplify NEAR’s growth, the NEAR Funding team is working with launchpads, accelerators, ecosystem funds, and a VC Network that are all deeply rooted in the NEAR ecosystem. Launchpads are blockchain-based platforms that help startups and crypto-related projects launch on-chain. NEAR Native: GoNear Skyward Finance BocaChica Aurora: NearPad NFTs: AstroGen Utopia Enleap NEAR & Aurora: SmartPad For further information about launchpads on NEAR, please visit this guide. Accelerators help founders validate, build, and de-risk by defining and growing KPIs, developing product-market fit, and fundraising. OWC Octopus Network NearStarter Encode SWG Wharton Cypher Accelerator Ecosystem Funds are deeply rooted in the NEAR Ecosystem with global or vertical focuses, primarily investing and deploying capital to projects in the NEAR ecosystem. MetaWeb Stealth Capital Lyrik Ventures Caerus Ventures Regional Hubs, as part of our path toward decentralization, the NEAR Foundation will be redirecting projects related to specific regions. The NEAR Foundation is currently supporting 6 regional hubs in strategic locations (Ukraine, Kenya, Balkans, Vietnam, India and Korea) with others to come. Local experts are able to tailor NEAR initiatives to support local communities and regional ecosystem building. A summary of different funding programs can be found here. VC Network NEAR Foundation’s VC Network includes 300+ VCs representing 30Bn+ in capital that are actively engaged and supporting the growth of projects within NEAR. They have already deployed $300 million to 60 projects thus far. 2. Success stories in the NEAR ecosystem NearNauts – NFT The NearNauts team came to NEAR with a vision, received funding from the NEAR Foundation Grants team, and have since launched what is now the top NFT project on NEAR. They started off as a PFP NFT project, utilizing grant funds to develop their website, smart contract, and marketing. Then, they expanded to build out a no-code NFT launchpad and a KYC platform. Their marketplace is on the way featuring a revenue sharing model for holders. Apollo42 – NFT The Apollo42 team is a great example of a NEAR Foundation grant recipient that came to NEAR with a vision, and by receiving funding from NF was able to realize that vision. Apollo 42 is an ecosystem of NFT services that started out by building and integrating NFT ranking tools. From there, they went on to develop their own NFT Marketplace with elements of AR built into it. Apollo42 has made some amazing developments along the way, and continues to build out and update their platform. Blogchain – Social Impact Capsule Social is another great example of a team that received funding from the NEAR Foundation Grants team and went on to build an amazing platform. With the funding received from NF, the Capsule Social team developed Blogchain, a creative writing platform that empowers writers to publish content and get paid on Web3. NearBlocks – Tools/Infrastructure The team behind NearBlocks initially came into the NEAR ecosystem curious about the blockchain and underlying tech. They received a grant from NF and built NearBlocks, a blockchain explorer, search, API and analytics platform with the goal of providing equitable access to blockchain data. Once they launched NearBlocks and saw how successful it was, they went on to build and launch https://nearsend.io/, a tool for bulk transacting. The team also has another exciting project in the works. Located in Indonesia, the team has gone from 3 to 11 full time Rust developers, with the goal of increasing to 50 in the next year. Sender – Wallet Sender Wallet is a great case study of a project that came into the NEAR ecosystem with a plan. The team received funding from the NEAR Foundation Grants team to build out and launch a non-custodial browser extension wallet for NEAR users. Sender Wallet has gone on to be one of the most popular wallets in the ecosystem. 3. Projects that have raised capital Niche – Social Networking app on NEAR – Twitter Niche is a decentralized social networking app, built to help people discover and grow communities. The mission of Niche is to return agency to individuals and enable them to benefit from their content, not big corporations. External Raised capital: $1.8M – Announcement Latest update: Launched beta in August, read about their NEAR launch here. Tonic – Orderbook DEX on NEAR – Twitter Tonic is a high-performance trading platform that brings the speed and convenience of centralized exchanges to NEAR while being fully decentralized. External Raised capital: $5M – Announcement Latest update: Launched mainnet in May 2022, launched Tonic Swap in July Capsule Social – Decentralized social discourse on NEAR – Twitter Capsule Social launched Blogchain, a Web3 publishing platform with unrivaled protections for free speech, where content is protected by a censorship-resistant architecture. External Capital Raised: $2.5M – Announcement Latest update: Launched Blogchain, a decentralized Substack competitor in June. You can check out the content on Blogchain or participate in writing here. Sender Wallet – Browser extension wallet built on NEAR – Twitter Sender is a browser extension wallet built on NEAR. Its goal is to build a secure and smooth wallet for decentralized digital assets like crypto and NFTs. External Capital Raised: $4.5M – Announcement Interested in getting funded? If you are interested in funding for your project, check out the following resources: Explore NEAR Funding Programs: linktree Visit the NEAR website : https://pages.near.org/ Contact the NEAR Grants team at [email protected] ⌛️ In the next blog post, the NEAR Funding team will reintroduce the NEAR Foundation’s Grant Program, providing grant data and including key updates.
--- title: 3.3 Stablecoins description: Understanding the logic and variables behind stable coin mechanics --- # 3.3 Stablecoins Perhaps no topic in crypto is more controversial or enlightening, than that of ‘stable coins’. Before 2022, most people would not have thought much of these assets, beyond perhaps questioning the legitimacy of Tether (and being accused of being a conspiracy theorist). But since 2022, stablecoins have been responsible for an incredible loss of value across the industry - as well as a safe haven for investors and token holders during times of volatility and turbulence. The focus of this lecture, is on understanding the logic and variables behind how stable coins are created - and - what role stable coins are positioned to play in the evolution of crypto into the future. ## What is a Stable Coin? Let’s start with some basic definitions: _What is a stablecoin?_ A stable coin refers to a digital asset that is pegged to an external form of value, such that it only expands or contracts in value, based upon fluctuations in the external form of value. The intention behind stable coins is to provide reliable value from currencies and existing forms of stable value, in the world of crypto, whereby most tokens are volatile or in the process of price discovery. The most commonly used stable coins are pegged to the US Dollar. However depending on the design and issuance of the stable coin in question, certain stable coins are far more reliable than others. This leads us to our macro orientator for stable coins, known as the Stable Coin Matrix: ## The Stable Coin Matrix ![](@site/static/img/bootcamp/mod-em-3.3.1.png) There are two fundamental considerations when understanding a stable coin, from a high level: 1. How is the stable coin issued? Meaning specifically, what is required in order for a stable coin to be generated and used in the crypto-verse. 2. How is the stable coin backed? Meaning what external value, lies behind the stable coin, providing the necessary foundations from which it can be issued. As the Matrix outlines, these options can be conceptualized on a horizontal and vertical grid. **Horizontally:** The spectrum trends from a stablecoin being _overcollateralized_ to it being _undercollateralized_. When a stable coin is overcollateralized, it means that for every stablecoin minted into existence, there is _more value backing the stablecoin_, than the value of the stablecoin itself. When a stablecoin is undercollateralized it means the opposite: That there is _less value backing the stable coin_, than the value of the stablecoin itself. This dichotomy becomes crystal clear with the examples below. **Vertically:** The spectrum trends from the top, with the stablecoin being issued by a centralized entity whereby a single authority can control supply and burn rates of the stable coin - usually with some legal precedent or license. The bottom end of the spectrum refers to decentralized issuance, meaning it is usually minted via smart-contract or DAO, and based upon certain functions being fulfilled via smart contract (exchange an accepted asset, and receive a new stablecoin). ## 3 Different Types of Stablecoins To date, the stablecoin matrix comprises three types of stablecoins. **Algorithmically Backed:** These stablecoins are perhaps most well known. An algorithmically backed stable coin attempts to maintain its peg through dynamic expansion and contraction of a secondary token supply. Examples of this include UST (Terra) and RSR (Reserve). The vulnerability of such stable coins have [been well documented.](http://www.wakeforestlawreview.com/2021/10/built-to-fail-the-inherent-fragility-of-algorithmic-stablecoins/) **Custodial:** These stablecoins are most used, and also most trusted. While they require trust in a centralized custodian (such as Circle in the case of USDC), they are ‘legally’ backed by the entity with a 1:1 ratio of stablecoin issued for backed value behind the stablecoin. As shown below, these are the most popular (and reliable) stablecoins to date. Note: They are also the basis of the crypto-dollar thesis (also discussed below). **Asset / Basket Backed:** These stablecoins are backed by a basket of assets, and tend to straddle the line between being centrally managed and decentralized in their access or issuance. Asset backed stable coins pool different types of value together - such that the value of the assets backing the stable coin are over-collateralized relative to the amount of stable value issued. An example of this would be DAI - or the now sunset _Diem_ project originally proposed by Facebook / Meta. Note: DAI is currently overcollateralized with a basket of assets, by [127](https://daistats.com/#/)% to every issued DAI stablecoin. While these three categories encompass the types of stablecoin innovation to date, the first (algorithmically backed) has been seriously questioned (and rarely implemented), while the third (asset-backed) remains limited in its total supply (as a significant amount of value must be collateralized in order for it to be trusted). The second option - custodial stable coins remain by far the most popular, and are also the most well positioned to thrive into the future. ## Examples of Stablecoins ![](@site/static/img/bootcamp/mod-em-3.3.2.png) ### USD Coin - Circle USD Coin, or USDC, is issued by Circle. Each USDC is redeemable for one dollar, and is backed by one dollar (fiat). The entities holding the backed-value are audited on the monthly by the accounting firm Grant Thornton LLP. _Market Cap: $42.75 billion USD._ _Average 24 hour volume: $2.3 billion USD._ ### USDT - Tether Tether (USDT) is the largest stablecoin in crypto, and remains the most traded stable asset. Since its inception however, Tether has undergone a series of challenges and controversies, specifically pertaining to the reliability of its backed assets. Tether is the subsidiary of Bitfinex - one of the largest exchanges in crypto. Yet while many have speculated on the legitimacy of its 1:1 peg to USDT, both Bitfinex (British Virgin Islands) and Tether (Hong Kong) remain firmly outside of any regulatory jurisdiction that would be able to determine the truthfulness of the claims. _Market Cap: $65.8 billion USD._ _Average 24 hour volume: $21.8 billion USD._ ### BUSD - Binance Binance USD is a newcomer to the stablecoin game, launching in 2019, but becoming increasingly competitive in terms of volume and access. Similar to Tether and USDC, BUSD is a 1:1 backed stable coin with reserves guaranteed by Binance itself. _Market Cap: $22.0 billion USD._ _Average 24 hour volume: $7.7 billion USD._ ### UST - Terra _(Failed)_ Terra remains one of the most infamous stablecoin experiments to date. Originally conceived as a design for an L1 ecosystem on Cosmos, Terra purported to offer its own algorithmic stable coin known as UST. The allure of building dApps on top of a stablecoin based L1 ecosystem was such that in March of 2022, Terra was valued at 94$ per token, for a total market cap of $40 billion USD. When the stable coin began to de-peg - meaning the price of the collateralized asset LUNA dropped to a point in which there was insufficient value backing each already issued stable coin. This created a hyperinflationary spiral, from which both LUNA and UST entirely devolved to zero. Of particular note is that during this saga, the Terra team attempted to purchase billions of dollars of Bitcoin, to back their reserves. However, the sell-pressure and preceding 80 billion dollar market cap was far too much pressure for BTC to absorb the value of. This ultimately led to the liquidation of all of the BTC, and a total collapse to zero. _“The UST stablecoin algorithm created trillions of LUNA tokens, fell into a hyperinflationary spiral, and reduced the value of the original LUNA token by 99%.” ([Coinmarketcap](https://coinmarketcap.com/currencies/terra-luna/))_ A full case study of the event[ can be found here.](https://coinmarketcap.com/alexandria/article/are-algorithmic-stablecoins-dead-already-a-full-breakdown-of-the-terra-crash) ### FRAX - Curve Frax identifies as the ‘[first fractional reserve stable coin](https://frax.finance/)’. In reference to the types of stablecoins discussed above, FRAX sits firmly between two different options: _“The Frax Protocol introduced the world to the concept of a cryptocurrency being partially backed by collateral and partially stabilized algorithmically.”_ In addition to the variant backed stablecoin, FRAX also has a consumer-price index pegged asset, known as FPI. Ongoing data about the state of FRAX is available [here](https://facts.frax.finance/). ![](@site/static/img/bootcamp/mod-em-3.3.3.png) _Market Cap: $1 billion USD._ _Average 24 hour volume: $8.6 million USD._ ### DAI - MakerDAO DAI is discussed in detail in the following lecture on lending. But for now, we can say the following: It remains one of the oldest and most successful stable coins to date. It is significantly overcollateralized at 127% per stablecoin issued, and is predominantly backed by a basket of assets from both the real world and the world of crypto. _Market Cap: $5.2 billion USD._ _Average 24 hour volume: $198 million USD._ ## Collateral Backing for Stable Coins With these examples in mind, we can now start to scrutinize and dig into the weeds of the stabilization mechanisms for the different types of stablecoins. This specifically refers to the _collateralization ratio_ as well as the nature of _value_ used to support the stable asset. ### _The Collateralization Ratio:_ Refers to the extent to which a stablecoin is backed by something else of quantifiable value. There are four possible collateralization ratios: 1. **Over Collateralized:** Whereby more value per asset is held in reserve, backing the stablecoin that is issued. 2. **Under Collateralization:** Whereby less value per asset is held in reserve, backing the stablecoin that is issued. Note: Undercollateralized stable coins are short lived and will not exist for long, unless they are able to re-establish the parity in some manner (either by adding assets, or removing stables from the market). 3. **Equilibrium Backing**: Whereby there is a perfect 1:1 ratio between the reserve asset and the stable coin. 4. **Fractional Backing:** Whereby a basket of assets, together back the stable value that is issued. The following diagram below outlines these different collateral models: ![](@site/static/img/bootcamp/mod-em-3.3.4.png) As a general rule of thumb: Centralized stablecoins (from the Matrix above) tend to be 1:1 backed, as there is a legal precedent for their claim of equilibrium. Decentralized stablecoins are either overcollateralized, fractionalized, or undercollateralized (with algorithmic stablecoins being the most common undercollateralized suspect). ![](@site/static/img/bootcamp/mod-em-3.3.5.png) ## _The Underlying Value: Exogenous vs. Endogenous Value_ The second criteria refers to the nature of the value used to back the stablecoin in question. _Exogenous value_ refers to value that is not native to the protocol issuing the stable coin. You can think of this as ‘stand alone value’ or ‘value that exists regardless of whether there is a stablecoin or not’. Examples of _exogenous value_ would include fiat currency, Bitcoin, Ethereum, or other established assets like real-estate, a basket of currencies, or commodities. Meanwhile, _Endogenous value_ refers to value created by the protocol itself, or within the system of the protocol. Examples of _endogenous value_ would be the native token of the protocol in question (for example LUNA for UST). ![](@site/static/img/bootcamp/mod-em-3.3.6.png) Since the collapse of Terra / LUNA, the majority of stablecoin theorists have moved towards stablecoins requiring exogenous value reserves. The nature of these exogenous reserves remains open to discussion. ## A Breakdown of Advantages and Disadvantages With Current Stablecoins According to Vitalik In his [December, 2022 blog,](https://vitalik.eth.limo/general/2022/12/05/excited.html) Vitalik delves into the world of stablecoins, and outlines in his opinion the underlying advantages and disadvantages of the different approaches that exist to date. ![](@site/static/img/bootcamp/mod-em-3.3.7.png) This graphic nicely outlines the state of current stablecoin options, as of 2022 / 2023: Centralized stablecoins, remain most in demand and most trusted. DAO governed ‘real-world asset’ backed stable coins provide a decentralized option, but still remain somewhat vulnerable under certain circumstances (and depending on what it is backed by specifically). Meanwhile a highly collateralized oftentimes _negative interest yielding instrument_ [such as RAI](https://www.stakingrewards.com/journal/rai-decentralised-semi-stable-coin/) can be both decentralized and peg-resilient, yet also remaining limited in scale and not necessarily remaining stuck at 1 USD of value. ## Stable Coins as a breakout technology in crypto? On the whole, stablecoins account [for 140 billion dollars of value](https://defillama.com/stablecoins) in the crypto verse. ![](@site/static/img/bootcamp/mod-em-3.3.8.png) With the dominance of Tether sitting at 46.69% there remains ample room for competitors to increase stablecoin market share. What the existing volume has demonstrated however, is that stablecoins are one of crypto’s first _killer dApps_, bringing serious value and innovation into the crypto verse - from which many other products and services can flourish. ## Stablecoins: The Crypto-dollar Emergent? Central Bank Digital Currencies The final point of discussion on this topic, is indeed twofold: 1. What happens if a Central Bank launches a digital currency? So called **CBDCs** are under development from a number of different countries. Would these instruments rival existing stable coins, or would they operate fundamentally separately? 2. Second, is there the potential for the emergence of a crypto-dollar? That is to say, since almost all stablecoins are denominated in USD, there is the capacity for the United States Dollar to remain the defacto crypto-reserve standard, regardless of what happens to fiat currencies, or Bitcoin. Is the United States aware of this positioning and could this be leveraged to expand the longevity of the US Dollars’ reign as the world’s reserve currency?
Nightshade: Near Protocol Sharding Design 2.0 Alex Skidanov 7/AlexSkidanov alex@near.org Illia Polosukhin 7/ilblackdragon illia@near.org Bowen Wang 7/BowenWang18 bowen@near.org July 2019 Updated February 2024 Contents 1 Sharding Basics 4 1.1 Validator partitioning and beacon chains . . . . . . . . . . . . . . 4 1.2 Quadratic sharding . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 State sharding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4 Cross-shard transactions . . . . . . . . . . . . . . . . . . . . . . . 7 1.5 Malicious behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.5.1 Malicious forks . . . . . . . . . . . . . . . . . . . . . . . . 8 1.5.2 Approving invalid blocks . . . . . . . . . . . . . . . . . . . 9 2 State Validity and Data Availability 10 2.1 Validators rotation . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 State validity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.3 Fishermen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.4 Stateless Validation . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 Succinct Non-interactive Arguments of Knowledge . . . . . . . . 17 2.6 Data Availability . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.6.1 Proofs of Custody . . . . . . . . . . . . . . . . . . . . . . 20 2.6.2 Erasure Codes . . . . . . . . . . . . . . . . . . . . . . . . 21 2.6.3 Polkadot’s approach to data availability . . . . . . . . . . 21 2.6.4 Long term data availability . . . . . . . . . . . . . . . . . 22 3 Nightshade 23 3.1 From shard chains to shard chunks . . . . . . . . . . . . . . . . . 23 3.2 Consensus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.3 Block production . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.4 Ensuring data availability . . . . . . . . . . . . . . . . . . . . . . 26 3.4.1 Dealing with lazy block producers . . . . . . . . . . . . . 26 3.5 State transition application . . . . . . . . . . . . . . . . . . . . . 27 3.5.1 State Representation . . . . . . . . . . . . . . . . . . . . . 28 1 3.6 Cross-shard transactions and receipts . . . . . . . . . . . . . . . . 29 3.6.1 Receipt transaction lifetime . . . . . . . . . . . . . . . . . 29 3.6.2 Handling too many receipts . . . . . . . . . . . . . . . . . 30 3.7 Chunks validation . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.7.1 Zero-knowledge proofs . . . . . . . . . . . . . . . . . . . . 33 3.8 State Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 3.9 Snapshots Chain . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 4 Conclusion 34 2 Introduction The past several years have seen significant progress in scaling blockchains. Back in 2018, when the early team first started to build NEAR Protocol, Ethereum was one of the only smart contract platforms available to builders and it suffered from high transaction costs and low throughput. Today, Ethereum is scaling through rollups (a.k.a. L2s1). Quite a few other layer 1 blockchains such as Polkadot, Solana, Sui, and Aptos that promise different kinds of scaling have launched in the past few years. In general, most layer-one blockchains use one of two scaling approaches: vertical scaling and horizontal scaling. For vertical scaling, a few approaches are explored, including each validator operating more expensive hardware, par- allelizing transaction execution, separating consensus from execution, etc. Hor- izontal scaling has two categories: heterogeneous and homogeneous. In the heterogeneous approach, there are different chains or execution environments that operate independently and there is usually a main chain that orchestrates everything and provides security guarantees. In the homogeneous approach, a blockchain is divided into multiple parallel shards that have the same execution environment and the protocol dictates how different shards communicate with each other. Each shard maintains its own state, which allows the blockchain to scale linearly by adding more shards. NEAR Protocol chooses a homogeneous sharding approach to build a highly scalable blockchain. This document outlines the general approach to blockchain sharding as it exists today, the major problems that need to be overcome (in- cluding state validity and data availability problems), and presents Nightshade, the solution NEAR Protocol is built upon that addresses those issues. As of this writing of the revised version in February 2024, NEAR has been live for three and half years. There have been a total of 750M transactions and 57M accounts on chain since the mainnet launch in October 2020. Since the original publication of the Nightshade whitepaper in July 2019, there have been a lot of new developments in blockchain protocol research, most notably zero-knowledge proofs. In the case of NEAR, during the implementation of Nightshade across different phases over three-plus years, we gained a better understanding of blockchain scalability and also came to realize some limitations of the original design. In short, we underestimated the engineering complexity of fraud proofs in a sharded blockchain and started to question whether that was still the most promising direction for the protocol. Recent advancements in stateless validation research provided an alternative path, which not only elim- inates the critical dependency on fraud proofs, but also significantly increases per-shard throughput by enabling nodes to hold state in memory. As a result, we decided to update the Nightshade design to incorporate stateless validation. This is a revised edition of the Nightshade paper, version 2.0, reflecting this change in the Nightshade roadmap. We will also elaborate on the power of zero- knowledge proofs, and how they may be combined with stateless validation to 1Technically a rollup is a type of L2, but the success of rollups has made the two terms almost synonymous today. 3 produce a future-proof sharding design that is both highly scalable and highly decentralized. New or heavily modified text is included in section 2.4, section 2.5, section 3.5, section 3.7, and section 3.8. 1 Sharding Basics Let’s start with the simplest approach to sharding. In this approach, instead of running one blockchain we will run multiple, and call each such blockchain a “shard.” Each shard will have its own set of validators. Here, and below, we use a generic term “validator” to refer to participants that verify transactions and produce blocks — either by mining, such as in Proof of Work, or via a voting- based mechanism. For now, let’s assume that the shards never communicate with each other. This design, though simple, is sufficient to outline some of the initial major challenges in sharding. 1.1 Validator partitioning and beacon chains Say that the system comprises 10 shards. The first challenge is that with each shard having its own validators, each shard is now 10 times less secure than the entire chain. So if a non-sharded chain with X validators decides to hard-fork into a sharded chain, and splits X validators across 10 shards, each shard now only has X/10 validators, and corrupting one shard only requires corrupting 5.1% (51% / 10) of the total number of validators (see figure 1), Figure 1: Splitting the validators across shards which brings us to the second point: who chooses the validators for each shard? Controlling 5.1% of validators is only damaging if all those 5.1% of validators are in the same shard. If validators can’t choose which shard they get to validate 4 in, a participant controlling 5.1% of the validators is highly unlikely to get all their validators in the same shard, heavily reducing their ability to compromise the system. Almost all sharding designs today rely on some source of randomness to assign validators to shards. Randomness on a blockchain is in itself a very chal- lenging topic and is out of scope for this document. For now let’s assume there’s some source of randomness we can use. We will cover validator assignment in more detail in section 2.1. Both randomness and validator assignment require computation that is not specific to any particular shard. For that computation, practically all existing designs have a separate blockchain that is tasked with performing operations necessary for the maintenance of the entire network. Besides generating random numbers and assigning validators to the shards, these operations often also include receiving updates from shards and taking snapshots of them, processing stakes and slashing in Proof-of-Stake systems, and rebalancing shards (when that feature is supported). Such chain is called a Beacon chain in Ethereum, a Relay chain in Polkadot, and the Cosmos Hub in Cosmos. Throughout this document we will refer to such a chain as a Beacon chain. The existence of the Beacon chain brings us to the next interesting topic: quadratic sharding. 1.2 Quadratic sharding Sharding is often advertised as a solution that scales infinitely with the number of nodes participating in the network operation. While it is possible in theory to design such a sharding solution, any solution that includes the concept of a beacon chain doesn’t have infinite scalability. To understand why, note that the beacon chain has to do some bookkeeping computation, such as assigning validators to shards, or snapshotting shard chain blocks, that is proportional to the number of shards in the system. Since the beacon chain is itself a single blockchain, with computation bounded by the computational capabilities of its operating nodes, the number of shards is naturally limited. However, the structure of a sharded network does bestow a multiplicative effect on any improvements to its nodes. Consider the case in which an arbitrary improvement is made to the efficiency of nodes in the network, which will allow them to process transactions faster. If the nodes operating the network, including the nodes in the beacon chain, become four times faster, then each shard will be able to process four times more transactions, and the beacon chain will be able to maintain 4 times more shards. The throughput across the system will increase by the factor of 4 × 4 = 16 — thus the name quadratic sharding. It is hard to provide an accurate measurement for how many shards are viable today, but it is unlikely that in any foreseeable future the throughput needs of blockchain users will outgrow the limitations of quadratic sharding. 5 1.3 State sharding Until now, we haven’t defined clearly what exactly is and is not separated when a network is divided into shards. Specifically, nodes in a blockchain perform three important tasks: not only do they 1) process transactions, they also 2) relay validated transactions and completed blocks to other nodes and 3) store the state and the history of the entire network ledger. Each of these three tasks imposes a growing requirement on the nodes operating the network: 1. The task of processing transactions requires more compute power with the increasing number of transactions being processed; 2. The task of relaying transactions and blocks requires more network band- width with the increasing number of transactions being relayed; 3. The task of storing data requires more storage as the state grows. Im- portantly, unlike the needs for processing power and network bandwidth, the storage requirement grows even if the transaction rate (number of transactions processed per second) remains constant. From the above list it might appear that the storage requirement would be the most pressing, since it is the only one that is being increased over time even if the number of transactions per second doesn’t change, but in practice the most pressing requirement today is the compute power. The entire state of Ethereum as of this writing is 300GB — easily manageable by most of the nodes. But the number of transactions Ethereum can process per second is around 20 - orders of magnitude less than what is needed for many practical use cases. Zilliqa is the most well-known project that shards processing but not storage. Sharding of processing is an easier problem because each node keeps the entire state, meaning that contracts can freely invoke other contracts and read any data from the blockchain. Some careful engineering is needed to make sure updates from multiple shards updating the same parts of the state do not conflict. In those regards Zilliqa takes a relatively simplistic approach2. While sharding of storage without sharding of processing was proposed, it is extremely uncommon. Thus in practice sharding of storage, or State Sharding, almost always implies sharding of processing and sharding of network band- width. Practically, under State Sharding, the nodes in each shard are building their own blockchain that contains transactions affecting only the local part of the global state that is assigned to that shard. Therefore, the validators in each shard only need to store their local part of the global state and only execute (and as such only relay) transactions that affect their part of the state. This partition linearly reduces the requirement on all compute power, storage, and network bandwidth, but introduces new problems, such as data availability and cross-shard transactions, both of which we will cover below. 2Our analysis of their approach can be found here: https://medium.com/nearprotocol/ 8f9efae0ce3b 6 1.4 Cross-shard transactions The sharding model we have described so far is not very useful, because if in- dividual shards cannot communicate with each other, they are no better than multiple independent blockchains that can’t efficiently communicate. The pro- liferation of bridges in today’s multichain ecosystem is a clear signal that cross- chain (or cross-shard) communication is crucial. For now let’s only consider simple payment transactions, where each partici- pant has an account on exactly one shard. If someone wishes to transfer money from one account to another within the same shard, the transaction can be processed entirely by the validators in that shard. If, however, Alice resides on shard #1, and wants to send money to Bob who resides on shard #2, neither the validators on shard #1 (who can’t credit Bob’s account) nor the validators on shard #2 (who can’t debit Alice’s account) can process the entire transaction. There are two families of approaches to cross-shard transactions: • Synchronous: whenever a cross-shard transaction needs to be executed, all blocks in the relevant shards that contain state transitions related to the transaction get produced at the same time, and the validators of the relevant shards collaborate to execute such transactions.3 • Asynchronous: a cross-shard transaction that affects multiple shards is executed in those shards asynchronously, the “Credit” shard executing its half once it has sufficient evidence that the “Debit” shard has executed its portion. This approach tends to be more prevalent due to its simplicity and ease of coordination. This system has been proposed today in Cosmos, Ethereum Serenity, NEAR, Kadena, and others. A problem with this approach is that if blocks are produced independently, there’s a non-zero chance that one of the multiple blocks will be orphaned, thus making the transaction only partially applied. Consider figure 2 depicting two shards, both of which encounter a fork, and a cross-shard transaction that was recorded in blocks A and X’ correspondingly. If the chains A-B and V’-X’- Y’-Z’ end up being canonical in the corresponding shards, the transaction is fully finalized. If A’-B’-C’-D’ and V-X become canonical, then the transaction is fully abandoned, which is acceptable. But if, for example, A- B and V-X become canonical, then one part of the transaction is finalized and one is abandoned, creating an atomicity failure. We will cover how this problem is addressed in the proposed protocols in the second part, when covering changes to the fork-choice rules and consensus algorithms proposed for sharded protocols. Note that communication between chains is useful outside of sharded blockchains too. Interoperability between chains is a complex problem that many projects are trying to solve. In sharded blockchains the problem is somewhat more 3The most detailed proposal known to the authors of this doc- ument is Merge Blocks, described here: https://ethresear.ch/t/ merge-blocks-and-synchronous-cross-shard-state-execution/1240 7 Figure 2: Asynchronous cross-shard transactions straightforward since the block structure and consensus are the same across shards, and there’s a beacon chain that can be used for coordination. However, in a sharded blockchain, all the shard chains are the same, while in the global blockchain ecosystem there are lots of different blockchains, with different target use cases, levels of decentralization, and privacy guarantees. Building a system in which a set of chains have different properties but use sufficiently similar consensus and block structure and have a common beacon chain could enable an ecosystem of heterogeneous blockchains with a working interoperability subsystem. Such a system is unlikely to feature validator rota- tion, so some extra measures need to be taken to ensure security. Both Cosmos and Polkadot are effectively these types of systems.4 1.5 Malicious behavior In this section we will review the adversarial behaviors malicious validators can exercise if they manage to corrupt a shard. We will review classic approaches to avoiding corrupting shards in section 2.1. 1.5.1 Malicious forks A set of malicious validators might attempt to create a fork. Note that it doesn’t matter if the underlying consensus is byzantine fault tolerant (BFT) or not; corrupting a sufficient number of validators will always make it possible to create a fork. It is significantly more likely that more that 50% of a single shard will be corrupted, than that more than 50% of the entire network will be corrupted (we 4Refer to this writeup by Zaki Manian from Cosmos: and this Tweet-storm by the first author of this document: for a detailed comparison of the two. 8 will dive deeper into these probabilities in section 2.1). As discussed in section 1.4, cross-shard transactions involve certain state changes in multiple shards, and the corresponding blocks in such shards that apply such state changes must either all be finalized (i.e. appear in the selected chains on their corresponding shards), or all be orphaned (i.e. not appear in the selected chains on their cor- responding shards). Since in general the probability of shards being corrupted is non-negligible, we can’t assume that forks won’t happen, even if byzantine consensus had been reached among the shard validators, or if many blocks were produced on top of the block with the state change. This problem has multiple potential solutions, the most common being oc- casional cross-linking of the latest shard chain block to the beacon chain. The fork choice rule in the shard chains is then changed to always prefer the chain that is cross-linked, and only apply the shard-specific fork-choice rule for blocks published since the last cross-link. 1.5.2 Approving invalid blocks A set of validators might attempt to create a block that applies the state tran- sition function incorrectly. For example, starting with a state in which Alice has 10 tokens and Bob has 0 tokens, the block might contain a transaction that sends 10 tokens from Alice to Bob, but ends up with a state in which Alice has 0 tokens and Bob has 1000 tokens, as shown in figure 3. Figure 3: An example of an invalid block In a classic non-sharded blockchain, such an attack is not possible, since all the participants in the network validate all the blocks. A block with such an invalid state transition will be rejected both by other block producers and non- block-producing participants in the network. Even if the malicious validators continue creating blocks on top of the invalid block faster than honest validators build the correct chain (thus making the chain with the invalid block longer than 9 the chain without it), every participant using the blockchain for any purpose validates all the blocks, and will discard all blocks built on top of the invalid block. Figure 4: Attempt to create an invalid block in a non-sharded blockchain In figure 4 there are five validators, three of whom are malicious. They created an invalid block A’, and then continued building new blocks on top of it. Two honest validators have discarded A’ as invalid and built on top of the last valid block known to them, creating a fork. Since there are fewer validators in the honest fork, their chain is shorter. However, in a classic non- sharded blockchain, every participant using the blockchain for any purpose is responsible for validating all the blocks they receive and recomputing the state. Thus any person with any interest in the blockchain would observe that A’ is invalid, and thus also immediately discard B’, C’ and D’, taking the chain A-B as the current longest valid chain. In a sharded blockchain, however, no participant can validate all the trans- actions on all the shards, so they need to have some way to confirm that at no point in the history of any shard of the blockchain was an invalid block included. Note that unlike with forks, cross-linking to the beacon chain is not a suf- ficient solution for proving that the blockchain’s history contains no invalid blocks, since the beacon chain doesn’t have the capacity to validate the blocks. It can only validate that a sufficient number of validators in that shard signed the block (and as such have attested to its correctness). We will discuss solutions to this problem in section 2.2 below. 2 State Validity and Data Availability The core idea in sharded blockchains is that most participants operating or using the network cannot validate all blocks in all shards. As such, whenever 10 any participant needs to interact with a particular shard, they generally cannot download and validate the entire history of the shard. The partitioning aspect of sharding, however, raises a significant potential problem: without downloading and validating the entire history of a particular shard, a participant cannot be certain that the state they interact with is the result of some valid sequence of blocks and that this sequence of blocks is indeed the canonical chain in the shard. This is a problem that doesn’t exist in non- sharded blockchains. We will first present a simple solution to this problem that has been previ- ously proposed by many protocols, and then analyze the way this solution can break and the attempts that have been made to address it. 2.1 Validators rotation The naive solution to state validity is shown on figure 5: let’s say we assume that the entire system has on the order of thousands of validators, out of which no more than 20% are malicious or will otherwise fail (such as by failing to be online to produce a block). Then if we sample 200 validators, the probability of more than 1/3 failing can (for practical purposes) be assumed to be zero. Figure 5: Sampling validators 1/3 is an important threshold. There’s a family of consensus protocols, called byzantine fault tolerant (BFT) consensus protocols, that guarantees that as long as fewer than 1/3 of participants fail, either by crashing or by acting in some way that violates the protocol, consensus will be reached. With this assumed honest validator percentage, if the current set of valida- tors in a shard provides us with some block, the naive solution assumes that the block is valid and that it is built on what the validators believed to be the canonical chain for that shard when they started validating. The validators learned the canonical chain from the previous set of validators, who by the same 11 assumption built on top of the block which was the head of the canonical chain before that. By induction the entire chain is valid, and since no set of validators at any point produced forks, the naive assumption is also that the current chain is the only chain in the shard. See figure 6 for a visualization. Figure 6: A blockchain with each block finalized via BFT consensus This simple solution doesn’t work if we assume that validators can be cor- rupted adaptively, which is not an unreasonable assumption.5 Adaptively cor- rupting a single shard in a system with 1000 shards is significantly cheaper than corrupting the entire system. Therefore, the security of the protocol decreases linearly with the number of shards. To be certain about the validity of a block, we must know that at any point in history no shard in the system has had a colluding validator majority; taking into consideration adaptive adversaries, we no longer have such certainty. As we discussed in section 1.5, colluding valida- tors can produce two basic malicious behaviors: creating forks, and producing invalid blocks. Malicious forks can be addressed by blocks being cross-linked to the beacon chain, which is generally designed to have significantly higher security than the shard chains. Producing invalid blocks, however, is a significantly more challenging problem to tackle. 2.2 State validity Consider figure 7, in which Shard #1 is corrupted and a malicious actor produces invalid block B. Suppose that in this block B 1000 tokens were minted out of thin air and deposited in Alice’s account. The malicious actor then produces valid 5Read this article for details on how adaptive corruption can be carried out: https://medium.com/nearprotocol/d859adb464c8. For more details on adap- tive corruption, read https://github.com/ethereum/wiki/wiki/Sharding-FAQ# what-are-the-security-models-that-we-are-operating-under. 12 block C (in a sense that the transactions in C are applied correctly) on top of B, obfuscating the invalid block B, and initiates a cross-shard transaction to Shard #2 that transfers those 1000 tokens to Bob’s account. From this moment, the improperly created tokens reside on an otherwise completely valid blockchain in Shard #2. Figure 7: A cross-shard transaction from a chain that has an invalid block Some simple approaches to tackling this problem are: 1. For validators of Shard #2 to validate the block from which the transaction is initiated. This won’t work even in the example above, since block C appears to be completely valid. 2. For validators in Shard #2 to validate some large number of blocks pre- ceding the block from which the transaction is initiated. Naturally, for any number of blocks N validated by the receiving shard, the malicious validators can create N+1 valid blocks on top of the invalid block they produced. A promising idea to resolve this issue would be to arrange shards into an un-directed graph in which each shard is connected to several other shards, and only allow cross-shard transactions between neighboring shards (for example, this is how Vlad Zamfir’s sharding essentially works6, and a similar idea is used in Kadena’s Chainweb [1]). If a cross-shard transaction is needed between shards that are not neighbors, such a transaction is routed through multiple shards. In this design, a validator in each shard is expected to validate all the blocks in their shard as well as all the blocks in all the neighboring shards. Consider the figure below with 10 shards, each with four neighbors, where no two shards require more than two hops for a cross-shard communication — shown on figure 8. 6Read more about the design here: https://medium.com/nearprotocol/37e538177ed9. 13 Figure 8: An invalid cross-shard transaction in a Chainweb-like system that will get detected Shard #2 is not only validating its own blockchain, but also the blockchains of all the neighbors, including Shard #1. So if a malicious actor on Shard #1 attempts to create an invalid block B, then build block C on top of it and initiate a cross-shard transaction, such a cross-shard transaction will not go through since Shard #2 will have validated the entire history of Shard #1 which will have caused it to identify invalid block B. While corrupting a single shard is no longer a viable attack, corrupting a few shards remains a potential problem. On figure 9 an adversary corrupting both Shard #1 and Shard #2 successfully executes a cross-shard transaction to Shard #3 with funds from an invalid block B by corrupting both shard #1 and shard #2. Shard #3 validates all the blocks in Shard #2, but not in Shard #1, and has no way to detect the malicious block. There are a few directions towards properly solving state validity: fraud proofs, stateless validation, and cryptographic computation proofs. 2.3 Fishermen The idea behind the first approach is the following: whenever a block header is communicated between chains for any purpose (such as cross-linking to the beacon chain, or a cross-shard transaction), there is a period of time during which any honest validator can provide a proof that the block is invalid. There are various constructions that enable very succinct proofs that the blocks are invalid, so the communication overhead for the receiving nodes is much smaller than that of receiving a full block. With this approach, as long as there is at least one honest validator in the shard, the system is secure. 14 Figure 9: An invalid cross-shard transaction in a Chainweb-like system that will not get detected Figure 10: Fisherman This is a well-known approach to the state validity problem. This approach, however, has a few major disadvantages: 1. The challenge period needs to be sufficiently long for the honest validator to recognize a block was produced, download it, fully verify it, and prepare the challenge (if the block is in fact invalid). Introducing such a period would significantly slow down cross-shard transactions. 2. The existence of the challenge protocol creates a new vector of attack as malicious nodes could spam the network with invalid challenges. An obvi- 15 ous solution to this problem is to make challengers deposit some amount of tokens that are returned if the challenge is valid. This is only a par- tial solution, as it might still be beneficial for the adversary to spam the system with invalid challenges (and burn their deposits) — for example, to prevent a valid challenge from an honest validator from going through. These attacks are called Grieving Attacks. 3. The implementation is quite complex and difficult to test. The complexity comes from two aspects: 1) making sure that a challenge can be properly processed by validators who do not have the state of the shard and 2) rolling back the state of the blockchain after a challenge is successfully processed and slashing the offending validator. The first one is not easy, as it involves building a lot of the machinery described in section 2.4. The second one is even more difficult, especially in a sharded blockchain. When an invalid state transition is found, we cannot just roll back the state of the affected shard because it is possible for an invalid state transition to mint, say, 1 billion native or fungible tokens, and send them to other shards. As a result, the state of all shards needs to be rolled back simultaneously, which leads to a multitude of problems, especially in regards to consensus and validator assignment. Testing challenges is even more daunting. This is a mechanism that is never expected to trigger in practice yet is crucial to the design – if some- one finds a vulnerability in the implementation, it is very likely that the exploit could cause someone to lose money. This is likely the reason why after quite a few years of the idea being proposed, there is still no full (i.e., permissionless) implementation of challenges in any blockchain at the time of writing.7 2.4 Stateless Validation One of the core issues mentioned in section 2.1 is the adaptive corruption of validators in a single shard. This is why the simple solution proposed above does not work. One possible way to address the issue is to rotate validators very frequently, e.g. every block. Since we assume that each validator assignment is the result of a shuffling based on the on-chain randomness beacon, adaptive corruption won’t work in this case. However, a core challenge of rotating validators with each block is determin- ing how validators will retrieve the state to verify the validity of shard blocks, since they may be assigned to a different shard at every single block. Assuming fast blocks (˜1s) and a reasonable state size (>10GB), it is not feasible to expect that a node could download the state of a new shard and validate the new block within a few seconds. Stateless validation provides an elegant solution. Instead of maintaining the full state to execute transactions and validate blocks, a validator is provided a 7Arbitrum implemented fraud proofs but as of this writing, only whitelisted entities can submit them. 16 state witness to validate a block. State Witness refers to the state touched during the execution of a chunk alonside with proof that they belong to the state as of before the chunk. More specifically, assuming that a validator needs to validate block h and it knows the prev state root sprev, i.e, state root as of before block h, then a state witness is the state touched during the execution of h and the proof that they indeed belong to the state specified by sprev. Using the state witness, a validator can execute and verify blocks without maintaining the state of that shard locally. In order for stateless validation to work, some entity needs to be able to provide state witness. Usually they are part of the overall validator set so that they have an incentive to maintain the full state. It is worth noting that the state witness provider, while necessary for the network to function, could not single- handedly corrupt the network. This is because the state witness is validated against the state root and even though a single node may be responsible for producing the state witness, it has no way to produce an invalid state witness without getting caught. This property enables a design where most validators are lightweight and only a few validators need to operate more expensive hardware. This is beneficial for the decentralization of a blockchain network as it lowers the barrier to entry to become a validator. 2.5 Succinct Non-interactive Arguments of Knowledge Another solution to the multiple-shard corruption problem is to use a crypto- graphic construction that allow participants to prove that a certain computation (such as computing a block from a set of transactions) was carried out correctly. Such constructions do exist, e.g. zkSNARKs, zkSTARKs, and a few others, and some are actively used in blockchain protocols today for private payments — most notably ZCash. The primary problem with such primitives is that they are notoriously slow to compute. Despite significant progress made in this area in the past few years with the emergence of new proving systems and engineering optimizations, the state-of-the-art zero-knowledge (ZK) proving systems today such as Polygon Hermez and Risc Zero are about 10,000 times slower than native execution. Interestingly, a proof doesn’t need to be computed by a trusted party, since the proof not only attests to the validity of the computation it is validating, but also to the validity of the proof itself. Thus, the computation of such proofs can be split among a set of participants with significantly less redundancy than would be necessary to perform some trustless computation. It also allows for participants computing zk-SNARKs to run their processes on special hardware without reducing the decentralization of the system. The challenges of zk-SNARKs, besides performance, are: 1. Dependence on less researched and less time-tested cryptographic primi- tives; 17 2. “Toxic waste” — zkSNARKs depend on a trusted setup in which a group of people performs some computation and then discards the intermediate values of that computation. If all the participants of the procedure collude and keep the intermediate values, fake proofs can be created. zkSTARKs, however, do not rely on the same underlying cryptographic primitives such as KZG commitments and therefore do not suffer from the same problem; 3. Extra complexity introduced into the system design. While there are a few zkEVM rollups in production today, they rely on a single sequencer and a single prover, which greatly simplifies the design. How exactly ZK proofs should be integrated into the design of a scalable blockchain is still mostly a research topic at this point; 4. Generating zk-SNARK proofs can be computationally intensive, especially for complex computation such as hashing. The computational resources required for zk proofs inevitably lead to high cost of proof generation, which poses a barrier for wide adoption. Despite these challenges, the field of zero-knowledge research is progressing very rapidly. When this paper was first written in 2019, few people believed that a production-grade zkEVM would be possible in the next five years. Today, however, there are multiple zkEVMs (Polygon, Scroll, zkSync, Linea, etc.) live on Ethereum mainnet. It is not unreasonable to expect that in the next one or two years, the overhead of zero-knowledge proofs would go down by one or two orders of magnitude, which would greatly improve their usability in different applications, including protocol design. 2.6 Data Availability The second problem we will touch upon is data availability. Generally nodes operating a particular blockchain are separated into two groups: Full Nodes, those that download every full block and validate every transaction, and Light Nodes, those that only download block headers, and use Merkle proofs for the parts of state and transactions they are interested in, as shown in figure 11. Now, if a majority of full nodes collude, they can produce a block (valid or invalid) and send its hash to the light nodes, while never disclosing the full contents of the block. There are various ways they can benefit from this. For example, consider figure 12. There are three blocks: the previous, A, is produced by honest validators; the current, B, is produced by colluding validators; and the next, C, also will be produced by honest validators (the blockchain is depicted in the lower right corner). Say you are a merchant. The validators of the current block (B) received block A from the previous validators, computed a block in which you receive money, and sent you a header of that block with a Merkle proof of the state in which you have money (or a Merkle proof of a valid transaction that sends 18 Figure 11: Merkle Tree Figure 12: Data Availability problem the money to you). Confident that the transaction is finalized, you provide the service. However, the validators never distributed the full content of block B to anyone. As such, the honest validators of block C can’t retrieve the block, and are either forced to stall the system or to build on top of A — and depriving you, as a merchant, of money. When we apply the same scenario to sharding, the definitions of full and light node generally apply per shard: validators in each shard download every block in that shard and validate every transaction in that shard, but other nodes in the system, including those that snapshot shard chains’ state into the 19 beacon chain, only download the headers. Thus the validators in the shard are effectively full nodes for that shard, while other participants in the system, including the beacon chain, operate as light nodes. For the fisherman approach we discussed above to work, honest validators need to be able to download blocks that are cross-linked to the beacon chain. If malicious validators cross-linked the header of an invalid block (or used it to initiate a cross-shard transaction), but never distributed the block, honest validators have no way to craft a challenge. We will cover three complementary approaches to address this problem. 2.6.1 Proofs of Custody The most immediate problem to be solved is whether a block is available once it is published. One proposed idea is to have so-called Notaries that rotate between shards more often than validators whose only job is to download a block and attest to the fact that they were able to download it. They can be rotated more frequently because they don’t need to download the entire state of the shard — unlike validators, who cannot be rotated as frequently, since they must download the entire state of the shard each time they rotate (as shown in figure 13).8 Figure 13: Validators need to download state and thus cannot be rotated frequently The problem with this naive approach is that it is impossible to prove later whether the Notary was or was not able to download the block, so a Notary can choose to always attest that they were able to download the block without even attempting to retrieve it. One solution to this is for Notaries to provide 8Here we assume stateless validation is not used, so validators all have to download the state of a shard. 20 some evidence or to stake some amount of tokens attesting that the block was downloaded. One such solution is discussed here: https://ethresear.ch/t/ 1-bit-aggregation-friendly-custody-bonds/2236. 2.6.2 Erasure Codes When a particular light node receives a hash of a block, in order to increase the node’s confidence that the block is available, it can attempt to download a few random pieces of the block. This is not a complete solution, because unless the light nodes collectively download the entire block, the malicious block producers can choose to withhold the parts of the block that were not downloaded by any light node, thus still making the block unavailable. One solution is to use a construction called Erasure Codes to make it possible to recover the full block even if only some part of the block is available, as shown in figure 14. Figure 14: Merkle tree built on top of erasure coded data Both Polkadot and Ethereum Serenity have designs around this idea that provide a way for light nodes to be reasonably confident that blocks are available. The Ethereum Serenity approach has a detailed description in [2]. 2.6.3 Polkadot’s approach to data availability In Polkadot, like in most sharded solutions, each shard (called a parachain) sends snapshots of its blocks to the beacon chain (called a relay chain). Say there are 2f + 1 validators on the relay chain. The block producers of the parachain blocks (called collators) compute an erasure coded version of the block that consists of 2f + 1 parts, once the parachain block is produced, such that any f parts are sufficient to reconstruct the block. They then distribute one part to each validator on the relay chain. A particular relay chain validator would only 21 sign a relay chain block if they have their part of each parachain block that is snapshotted to the relay chain block. Thus, if a relay chain block has signatures from 2f + 1 validators, and as long as no more than f of them have violated the protocol, each parachain block can be reconstructed by fetching the relevant parts from the validators that followed the protocol. See figure 15. Figure 15: Polkadot’s data availability 2.6.4 Long term data availability Note that all the approaches discussed above only attest to the fact that a block was published at all, and is available now. Blocks can become unavailable later for a variety of reasons: nodes going offline, nodes intentionally erasing historical data, etc. A whitepaper worth mentioning that addresses this issue is Polyshard’s [3], which uses erasure codes to make blocks available across shards even if several shards completely lose their data. Unfortunately their specific approach requires that all the shards download blocks from all other shards, which is prohibitively expensive. Long-term availability is not as pressing an issue; since no participant in the system is expected to be capable of validating all the chains in all the shards, the security of a sharded protocol needs to be designed in such a way that the system is secure even if some of the old blocks in some shards become completely unavailable. 22 3 Nightshade 3.1 From shard chains to shard chunks The sharding model with shard chains and a beacon chain is very powerful but comes with certain complexities. In particular, the fork choice rule needs to be executed separately in each chain, so therefore the fork choice rule in the shard chains and the beacon chain must be built differently and tested separately. In Nightshade we model the system as a single blockchain, in which each block logically contains all the transactions for all the shards, and changes the whole state of all the shards. Physically, however, no participant downloads the full state or the full logical block. Instead, each participant of the network either maintains the state that corresponds to the shards that they validate transac- tions for, or relies on others to provide them with state to validate transactions. The list of all the transactions in the block is split into physical chunks (one chunk per shard). Under ideal conditions each block contains exactly one chunk per shard per block, which roughly corresponds to the model with shard chains in which the shard chains produce blocks with the same speed as the beacon chain. However, some chunks might be missing due to network delays, so in practice each block contains either one or zero chunks per shard. See section 3.3 for details on how blocks are produced. Figure 16: A model with shard chains on the left and with one chain with blocks split into chunks on the right 3.2 Consensus The two dominant approaches to consensus in blockchains today are longest (or heaviest) chain, in which the chain that has the most work or stake used to 23 build it is considered canonical, and BFT, in which some set of validators reach BFT consensus for each block. In the recently proposed protocols, the latter is the dominant approach, since it provides immediate finality. In the longest chain approach, more blocks need to be built on top of a given block to ensure finality. For meaningful security, the time it takes for a sufficient number of blocks to be built is often on the order of hours. Using BFT consensus on each block also has disadvantages, such as: 1. BFT consensus involves a considerable amount of communication. While recent advances allow consensus to be reached in an interval of time that is linear to number of participants (see e.g. [4]), it still adds noticeable overhead per block; 2. It is not feasible for all network participants to participate in BFT con- sensus for each block; thus, usually only a randomly sampled subset of participants reaches consensus. A randomly sampled set can, in princi- ple, be adaptively corrupted, and in theory a fork can be created. The system either needs to be modelled to be ready for such an event, and thus still have a fork-choice rule in addition to BFT consensus, or should be designed to shut down in such an event. It is worth mentioning that some designs, such as Algorand [5], significantly reduce the probability of adaptive corruption. 3. Most importantly, the system stalls if 1 3 or more of all the participants are offline. Thus, a temporary network glitch or a network split can com- pletely stall the system. The system ideally should be able to continue to operate, as long as at least half of the participants are online (heaviest chain-based protocols continue operating even if fewer than half of the participants are online, but the desirability of this property is debated within the blockchain community). A hybrid model, in which the consensus used is some sort of heaviest chain approach, but some blocks are periodically finalized using a BFT finality gadget, maintains the advantages of both models. Such BFT finality gadgets are Casper FFG [6], used in Ethereum 2.09, Casper CBC, and GRANDPA used in Polkadot. Nightshade uses heaviest-chain consensus. Specifically, when a block pro- ducer produces a block (see section 3.3), they can collect signatures from other block producers and validators, attesting to the previous block. The weight of a block is then the cumulative stake of all the signers whose signatures are included in the block. The weight of a chain is the sum of the block weights. On top of heaviest-chain consensus, Nightshade uses a finality gadget that uses attestations to finalize the blocks. To reduce the complexity of the system, we use a finality gadget that doesn’t influence the fork-choice rule in any way. Instead the gadget only introduces extra slashing conditions such that once a 9Also see the whiteboard session with Justin Drake for an in-depth overview of Casper FFG, and how it is integrated with GHOST heaviest-chain consensus. 24 block is finalized by the finality gadget, a fork is impossible, unless a very large percentage of the total stake is slashed. The full details of NEAR’s consensus algorithm can be found in the Doomslug paper. 3.3 Block production In Nightshade there are two roles: block producers and validators. At any point the system contains w block producers, w = 100 in our models, and wv validators, in our model v = 100, wv = 10, 000. The system is Proof-of-Stake, meaning that both block producers and validators have some number of internal currency (referred to as ”tokens”) locked for a duration of time far exceeding the time they spend performing their duties of building and validating the chain. As with all the Proof-of-Stake systems, not all the w block producers and not all the wv validators are different entities, since that cannot be enforced. Each of the w block producers and the wv validators, however, does have a separate stake. The system contains n shards, where n = 100 in our model. As mentioned in section 3.1, in Nightshade there are no shard chains; instead all the block producers and validators are building a single blockchain, which we refer to as the main chain. The state of the main chain is split into n shards, and each block producer has at any moment only downloaded locally a subset of the state that corresponds to some subset of the shards, and only processes and validates transactions that affect those parts of the state. Validators do not maintain the state of any shard locally, but they do download and verify all the block headers. They validate chunks using state witness created by chunk producers. The details of this mechanism will be discussed in section 3.5. To become a block producer, a participant of the network locks some large amount of tokens (a stake). The maintenance of the network is done in epochs, where an epoch is roughly 16 hours. The participants with the w largest stakes at the beginning of a particular epoch are the block producers for that epoch. Each block producer is assigned to sw shards, (say sw = 4, which would make sww/n = 4 block producers per shard). The block producer downloads the state of the shard they are assigned to before the epoch starts, and throughout the epoch collects transactions that affect that shard, and applies them to the state. For each block b on the main chain, and for every shard s, one of the assigned block producers to s is responsible to produce the part of b related to the shard. The part of b related to shard s is called a chunk, and contains the list of the transactions for the shard to be included in b, as well as the Merkle root of the resulting state. b will ultimately only contain a very small header of the chunk, namely the Merkle root of all the applied transactions, and the Merkle root of the final state. When a block producer produces a chunk, they also produce an associated state witness required to execute the chunk. Throughout the rest of this document we refer to the block producer that is responsible for producing a chunk at a particular time for a particular shard as a chunk producer. A chunk producer is always a block producer and vice versa, 25 this distinction is made to help provide more accurate context when we discuss block production or chunk production. Within an epoch, the block and chunk production schedule is determined by a randomness seed generated at the beginning of the epoch and for each block height, there is an assigned block producer. Similarly, for each height, there is an assigned chunk producer for each shard. Since chunk production, unlike block production, requires maintaining the state, and for each shard only sww/n block producers maintain the state per shard, correspondingly only those sww/n block producers are responsible for producing chunks and associated state witnesses. 3.4 Ensuring data availability To ensure data availability, Nightshade uses an approach similar to that of Polkadot described in section 2.6.3. Once a block producer produces a chunk, they create an erasure coded version of it with an optimal (w, ⌊w/6 + 1⌋) block code of the chunk. They then send one piece of the erasure coded chunk (we call such pieces chunk parts, or just parts) to each block producer. We compute a Merkle tree that contains all the parts as the leaves, and the header of each chunk contains the Merkle root of such tree. The parts are sent to the validators via onepart messages. Each such message contains the chunk header, the ordinal of the part, and the part contents. The message also contains the signature of the block producer who produced the chunk and the Merkle path to prove that the part corresponds to the header and is produced by the proper block producer. Once a block producer receives a main chain block, they first check if they have onepart messages for each chunk included in the block. If not, the block is not processed until the missing onepart messages are retrieved. Once all the onepart messages are received, the block producer fetches the remaining parts from the peers and reconstructs the chunks for which they hold the state. The block producer doesn’t process a main chain block if, for at least one chunk included in the block, they don’t have the corresponding onepart mes- sage, or if for at least one shard for which they maintain the state they cannot reconstruct the entire chunk. For a particular chunk to be available, it is enough that ⌊w/6⌋+1 of the block producers have their parts and serve them. Thus, for as long as the number of malicious actors doesn’t exceed ⌊w/3⌋no chain that has more than half of the block producers building it can have unavailable chunks. 3.4.1 Dealing with lazy block producers If a block producer has a block for which a onepart message is missing, they might choose to still sign on it, because if the block ends up being on-chain, it will maximize the reward for the block producer. There’s no risk for the block 26 Figure 17: Each block contains one or zero chunks per shard, and each chunk is erasure coded. Each part of the erasure coded chunk is sent to a designated block producer via a special onepart message producer since it is impossible to prove later that the block producer didn’t have the onepart message. To address the lazy block producer problem, each chunk producer when creating a chunk must choose a color (red or blue) for each part of the future encoded chunk, as well as store the bitmask of assigned color in the chunk before it is encoded. Each onepart message then contains the color assigned to the part, and the color is used when computing the Merkle root of the encoded parts. If the chunk producer deviates from the protocol, it can be easily, since either the Merkle root will not correspond to onepart messages, or the colors in the onepart messages that correspond to the Merkle root will not match the mask in the chunk. When a block producer signs on a block, they include a bitmask of all the red parts they received for the chunks included in the block. Publishing an incorrect bitmask is a slashable behavior. If a block producer hasn’t received a onepart message, they have no way of knowing the color of the message, and thus have a 50% chance of being slashed if they attempt to blindly sign the block. 3.5 State transition application A chunk producer chooses transactions to include in a chunk, applies the state transition, and generates state witness along the way when they produce a chunk. More specifically, when a chunk producer applies a chunk they produces, they record all the trie nodes visited during the execution. This set of trie nodes is the state witness for this chunk. The chunk header contains a Merkle root 27 of the Merkleized state after the chunk is applied.10 The state witness is then shared with validators assigned to this shard for the next block so that they could validate the chunk. A validator only processes a block if: 1. The previous block was received and processed; 2. For each chunk, it receives the onepart message if it is not assigned to the corresponding shard. 3. For each chunk, it receives the full chunk if it is assigned to the corre- sponding shard Once the block is being processed, a validator applies the state transition of the shard they are assigned to and checks whether the resulting state root matches what is posted in the chunk header. If they match, the validator sends an chunk endorsement to the next block producer. Block producers would only include a chunk in a block if they have more than 2/3 endorsements from validators assigned to the corresponding shard. 3.5.1 State Representation In section 2.4, we define state witness as the state touched during the execution of a chunk, along with a proof that the recorded state pieces indeed belong to the state as specified by a state root. An important question left unanswered is how the state is represented. In blockchains where state proofs are required, their state is usually represented as a Merkle Patricia Trie (MPT). However, even for MPTs, the branching factor matters for the size of state witness — a critical component of the stateless validation design. A branching factor of 1611 means that when the state is full, each branch node will have an overhead of 15 hashes, which is 480 bytes. In comparison, a branching factor of 2, or binary Merkle trees, only have an overhead of 1 hash, which is 32 bytes, at each branch node. An analysis shows that based on Ethereum data, the state witness size can be reduced 40% by switching the state representation to a binary MPT. Recent research on Verkle Trees shows even more promising results. Verkle trees only require one 48-byte KZG commitment [7] per level. Therefore Verkle trees can have a large branching factor (256 - 1024), which results in much shallower trees and smaller witness sizes. Verkle tree is currently considered to be the best state representation for stateless validation. 10This is not exactly what is implemented. To allow for an easier upgrade from the pre- vious version where the previous state root instead of the post state root is stored in the chunk headers, the implementation is changed to accommodate that. We describe the design conceptually here to make it easier for readers to understand. 11This is what Ethereum and many other blockchains use as of this writing. 28 3.6 Cross-shard transactions and receipts If a transaction needs to affect more than one shard, it needs to be consecutively executed in each shard separately. The full transaction is sent to the first shard affected, and once the transaction is included in the chunk for such shard and is applied after the chunk is included in a block, it generates a so-called receipt transaction, which is routed to the next shard in which the transaction need to be executed. If more steps are required, the execution of the receipt transaction generates a new receipt transaction, and so on. 3.6.1 Receipt transaction lifetime It is desirable that the receipt transaction should be applied in the block that immediately follows the block in which it was generated. The receipt transaction is only generated after the previous block was received and applied by block producers that maintain the originating shard, and needs to be known by the time the chunk for the next block is produced by the block producers of the destination shard. Thus, the receipt must be communicated from the source shard to the destination shard in the short time frame between those two events. Let A be the last produced block which contains a transaction t that gener- ates a receipt r. Let B be the next produced block (i.e. a block that has A as its previous block) that we want to contain r. Let t be in the shard a and r be in the shard b. The lifetime of the receipt, also depicted on figure 18, is the following: Producing and storing the receipts. The chunk producer cpa for shard a receives the block A, applies the transaction t, and generates the receipt r. cpa then stores all such produced receipts in its internal persistent storage indexed by the source shard ID. Distributing the receipts. Once cpa is ready to produce the chunk for shard a within block B, they fetch all the receipts generated by applying the transactions from block A for shard a, and include them in the chunk for shard a in block B. Once such a chunk is generated, cpa produces its erasure coded version and all the corresponding onepart messages. cpa knows which block producers maintain the full state for which shards. For a particular block pro- ducer, bp, let Sbp denote the set of shards that bp maintains full state for. Let R denote the receipts that are results of applying transactions in block A for shard a that have any shard in Sbp as the destination shard. Then cpa would include R in the onepart message when they distribute the chunk for shard in block B to bp. Receiving the receipts. Remember that the participants (both block pro- ducers and validators) do not process blocks until they have onepart messages for each chunk included in the block. Thus, by the time any particular partici- pant applies the block B, they have all the onepart messages that correspond to chunks in B, and thus they have all the incoming receipts that have the shards for which the participant maintains state as their destination. When applying the state transition for a particular shard, the participant applies both the re- 29 ceipts that they have collected for the shard in the onepart messages, as well as all the transactions included in the chunk itself. Figure 18: The lifetime of a receipt transaction 3.6.2 Handling too many receipts It is possible that the number of receipts that target a particular shard in a particular block is too large to be processed. For example, consider figure 19, in which each transaction in each shard generates a receipt that targets shard 1. By the next block, the number of receipts that shard 1 needs to process is comparable to the load that all the shards combined processed while handling the previous block. To address it we use a technique similar to that used in QuarkChain 12. Specifically, for each shard the last block B and the last shard s within that block from which the receipts were applied is recorded. When the new shard is created, the receipt are applied in order first from the remaining shards in B, and then in blocks that follow B, until the new chunk is full. Under normal circumstances with a balanced load it will generally result in all the receipts being applied (and thus the last shard of the last block will be recorded for each chunk), but during times when the load is not balanced, and a particular shard receives disproportionately many receipts, this technique allows them to be processed while respecting the limits on the number of transactions included. Note that if such an imbalanced load remains for a long time, the delay from the receipt creation until the application can continue growing indefinitely. One way to address this is to drop any transaction that creates a receipt targeting a shard that has a processing delay exceeding some constant (e.g. one epoch). 12See the whiteboard episode with QuarkChain here: https://www.youtube.com/watch?v= opEtG6NM4x4, in which the approach to cross-shard transactions is discussed. 30 Figure 19: If all the receipts target the same shard, the shard may not have the capacity to process them Consider figure 20. By block B the shard 4 cannot process all the receipts, so it only processes receipts originating from up to shard 3 in block A, and records this. In block C the receipts up to shard 5 in block B are included, and then by block D, the shard catches up, processing all the remaining receipts in block B and all the receipts from block C. Figure 20: Delayed receipts processing 31 3.7 Chunks validation As mentioned in section 3.5, a chunk is validated by a set of stateless validators assigned to the shard. In this section, we provide a more detailed analysis of the security of the design. Again, we assume the existence of a on-chain randomness beacon that can be used to generate random seeds with each block, which then can be used to shuffle validators. The core problem here can be formulated as follows: let’s assume a total of n validators (with equal stake) where at most 1/3 of them are malicious. There are s shards and k validators are assigned to each shard at every block, so n = sk. What is the probability of a random assignment of validators to a shard that results in a shard getting corrupted? First, it is worth noting that a shard being corrupted means that more than 2/3 of validators assigned to that specific shard are malicious and can perform an invalid state transition. If less than 2/3 of validators are malicious, it is still possible for the chunk to be skipped due to insufficient endorsement, but no invalid state transition is possible. In addition, since validators rotate every single block, it is not possible for a shard to get indefinitely stalled due to a bad assignment. Now let’s consider the probability of a single shard getting corrupted. Let p denote the probability of a randomly chosen validator being malicious (so p ≤1/3). For a single shard to have l malicious validators, the probability is hypergeometric distribution: P(X = l) = k l n−k k−l  n k  Therefore, the probability of having more than 2/3 malicious validators for a single shard is P(X ≥2k/3) ≤e−D(p+1/3||p)k = e−k 3 by Chernoff bound. For s shards, the probability that at least one shard is corrupted is Pbad ≤ s X i=1 P(one shard is corrupted) ≤se−n 3s When n and k are large, i.e, there are many validators assigned to the same shard, the last term se−n 3s can be made negligbly small. Our numeric calculation based on multivariate hypergeometric distribution shows that with 800 validators and 4 shards, the probability of the networking getting corrupted is roughtly 10−29, which means that in expectation it takes 1029 blocks for the system to fail. Assuming one block per second, that translates to 3×1021 years. Therefore, while the security of the system is probabilistic, it is safe enough in practice. 32 3.7.1 Zero-knowledge proofs One problem that is often ignored in blockchain design is what happens when the BFT assumption is violated, i.e, if there are more than 1/3 malicious validators in a blockchain. Obviously the consensus could be broken and the network may fail to produce blocks. More importantly, the malicious validators could poten- tially attempt to create an invalid state transition. In a non-sharded blockchain, doing this would not only require a higher total stake (2/3 of validators being malicious), but also it is also very likely to be immediately noticed and a social consensus may ensue to resolve the attack. This is because the likelihood of every single validator being corrupted in a non-sharded blockchain is extremely low; there may also be others running RPC nodes who would notice the invalid state transition, as well. In a sharded blockchain, however, things are a bit different. It is more likely that the validators assigned to a shard could all be malicious and it is less likely that many people would run nodes that track every shard. This gives rise to the theoretical possibility of an invalid state transition attack occurring with few or any participants noticing. The result would be disastrous: a billion tokens could be minted out of thin air and moved to other shards and potentially even be bridged to other blockchains. This is where zero-knowledge proofs (ZKPs) can come in. Since ZKPs are very cheap to verify, if there is a proof generated for the state transition of each shard, then a very large number of people can independently verify the state transition without having to rely on the signatures of validators to trust the validity of a state transition. More specifically, every wallet could run a ZK full client that verifies the state transition of the entire blockchain and be assured that no invalid state transition has happened in the history of the blockchain. ZKPs also enable a stateless validation design that is simpler and more powerful than the one described in section 3.7. Instead of validators executing the chunk using state witness and verifying the state transition, they could verify one ZKP instead – which is much cheaper. The problem, however, is that generating a ZKP takes a long time. So if we naively swap out state witness with a ZKP, it won’t work due to the proof generation latency. Recent advancements in separating consensus and execution [8] provide a possible solution: blocks and chunks can be produced and optimistically ex- ecuted while ZK proofs are being generated. Once a ZKP is generated, it is submitted into a block for all validators to verify. Because ZKPs can be small in size and quite cheap to verify13, they can be included in the blocks directly and all validators can validate the state transition of all shards14. In this design, the validators would be much more lightweight, given that they only need to verify some ZKP. This means that the cost of operating a validator is going to be much cheaper and that the validator set could be much larger, which further improves the decentralization of the design. 13While STARK proofs can be relatively large (a few hundred kilobytes), they can be compressed again using a SNARK which would result in a proof of a few hundred bytes. 14Alternatively, proofs from different shards can be aggregated into one ZKP for a block. 33 3.8 State Size Sharding allows us to divide the state of the entire blockchain into those of individual shards, which provides a solution to the state growth problem that is becoming more and more imminent today. The stateless validation approach makes the blockchain even more performant: there are relatively few chunk producers and they can afford to operate more expensive hardware, which means that for each individual shard, the state of the shard can be held in memory when chunk producers produce and process chunks. Validators, on the other hand, receive state witness, which is small in size, when they need to apply a chunk and can also have the required state in memory. As a result, the state reads and writes are very fast. The cost of operating a chunk producer is not going to be exorbitantly high either. If we limit the size of each shard to 50GB, then a chunk producer could be operated with a 64GB RAM machine, which is fairly commonplace today. This asymmetry between chunk producer and validator also works well when state witness is replaced by ZKPs. Chunk producer could also operate a prover, which requires more hardware resources and the validators can run on even cheaper hardware due to the low cost of verifying ZKPs. 3.9 Snapshots Chain Since the blocks on the main chain are produced very frequently, downloading the full history might become expensive very quickly. Since the block producers set is constant throughout the epoch, validating only the first snapshot blocks in each epoch is sufficient assuming that at no point a large percentage of block producers and validators colluded and created a fork. The first block of the epoch must contain information sufficient to compute the block producers and validators for the epoch. We call the subchain of the main chain that only contains the snapshot blocks a snapshot chain. Such a chain can also be built and validated on Ethereum inside a smart contract can provides a secure method of cross-chain communi- cation. To sync with the NEAR chain, one only needs to download all the snapshot blocks and confirm that the signatures are correct, and then only have to sync the main chain blocks from the last snapshot block. 4 Conclusion In this document, we discussed approaches to building sharded blockchains and covered two major challenges that come with existing approaches, namely state validity and data availability. We then presented Nightshade, a sharding design that powers NEAR Protocol. The design is a work in progress. If you have comments, questions, or feedback on this document, please go to https://github.com/near/neps. 34 References [1] Monica Quaintance Will Martino and Stuart Popejoy. Chainweb: A proof- of-work parallel-chain architecture for massive throughput. 2018. [2] Mustafa Al-Bassam, Alberto Sonnino, and Vitalik Buterin. Fraud proofs: Maximising light client security and scaling blockchains with dishonest ma- jorities. CoRR, abs/1809.09044, 2018. [3] Songze Li, Mingchao Yu, Salman Avestimehr, Sreeram Kannan, and Pramod Viswanath. Polyshard: Coded sharding achieves linearly scaling efficiency and security simultaneously. CoRR, abs/1809.10361, 2018. [4] Ittai Abraham, Guy Gueta, and Dahlia Malkhi. Hot-stuff the linear, optimal- resilience, one-message BFT devil. CoRR, abs/1803.05069, 2018. [5] Yossi Gilad, Rotem Hemo, Silvio Micali, Georgios Vlachos, and Nickolai Zeldovich. Algorand: Scaling byzantine agreements for cryptocurrencies. In Proceedings of the 26th Symposium on Operating Systems Principles, SOSP ’17, pages 51–68, New York, NY, USA, 2017. ACM. [6] Vitalik Buterin and Virgil Griffith. Casper the friendly finality gadget. CoRR, abs/1710.09437, 2017. [7] Aniket Kate, Gregory Zaverucha, and Ian Goldberg. Constant-size commit- ments to polynomials and their applications. pages 177–194, 12 2010. [8] George Danezis, Eleftherios Kokoris-Kogias, Alberto Sonnino, and Alexan- der Spiegelman. Narwhal and tusk: A dag-based mempool and efficient BFT consensus. CoRR, abs/2105.11827, 2021. 35
Mooniswap brings its next-generation AMM protocol by 1inch to NEAR COMMUNITY November 24, 2020 In the month since the unrestricted Mainnet went live, the NEAR community is hard at work to bring best-in-class applications to the platform. Mooniswap by 1inch.exchange is the latest addition to a vibrant ecosystem of protocols building on NEAR. NEAR’s focus on both usability and performance is opening up new opportunities for DeFi by supporting at-scale real world applications with lower gas fees, low latency, and a flexible account model. 1inch’s decentralized exchange (DEX) aggregator is designed to roll liquidity and pricing from all major DEXes into one platform, making it easy to get the best price for the desired trade. Mooniswap building on NEAR will bring next-generation Automated Market Making possibilities to the OpenWeb. Sergej Kunz, CEO and co-founder of 1inch, spoke about the growth of their platform and why Mooniswap is excited to be building on NEAR. “We see substantial potential in NEAR as it is already offering what Ethereum just promises to offer. By building on NEAR, we’ll be able to experiment with sharding and be prepared for the arrival of Ethereum 2.0.” NEAR delivering on the promise of sharding ahead of Ethereum 2.0 has caught the attention of decentralized applications that need scale now in order to grow. Mooniswap is just the first of many applications building on NEAR that will leverage the performance, cost efficiency, and portability of the NEAR<>ETH Rainbow Bridge. Front Running Exploitation in Decentralized Exchanges Blockchain applications have long sought to solve the issues of fairness and transparency in financial trading ecosystems. However, due to the public nature of blockchains, one can easily identify the widespread use of nefarious tactics like arbitrage bots which exploit inefficiencies in decentralized exchanges. Similar to high-frequency traders on Wall Street, arbitrage bots are able to anticipate ordinary users’ trades and optimize for network latency in order to maximize profit at the expense of ordinary users. Commonly called “Front Running,” this is the primary problem that inspired the 1inch team to launch Mooniswap. Because transactions and gas fees are publicly visible before a block is mined, arbitrage bots are able to predict the direction in which a market is headed and submit a transaction with a higher gas price, forcing their transaction to be mined first. By trading on price swings, arbitrage traders use Front Running essentially to steal from liquidity providers. The Mooniswap Solution Mooniswap sought to solve this problem by simply using time to combat arbitrage bots. Virtual balances normalize pricing over a short five-minute period, keeping slippage revenue in a pool to be distributed more equitably. When a swap occurs, the Mooniswap AMM does not immediately improve price in the opposite direction, but gradually opens it over time. These high-slippage trades are the opportunity arbitrageurs seek to profit on, but in the fairer, more transparent ecosystem on Mooniswap, the actual balance of the exchange does not immediately reflect changes from slippage. Any new trades are still executed at the old price. Over a five-minute period, the price gradually updates to its true value based on the pool balances. This leaves only small windows of arbitrage opportunities, limiting exposure to average users in a fairer ecosystem. Additionally, during that short window, the exchange takes a much higher percentage of the trader’s profit, forcing arbitrageurs to return a higher proportion of the price slippage to the pool. On Mooniswap, arbitrageurs can only collect a portion of the slippage, while the rest remains in the pool and is shared among liquidity providers. Since prices are not updated immediately, no profit can be obtained by simply being faster than someone else. Mooniswap’s Preparation for Sharding NEAR’s launch introduced a scalable model for sharding to the blockchain industry: a first among leading protocols promising to deliver a real-world usable blockchain. This architecture presents a unique opportunity for existing dapps to start building and testing their infrastructure on a sharded network now to experience the benefits of scale that other blockchains promise to deliver in future versions. “As a previous bridge developer of NEAR, I’m quite excited to see the game-changing Mooniswap innovation build on the game-changing innovation that is NEAR Protocol,” says Anton Bukov, 1inch co-founder and CTO. “Mooniswap’s move to NEAR highlights the community synergy and virtuous circle that make up the overall blockchain and DeFi space. Moreover, this synergy underscores 1inch’s ultimate mission: to improve DeFi technology as much as possible for as many users as possible.” To start, Mooniswap will migrate their protocol to NEAR’s virtual machine along with establishing a native liquidity protocol on NEAR. The NEAR Rainbow Bridge and EVM integration create a seamless path to market on NEAR in the short term while they architect long term solutions for even more scalability. Eventually, the team will rebuild their core protocol native to NEAR, based on a sharded architecture, and become the first sharded decentralized exchange. Key Milestones for Mooniswap The team has recently launched 1inch version 2. Its major highlights are Pathfinder, an API that contains a new discovery and routing algorithm, and an intuitive, user-friendly UI. Thanks to the improvements, users will get even better rates on swaps, while response time will be cut even further. Many more products and features are in the works to power a more fair and transparent future for scalable decentralized exchanges. Welcome to the Community Please join us in welcoming the 1inch team to the NEAR community. We look forward to supporting their goal of creating more fair and transparent scalable decentralized exchanges. Stay tuned for news about more great partners joining NEAR with applications across the ecosystem. If you’re just learning about NEAR for the first time, we invite you to join us on the journey to make blockchain accessible to everyday people with NEAR. If you’re a developer, be sure to sign up for our developer program and join the conversation in our Discord chat. You can also keep up to date on future releases, announcements, and event invitations by subscribing to our newsletter for the latest news on NEAR.
--- id: hardware-archival title: Hardware Requirements for Archival Node sidebar_label: Hardware Requirements sidebar_position: 1 description: NEAR Archival Node Hardware Requirements --- This page covers the minimum and recommended hardware requirements for engaging with the NEAR platform as an Archival node. ## Recommended Hardware Specifications {#recommended-hardware-specifications} | Hardware | Recommended Specifications | | -------------- | ----------------------------------------------------------------------- | | CPU | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support | | CPU Features | CMPXCHG16B, POPCNT, SSE4.1, SSE4.2, AVX | | RAM | 24GB DDR4 | | Storage | 9 Terabyte SSD | _Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh avx```. If the output is empty, your CPU is not supported._ ## Minimal Hardware Specifications {#minimal-hardware-specifications} | Hardware | Minimal Specifications | | -------------- | -------------------------------------------------------------------------- | | CPU | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support | | RAM | 16GB DDR4 | | Storage | 9 Terabyte SSD | _Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh avx```. If the output is empty, your CPU is not supported._ ## Cost Estimation {#cost-estimation} Estimated monthly costs depending on operating system: | Cloud Provider | Machine Size | Linux | | -------------- | --------------- | ------------------------ | | AWS | m5.2xlarge | $330 CPU + $800 storage † | | GCP | n2-standard-8 | $280 CPU + $800 storage † | | Azure | Standard_F8s_v2 | $180 CPU + $800 storage † | _( † ) The storage cost will grow overtime as an archival node stores more data from the growing NEAR blockchain._ <blockquote class="info"> <strong>Resources for Cost Estimation</strong><br /><br /> All prices reflect *reserved instances* which offer deep discounts on all platforms with a 1 year commitment - AWS - cpu: https://aws.amazon.com/ec2/pricing/reserved-instances/pricing - storage: https://aws.amazon.com/ebs/pricing - GCP - cpu: https://cloud.google.com/compute/vm-instance-pricing - storage: https://cloud.google.com/compute/disks-image-pricing - Azure — https://azure.microsoft.com/en-us/pricing/calculator </blockquote> > Got a question? > <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> > <h8>Ask it on StackOverflow!</h8></a>
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="NFT Primitive" label="Reference" default> ```js import { Wallet } from './near-wallet'; const CONTRACT_ADDRESS = "nft.primitives.near"; const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS }); await wallet.callMethod({ method: 'nft_mint', args: { token_id: "1", receiver_id: "bob.near", token_metadata: { title: "NFT Primitive Token", description: "Awesome NFT Primitive Token", media: "string", // URL to associated media, preferably to decentralized, content-addressed storage } }, contractId: CONTRACT_ADDRESS, deposit: 10000000000000000000000 }); ``` </TabItem> <TabItem value="Paras" label="Paras"> ```js import { Wallet } from './near-wallet'; const CONTRACT_ADDRESS = "x.paras.near"; const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS }); await wallet.callMethod({ method: 'nft_mint', args: { token_series_id: "490641", receiver_id: "bob.near", }, contractId: CONTRACT_ADDRESS, deposit: 10000000000000000000000 // Depends on your NFT metadata }); ``` :::note In order to use `nft_mint` method of the `x.paras.near` contract you have to be a creator of a particular token series. ::: </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```js import { Wallet } from './near-wallet'; const CONTRACT_ADDRESS = "thomasettorreiv.mintbase1.near"; const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS }); await wallet.callMethod({ method: 'nft_batch_mint', args: { num_to_mint: 1, owner_id: "bob.near", metadata: {}, }, contractId: CONTRACT_ADDRESS, deposit: 10000000000000000000000 // Depends on your NFT metadata }); ``` :::note In order to use `nft_batch_mint` method of Mintbase store contract your account have to be a in the contract minters list. ::: :::tip Check how to do this using [`Mintbase JS`](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/sdk/mint) ::: </TabItem> </Tabs> _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
--- sidebar_position: 3 sidebar_label: "Add basic code, create a subaccount, and call methods" title: "Alter the smart contract, learning about basics of development" --- import {Github} from "@site/src/components/codetabs" import teachingDeployment from '/docs/assets/crosswords/teaching--jeheycell.near--artcultureac.jpeg'; import createAccount from '/docs/assets/crosswords/creating account with text--seanpineda.near--_seanpineda.png'; import chalkboardErase from '/docs/assets/crosswords/erasing-subaccount-chalkboard--iambon.near--JohnreyBona.mp4'; # Modifying the contract This section will modify the smart contract skeleton from the previous section. This tutorial will start by writing a contract in a somewhat useless way in order to learn the basics. Once we've got a solid understanding, we'll iterate until we have a crossword puzzle. ## Add a const, a field, and functions Let's modify the contract to be: <Github language="rust" start="1" end="29" url="https://github.com/near-examples/crossword-snippets/blob/00223633f3e6b5b7137097e996b0aee90d632b0f/src/lib.rs" /> We've done a few things here: 1. Set a constant for the puzzle number. 2. Added the field `crossword_solution` to our main struct. 3. Implemented three functions: one that's view-only and two that are mutable, meaning they have the ability to change state. 4. Used logging, which required the import of `env` from our `near_sdk` crate. Before moving on, let's talk about these changes and how to think about them, beginning with the constant: `const PUZZLE_NUMBER: u8 = 1;` This is an in-memory value, meaning that when the smart contract is spun up and executed in the virtual machine, the value `1` is contained in the contract code. This differs from the next change, where a field is added to the struct containing the `#[near_bindgen]` macro. The field `crossword_solution` has the type of `String` and, like any other fields added to this struct, the value will live in **persistent storage**. With NEAR, storage is "paid for" via the native NEAR token (Ⓝ). It is not "state rent" but storage staking, paid once, and returned when storage is deleted. This helps incentivize users to keep their state clean, allowing for a more healthy chain. Read more about [storage staking here](https://docs.near.org/concepts/storage/storage-staking). Let's now look at the three new functions: ```rust pub fn get_puzzle_number(&self) -> u8 { PUZZLE_NUMBER } ``` As is covered in the [mutability section of these docs](/sdk/rust/contract-interface/contract-mutability), a "view-only" function will have open parenthesis around `&self` while "change methods" or mutable functions will have `&mut self`. In the function above, the `PUZZLE_NUMBER` is returned. A user may call this method using the proper RPC endpoint without signing any transaction, since it's read-only. Think of it like a GET request, but using RPC endpoints that are [documented here](https://docs.near.org/api/rpc/contracts#call-a-contract-function). Mutable functions, on the other hand, require a signed transaction. The first example is a typical approach where the user supplies a parameter that's assigned to a field: ```rust pub fn set_solution(&mut self, solution: String) { self.crossword_solution = solution; } ``` The next time the smart contract is called, the contract's field `crossword_solution` will have changed. The second example is provided for demonstration purposes: ```rust pub fn guess_solution(&mut self, solution: String) { if solution == self.crossword_solution { env::log_str("You guessed right!") } else { env::log_str("Try again.") } } ``` Notice how we're not saving anything to state and only logging? Why does this need to be mutable? Well, logging is ultimately captured inside blocks added to the blockchain. (More accurately, transactions are contained in chunks and chunks are contained in blocks. More info in the [Nomicon spec](https://nomicon.io/Architecture.html?highlight=chunk#blockchain-layer-concepts).) So while it is not changing the data in the fields of the struct, it does cost some amount of gas to log, requiring a signed transaction by an account that pays for this gas. --- ## Building and deploying Here's what we'll want to do: <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 jeheycell.near"/> <figcaption className="full-width">Art by <a href="https://twitter.com/artcultureac" target="_blank">jeheycell.near</a></figcaption> </figure> ### Build the contract The skeleton of the Rust contract we copied from the previous section has a `build.sh` and `build.bat` file for OS X / Linux and Windows, respectively. For more details on building contracts, please see [this section](/sdk/rust/building/basics). Run the build script and expect to see the compiled Wasm file copied to the `res` folder, instead of buried in the default folder structure Rust sets up. ./build.sh ### Create a subaccount If you've followed from the previous section, you have NEAR CLI installed and a full-access key on your machine. While developing, it's a best practice to create a subaccount and deploy the contract to it. This makes it easy to quickly delete and recreate the subaccount, which wipes the state swiftly and starts from scratch. Let's use NEAR CLI to create a subaccount and fund with 1 NEAR: near create-account crossword.friend.testnet --masterAccount friend.testnet --initialBalance 1 If you look again in your home directory's `.near-credentials`, you'll see a new key for the subaccount with its own key pair. This new account is, for all intents and purposes, completely distinct from the account that created it. It might as well be `alice.testnet`, as it has, by default, no special relationship with the parent account. To be clear, `friend.testnet` cannot delete or deploy to `crossword.friend.testnet` unless it's done in a single transaction using Batch Actions, which we'll cover later. :::info Subaccount nesting It's possible to have the account `another.crossword.friend.testnet`, but this account must be created by `crossword.friend.testnet`. `friend.testnet` **cannot** create `another.crossword.friend.testnet` because accounts may only create a subaccount that's "one level deeper." See this visualization where two keys belonging to `mike.near` are able to create `new.mike.near`. We'll get into concepts around access keys later. <figure> <img src={createAccount} alt="Depiction of create account where two figures put together a subaccount. Art created by seanpineda.near"/> <figcaption className="full-width">Art by <a href="https://twitter.com/_seanpineda" target="_blank">seanpineda.near</a></figcaption> </figure> ::: We won't get into top-level accounts or implicit accounts, but you may read more [about that here](https://docs.near.org/docs/concepts/account). Now that we have a key pair for our subaccount, we can deploy the contract to testnet and interact with it! #### What's a codehash? We're almost ready to deploy the smart contract to the account, but first let's take a look at the account we're going to deploy to. Remember, this is the subaccount we created earlier. To view the state easily with NEAR CLI, you may run this command: near state crossword.friend.testnet What you'll see is something like this: ```js { amount: '6273260568737488799170194446', block_hash: 'CMFVLYy6UP6c6vrWiSf1atWviayfZF2fgPoqKeUVtLhi', block_height: 61764892, code_hash: '11111111111111111111111111111111', locked: '0', storage_paid_at: 0, storage_usage: 4236, formattedAmount: '6,273.260568737488799170194446' } ``` Note the `code_hash` here is all ones. This indicates that there is no contract deployed to this account. Let's deploy the contract (to the subaccount we created) and then check this again. ### Deploy the contract Ensure that in your command line application, you're in the directory that contains the `res` directory, then run: ```bash near deploy crossword.friend.testnet --wasmFile res/my_crossword.wasm ``` Congratulations, you've deployed the smart contract! Note that NEAR CLI will output a link to [NEAR Explorer](https://nearblocks.io/) where you can inspect details of the transaction. Lastly, let's run this command again and notice that the `code_hash` is no longer all ones. This is the hash of the smart contract deployed to the account. ```bash near state crossword.friend.testnet ``` **Note**: deploying a contract is often done on the command line. While it may be _technically_ possible to deploy via a frontend, the CLI is likely the best approach. If you're aiming to use a factory model, (where a smart contract deploys contract code to a subaccount) this isn't covered in the tutorial, but you may reference the [contracts in SputnikDAO](https://github.com/near-daos/sputnik-dao-contract). ### Call the contract methods (interact!) Let's first call the method that's view-only: ```bash near view crossword.friend.testnet get_puzzle_number ``` Your command prompt will show the result is `1`. Since this method doesn't take any arguments, we don't pass any. We could have added `'{}'` to the end of the command as well. Next, we'll add a crossword solution as a string (later we'll do this in a better way) argument: ```bash near call crossword.friend.testnet set_solution '{"solution": "near nomicon ref finance"}' --accountId friend.testnet ``` :::info Windows users Windows users will have to modify these commands a bit as the Command Prompt doesn't like single quotes as we have above. The command must use escaped quotes like so: ```bash near call crossword.friend.testnet set_solution "{\"solution\": \"near nomicon ref finance\"}" --accountId friend.testnet ``` ::: Note that we used NEAR CLI's [`view` command](https://docs.near.org/docs/tools/near-cli#near-view), and didn't include an `--accountId` flag. As mentioned earlier, this is because we are not signing a transaction. This second method uses the NEAR CLI [`call` command](https://docs.near.org/docs/tools/near-cli#near-call) which does sign a transaction and requires the user to specify a NEAR account that will sign it, using the credentials files we looked at. The last method we have will check the argument against what is stored in state and write a log about whether the crossword solution is correct or incorrect. Correct: ```bash near call crossword.friend.testnet guess_solution '{"solution": "near nomicon ref finance"}' --accountId friend.testnet ``` You'll see something like this: ![Command line shows log for successful solution guess](/docs/assets/crosswords/cli-guess-solution.png) Notice the log we wrote is output as well as a link to NEAR Explorer. Incorrect: ```bash near call crossword.friend.testnet guess_solution '{"solution": "wrong answers here"}' --accountId friend.testnet ``` As you can imagine, the above command will show something similar, except the logs will indicate that you've given the wrong solution. ## Reset the account's contract and state We'll be iterating on this smart contract during this tutorial, and in some cases it's best to start fresh with the NEAR subaccount we created. The pattern to follow is to **delete** the account (sending all remaining testnet Ⓝ to a recipient) and then **create the account** again. <video autoPlay controls loop> <source src={chalkboardErase} type="video/mp4" /> Sorry, your browser doesn't support embedded videos. </video> <figure> <figcaption>Deleting a recreating a subaccount will clear the state and give us a fresh start.<br/>Animation by <a href="https://twitter.com/JohnreyBona" target="_blank">iambon.near</a></figcaption> </figure> Using NEAR CLI, the commands will look like this: ```bash near delete crossword.friend.testnet friend.testnet near create-account crossword.friend.testnet --masterAccount friend.testnet ``` The first command deletes `crossword.friend.testnet` and sends the rest of its NEAR to `friend.testnet`. ## Wrapping up So far, we're writing a simplified version of smart contract and approaching the crossword puzzle in a novice way. Remember that blockchain is an open ledger, meaning everyone can see the state of smart contracts and transactions taking place. :::info How would you do that? You may hit an RPC endpoint corresponding to `view_state` and see for yourself. Note: this quick example serves as demonstration purposes, but note that the string being returned is Borsh-serialized and contains more info than just the letters. ```bash curl -d '{"jsonrpc": "2.0", "method": "query", "id": "see-state", "params": {"request_type": "view_state", "finality": "final", "account_id": "crossword.friend.testnet", "prefix_base64": ""}}' -H 'Content-Type: application/json' https://rpc.testnet.near.org ``` ![Screenshot of a terminal screen showing a curl request to an RPC endpoint that returns state of a smart contract](/docs/assets/crosswords/rpc-api-view-state.png) More on this RPC endpoint in the [NEAR docs](https://docs.near.org/docs/api/rpc/contracts#view-contract-state). ::: In this section, we saved the crossword solution as plain text, which is likely not a great idea if we want to hide the solution to players of this crossword puzzle. Even though we don't have a function called `show_solution` that returns the struct's `crossword_solution` field, the value is stored transparently in state. We won't get into viewing contract state at this moment, but know it's rather easy [and documented here](https://docs.near.org/docs/api/rpc/contracts#view-contract-state). The next section will explore hiding the answer from end users playing the crossword puzzle.
--- id: blog-posts title: Blog Posts --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" The Blog post components enable your gateway to promote regular Near Social posts into fully fledged blog posts. In this article you'll learn how to set up the required components so you can define a custom URL to show a clean feed of blog posts. ## Setup To set up the Blog post features on your [`near-discovery`](https://github.com/near/near-discovery/) gateway: 1. Add the [`Blog.Feed`](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/Blog.Feed) and [`BlogPostPage`](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/BlogPostPage) components 2. Add `near/widget/Blog.Feed` and `near/widget/BlogPostPage` to your configuration <Tabs> <TabItem value="discovery" label="near-discovery" default> - Edit your `bos-components.ts` configuration file: <Github fname="bos-components.ts" language="js" value="near-discovery" url="https://github.com/near/near-discovery/blob/c275ab7d70a6ee7baf3a88ace1c2e02f605da644/src/data/bos-components.ts" start="160" end="165" /> </TabItem> <TabItem value="viewer" label="nearsocial viewer"> - Edit your `widgets.js` configuration file: ```js title="src/data/widgets.js" const MainnetWidgets = { blog: 'near/widget/Blog.Feed', blogPost: 'near/widget/BlogPostPage', image: "mob.near/widget/Image", default: "mob.near/widget/Homepage", viewSource: "mob.near/widget/WidgetSource", widgetMetadataEditor: "mob.near/widget/WidgetMetadataEditor", ``` </TabItem> </Tabs> ### Blog feed URL To set a custom URL such as `/bosblog` for your Blog feed, and define which users will be shown on it, do the following changes on your `near-discovery` gateway: <Tabs> <TabItem value="discovery" label="near-discovery" default> 1. Create a folder `src/pages/<customURL>` for your desired custom path (e.g., `/bosblog`) 2. Add this [`index.tsx`](https://github.com/near/near-discovery/blob/c275ab7d70a6ee7baf3a88ace1c2e02f605da644/src/pages/bosblog/index.tsx) file to `src/pages/bosblog/`: <Github fname="index.tsx" language="js" value="near-discovery" url="https://github.com/near/near-discovery/blob/c275ab7d70a6ee7baf3a88ace1c2e02f605da644/src/pages/bosblog/index.tsx" start="1" end="50" /> </TabItem> <TabItem value="viewer" label="nearsocial viewer"> 1. Add this `BlogPage.js` file to `src/pages/`: ```js title="src/pages/BlogPage.js" import React, { useEffect, useState } from "react"; import { Widget } from "near-social-vm"; import { useParams } from "react-router-dom"; import { useQuery } from "../hooks/useQuery"; import { useHashRouterLegacy } from "../hooks/useHashRouterLegacy"; export default function BlogPage(props) { useHashRouterLegacy(); const { widgetSrc } = useParams(); const query = useQuery(); const [widgetProps, setWidgetProps] = useState({}); const src = widgetSrc || props.widgets.default; const contributors = ['near', 'jacksonthedev.near']; useEffect(() => { setWidgetProps( [...query.entries()].reduce((props, [key, value]) => { props[key] = value; return props; }, {}) ); }, [query]); if (widgetProps.accountId && widgetProps.blockHeight) { return ( <div className="d-inline-block position-relative overflow-hidden"> <Widget src={props.widgets.blogPost} props={widgetProps} />{" "} </div> ); } widgetProps.contributors = contributors; return ( <div className="d-inline-block position-relative overflow-hidden"> <Widget src={props.widgets.blog} props={widgetProps} />{" "} </div> ); } ``` 2. Update your `App.js` router file, adding the new route to your custom path (e.g., `/bosblog`): ```js title="src/App.js" import BlogPage from "./pages/BlogPage"; ``` ```js title="src/App.js" <Route path={"/signin"}> <NavigationWrapper {...passProps} /> <SignInPage {...passProps} /> </Route> <Route path={"/bosblog"}> <NavigationWrapper {...passProps} /> <BlogPage {...passProps} /> </Route> ``` </TabItem> </Tabs> 3. Edit the `contributors` list, with the account(s) that you want to showcase on your blog feed: ```js const contributors = ['near', 'jacksonthedev.near']; ``` That's all, your gateway setup is done and you're ready to show your blog feed. Check the next sections if you want to learn more about the blog post [content formatting](#blog-post-formatting) and how to promote social messages into blog posts. :::tip In this code example, only promoted blog posts from users `near` and `jacksonthedev.near` will appear in the Blog feed when someone browses the `/bosblog` URL. ::: ### Promoting posts If you're using `near-discovery` you're all set, the <kbd>Promote</kbd> menu is already available using the [`v1.Posts.Feed`](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/v1.Posts.Feed) component. If you're using a different gateway or your own custom feed, and you want to allow users to promote social messages into blog posts, you can integrate this `promoteToBlog` code snippet: ```js const { accountId, blockHeight, item } = props; const promoteToBlog = () => { if (state.loading) { return; } if (!context.accountId && props.requestAuthentication) { props.requestAuthentication(); return; } else if (!context.accountId) { return; } State.update({ loading: true, }); const data = { index: { promote: JSON.stringify({ key: context.accountId, value: { operation: "add", type: "blog", post: item, blockHeight, }, }), }, }; Social.set(data, { onCommit: () => State.update({ loading: false }), onCancel: () => State.update({ loading: false, }), }); }; ``` :::tip Check the [`Posts.Menu`](https://near.org/near/widget/ComponentDetailsPage?src=near/widget/Posts.Menu&tab=source) component for a complete implementation that includes a drop-down menu and a button to promote a blog post. ::: --- ## Blog post formatting When writing blog posts, you can format the content using standard [Markdown syntax](https://www.markdownguide.org/basic-syntax/). Markdown is an easy-to-read, easy-to-write language for formatting plain text. The only two special cases that you should keep in mind when writing a blog post are: - the blog post's title - an optional header image #### Header image To define an image for your blog post, just add a markdown image link at the top of your post: ```md ![header-image](https://example.com/image.png) ``` #### Blog post title To set the post's title, define it using a top heading tag: ```md # This is the title of a demo blog post ``` :::tip If you're new to Markdown, you might want to check this page about [basic writing and formatting syntax](https://www.markdownguide.org/basic-syntax/). ::: --- ## Writing a blog post Adding a new blog post is simple. To publish a new blog post, you only need to: 1. Write a regular Near Social message 2. Promote the message and convert it to a Blog post <img src="/docs/bosblog/blog-promote1.png" width="60%" /> #### Promote a message to blog post Once the message has been posted, promoting it to a blog post is straight forward. Just click on the 3 dots next to your post (`...`), and select the `Promote this Post to Blog` option: ![blog post](/docs/bosblog/blog-promote2.png) :::note You can find the published blog post example in [this link](https://near.org/near/widget/BlogPostPage?accountId=bucanero.near&blockHeight=117452680&returnLocation=/near/widget/ProfilePage?accountId=bucanero.near&tab=blog). ::: That's it, your blog post has been promoted and published, and you can find it under the `Blog` tab in your [social profile](https://near.org/near/widget/ProfilePage?accountId=bucanero.near&tab=blog): ![blog post](/docs/bosblog/blog-promote3.png)
--- id: what-is-a-node title: What is a Node sidebar_label: What is a Node sidebar_position: 1 description: What is a NEAR Node and Why Run a Node --- NEAR Protocol runs on a collection of publicly maintained computers (or "nodes"). All nodes are running the same `nearcore` codebase with the latest releases available on [GitHub](https://github.com/near/nearcore/releases/). In the following section, we will introduce three types of nodes. It is important to keep in mind all nodes run the same codebase, with different configurations. As such, we have split up the documentation for running different types of node into sections specific to the type of nodes. ## Why run a Node? {#why-run-a-node} You may decide to run a node of your own for a few reasons: - To join a network as a validator running a validator node. Running a validator node is a public good and you are effectively securing the NEAR network and earning rewards. - To run applications that heavily depend on RPC performance and/or availability. - To develop and deploy contracts on a local (independent and isolated) node (sometimes called "localnet"). (†) - To quickly extract blockchain data that can be used for chain analytics, block explorer, etc. _( † ) `localnet` would be the right choice if you prefer to avoid leaking information about your work during the development process since `testnet` and `betanet` are *public* networks. `localnet` also gives you total control over accounts, economics and other factors for more advanced use cases (ie. making changes to `nearcore`)._ ## Types of Network {#types-of-network} There are a few different networks to potentially run a node. Each network operates with its own independent validators and unique state. To find out more, head to the [network overview](https://docs.near.org/concepts/basics/networks). * [`mainnet`](https://docs.near.org/concepts/basics/networks#mainnet) * [`testnet`](https://docs.near.org/concepts/basics/networks#testnet) * [`betanet`](https://docs.near.org/concepts/basics/networks#betanet) * [`localnet`](https://docs.near.org/concepts/basics/networks#localnet) >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
NEAR Launches Sustainable Learn and Earn Program with Coinbase COMMUNITY September 1, 2022 NEAR Foundation is excited to announce a new campaign with Coinbase designed to educate people on the utility of the NEAR token. A secure platform for buying, selling, transferring, and storing digital currency, Coinbase is one of the world’s largest digital currency exchanges, fully registered and operating in over 100 countries. This educational series will utilize the Coinbase Earn program to educate users about NEAR through video tutorials and interactive quizzes produced by Coinbase. Learn about running smart contracts in Javascript and Rust, joining or creating a DAO with a NEAR wallet, how Nightshade sharding is powering NEAR’s incredible scalability, and more. Funding Learn and Earn with Staking Rewards What makes this campaign unique is that it will be the first of its kind to use staking rewards to fund the initiative. Coinbase will manage NEAR tokens over a period of three years, collecting staking rewards and using those rewards to sustainably help users to learn about the utility of the NEAR token and what makes NEAR the world’s leading blockchain for developers, with its low fees, high speeds, and infinite scalability. “In an era when many crypto companies have relied on unsustainable business models to grow and scale, it was important we found a way of helping educate people about the unique features of NEAR in a sustainable way,” says Marieke Flament, CEO of the NEAR Foundation. Certified climate neutral by SouthPole, the leading company for voluntary carbon offsetting, sustainability is at the core of NEAR’s mission of providing a platform that is low-cost, high speed, secure, and easy to use for developers and lay users alike. To participate in the Earn campaign, open the Coinbase app and navigate to the “Learning Rewards” tab on the left hand menu. Once there, those logged in and eligible to earn will see the NEAR campaign. Integrating NEAR with Coinbase Custody In addition to the Coinbase Earn program, the partnership will also integrate NEAR with Coinbase Custody—an independent entity offering clients access to secure institutional grade offline custody—and Coinbase Prime, an integrated solution that provides secure custody, an advanced trading platform, and additional prime services. “We are committed to democratizing access to the world of Web3 and giving more people the opportunity to help shape its future,” Flament says. “We are making it easier than ever for anyone to learn about the utility of the NEAR token and its ability to create a more accessible and sustainable Web3. We believe that through education, we take another step towards mass adoption.” This partnership will allow NEAR Foundation to expand its ecosystem by tapping into the huge number of users who put their trust in Coinbase and showing them just how easy NEAR is to use and understand.
--- id: help title: NEAR - Your Gateway to an Open Web --- # Developer Help & Resources [![DEVHUB](https://img.shields.io/badge/DEV_HUB-03BE09)](https://neardevhub.org/) [![CALENDAR](https://img.shields.io/badge/CALENDAR-F9F502)](https://bit.ly/near-dev-calendar) [![DEV SUPPORT](https://img.shields.io/badge/DEV_SUPPORT-BE0303)](https://t.me/addlist/VyVjNaP190JlOGMx) [![NEWSLETTER](https://img.shields.io/badge/NEWSLETTER-0087E5)](https://newsletter.neardevhub.org/) [![FEEDBACK](https://img.shields.io/badge/FEEDBACK-purple)](https://github.com/orgs/near/discussions/new?category=dev-feedback) NEAR is dedicated to providing the best developer experience possible for building an open web. This mission is next to impossible to achieve without feedback and contributions from **people like you**. 🫵 **Get involved!** 👉 please select one of the options above or contribute to one of the essential developer repositories listed below 🙏 :::info Contact Us - [Developer Hub](https://neardevhub.org/) - [Telegram Support](https://t.me/neardev) - [Discord](https://near.chat) - [Zulip](https://near.zulipchat.com) ::: --- ### 📝 Docs | Website | Description | Repo | | ----------- | ----------- | --- | |[docs.near.org](https://docs.near.org) | NEAR Developer Documentation |[near/docs](https://github.com/near/docs) |[nomicon.io](https://nomicon.io)| NEAR Protocol Specification Documentation | [near/neps](https://github.com/near/neps) |[near-nodes.io](https://near-nodes.io)| NEAR Node Documentation _(Validator, RPC, Archival)_ |[near/node-docs](https://github.com/near/node-docs) --- ### ⛓️ Protocol | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- | --- | | nearcore | Reference implementation of NEAR Protocol |[near/nearcore](https://github.com/near/nearcore)|[![Latest Release](https://img.shields.io/github/v/release/near/nearcore?label=)](https://github.com/near/nearcore/releases) | NEPs | NEAR Protocol Specifications and Standards |[near/neps](https://github.com/near/neps)| ➖ --- ### 🚀 Decentralized Frontend Stack > Create decentralized frontend components by storing it's source code on the blockchain 🤯. | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- |--| |**👉 GATEWAY**|||| | near-discovery | near.org Gateway |[near/near-discovery](https://github.com/near/near-discovery)| [![Latest Release](https://img.shields.io/github/v/release/near/near-discovery?label=)](https://github.com/near/near-discovery/releases) | near.social | near.social Gateway | [NearSocial/viewer](https://github.com/NearSocial/viewer) | ➖ | near-discovery-components | Core components / primitives for near.org | [near/near-discovery-components](https://github.com/near/near-discovery-components)| ➖ |**👉 EXECUTION ENVIRONMENT**|||| | VM | B.O.S. Virtual Machine | [nearsocial/VM](https://github.com/NearSocial/VM) |[![Latest Release](https://img.shields.io/github/v/release/nearsocial/vm?label=)](https://github.com/nearsocial/vm/releases) | BWE | B.O.S. Web Engine ***(WIP replacement for VM)*** | [near/bos-web-engine](https://github.com/near/bos-web-engine) |➖ |**👉 DATABASE**|||| | B.O.S. Database | Smart contract hosting frontend source code & user data | [nearsocial/social-db](https://github.com/NearSocial/social-db)|➖ --- ### 🛠️ Dev Tools | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- |--| | create-near-app | Easy fullstack dApp deployment tool | [near/create-near-app](https://github.com/near/create-near-app) | [![Latest Release](https://img.shields.io/github/v/release/near/create-near-app?label=)](https://github.com/near/create-near-app/releases) | cargo-near | Cargo extension for building smart contracts and ABI schemas on NEAR | [near/cargo-near](https://github.com/near/cargo-near) | [![Latest Release](https://img.shields.io/github/v/release/near/cargo-near?label=)](https://github.com/near/cargo-near/releases) | BOS VSCode Ext. | VSCode extension for building B.O.S. components | [near/near-vscode](https://github.com/near/near-vscode) | [![Latest Release](https://img.shields.io/github/v/release/near/near-vscode?label=)](https://github.com/near/near-vscode/releases) | BOS Loader | Simplifying multiple component local development | [near/bos-loader](https://github.com/near/bos-loader) | [![Latest Release](https://img.shields.io/github/v/release/near/bos-loader?label=)](https://github.com/near/bos-loader/releases) ### 💻 CLI | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- |--| | near-cli | JS based CLI for interacting w/ NEAR | [near/near-cli](https://github.com/near/near-cli)|[![Latest Release](https://img.shields.io/github/v/release/near/near-cli?label=)](https://github.com/near/near-cli/releases) | near-cli-rs| Rust based CLI for interacting w/ NEAR | [near/near-cli-rs](https://github.com/near/near-cli-rs)| [![Latest Release](https://img.shields.io/github/v/release/near/near-cli-rs?label=)](https://github.com/near/near-cli-rs/releases) | BOS CLI | CLI for simplifying local development on BOS | [bos-cli-rs/bos-cli-rs](https://github.com/bos-cli-rs/bos-cli-rs) | [![Latest Release](https://img.shields.io/github/v/release/bos-cli-rs/bos-cli-rs?label=)](https://github.com/bos-cli-rs/bos-cli-rs/releases) ### 🔑 Wallet / Auth | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- | --- | | wallet-selector |Wallet integration tool for NEAR|[near/wallet-selector](https://github.com/near/wallet-selector)|[![Latest Release](https://img.shields.io/github/v/release/near/wallet-selector?label=)](https://github.com/near/wallet-selector/releases) | web3-onboard | Wallet integration tool for multichain |[blocknative/web3-onboard](https://github.com/blocknative/web3-onboard)|[![Latest Release](https://img.shields.io/github/v/release/blocknative/web3-onboard?label=)](https://github.com/blocknative/web3-onboard/releases) | FastAuth Signer | Authenticate and sign transactions w/ FastAuth |[near/fast-auth-signer](https://github.com/near/fast-auth-signer)|➖ | mpc-recovery | Create and restore accounts w/ OIDC protocol|[near/mpc-recovery](https://github.com/near/mpc-recovery)|➖ | iDOS | Decentralized identity, storage, and verification | [idos-network/idos-sdk-js](https://github.com/idos-network/idos-sdk-js)|➖ ### 🔌 API | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- | --- | | near-api-js | API tool for frontend & backend JS libraries |[near/near-api-js](https://github.com/near/near-api-js)|[![Latest Release](https://img.shields.io/github/v/release/near/near-api-js?label=)](https://github.com/near/near-api-js/releases) ### 📝 Smart Contracts | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- |---| | near-sdk-js|Create smart contracts w/ JavaScript | [near/near-sdk-js](https://github.com/near/near-sdk-js) | [![Latest Release](https://img.shields.io/github/v/release/near/near-sdk-js?label=)](https://github.com/near/near-sdk-js/releases) | near-sdk-rs|Create smart contracts w/ Rust | [near/near-sdk-rs](https://github.com/near/near-sdk-rs)| [![Latest Release](https://img.shields.io/github/v/release/near/near-sdk-rs?label=)](https://github.com/near/near-sdk-rs/releases) | Keypom | Customizable key creation for NFT/FT drops |[keypom/keypom](https://github.com/keypom/keypom)|[![Latest Release](https://img.shields.io/github/v/release/keypom/keypom?label=)](https://github.com/keypom/keypom/releases) ### 🧪 Testing | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- | --- | | workspaces-js| Testing sandbox written in JS |[near/workspaces-js](https://github.com/near/workspaces-js)|[![Latest Release](https://img.shields.io/github/v/release/near/near-workspaces-js?label=)](https://github.com/near/near-workspaces-js/releases) | workspaces-rs| Testing sandbox written in Rust |[near/workspaces-rs](https://github.com/near/workspaces-rs)|[![Latest Release](https://img.shields.io/github/v/release/near/near-workspaces-rs?label=)](https://github.com/near/near-workspaces-rs/releases) ### 🔎 Blockchain Data Indexing | Name | Description | Repo | Latest Release | | ----------- | ----------- | --- | --- | | QueryApi | Build custom indexers and query with GraphQL endpoints|[near/queryapi](https://github.com/near/queryapi)|➖ | near-lake-indexer | Built on [NEAR Indexer](https://github.com/near/nearcore/tree/master/chain/indexer) that stores JSON in AWS S3 bucket |[near/near-lake-indexer](https://github.com/near/near-lake-indexer)|[![Latest Release](https://img.shields.io/github/v/release/near/near-lake-indexer?label=)](https://github.com/near/near-lake-indexer/releases) | near-lake-framework-rs | Stream blocks from NEAR Lake into your server |[near/near-lake-framework-rs](https://github.com/near/near-lake-framework-rs)|[![Latest Release](https://img.shields.io/github/v/release/near/near-lake-framework-rs?label=)](https://github.com/near/near-lake-framework-rs/releases) | near-lake-framework-js | Stream blocks from NEAR Lake into your server |[near/near-lake-framework-js](https://github.com/near/near-lake-framework-js)| ➖
--- sidebar_position: 6 sidebar_label: "Base64 params, wrap up" title: "Using base64-encoded arguments when we create a new crossword puzzle" --- import {Github} from "@site/src/components/codetabs" # Final modifications import base64Encode from '/docs/assets/crosswords/boop-base64-encode.gif'; Let's modify our `new_puzzle` method a bit, and demonstrate how a smart contract author might use base64-encoded arguments. In the previous chapter we had a fairly long NEAR CLI command that called the `new_puzzle`, providing it the parameters for all the clues. Having these lengthy parameters on the CLI might get cumbersome. There may be issues needing to escape single or double quotes, and each operating system may wish for a different format on the Terminal or Command Prompt. We're going to send all the arguments as a base64-encoded string, and make this a bit simpler. For this, we're going to use [`Base64VecU8` from the SDK](https://docs.rs/near-sdk/latest/near_sdk/json_types/struct.Base64VecU8.html). :::note `Base64VecU8` is great for binary payloads What we're doing makes sense, but it's worth noting that it's perhaps more common to use `Base64VecU8` when sending binary parameters. Read more [about it here](/sdk/rust/contract-interface/serialization-interface#base64vecu8). ::: First we'll set up a struct for the arguments we're expecting: <Github language="rust" start="111" end="117" url="https://github.com/near-examples/crossword-tutorial-chapter-3/blob/ec07e1e48285d31089b7e8cec9e9cf32a7e90c35/contract/src/lib.rs" /> Then we modify our `new_puzzle` method like so: <Github language="rust" start="290" end="297" url="https://github.com/near-examples/crossword-tutorial-chapter-3/blob/ec07e1e48285d31089b7e8cec9e9cf32a7e90c35/contract/src/lib.rs" /> We can take our original arguments and base64 encode them, using whatever method you prefer. There are plenty of online tool, Terminal commands, and open source applications like [Boop](https://boop.okat.best). We'll copy this: ```json { "answer_pk": "ed25519:7PkKPmVUXcupA5oU8d6TbgyMwzFe8tPV6eV1KGwgo9xg", "dimensions": { "x": 11, "y": 10 }, "answers": [ { "num": 1, "start": { "x": 0, "y": 1 }, "direction": "Across", "length": 12, "clue": "NEAR transactions are more ______ instead of atomic." }, { "num": 2, "start": { "x": 6, "y": 0 }, "direction": "Down", "length": 7, "clue": "In a smart contract, when performing an Action, you use this in Rust." }, { "num": 3, "start": { "x": 9, "y": 0 }, "direction": "Down", "length": 6, "clue": "In docs.rs when you search for the near-sdk crate, these items a considered a what: collections, env, json_types." }, { "num": 4, "start": { "x": 1, "y": 1 }, "direction": "Down", "length": 10, "clue": "A series of words that can deterministically generate a private key." }, { "num": 5, "start": { "x": 1, "y": 3 }, "direction": "Across", "length": 3, "clue": "When doing high-level cross-contract calls, we import this that ends in _contract. When calling ourselves in a callback, it is convention to call it THIS_self." }, { "num": 6, "start": { "x": 0, "y": 8 }, "direction": "Across", "length": 8, "clue": "Use this to determine the execution outcome of a cross-contract call or Action." }, { "num": 7, "start": { "x": 4, "y": 6 }, "direction": "Across", "length": 4, "clue": "You chain this syntax onto a promise in order to schedule a callback afterward." } ] } ``` and base64 encode it: <figure> <img src={base64Encode} alt="Animated gif of parameters getting base64 encoded with the program Boop" width="600"/> </figure> <br/> Now we can build and run the new crossword puzzle contract as we have before: ```bash ./build.sh export NEAR_ACCT=crossword.friend.testnet export PARENT_ACCT=friend.testnet near delete $NEAR_ACCT $PARENT_ACCT near create-account $NEAR_ACCT --masterAccount $PARENT_ACCT near deploy $NEAR_ACCT --wasmFile res/crossword_tutorial_chapter_3.wasm --initFunction new --initArgs '{"owner_id": "'$NEAR_ACCT'", "creator_account": "testnet"}' near call $NEAR_ACCT new_puzzle '{ "args": "ewogICJhbnN3ZXJfcGsiOiAiZWQyNTUxOTo3UGtLUG1WVVhjdXBBNW9VOGQ2VGJneU13ekZlOHRQVjZlVjFLR3dnbzl4ZyIsCiAgImRpbWVuc2lvbnMiOiB7CiAgICJ4IjogMTEsCiAgICJ5IjogMTAKICB9LAogICJhbnN3ZXJzIjogWwogICB7CiAgICAgIm51bSI6IDEsCiAgICAgInN0YXJ0IjogewogICAgICAgIngiOiAwLAogICAgICAgInkiOiAxCiAgICAgfSwKICAgICAiZGlyZWN0aW9uIjogIkFjcm9zcyIsCiAgICAgImxlbmd0aCI6IDEyLAogICAgICJjbHVlIjogIk5FQVIgdHJhbnNhY3Rpb25zIGFyZSBtb3JlIF9fX19fXyBpbnN0ZWFkIG9mIGF0b21pYy4iCiAgIH0sCiAgIHsKICAgICAibnVtIjogMiwKICAgICAic3RhcnQiOiB7CiAgICAgICAieCI6IDYsCiAgICAgICAieSI6IDAKICAgICB9LAogICAgICJkaXJlY3Rpb24iOiAiRG93biIsCiAgICAgImxlbmd0aCI6IDcsCiAgICAgImNsdWUiOiAiSW4gYSBzbWFydCBjb250cmFjdCwgd2hlbiBwZXJmb3JtaW5nIGFuIEFjdGlvbiwgeW91IHVzZSB0aGlzIGluIFJ1c3QuIgogICB9LAogICB7CiAgICAgIm51bSI6IDMsCiAgICAgInN0YXJ0IjogewogICAgICAgIngiOiA5LAogICAgICAgInkiOiAwCiAgICAgfSwKICAgICAiZGlyZWN0aW9uIjogIkRvd24iLAogICAgICJsZW5ndGgiOiA2LAogICAgICJjbHVlIjogIkluIGRvY3MucnMgd2hlbiB5b3Ugc2VhcmNoIGZvciB0aGUgbmVhci1zZGsgY3JhdGUsIHRoZXNlIGl0ZW1zIGEgY29uc2lkZXJlZCBhIHdoYXQ6IGNvbGxlY3Rpb25zLCBlbnYsIGpzb25fdHlwZXMuIgogICB9LAogICB7CiAgICAgIm51bSI6IDQsCiAgICAgInN0YXJ0IjogewogICAgICAgIngiOiAxLAogICAgICAgInkiOiAxCiAgICAgfSwKICAgICAiZGlyZWN0aW9uIjogIkRvd24iLAogICAgICJsZW5ndGgiOiAxMCwKICAgICAiY2x1ZSI6ICJBIHNlcmllcyBvZiB3b3JkcyB0aGF0IGNhbiBkZXRlcm1pbmlzdGljYWxseSBnZW5lcmF0ZSBhIHByaXZhdGUga2V5LiIKICAgfSwKICAgewogICAgICJudW0iOiA1LAogICAgICJzdGFydCI6IHsKICAgICAgICJ4IjogMSwKICAgICAgICJ5IjogMwogICAgIH0sCiAgICAgImRpcmVjdGlvbiI6ICJBY3Jvc3MiLAogICAgICJsZW5ndGgiOiAzLAogICAgICJjbHVlIjogIldoZW4gZG9pbmcgaGlnaC1sZXZlbCBjcm9zcy1jb250cmFjdCBjYWxscywgd2UgaW1wb3J0IHRoaXMgdGhhdCBlbmRzIGluIF9jb250cmFjdC4gV2hlbiBjYWxsaW5nIG91cnNlbHZlcyBpbiBhIGNhbGxiYWNrLCBpdCBpcyBjb252ZW50aW9uIHRvIGNhbGwgaXQgVEhJU19zZWxmLiIKICAgfSwKICAgewogICAgICJudW0iOiA2LAogICAgICJzdGFydCI6IHsKICAgICAgICJ4IjogMCwKICAgICAgICJ5IjogOAogICAgIH0sCiAgICAgImRpcmVjdGlvbiI6ICJBY3Jvc3MiLAogICAgICJsZW5ndGgiOiA4LAogICAgICJjbHVlIjogIlVzZSB0aGlzIHRvIGRldGVybWluZSB0aGUgZXhlY3V0aW9uIG91dGNvbWUgb2YgYSBjcm9zcy1jb250cmFjdCBjYWxsIG9yIEFjdGlvbi4iCiAgIH0sCiAgIHsKICAgICAibnVtIjogNywKICAgICAic3RhcnQiOiB7CiAgICAgICAieCI6IDQsCiAgICAgICAieSI6IDYKICAgICB9LAogICAgICJkaXJlY3Rpb24iOiAiQWNyb3NzIiwKICAgICAibGVuZ3RoIjogNCwKICAgICAiY2x1ZSI6ICJZb3UgY2hhaW4gdGhpcyBzeW50YXggb250byBhIHByb21pc2UgaW4gb3JkZXIgdG8gc2NoZWR1bGUgYSBjYWxsYmFjayBhZnRlcndhcmQuIgogICB9CiAgXQp9" }' --accountId $NEAR_ACCT ``` Back at the project root (not in the `contract` directory) we can run our app and see the new crossword puzzle: CONTRACT_NAME=crossword.friend.testnet npm run start ## Wrapping up Once you understand cross-contract calls and callbacks and where the logic should go, you can build just about anything on NEAR. This might be a good time for a reminder that this crossword puzzle, which checks permissions to methods based on a public key, is a bit unusual. It's more common to have simple collections or mappings for allowed users, or utilize the `owner_id` field we set up. The account and access key system in NEAR is quite powerful, and hopefully this tutorial helps stretch the limits of what's possible, like the seamless onboarding we have with the crossword puzzle. Again, the final code for this chapter: https://github.com/near-examples/crossword-tutorial-chapter-3 Happy hacking!
The NEAR Blockchain is Climate Neutral NEAR FOUNDATION March 10, 2021 – Guest Post by Yessin Schiegg The NEAR Blockchain is Climate Neutral. If you are concerned about climate change and the effect that blockchain is having on the earth, this text should open your eyes that the NEAR Protocol is the right choice to save the climate! The Dilemma Climate change is arguably the most critical global crisis facing humans today. From carbon dioxide (CO2) emissions warming the atmosphere, to rising sea levels and changing weather patterns, it is clear that human industries’ impact on earth is accelerating. While the technology sector is not generally cited as one of the top contributors to climate change, the increasingly widespread manufacturing of devices and related energy consumption has a major impact. In the blockchain space, energy consumption has become a point of focus for believers and skeptics alike, particularly as popularity and awareness have increased in the past six months. These debates generally begin with Bitcoin, the first blockchain with the highest market cap and greatest global awareness today. Bitcoin and PoW (Proof of work) Bitcoin is a proof-of-work (PoW) blockchain protocol in which miners prove that they extended a certain amount of computational effort before receiving the reward for a validated block. The PoW consensus mechanism is the heart of the blockchain energy debate. The computational effort of producing blocks is made by putting thousands of tons of mining gear at work. This equipment consumes high amounts of electricity during production, installation, and operation. The miners compete against each other for block rewards and tend to gear up as long the block reward is higher than their spending on gear and electricity; much of this computation energy is wasted in the race to earn the reward. The block reward is currently 6.25 BTC created by inflation and paid out approximately every 10 minutes. Energy consumed via PoW Depending on the electricity source, the PoW mining activity comes with a high carbon footprint, both because it is inefficient and because the global scale of Bitcoin mining now rivals the energy consumption of some nations. Some miners claim to operate climate neutral by employing hydro or nuclear power in running their mining rigs. However, due to the vast extent of electricity consumption, these energy sources take a considerable toll on the environment and come with long-term disposal issues (as do many other forms of computer hardware) too. Based on Digiconomist’s Energy Consumption Index, Bitcoin generates a whopping 37 million tons of CO2 emissions annually. Breaking this down to the 365 days per year and the approximately 330,000 transactions per day on the Bitcoin blockchain, a Bitcoin transaction generates about 0.3 tons of CO2 exhaust. That is the equivalent of the carbon footprint of a 1,600 km (or 1,000 mile) car ride on a car that consumes 8 liters of gas per 100km. You can also think about it as burning 130 liters of gasoline for just one Bitcoin transaction. If you transfer Bitcoin to an exchange, the exchange typically transfers your Bitcoin to a pool with another transaction on the blockchain. By that measure, there goes another 1,600km equivalent of CO2 exhaust. Now add a test transaction too, and in aggregate you caused the carbon footprint of a car ride from San Francisco to New York by pushing a few buttons. Ethereum and PoW (Proof of work) Ethereum, the second biggest blockchain by market cap, also runs on PoW consensus but has a considerably lower carbon footprint than Bitcoin. According to the Digiconomist’s Energy Consumption Index, Ethereum generates approximately 12 million tons of CO2 emissions annually, which is about a third of Bitcoin’s. Ethereum allows for about four times as many transactions per second vs. Bitcoin. Therefore, Ethereum transactions result in approximately 12 times lower carbon footprint than Bitcoin transactions. Unfortunately, that is still like burning 12 liters of gasoline per transaction or a carbon footprint of 27 kilograms of CO2 per transaction. Ethereum 2.0 and PoS (Proof of Stake) Ethereum is working on a network architecture upgrade to Ethereum 2.0 that will roll out over the next several years. By the time the final stage of the upgrade is complete, proof-of-stake (PoS) consensus will replace PoW to maintain the network. In PoS, there are no miners that prove a computational effort. Instead, validators put up a certain token amount as a stake to prove that they have skin in the game before they get to validate blocks and collect a block reward. The energy efficiency of PoS is orders of magnitude better than PoW and, unlike PoW, it doesn’t suffer from economies of scale, so validators are not incentivized to maximize their hardware footprint in the same way. While the Beacon chain, the so-called “heartbeat” chain at the core of Ethereum’s new architecture, has already launched, it will take at least a couple of years before users can build and transact on ETH 2.0. Ethereum 2.0 will not be the first PoS blockchain to go live. Several, including NEAR Protocol, are already running today. NEAR Protocol and PoS – the Greener Alternative The NEAR Protocol, launched in 2020, is a third-generation blockchain based on PoS, processes 1,000 transactions per second while running much more efficiently than PoW chains. This throughput will increase further with sharding, a blockchain scaling technology that divides computation across parallel “shards.” Developers find it easy to build on NEAR, and the toolset of the blockchain is growing very fast. Beyond just energy efficiency with PoS consensus, the NEAR Foundation has committed to making NEAR Protocol climate neutral this year. In February 2021, NEAR Protocol engaged South Pole, a leading project developer and global climate solutions provider headquartered in Zurich, Switzerland, to assess NEAR’s carbon footprint, reduce it where possible, and fully compensate the remaining exhaust with CO2 offsetting projects going forward. South pole considered the NEAR Foundation’s carbon footprint, the Core Collective (all employees and contractors working on the NEAR Protocol), and all validators in the assessment. The results show that the NEAR Protocol currently generates a carbon footprint of 174 tons of CO2 per year. Therefore, NEAR Protocol is more than 200,000 times more carbon efficient than Bitcoin, mainly by applying PoS instead of PoW. Another advantage of PoS is that the carbon footprint of NEAR will only marginally grow by the increasing transaction throughput. Compensating that footprint with reforestation projects makes the NEAR Blockchain carbon neutral. Doing transactions on NEAR plants trees in Colombia, Zimbabwe, and the United States via these carbon offsetting projects. Follow all the news on NEAR via our Twitter, or join our community via our Discord server.
--- id: near-cli-rs title: NEAR CLI RS --- # NEAR-CLI-RS ## Quick Start Guide The `near-cli-rs` tool is a human-friendly companion that helps you interact with the [NEAR Protocol](https://near.org/) from the command line. This has a guided prompt interface to help you make your own commands built in Rust. :::info note This is a separate tool from [near-cli](https://docs.near.org/tools/near-cli), a CLI tool of similar functionality without the guided prompts. ::: ## Install Download the pre-compiled version of `near-cli-rs` for your OS from [GitHub Releases Page](https://github.com/near/near-cli-rs/releases/) or install it with [Cargo](https://doc.rust-lang.org/cargo/) (Rust's package manager tool) with the following command: ``` $ cargo install near-cli-rs ``` ## Getting Started To utilize the commands that involve transactions, sending tokens, deploying contracts, etc., you'll have to store a full access key to a given account on your machine. Run... ``` near ``` Using the arrow keys navigate to... ``` account -Manage accounts ``` Navigate to... ``` import-account -Import existing account (a.k.a. "sign-in") ``` choose any of the preferred sign-in methods. For this example, we'll choose the... ``` using-web-wallet -Import existing account using NEAR Wallet (a.k.a. "sign in") ### Account - Gives you information on a specified account, near balance, storage, list of access keys, etc. ``` For this tutorial select `testnet` ``` What is the name of the network? mainnet >testnet shardnet ``` You'll get redirected to `wallet.testnet.near.org`. Once there, grant authorization. Then in your terminal, you'll be asked to enter your account ID. Give it the name of the account you just authorized access to and a full access key. If you're on Mac you'll have the option to use the [Mac Keychain](https://support.apple.com/guide/keychain-access/what-is-keychain-access-kyca1083/mac) option. Either storage option is fine. Using the legacy storage option will save a file in your root directory in a hidden folder called `./near-credentials`. This storage option is compatable with the `near-cli` tool (a cli tool without the guided prompts but similar functionality). **Good Job!** Now you can use `near-cli-rs` to it's full capacity. --- ## Usage To use the `near-cli-rs` simply run the following in your terminal. ```bash $ near ``` You should then see the following. Use the arrow keys and hit `enter` or simply type out one of the available options to select an option ![](/docs/assets/near-cli-rs.png) ### Accounts This option will allow you to manage, control, and retrieve information on your accounts. | Option | Description | | ---------------------- | ------------------------------------------ | | `view-account-summary` | View properties for an account | | `import-account` | Import existing account (a.k.a. "sign in") | | `create-account` | Create a new account | | `delete-account` | Delete an Account | | `list-keys` | View a list of keys for an account | | `add-key` | Add an access key to an account | | `delete-key` | Delete an access key from an account | ### Tokens This will allow you to manage your token assets such as NEAR, FTs and NFTs | Option | Description | | ------------------- | --------------------------------------------------------------------- | | `send-near` | Transfers NEAR to a specified recipient in units of NEAR or yoctoNEAR | | `send-ft` | Transfer Fungible Tokens to a specified user | | `send-nft` | Transfers NFTs between accounts | | `view-near-balance` | View the balance of NEAR tokens | | `view-ft-balance` | View the balance of Fungible Tokens | | `view-nft-assets` | View the balance of NFT Tokens | ### Contract This option allows you to manage and interact with your smart contracts | Option | Description | | --------------- | ----------------------- | | `call-function` | Execute Function | | `deploy` | Add a new contract code | | `download-wasm` | Download Wasm | ### Transaction Operate Transactions | Option | Description | | ---------------------- | --------------------------- | | `view-status` | View a transaction status | | `construct-tansaction` | Construct a new transaction | ### Config Manage the connection parameters inside the `config.toml` file for `near-cli-rs` This will allow you to change or modify the network connections for your CLI. | Option | Description | | ------------------- | ---------------------------------- | | `show-connections` | Show a list of network connections | | `add-connection` | Add a network connection | | `delete-connection` | Delete a network Connection | ---
# Events Format ## [NEP-297](https://github.com/near/NEPs/blob/master/neps/nep-0297.md) Version `1.0.0` ## Summary Events format is a standard interface for tracking contract activity. This document is a meta-part of other standards, such as [NEP-141](https://github.com/near/NEPs/issues/141) or [NEP-171](https://github.com/near/NEPs/discussions/171). ## Motivation Apps usually perform many similar actions. Each app may have its own way of performing these actions, introducing inconsistency in capturing these events. NEAR and third-party applications need to track these and similar events consistently. If not, tracking state across many apps becomes infeasible. Events address this issue, providing other applications with the needed standardized data. Initial discussion is [here](https://github.com/near/NEPs/issues/254). ## Events Many apps use different interfaces that represent the same action. This interface standardizes that process by introducing event logs. Events use the standard logs capability of NEAR. Events are log entries that start with the `EVENT_JSON:` prefix followed by a single valid JSON string. JSON string may have any number of space characters in the beginning, the middle, or the end of the string. It's guaranteed that space characters do not break its parsing. All the examples below are pretty-formatted for better readability. JSON string should have the following interface: ```ts // Interface to capture data about an event // Arguments // * `standard`: name of standard, e.g. nep171 // * `version`: e.g. 1.0.0 // * `event`: type of the event, e.g. nft_mint // * `data`: associate event data. Strictly typed for each set {standard, version, event} inside corresponding NEP interface EventLogData { standard: string, version: string, event: string, data?: unknown, } ``` Thus, to emit an event, you only need to log a string following the rules above. Here is a barebones example using Rust SDK `near_sdk::log!` macro (security note: prefer using `serde_json` or alternatives to serialize the JSON string to avoid potential injections and corrupted events): ```rust use near_sdk::log; // ... log!( r#"EVENT_JSON:{"standard": "nepXXX", "version": "1.0.0", "event": "YYY", "data": {"token_id": "{}"}}"#, token_id ); // ... ``` #### Valid event logs: ```js EVENT_JSON:{ "standard": "nepXXX", "version": "1.0.0", "event": "xyz_is_triggered" } ``` ```js EVENT_JSON:{ "standard": "nepXXX", "version": "1.0.0", "event": "xyz_is_triggered", "data": { "triggered_by": "foundation.near" } } ``` #### Invalid event logs: * Two events in a single log entry (instead, call `log` for each individual event) ```js EVENT_JSON:{ "standard": "nepXXX", "version": "1.0.0", "event": "abc_is_triggered" } EVENT_JSON:{ "standard": "nepXXX", "version": "1.0.0", "event": "xyz_is_triggered" } ``` * Invalid JSON data ```js EVENT_JSON:invalid json ``` * Missing required fields `standard`, `version` or `event` ```js EVENT_JSON:{ "standard": "nepXXX", "event": "xyz_is_triggered", "data": { "triggered_by": "foundation.near" } } ``` ## Drawbacks There is a known limitation of 16kb strings when capturing logs. This impacts the amount of events that can be processed.
Why Web3 is Needed More than Ever NEAR FOUNDATION July 28, 2022 The world is literally on fire. Europe, Asia and parts of America have all experienced record temperatures this summer, causing wildfires and devastation. The world economy too, is running hotter than anytime in living memory. War wages in Europe, inflation continues to climb, energy supplies are dwindling, and food shortages are becoming the norm. Last, but certainly not least, civil rights are in retreat. Women’s autonomy is under threat–half the world’s female population lack the ability to make choices about their own bodies–and democracy has been in decline in every continent for over a decade. The outlook for humanity is grim. But amidst this backdrop represents a unique opportunity. An opportunity for Web3 to step forward and help re-imagine the world as we know it. A broken system needs a new way of thinking Crypto was born out of a crisis. When the Bitcoin whitepaper was released in 2008, the world was in the midst a recession the International Monetary Fund described as the most severe economic and financial meltdown since the Great Depression. While the world has moved on, the issues that caused the depression still remain. The financial system that underpins this world has maintained its monopoly. The world’s global elite exert more control than ever. Governments have been ‘too slow’ in tackling the existential threat posed by climate change. And marginalised communities struggle to have their voices heard at a local and global level. While there is no silver bullet to these issues, there are solutions, many of them being worked on in the Web3 space. But they are in their early stages, and need help. They need talent, money and voices from all walks of life to take part in shaping how this technology works. Web3 was designed as an antithesis to what came before. At its heart is a vision to decentralise power and control, and help level the playing field when it comes to inclusion and participation. But those ideas are fragile, and need protecting. It’s one of the reasons I joined NEAR, and why I believe this project can contribute to this change. One part of the puzzle The technology that sits beneath NEAR is revolutionary. It has managed to find a working solution to the blockchain trilemma, creating a blockchain that is secure, scalable and decentralized. It’s also sustainable, achieving climate neutral status for two years in a row. Built on top of that are more than 700 diverse projects from across the world. From education projects in Africa, to humanitarian aid projects in Europe and conservation projects in Latin America. Alongside these projects, there is critical work being carried out to reimagine and repurpose what we mean when we talk about ownership, community and incentive. Projects like Brave, Youminter, NEARPay and Tamago are rethinking what ownership means beyond the Web2 world of middlemen and rent seekers. The NEAR Hubs program is bringing empowerment and inclusion to regions historically overlooked when new technologies are in their nascent stages. Last, but not least, projects like Sweatcoin, and Open Forest Protocol are radically rethinking how to incentivise people to make changes in their lives for the benefit of everyone else’s. But NEAR is just one piece of this puzzle. We believe that in order for change to happen, we need more voices, more ideas, more radical thinking to help take on threats to our very existence. Now is the time to build. Now is the time for change. If you want to learn more about NEAR, come and see us at NEARCON, or attend one of our regional events, or join our community.
# Storage Management ## [NEP-145](https://github.com/near/NEPs/blob/master/neps/nep-0145.md) Version `1.0.0` NEAR uses [storage staking] which means that a contract account must have sufficient balance to cover all storage added over time. This standard provides a uniform way to pass storage costs onto users. It allows accounts and contracts to: 1. Check an account's storage balance. 2. Determine the minimum storage needed to add account information such that the account can interact as expected with a contract. 3. Add storage balance for an account; either one's own or another. 4. Withdraw some storage deposit by removing associated account data from the contract and then making a call to remove unused deposit. 5. Unregister an account to recover full storage balance. [storage staking]: https://docs.near.org/concepts/storage/storage-staking Prior art: - A previous fungible token standard ([NEP-21](https://github.com/near/NEPs/pull/21)) highlighting how [storage was paid](https://github.com/near/near-sdk-rs/blob/1d3535bd131b68f97a216e643ad1cba19e16dddf/examples/fungible-token/src/lib.rs#L92-L113) for when increasing the allowance of an escrow system. ## Example scenarios To show the flexibility and power of this standard, let's walk through two example contracts. 1. A simple Fungible Token contract which uses Storage Management in "registration only" mode, where the contract only adds storage on a user's first interaction. 1. Account registers self 2. Account registers another 3. Unnecessary attempt to re-register 4. Force-closure of account 5. Graceful closure of account 2. A social media contract, where users can add more data to the contract over time. 1. Account registers self with more than minimum required 2. Unnecessary attempt to re-register using `registration_only` param 3. Attempting to take action which exceeds paid-for storage; increasing storage deposit 4. Removing storage and reclaiming excess deposit ### Example 1: Fungible Token Contract Imagine a [fungible token](Tokens/FungibleToken/Core.md) contract deployed at `ft`. Let's say this contract saves all user balances to a Map data structure internally, and adding a key for a new user requires 0.00235Ⓝ. This contract therefore uses the Storage Management standard to pass this cost onto users, so that a new user must effectively pay a registration fee to interact with this contract of 0.00235Ⓝ, or 2350000000000000000000 yoctoⓃ ([yocto](https://www.metricconversion.us/prefixes.htm) = 10<sup>-24</sup>). For this contract, `storage_balance_bounds` will be: ```json { "min": "2350000000000000000000", "max": "2350000000000000000000" } ``` This means a user must deposit 0.00235Ⓝ to interact with this contract, and that attempts to deposit more than this will have no effect (attached deposits will be immediately refunded). Let's follow two users, Alice with account `alice` and Bob with account `bob`, as they interact with `ft` through the following scenarios: 1. Alice registers herself 2. Alice registers Bob 3. Alice tries to register Bob again 4. Alice force-closes her account 5. Bob gracefully closes his account #### 1. Account pays own registration fee **High-level explanation** 1. Alice checks if she is registered with the `ft` contract. 2. Alice determines the needed registration fee to register with the `ft` contract. 3. Alice issues a transaction to deposit Ⓝ for her account. **Technical calls** 1. Alice queries a view-only method to determine if she already has storage on this contract with `ft::storage_balance_of({"account_id": "alice"})`. Using [NEAR CLI](https://docs.near.org/tools/near-cli) to make this view call, the command would be: near view ft storage_balance_of '{"account_id": "alice"}' The response: null 2. Alice uses [NEAR CLI](https://docs.near.org/docs/tools/near-cli) to make a view call. near view ft storage_balance_bounds As mentioned above, this will show that both `min` and `max` are both 2350000000000000000000 yoctoⓃ. 3. Alice converts this yoctoⓃ amount to 0.00235 Ⓝ, then calls `ft::storage_deposit` with this attached deposit. Using NEAR CLI: near call ft storage_deposit '' \ --accountId alice --amount 0.00235 The result: { total: "2350000000000000000000", available: "0" } #### 2. Account pays for another account's storage Alice wishes to eventually send `ft` tokens to Bob who is not registered. She decides to pay for Bob's storage. **High-level explanation** Alice issues a transaction to deposit Ⓝ for Bob's account. **Technical calls** Alice calls `ft::storage_deposit({"account_id": "bob"})` with the attached deposit of '0.00235'. Using NEAR CLI the command would be: near call ft storage_deposit '{"account_id": "bob"}' \ --accountId alice --amount 0.00235 The result: { total: "2350000000000000000000", available: "0" } #### 3. Unnecessary attempt to register already-registered account Alice accidentally makes the same call again, and even misses a leading zero in her deposit amount. near call ft storage_deposit '{"account_id": "bob"}' \ --accountId alice --amount 0.0235 The result: { total: "2350000000000000000000", available: "0" } Additionally, Alice will be refunded the 0.0235Ⓝ she attached, because the `storage_deposit_bounds.max` specifies that Bob's account cannot have a total balance larger than 0.00235Ⓝ. #### 4. Account force-closes registration Alice decides she doesn't care about her `ft` tokens and wants to forcibly recover her registration fee. If the contract permits this operation, her remaining `ft` tokens will either be burned or transferred to another account, which she may or may not have the ability to specify prior to force-closing. **High-level explanation** Alice issues a transaction to unregister her account and recover the Ⓝ from her registration fee. She must attach 1 yoctoⓃ, expressed in Ⓝ as `.000000000000000000000001`. **Technical calls** Alice calls `ft::storage_unregister({"force": true})` with a 1 yoctoⓃ deposit. Using NEAR CLI the command would be: near call ft storage_unregister '{ "force": true }' \ --accountId alice --depositYocto 1 The result: true #### 5. Account gracefully closes registration Bob wants to close his account, but has a non-zero balance of `ft` tokens. **High-level explanation** 1. Bob tries to gracefully close his account, calling `storage_unregister()` without specifying `force=true`. This results in an intelligible error that tells him why his account can't yet be unregistered gracefully. 2. Bob sends all of his `ft` tokens to a friend. 3. Bob retries to gracefully close his account. It works. **Technical calls** 1. Bob calls `ft::storage_unregister()` with a 1 yoctoⓃ deposit. Using NEAR CLI the command would be: near call ft storage_unregister '' \ --accountId bob --depositYocto 1 It fails with a message like "Cannot gracefully close account with positive remaining balance; bob has balance N" 2. Bob transfers his tokens to a friend using `ft_transfer` from the [Fungible Token Core](Tokens/FungibleToken/Core.md) standard. 3. Bob tries the call from Step 1 again. It works. ### Example 2: Social Media Contract Imagine a social media smart contract which passes storage costs onto users for posts and follower data. Let's say this this contract is deployed at account `social`. Like the Fungible Token contract example above, the `storage_balance_bounds.min` is 0.00235, because this contract will likewise add a newly-registered user to an internal Map. However, this contract sets no `storage_balance_bounds.max`, since users can add more data to the contract over time and must cover the cost for this storage. So for this contract, `storage_balance_bounds` will return: ```json { "min": "2350000000000000000000", "max": null } ``` Let's follow a user, Alice with account `alice`, as she interacts with `social` through the following scenarios: 1. Registration 2. Unnecessary attempt to re-register using `registration_only` param 3. Attempting to take action which exceeds paid-for storage; increasing storage deposit 4. Removing storage and reclaiming excess deposit #### 1. Account registers with `social` **High-level explanation** Alice issues a transaction to deposit Ⓝ for her account. While the `storage_balance_bounds.min` for this contract is 0.00235Ⓝ, the frontend she uses suggests adding 0.1Ⓝ, so that she can immediately start adding data to the app, rather than *only* registering. **Technical calls** Using NEAR CLI: near call social storage_deposit '' \ --accountId alice --amount 0.1 The result: { total: '100000000000000000000000', available: '97650000000000000000000' } Here we see that she has deposited 0.1Ⓝ and that 0.00235 of it has been used to register her account, and is therefore locked by the contract. The rest is available to facilitate interaction with the contract, but could also be withdrawn by Alice by using `storage_withdraw`. #### 2. Unnecessary attempt to re-register using `registration_only` param **High-level explanation** Alice can't remember if she already registered and re-sends the call, using the `registration_only` param to ensure she doesn't attach another 0.1Ⓝ. **Technical calls** Using NEAR CLI: near call social storage_deposit '{"registration_only": true}' \ --accountId alice --amount 0.1 The result: { total: '100000000000000000000000', available: '97650000000000000000000' } Additionally, Alice will be refunded the extra 0.1Ⓝ that she just attached. This makes it easy for other contracts to always attempt to register users while performing batch transactions without worrying about errors or lost deposits. Note that if Alice had not included `registration_only`, she would have ended up with a `total` of 0.2Ⓝ. #### 3. Account increases storage deposit Assumption: `social` has a `post` function which allows creating a new post with free-form text. Alice has used almost all of her available storage balance. She attempts to call `post` with a large amount of text, and the transaction aborts because she needs to pay for more storage first. Note that applications will probably want to avoid this situation in the first place by prompting users to top up storage deposits sufficiently before available balance runs out. **High-level explanation** 1. Alice issues a transaction, let's say `social.post`, and it fails with an intelligible error message to tell her that she has an insufficient storage balance to cover the cost of the operation 2. Alice issues a transaction to increase her storage balance 3. Alice retries the initial transaction and it succeeds **Technical calls** 1. This is outside the scope of this spec, but let's say Alice calls `near call social post '{ "text": "very long message" }'`, and that this fails with a message saying something like "Insufficient storage deposit for transaction. Please call `storage_deposit` and attach at least 0.1 NEAR, then try again." 2. Alice deposits the proper amount in a transaction by calling `social::storage_deposit` with the attached deposit of '0.1'. Using NEAR CLI: near call social storage_deposit '' \ --accountId alice --amount 0.1 The result: { total: '200000000000000000000000', available: '100100000000000000000000' } 3. Alice tries the initial `near call social post` call again. It works. #### 4. Removing storage and reclaiming excess deposit Assumption: Alice has more deposited than she is using. **High-level explanation** 1. Alice views her storage balance and sees that she has extra. 2. Alice withdraws her excess deposit. **Technical calls** 1. Alice queries `social::storage_balance_of({ "account_id": "alice" })`. With NEAR CLI: near view social storage_balance_of '{"account_id": "alice"}' Response: { total: '200000000000000000000000', available: '100100000000000000000000' } 2. Alice calls `storage_withdraw` with a 1 yoctoⓃ deposit. NEAR CLI command: near call social storage_withdraw \ '{"amount": "100100000000000000000000"}' \ --accountId alice --depositYocto 1 Result: { total: '200000000000000000000000', available: '0' } ## Reference-level explanation **NOTES**: - All amounts, balances and allowance are limited by `U128` (max value 2<sup>128</sup> - 1). - This storage standard uses JSON for serialization of arguments and results. - Amounts in arguments and results are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of 2<sup>53</sup>. - To prevent the deployed contract from being modified or deleted, it should not have any access keys on its account. **Interface**: ```ts // The structure that will be returned for the methods: // * `storage_deposit` // * `storage_withdraw` // * `storage_balance_of` // The `total` and `available` values are string representations of unsigned // 128-bit integers showing the balance of a specific account in yoctoⓃ. type StorageBalance = { total: string; available: string; } // The below structure will be returned for the method `storage_balance_bounds`. // Both `min` and `max` are string representations of unsigned 128-bit integers. // // `min` is the amount of tokens required to start using this contract at all // (eg to register with the contract). If a new contract user attaches `min` // NEAR to a `storage_deposit` call, subsequent calls to `storage_balance_of` // for this user must show their `total` equal to `min` and `available=0` . // // A contract may implement `max` equal to `min` if it only charges for initial // registration, and does not adjust per-user storage over time. A contract // which implements `max` must refund deposits that would increase a user's // storage balance beyond this amount. type StorageBalanceBounds = { min: string; max: string|null; } /************************************/ /* CHANGE METHODS on fungible token */ /************************************/ // Payable method that receives an attached deposit of Ⓝ for a given account. // // If `account_id` is omitted, the deposit MUST go toward predecessor account. // If provided, deposit MUST go toward this account. If invalid, contract MUST // panic. // // If `registration_only=true`, contract MUST refund above the minimum balance // if the account wasn't registered and refund full deposit if already // registered. // // The `storage_balance_of.total` + `attached_deposit` in excess of // `storage_balance_bounds.max` must be refunded to predecessor account. // // Returns the StorageBalance structure showing updated balances. function storage_deposit( account_id: string|null, registration_only: boolean|null ): StorageBalance {} // Withdraw specified amount of available Ⓝ for predecessor account. // // This method is safe to call. It MUST NOT remove data. // // `amount` is sent as a string representing an unsigned 128-bit integer. If // omitted, contract MUST refund full `available` balance. If `amount` exceeds // predecessor account's available balance, contract MUST panic. // // If predecessor account not registered, contract MUST panic. // // MUST require exactly 1 yoctoNEAR attached balance to prevent restricted // function-call access-key call (UX wallet security) // // Returns the StorageBalance structure showing updated balances. function storage_withdraw(amount: string|null): StorageBalance {} // Unregisters the predecessor account and returns the storage NEAR deposit. // // If the predecessor account is not registered, the function MUST return // `false` without panic. // // If `force=true` the function SHOULD ignore existing account data, such as // non-zero balances on an FT contract (that is, it should burn such balances), // and close the account. Contract MAY panic if it doesn't support forced // unregistration, or if it can't force unregister for the particular situation // (example: too much data to delete at once). // // If `force=false` or `force` is omitted, the contract MUST panic if caller // has existing account data, such as a positive registered balance (eg token // holdings). // // MUST require exactly 1 yoctoNEAR attached balance to prevent restricted // function-call access-key call (UX wallet security) // // Returns `true` iff the account was successfully unregistered. // Returns `false` iff account was not registered before. function storage_unregister(force: boolean|null): boolean {} /****************/ /* VIEW METHODS */ /****************/ // Returns minimum and maximum allowed balance amounts to interact with this // contract. See StorageBalanceBounds. function storage_balance_bounds(): StorageBalanceBounds {} // Returns the StorageBalance structure of the valid `account_id` // provided. Must panic if `account_id` is invalid. // // If `account_id` is not registered, must return `null`. function storage_balance_of(account_id: string): StorageBalance|null {} ``` ## Drawbacks - The idea may confuse contract developers at first until they understand how a system with storage staking works. - Some folks in the community would rather see the storage deposit only done for the sender. That is, that no one else should be able to add storage for another user. This stance wasn't adopted in this standard, but others may have similar concerns in the future. ## Future possibilities - Ideally, contracts will update available balance for all accounts every time the NEAR blockchain's configured storage-cost-per-byte is reduced. That they *must* do so is not enforced by this current standard.
NEAR Foundation PR Roundup for April NEAR FOUNDATION May 2, 2023 As April draws to a close, we wanted to share the top global headlines from the NEAR Foundation and ecosystem this month. Let’s take a look at some of the biggest stories from NEAR in February. NEAR Foundation launches NEAR Horizon The NEAR Foundation attracted over 81 pieces of global coverage this month. One of April’s top stories was the NEAR Foundation’s launch of NEAR Horizon at Consensus 2023, a revolutionary accelerator supporting founders with open-access resources and incubator programmes from partners Dragonfly, Pantera and more. As covered by Coindesk, Horizon will enable the NEAR ecosystem to continue to build projects through the crypto winter, utilizing the dedicated marketplace to access over 15 service providers, 40 mentors and 300 backers. Illia Polosukhin talks building in a bear market Illia Polosukhin took to the stage at Consensus 2023, contributing to a Coindesk panel focused on BUIDLing in a bear market, stressing the crucial role of collaboration as Web3 strives to onboard Web2 users. Developers have created advanced and exciting infrastructure solutions, but now need to add a focus on delivering projects to the market, realising the potential of blockchain technology. Consensus 2023 also hosted the full launch of the BOS (Blockchain Operating System), providing users and developers with a one-stop-shop for interacting with any blockchain. As reported by Bloomberg, the open source platform enables builders to utilise thousands of community components to expedite the blockchain development process, at no cost to the developer or end user. NEAR Foundation announces the return of Women in Web3 Changemakers Following a successful launch last year, the NEAR Foundation announced the return of the Women in Web3 Changemakers list. The initiative, as covered by CryptoTVPlus, champions the achievements of female leaders from across the Web3 industry and aims to inspire higher rates of diversity in a field where women are severely underrepresented. Nominations are now open – submit your female colleagues here. Marieke Flament talks Web3 talent and leadership with BTC Echo Marieke Flament sat down for an exclusive interview with BTC Echo, Germany’s major crypto publication to talk about talent, leadership and more . In the profile piece, she explained how ​​the NEAR Foundation is moving away from supporting the blockchain rat race and helping NEAR protocol pivot to become a blockchain operation system. “We are at a major turning point,” she told the editor, and explained why working for NEAR Foundation is so special. “The community is inclusive. People come from all over the world. You can ask them any question and they will explain it in simple terms. It’s a safe space.” Cosmose AI’s switch to NEAR featured in TechCrunch Cosmose AI joined the NEAR ecosystem this month, leveraging Web3 innovations to ensure that users maintain complete control over data and privacy. Featured in TechCrunch, Cosmose AI’s recent funding round led by the NEAR Foundation will also enable the continued development of KaiChing, an in-house cryptocurrency leveraging NEAR to reduce payment processing times and significantly lower fees. NEAR Foundation at Women in Payments Symposium in London The Women in Payments Symposium took place in London during April, where Marieke Flament presented the closing keynote discussing the opportunity presented to Web3 by the recent banking woes in the USA and Europe. As covered by CityAM and TechFundingNews, Marieke spoke to attendees about the potential of DeFi and the need for a clear regulatory landscape, whilst highlighting the potential for partnerships between traditional finance and decentralised finance. Google Cloud and NEAR Foundation partnership featured in Cointelegraph Google Cloud announced a special initiative for Web3 startups, bringing blockchain-based projects into the fold and providing relevant technical tools and cloud services to series A companies. Cointelegraph covered the increased support for founders building in Web3, as Google partnered with the NEAR Foundation and other blockchains to provide scalable infrastructure to founders across the globe. Hackernoon calls BOS the “universal remote for crypto” Bringing April to a close, Hackernoon took a shine to NEAR’s Blockchain Operating System, comparing the BOS to a universal remote for crypto, enabling users to use the same wallet over different blockchains and decentralised applications. The Web3-focused publication is excited by the BOS’s replacement of centralised infrastructure and groundbreaking support for forkable developer components, likening the BOS to the early days of IOS and Android. That’s all for this month. If we missed anything out or want to share anything for next month’s roundup, get in touch!
Minting Minecraft Blueprints As NFTs DEVELOPERS December 9, 2021 Most of the time, when you hear people talking about non-fungible tokens (NFTs), your first thoughts may turn to media files such as images or music. But, actually, NFTs are not limited to such file types. In this article, you’ll discover how the DevRel team created non-fungible tokens based on Minecraft buildings designed inside the game. Blockheads Creative possibilities are endless thanks to the new developments and technologies rising in the crypto space. For example, Dorian (a member of Near Inc. DevRel team) runs a YouTube series called Blockheads, where he creates fun examples of things you can build on NEAR. He’s also fond of the world of Minecraft, especially during quarantine. After learning about NFTs, Dorian thought it would be fun to give Minecraft artists and builders the ability to mint their buildings and creations as NFTs and sell them on the open web. So, using the Mineflayer JavaScript library, he created a bot that could monitor the in-game chat and pull information about the game’s environment. Then, using that bot, he created blueprints that a user could then mint onto the NEAR blockchain. The following video shows the bot named Jerry in action: Minting Minecraft with NEAR The app grew and took shape. Finally, Ben Kurrek from Near Inc. DevRel had the great idea of using the popular World Edit mod to get the building data and store it in a .schem file. This file then gets uploaded to IPFS for storage, and the content identifier (CID) is saved to the NEAR blockchain itself. The flow is smooth, and .schem files capture the building designs more accurately than Jerry could on his own. If you’re interested in seeing how the complete flow works in minting a Minecraft building, check out the NFTs tutorial Ben created. It’s simple, fun, and very straightforward (of course, if you have questions, you can ask us during Office Hours). As it currently stands, getting Jerry to read .schem files has been tricky since they aren’t a conventional file type that JavaScript (Jerry’s preferred language of choice) can understand right out of the box. But progress is still being made. So if you would like to join Dorian on this endeavor to make Minecraft NFTs on NEAR, you can contact him on Discord.
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="Paras" label="Paras" default> ```bash near call x.paras.near buy '{"token_series_id": "299102", "receiver_id": "bob.near"}' --accountId bob.near --deposit 0.20574 ``` **Example response:** ```json "299102:1" ``` </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```bash near call simple.market.mintbase1.near buy '{"nft_contract_id": "rubennnnnnnn.mintbase1.near", "token_id": "38"}' --accountId bob.near --deposit 0.001 ``` **Example response:** ```json { "payout": { "rub3n.near": "889200000000000000000", "rubenm4rcus.near": "85800000000000000000" } } ``` </TabItem> </Tabs>
Highlights from NEAR at Paris Blockchain Week Summit COMMUNITY April 20, 2022 Hello, NEAR world. The global Web3 community rolled into France on April 12-14 for the Paris Blockchain Week Summit. Several key NEAR figures were there to take attendees on a tour of the major happenings in NEAR’s thriving ecosystem. PBWS is the flagship event of Paris Blockchain Week. Over two days, more than 3,000 attendees, 70 sponsors, 250 speakers, and 100 media partners hosted sessions on Web3 innovation, governance, international regulatory cooperation, and more. NEAR Foundation hosted a number of talks at PBWS from ecosystem figures, as well as a meetup with partner Atka. These events showcased NEAR’s simple, secure and scalable protocol, and its vibrant ecosystem of developers building decentralized apps. If you weren’t able to make it IRL, worry not. We’ve got highlights from NEAR at PBWS. April 12 — NEAR-Atka Meetup, Keynotes and ‘Building on NEAR’ Panel Day 1 of PBWS began in the evening with the NEAR-Atka meetup at Palais Brongniart. Attendees mingled and networked over champagne and food. NEAR Foundation CEO Marieke Flament kicked the Keynotes event off with opening remarks and an introduction of the NEAR ecosystem. Florian Le Goff, Founder of Synaps, followed Marieke with a talk on Amina, a newly-launched decentralized identity platform, built on NEAR. NEAR Co-founder Illia Polosukhin then updated the audience on NEAR infrastructure and what’s next, including details on protocol security and enterprise solutions. Following Polosukhin’s talk, Anton Vaisburd, general manager of NEAR’s Regional Hub in Ukraine took to the stage. The Ukraine Regional Hub is part of NEAR Foundation’s mission to create a network of thriving regional hubs. These NEAR hubs are places for community members to meet up, learn, and create. The Ukraine hub is a resource for efforts like Unchain Fund, a charity project that has raised nearly $10 million for humanitarian efforts in Ukraine. Day 1 wrapped up with the 90-minute panel “Building on NEAR”. Moderated by Atka’s William Piquard, the panel featured Didier Pironi (Ref Finance), Anton Paisov (Aurora), Jon Werthen (Founder and COO, ARterra Labs), Jasper De Gooijer (Flux Protocol), and Nadim Kobeissi (Capsule Social). “Building on NEAR” focused on developing decentralized apps on the NEAR protocol. Notably, Werthen shared his thoughts on esports on the blockchain. He said it’s imperative to make “Web3 [esports] applications feel like something people are already used to in Web2” apps. April 13 – NEAR Keynote On Day 2, NEAR Foundation CEO Marieke Flament gave a keynote address on the Paris Blockchain Week Summit Discovery Stage. She talked about access, movement, and the diversity of distinct apps and economies set to emerge in the near future. “What is NEAR? A world where people control their assets, data, and power of governance,” said Flament. “An open web world.” Flament then highlighted NEAR’s simple, infinitely scalable (thanks to Nightshade sharding), and secure next generation platform for dapps—one that is climate neutral. On NEAR there is more open access—the individual is empowered while gatekeepers are eliminated. Flament pointed to YouMinter, a decentralized social media app for iOS and Android, where creators can mint and post NFTs. Think of it as an alternative to Instagram, where creators can easily sell their work, instead of handing over data to centralized platforms for free. Flament pointed to NEAR Foundation’s partnerships with SailGP and Orange DAO as proof that DAOs are helping to power new economies through community-based decision-making. She also shared special news from the NEAR Ecosystem. London-based tech company Sweatcoin partnered with NEAR Foundation to create a new movement economy. Sweatcoin is on a mission to inspire a healthier planet by incentivizing people to move more. The NEAR-Sweatcoin partnership brings with it SWEAT, a radical new token that is minted purely by steps. “One of NEAR’s core missions is to help onboard the world to Web3, collaborating with SweatCoin allows us to take a step closer to that mission.” said Flament. Flament was joined on stage by Sweatcoin co-founder Oleg Fomenko, who shared his vision for a world where people have better control of their data, but can also be rewarded for taking steps to reduce their carbon footprint. April 14 – Interactive Roundtable On the final day of Paris Blockchain Week Summit, Flament led the “Interactive Roundtable: Pioneering the Future of DAOs”. Panelists included NEAR Co-founder Polosukhin, SailGP’s Charlie Dewhurst and Paraswap’s Founder, Mounir Benchelemb. Polosukhin is well-known for his love of DAOs. He said that a DAO is essentially an experiment with something, often real world problems, between a community and a company. With the DAO behind Unchain Fund, of which Polosukhin is a member, that meant getting funds and resources to Ukrainians who needed it. “In our case, time was of the essence,” said Polosukhin. “You can start a DAO in 5 minutes whereas starting a nonprofit would be more like 5 months or even 5 years.” “We are building NEAR to lower the barrier to entry for mainstream users,” he said. “Right now, DAOs are beyond regulation territory but we live in the physical world and understand how these new organizations will map. We need to figure out how DAOs can interact with the traditional world. Also, security and making users feel safe using this technology.” Dewhurst’s appearance came hot on the heels of NEAR Foundation’s partnership with SailGP, which will include the sale of a new sailing team to a NEAR-based DAO. This could revolutionize team ownership but also fan access to and interaction with teams and athletes. “A new generation of fans recognize how much of a role they have in shaping a brand or a product,” said Dewhurst. “It’s a lot less top down. Influencers are this whole new category and they’re engaging directly. There is a lot less distance between a brand and its users or customers. That’s also central to Web3 and has been since the beginning.” Paraswap’s Benchelemb emphasized that DAOs offer individual members a way to contribute through a crypto bank account, established processes, tooling for offline groups to increase online capabilities, and more. “[DAOs] give more people a voice without limitations like background, jurisdiction, social ties, level of access,” he said. As Benchelemb sees it, the major challenge facing mainstream adoption is the complexity of DAO tooling for non-crypto natives. One solution he offered is simplifying onboarding. In Amsterdam on April 21st? Visit NEAR @ DevConnect for a full day of in-depth NEAR sessions aimed at building a multi-chain, open web future. Register to attend NEAR @ DevConnect in-person here, or tune in via the Metaverse LiveStream.
NEAR 2021: A Year in Review NEAR FOUNDATION December 28, 2021 Welcome to the NEAR Retrospective! It’s been quite a year for NEAR Foundation, Near Inc., and, of course, all the incredible projects and community members that make all of this possible. So we thought it was high time to look back at some of the highlights from 2021: everything from protocol upgrades, ecosystem funding, community developments, and new projects launching on NEAR mainnet. We’ll also be giving a sneak peek at what’s to come in 2022 in a separate post, so keep a lookout for that. Protocol Progress The sign of a healthy network is one that is constantly adding improvements and tweaks to the performance, stability, and security—and NEAR protocol had that in abundance in 2021. Near Inc.’s engineering team racked up 20 upgrades to the protocol. Among the highlights were protocol update 35 – implicit accounts. This allows NEAR to have Ethereum style accounts that are public keys. They are created on-chain when someone transfers a nonzero amount of tokens to this account. Another stand-out upgrade was protocol update 42. Here engineers lowered storage staking cost from 1N per 10kb to 1N per 100kb. This dramatically reduced the barrier of entry for contract developers. Before this change, when a developer deployed a 300kb contract, they needed to have at least 30 $NEAR on the account. After the change, they only need 3 $NEAR. Lastly, not leastly, protocol upgrade 48 brought our WebAssembly runtime from wasmer0 to wasmer2. This shift helped half the cost of wasm operations, helping unlock many applications building on Aurora that were previously blocked because their transactions could not fit in NEAR’s gas limit. This trend continued throughout the year, culminating in our biggest protocol announcement this year, Sharding. Sharding Takes Shape When NEAR released its design for the protocol back in 2019, we initially envisioned a completely sharded blockchain. We quickly realized that this brand new network didn’t have an immediate demand for processing hundreds of millions of transactions. Besides, a fully sharded blockchain is a complex endeavor, and we’d need a little time to do it right. However, the average number of daily transactions has now surpassed 300K. As more and more projects are building on NEAR, the volume of transactions is only going to increase dramatically in 2022. While the NEAR network is still only using a fraction of its total capacity, we wanted to start the transition to sharding now to avoid any unpleasant surprises, as well as ensure we can support all applications on NEAR. November 15th marked the beginning of this transition, as we unveiled Simple Nightshade, the first step (Phase 0) in our fully-sharded and secure blockchain. We dropped Simple Nightshade now so that we could preempt any unpleasant surprises with transaction speeds later. In Phase 0 of Nightshade, NEAR’s sharding is split across many nodes, making it super fast and ready for the onboarding of leagues of new developers and blockchain users. In early 2022, NEAR will move into Nightshade Phase 1, in which we will introduce the new role of chunk-only producers—those who only validate one shard. They produce chunks (shard blocks) for a specific shard and don’t need expensive hardware to do so—all without sacrificing network security. In Phase 2, currently scheduled for Q3 of 2022, both state and processing will be fully sharded, and validators won’t need to track all shards. And in Q4 of 2022, we will enter Phase 3 (Dynamic Sharding), in which we will enable the network to dynamically split and merge shards based on resource utilization. This will make NEAR almost infinitely scalable and able to handle any short-term spikes in usage. For more details on sharding, head over to the NEAR Medium page, where we’re publishing a series of features on how Nightshade is impacting the platform. Beyond a simple primer on how sharding works, we’re also exploring how Simple Nightshade is now powering the DeFi space and helping make NEAR carbon-neutral, amongst other things. Funding finds its feet An ecosystem needs support, especially in its early days when projects are just finding their feet. In 2021, NEAR Foundation went above and beyond to foster growth and innovation. First up, there was the news that the NEAR ecosystem announced a monumental $800 million in funding initiatives targeted at accelerating growth. While NEAR is giving all communities access to this record amount of funding, there will be a special focus on Decentralized Finance (DeFi) teams who are actively revolutionizing and reimagining the way we interact with money. DeFi projects on NEAR have already been thriving this year, with $200 million total value locked across projects like Ref Finance, Skyward, and Octopus. In addition to ecosystem fund news, Proximity Labs, a research and development firm targeting the NEAR ecosystem, announced its own $350 million grants DAO to build on the momentum. In the ecosystem, key projects like Aurora raised $12 million in its first funding round. The Ethereum Virtual Machine (EVM) for scaling decentralized applications on NEAR, received funding from the likes of Pantera Capital, Electric Capital, Dragonfly Capital and other funds. Flux Protocol, meanwhile, the decentralized oracle provider building on NEAR, raised $10.3 million to build the future of open finance earlier in the year. The project’s round was led by Distributed Global, with participation from Coinbase Ventures, CoinFund, Uncorrelated, Figment Capital, Maven 11, Reciprocal Ventures, Jabre Capital, Greenfield One, IOSG, and Flow Ventures. With funding in place, it was only a matter of time before the ecosystem took off. Explosive Ecosystem Growth NEAR’s 2021 was marked by massive growth. Fueled by Rainbow Bridge, which connects NEAR with Ethereum, as well as Simple Nightshade sharding, the NEAR ecosystem saw an exciting proliferation of gaming, Metaverse, NFT, and DeFi projects. Gaming Gaming was probably always destined to be a strong crypto industry, and 2021 proved to be a fantastic year for NEAR-based gaming projects. We expect this Web3 gaming momentum to carry over into 2022. In 2021, OP Games, a blockchain-based Web3 gaming platform, began transforming how users buy, own, and trade in-game assets. Unlike current gaming platforms, which often monopolize worlds by sandboxing digital assets, OP Games is offering them as NFTs and turning entire games into fractionalized NFTs. This way, players and fans can co-own projects and, if the game finds success, shape how it develops through its DAO. Similarly, Vorto Network began developing its online marketplace, where users will be able to buy in-game items and digital assets through a crypto wallet. Hash Rush, a blockchain-based, real-time strategy (RTS) game set to launch on Vorto Network in January 2022, will let players immerse themselves in the Hermeian galaxy, where they build, compete, and exchange goods through various levels. Hash Rush will be a great example of Web3’s “play-to-earn” model, which creates a digital goods economy for participants. Another title, NEAR Lands, is a pixelated land-based open-world game designed as much for the community as the gameplay. In the NEAR Lands online universe, players create characters and items, as well as engage with friends and other participants, while adventuring through the game’s landscape. As Q4 drew to a close, Inite earned a $50,000 grant to help build its NFT gaming platform. A unique type of Metaverse experience, Inite is a motivational game based on the scientific method, where players receive daily tasks designed to boost their creativity. By playing Inite, players can earn tokens by generating ideas to improve individual cognitive skills and productivity. NFTs Even more than gaming, 2021 was a strong year for NFTs. And with NFTs percolating into the public consciousness, it’s easy to see why. Paras and Mintbase, two NEAR NFT marketplaces, led the charge in bringing more NFTs to the NEAR ecosystem. Mintbase, which began building on NEAR in August of 2020, officially launched in 2021. The team had originally begun developing on Ethereum, but migrated over to NEAR when it became prohibitively expensive for them. With its fast transaction speeds and low costs, NEAR was the obvious choice for Mintbase, which hosts its own NFT marketplace but also has an NFT utility engine that helps people build their own. In early December, electronic music DJ and producer deadmau5 and indie rock band Portugal. the Man collaborated with Mintbase and NEAR to mint their NFT single “this is fine”. If deadmau5 and Portugal. the Man go platinum (sell more than 1 million records in the US), they will make blockchain history. It’s already putting Mintbase firmly on the NFT map. The NFT marketplace Paras offers real-world trading cards of artworks as collectibles, which users can quickly mint, buy, and sell quickly at little cost. Paras recently launched Boom Boom! the first mini digital comic series on NEAR, and PARADIGM. Both of these are part of Paras Comics, the platform’s new comics-specific feature. The Paras marketplace already has thousands of users purchasing one-of-a-kind NFT collections. It also boasts over 18,000 Twitter and 3,000 Telegram followers—a testament to its rapidly expanding community. From July 17th to the 25th, 2021 at the Shanghai National Exhibition and Convention Centre, Paras collaborated with Web3Games and NEAR to showcase Chinese artists who were selling NFT artworks at an exhibition. One artist, Huang Heshen, created the “Toorich City Series”, a collection of exclusive NFTs on Paras that explores Bu Tu Garden Community, a digital set of 10 luxury single-family villas. Elsewhere in China, the NEAR dApp Feiyu recently debuted. Built atop NEAR, Feiyu is a new take on social media, where users express creativity by sharing memes and GIFs. All of this happens in an NFT-based metaverse where users don’t have to register a wallet. Driven by rewards, Feiyu users earn tokens or NFT items (skins, weapons, etc.) for participating in the community. On the audio NFT front, DAO Records is working to reimagine the record label and to fairly pay musicians for their recordings. In the current music industry model, record labels and streaming services take the majority of musicians’ earnings. With DAO records, the founders are encouraging independent artists to release and package new music as audio NFTs. To Date, DAO Records has released over 150 NFTs from over 100 artists. And in the last 14 months, DAO Records has also produced over 50 virtual events, where musicians, fans, and NFT lovers can meet and socialize in custom-designed Metaverse gatherings. Metaverse While much crypto momentum found its way into DeFi and NFT apps, a number of Metaverse apps also launched on NEAR in 2021. These Metaverse apps laid the groundwork, in their own unique ways, for integration with blockchain gaming, DeFi, NFTs, and other crypto projects. Metaverse AI, for example, is developing an Open Metaverse for Web3. Using Metaverse AI’s advanced AI engine, users will be able to create decentralized identities and high-fidelity 3D avatars. These blockchain-based DiD (decentralization identifier) avatars give users ownership of their virtual identities and assets, and the ability to move them across the larger Metaverse. Another NEAR Metaverse project is Reality Chain, which will launch on Octopus Network, a substrate-based appchain network on NEAR. Reality Chain offers users gaming and social activities with the feel of immersive, multiplayer functionality and features. A radically different take on the Metaverse can be found in the Illust Space app. Billing itself as an “open augmented reality infrastructure for the world,” the Illust Space team is building an augmented reality Metaverse. The app gives users the tools to mix the real and digital worlds for their artworks while making them collectible through NFT technology. Also in 2021, NEAR debuted its MetaBUILD series, a hackathon designed to encourage developers to build on NEAR. As the name indicates, building the Metaverse is a major emphasis of this hackathon. The first MetaBUILD held August 27th to September 19th, and the latest, MetaBUILD 2 (December 22 – February 10, 2022), both made $1 million in prizes available to developers and teams. DeFi DeFi, or decentralized finance, has become a cornerstone of any crypto ecosystem. In little more than 12 months since mainnet launch, there are now more than 40 DeFi projects calling NEAR home. From infrastructure providers like Rainbow Bridge, Flux and Aurora, to token swap markets 1inch, Trisolaris, and Onomy Protocol, there are staking platforms, lenders, borrowers, credit scorers, and even BananaSwappers. As noted above, both NEAR’s $800 million global ecosystem fund and Proximity Labs’ $350 million Grants DAO will support DeFi projects and other dapps building on NEAR. NEAR’s Nightshade sharding will also supercharge DeFI by expanding the blockchain’s transaction speeds and security. Launched this year, Aurora is one of the most notable DeFi projects on NEAR. A platform that makes EVM contracts interoperable on NEAR, Aurora allows developers to keep using Ethereum while boosting their apps with NEAR’s super-fast transactions and low barriers to entry. Aurora is partnering with a number of other promising DeFi projects on NEAR, like the cross-chain oracle Flux and Rose, a stable swap and borrowing protocol, to level up the ecosystem’s DeFi game. Yet another highly visible DeFi player on NEAR is Ref Finance, a community-led and multi-purpose decentralized exchange, asset issuer, and lender. Ref Finance accomplishes all of this through a single, synchronous DeFi stack. What’s more, it’s fun and easy to use. If you’re looking for an interest rate market protocol, then Burrow is a dApp to check out. And if you’re looking for a token launchpad, be sure to dive into Skyward Finance, a DeFi platform that makes token launches fair and community-centric, as well as bot and attack-resistant. Another cool thing about Skyward Finance is that its DAO gives the community access to the token launch immediately instead of letting front-runners like private investors and VC firms pump and dump tokens. If you’re looking for more on NEAR DeFi apps, we’ll be publishing an article on the top DeFi projects building on NEAR. So, stay tuned for that in the new year. The DAO Community is Growing One of the major takeaways of 2021 is that NEAR’s community of Decentralized Autonomous Organizations is rapidly growing and diversifying. This is another trend that the NEAR ecosystem and larger blockchain community can expect to carry over into 2022 and beyond. Sputnik DAO V1, a hub for NEAR’s DAO ecosystem, currently has a total of 248 DAOs, with a total of 17,633 transactions for a total payout of 989,598 $NEAR ($9,292,324 USD). The Sputnik DAO hub now has a Total Value Locked (TVL) of 113,969 $NEAR ($1,070,164 USD). Factoring in those decentralized organizations in the Astro DAOs ecosystem, it’s safe to say there are now over 400 DAOs on the NEAR platform. Much of the DAO community growth can be seen in NEAR’s blockchain infrastructure and the DeFi space. The biggest DAO by total assets is Aurora, a token exchange bridge between NEAR and Ethereum, and Octopus, a platform for building appchains (independent, custom blockchains). 2021 saw explosive growth in how DAOs experimented with governance tooling on NEAR. In the first half of the year, SputnikDAO went through two iterations—one for disseminating the Community Fund and the other to incorporate custom call ability. By the time Astro DAO launched in October, there was such demand for its offerings that hundreds of DAOs came into existence in only 2 months. And in Q4, the NEAR community did quite a lot of thinking about liability protection, legal entities, and state regulation of DAOs. Creatives DAO, a fully community-run DAO Vertical, launched this year to support the ecosystem’s creative Guilds and DAOs. Discussions are just beginning about MultiDAOs, and how DAOs can better coalesce for collaborative decision-making efforts. NEAR is also supporting a research initiative hosted by Governauts that is examining DAO-based reward systems. DAO projects are being supplemented by DAO Guilds, which support these and other blockchain sectors with different resources. Various Guilds are even acting as specialized sub-DAOs working in areas like legal, software development, and DeFi. These and other Guilds are there for when app founders and developers want to tap into specific expertise and resources to improve their own project, technology, or DAO. DaoBox, based in Switzerland, is another resource for projects and organizations looking to design DAOs. The company offers a toolkit for DAOs building in NEAR, helping them establish the DAO, get a headquarters address, raise funds, and stay compliant through accounting. A Brief Look Toward 2022 A number of developers building on NEAR will launch their projects in 2022, bringing many more DeFi, NFT, Gaming, Metaverse, and other exciting and cutting projects to the NEAR ecosystem. These teams came to NEAR because they know that whether you’re developing or simply using NEAR apps, joining the ecosystem is fast, easy, and secure. With NEAR’s $800 million global ecosystem funding initiative, expect to see many more DAOs established as we head into 2022. These funds, alongside Guilds and other blockchain-based expertise and resources, will be vital in helping DAOs succeed and, just as importantly, bringing the masses from Web2 to the Open Web.
--- id: storage-solutions title: Decentralized Storage Solutions sidebar_label: Alternative Solutions --- > In this article you'll find a brief overview of different decentralized storage solutions that can be integrated into your decentralized applications (dApps). This will allow you to store large amounts of data using a more economical alternative to native NEAR storage. - [Arweave](#arweave) - [Crust](#crust) - [IPFS](#ipfs) --- ## On-Chain Storage Constraints For storing data on-chain it's important to keep in mind the following: - You can store an unlimited amount of files, but will cost you 1N per 100KB - There is a 4 MB limit on how much you can upload at once For example, if you want to store an NFT purely on-chain (rather than using IPFS or some other decentralized storage solution as mentioned below) you'll have almost an unlimited amount of storage but will have to pay 1 $NEAR per 100 KB of storage used (see [Storage Staking](https://docs.near.org/concepts/storage/storage-staking)) Users will be limited to 4MB per contract call upload due to `MAX_GAS` constraints. The maximum amount of gas one can attach to a given `functionCall` is 300TGas. ## Arweave [Arweave](https://www.arweave.org/) is a new type of storage that backs data with sustainable and perpetual endowments (tokens held within the protocol that benefit from inflation and the decrease in the cost of storage over long periods of time). This allows users and developers to store data forever. Arweave acts as a collectively owned hard drive, and allows their users to preserve valuable information, apps, and history indefinitely. The Arweave protocol matches a torrent-like swarm of incentivised miners with massive collective hard drive space with those individuals and organizations that need to store data or host content permanently. This is achieved in a decentralized network, and all data stored is backed by block mining rewards and a [sustainable endowment](https://arwiki.wiki/#/en/storage-endowment) ensuring it is available in perpetuity. :::info To learn more about Arweave, check its [mining mechanism](https://arwiki.wiki/#/en/arweave-mining) and its [bandwidth-sharing system](https://arwiki.wiki/#/en/karma). ::: ### Example implementation Let's see how to store some files on Arweave, by running a local Arweave gateway-like server. ### Arlocal setup [Arlocal](https://github.com/textury/arlocal) essentially creates a simulated version of Arweave. Think of it like a local node that runs on your computer to store information. In this example you'll need to run **two terminals**. - Open your first terminal and run: ```bash npx arlocal ``` You should see the response: `arlocal started on port 1984`. :::tip You can specify the port by using `npx arlocal <desired port number>`. ::: ### NEAR-Arweave frontend The [NEAR-Arweave repository](https://github.com/near-examples/NEAR-Arweave-Tutorial) has a simple frontend that allows you to store `.png` files using arlocal. - Now open your second terminal and clone the frontend by running the following command: ```bash git clone https://github.com/near-examples/NEAR-Arweave-Tutorial.git ``` - Install dependencies by running the following in the project folder: ```bash cd NEAR-Arweave-Tutorial yarn ``` - Next, start the application by running: ```bash yarn start ``` - Now you're ready to upload an image by selecting the <kbd>Choose File</kbd> button: ![Arweave step 1](/docs/assets/arweave-1.png) - You should see the transaction ID window become populated after hitting the <kbd>Submit</kbd> button: ![Arweave step 2](/docs/assets/arweave-2.png) :::tip If you get an error, make sure your arlocal node is running in a **separate terminal.** ::: ### Mining your transaction On Arweave your transaction goes through two stages; a pending stage and a confirmed stage. For the transaction to be complete and for you to be able to retrieve your data, your transaction must be confirmed. - Visit `http://localhost:1984/mine` in your browser to send a mine request to your local node. :::tip you may find that you are still able to retrieve your data without this step, but that's because you are running a local node. When dealing with a real Arweave node you will have to wait until your transaction has been mined and confirmed. ::: ### Retrieve the image - Now you can copy and paste any of your listed arweave transaction IDs in step 5 on the frontend to retrieve your file from your local node: ![Arweave step 3](/docs/assets/arweave-3.png) :::info Using Arweave's live network will require purchasing artokens to pay for storage. You can find out more at [arweave.org](https://www.arweave.org/). ::: :::tip The [near-api-js](https://github.com/near/near-api-js) and [arweave-js](https://github.com/ArweaveTeam/arweave-js) JavaScript libraries allow you to automate most of these steps. ::: --- ## Crust [Crust](https://crust.network) provides a Web3.0 decentralized storage network for the Metaverse. It is designed to realize core values of decentralization, privacy and assurance. Crust supports multiple storage-layer protocols such as IPFS and exposes instant accessible on-chain storage functions to users. Crustʼs technical stack is also capable of supporting data manipulation and computing. The Crust protocol is 100% compatible with the [IPFS](https://ipfs.io) protocol, and it matches people who have hard drive space to spare with those who need to store data or host content. Crust is based on the Polkadot ecosystem and supports most contract platforms, including NEAR/Solana/Ethereum/Elrond/etc. with its cross-chain solution. :::info To learn more about Crust, check its [Decentralized Storage Market](https://wiki.crust.network/docs/en/DSM) and [Guaranteed Proof of Stake](https://wiki.crust.network/docs/en/GPoS). Also, you can start with [Build-101](https://wiki.crust.network/docs/en/build101). ::: ### Integration example Here's a simple integration example to store a file with Crust and NEAR. #### 1. Upload the file to IPFS First, you need to put your files into IPFS. :::tip If you want to learn how to upload **files and folders** into IPFS, please refer to [this section](https://wiki.crust.network/docs/en/buildFileStoringWithGWDemo#1-upload-files-to-ipfs-gateway). ::: There are 2 ways to upload a file to IPFS: - using a local IPFS node - using a remote [IPFS W3Authed Gateway](https://docs.ipfs.io/concepts/ipfs-gateway/#authenticated-gateways) :::info - You can find more details about `ipfsW3GW` endpoints on [this link](https://github.com/crustio/ipfsscan/blob/main/lib/constans.ts#L29). - You can also find a code example on how to upload a file to IPFS on [this link](https://github.com/crustio/crust-demo/blob/main/near/src/index.ts#L20-L51). ::: #### 2. Place an storage order Next, you need to send a transaction named `Place Storage Order` on Crust chain. This transaction will dispatch your storage requirement to each Crust IPFS nodes through the blockchain. Then the IPFS nodes will start pulling your file using the IPFS protocol. :::info - You can find more information about `crustChainEndpoint` on [this link](https://github.com/crustio/crust-apps/blob/master/packages/apps-config/src/endpoints/production.ts#L9). - You can create your own account (`seeds`) following [these instructions](https://wiki.crust.network/docs/en/crustAccount#create-an-account-1). - Check [this link](https://github.com/crustio/crust-demo/blob/main/near/src/index.ts#L82-L112) for a code example about placing a storage order on Crust. ::: #### 3. Query order status Then, you can query the storage order by calling on-chain status (`status{replica_count, storage_duration, ...}`). This call will return: ```json { "file_size": 23710, "spower": 24895, "expired_at": 2594488, // Storage duration "calculated_at": 2488, "amount": "545.3730 nCRU", "prepaid": 0, "reported_replica_count": 1, // Replica count "replicas": [{ "who": "cTHATJrSgZM2haKfn5e47NSP5Y5sqSCCToxrShtVifD2Nfxv5", "valid_at": 2140, "anchor": "0xd9aa29dda8ade9718b38681adaf6f84126531246b40a56c02eff8950bb9a78b7c459721ce976c5c0c9cd4c743cae107e25adc3a85ed7f401c8dde509d96dcba0", "is_reported": true, "created_at": 2140 }] // Who stores the file } ``` :::info Find a code example about quering storage status on [this link](https://github.com/crustio/crust-demo/blob/main/near/src/index.ts#L144-L147). ::: #### 4. Add file prepaid The default storage time for a single transaction (order) is 6 months. If you want to extend the storage duration, Crust provides a prepaid pool so you can customize the file's storage time. This pool allows you to put some tokens and will automatically extend the file's storage time. :::info Follow [this link](https://github.com/crustio/crust-demo/blob/main/near/src/index.ts#L114-L142) for a code snippet on how to add prepaid tokens to your files. ::: --- ## IPFS The [InterPlanetary File System](https://ipfs.io/) (IPFS) is a protocol and peer-to-peer network for storing and sharing data in a distributed file system. IPFS uses content-addressing to uniquely identify each file in a global namespace connecting all computing devices. ### Content identifier When you add a file to IPFS it is split into cryptographically hashed smaller chunks and then given a unique fingerprint called a content identifier (CID). :::tip The CID acts as an permanent record of a file as it exists at that point in time. ::: ### Look-up When a node looks up for a file, it ask the peer nodes for the content referenced by the file's CID. When a node views or downloads a file, it caches a copy and become another provider until the cache is cleared. ### Pinned content On the IPFS network, each node stores only content it is interested in. A node can pin content in order to keep it forever, or discard content it hasn't used to save space. ### File versions When you add a new version of your file to IPFS it will get a new CID since the cryptographic hash is different. This means that any changes to a file will not overwrite the original and common chunks across files can be reused in order to minimize storage costs. ### Naming system IPFS offers a decentralized naming system so you don't need to remember a long string of CIDs. IPFS can find the latest version of your file using the IPNS decentralized naming system and you can use DNSLink to map CIDs to human-readable DNS names. ### IPFS providers - [Web3.Storage](https://web3.storage/): it's a service that simplifies building on top of IPFS and Filecoin. Web3.Storage is backed by Filecoin and makes content available via IPFS, leveraging the unique properties of each network. - [NFT.Storage](https://nft.storage/): this service is built specifically for storing off-chain NFT data. Data is stored decentralized on IPFS and Filecoin. The data is referenced using content-addressed IPFS URIs that can be used in your smart contracts. - [Filebase](https://filebase.com/): a geo-redundant IPFS pinning provider that pins all IPFS files with automatic 3x redundancy across diverse, geographic locations for additional performance, redundancy, and reliability.
--- sidebar_position: 1 sidebar_label: "Overview" title: "Intermediate concepts (cross-contract calls and more)" --- import accessKeys from '/docs/assets/crosswords/keys-cartoon-good--alcantara_gabriel.near--Bagriel_5_10.png'; # Intermediate concepts This chapter will go a bit faster than the previous ones. We're going to be covering an important part of smart contract development: cross-contract calls. ## Cross-contract calls A cross-contract call is when a smart contract calls another smart contract. For instance, if `alice.near` calls contract A, and contract A makes a call to contract B. NEAR has asynchronous transactions, and some cross-contract calls will have callbacks in order to determine the result of the call. This works a bit different from other blockchains, as we'll explain more in this chapter. ## Access keys Last chapter covered access keys, and we implemented a login system where a user "logs in" by adding a function-call access key to their account which is tied to the crossword puzzle dApp. Login is a common use case for access keys, but let's think bigger! Remember the two (smaller, gray) function-call access keys from the keychain illustration? <figure> <img src={accessKeys} width="600" alt="A keychain with three keys. A large, gold key represents the full-access keys on NEAR. The two other keys are gray and smaller, and have detachable latches on them. They represent function-call access key. Art created by alcantara_gabriel.near" /> <figcaption>Art by <a href="https://twitter.com/Bagriel_5_10" target="_blank">alcantara_gabriel.near</a></figcaption> </figure><br/> Notice that they have a clasp to make them removable. While it's unlikely you'll want to give another person a full-access key, there are times when you could give a function-call access key to another person or make it public. Why? This can help enable a smooth onboarding experience, as we'll do soon. ## Completed project Here's the final code for this chapter: https://github.com/near-examples/crossword-tutorial-chapter-3
Remote Development and Debugging of Rust with CLion DEVELOPERS March 10, 2019 Rust, being a relatively new language, is still on its path to gaining wide support by IDEs. Most in our team use CLion for Rust development which is especially great for local debugging, alas it is not free. Since we are developing a blockchain it requires careful orchestration of the nodes running on separate machines, and occasionally we need to debug some corner case on a remotely running node. CLion and other JetBrains products have great support of the remote development and debugging. However, unfortunately, Rust is not a primary language of CLion which makes configuration tricky. In this post we walk through the configuration of CLion for remote Rust development and debugging, our goal is to be able to: Synchronize source code between local and remote machines, so that local modifications are automatically copied over; Compile and run on two different architectures: local Mac OS and remote Ubuntu; Interactively debug in local IDE the code running on the remote machine; Remote machine setup We will be using an AWS instance running an Ubuntu image as a remote machine. The following ports would need to be allowed: TCP 22 for ssh and TCP 2345 for gdbserver. Our team also likes using mosh because it tolerates interrupted connections and allows moving between WiFi hotspots, which needs UDP 60000–61000 ports. After launching an AWS instance and connecting to it through ssh or mosh, run the following commands on it: apt-get update && apt-get install -y curl gdb g++-multilib lib32stdc++6 libssl-dev libncurses5-dev curl https://sh.rustup.rs -sSf | sh -s — -y — default-toolchain nightly Local machine setup If you do not have Rust, run the following command to install it: curl https://sh.rustup.rs -sSf | sh -s — -y — default-toolchain nightly You can download CLion from here, and upon its launch, you would also need to install the Rust plugin which can be found in Preferences→Plugins. CLion deployment configuration We will be using Actix repository as a debugging example, so you would need to download it from here: https://github.com/actix/actix and clone it locally, e.g. to /Users/<username>/Repos/actix, if you are on Mac OS. Open this project in CLion, but note that IDE might need time to update its indices and cache. CLion deployment feature allows us to keep in sync the files on the local and the remote machines. It can also be used for a large number of other special cases used mostly for the web servers which we are going to omit in this post. We will use CLion deployment for copying the following files: Source code from the local machine to the remote machine; Debug symbols from the remote machine to the local machine. In CLion open Preferences→Build, Execution, Deployment→Deployment. Click on + to add the new deployment configuration and fill it in: Since we are using the standard AWS Ubuntu image, the default username is ubuntu. You would also need to go to the Mappings tab and add local to remote mappings of the project files, e.g.: Local path: /Users/<username>/Repos/actix; Deployment path: /home/ubuntu/Repos/actix. If you already have more than one deployment configuration in CLion, you might want to right-click on the newly created configuration and select Set As Default. Since we want to compile and run on two different architectures, we would need two folders for the build files. We will be using /Users/<username>/Repos/actix/target for the Mac OS build files, and /Users/<username>/Repos/actix/target_remote for the Linux build files. We want Linux build files to be synced to the local machine since we need the debug symbols, but we do not need to sync Mac OS build files to the remote machine. So go to Excluded Paths tab and add /Users/<username>/Repos/actix/target local path. We also recommend going to Preferences→Build, Execution, Deployment→Deployment→Options and switching Upload changed files automatically to the default server to Always which will allow CLion to automatically copy locally modified source files to the remote machine. Building on the remote machine Before we can build the source on the remote machine, we need to copy it. Select the root folder in the Project tree (you might need to open it with View→Tool Windows→Project), in our case it is actix. Right click →Deployment→Upload to remote machine. Wait until the files are copied. Then SSH/Mosh into the remote machine and run: cd /home/ubuntu/Repos/actix cargo build — package actix — example ping — target-dir ./target_remote gdbserver 0.0.0.0:2345 ./target_remote/debug/examples/ping CLion does not automatically synchronize new files, it only does it with the changed files, so we need to manually download target_remote to the local machine. Navigate to Tools→Deployment→Browse Remote Host, which will open a window with the remote file system view. Locate /home/ubuntu/Repos/actix/target_remote, then right-click→Download from here. Debug configuration Now it is time to connect local CLion to the remote machine. Navigate to Run→Edit Configurations, click on + and select GDB Remote Debug. Configure it like this: Start the debugging and observe that the execution stops at the breakpoints and we can observe the values of the variables. Compiling on several architectures Recall that we used target_remote folder for remote build files from Ubuntu. If we now execute the standard Rust build command from CLion, by e.g. clicking on the green arrow next to the main function or unit tests, CLion will use a different target folder for Mac OS build files. Missing features In general, JetBrains IDEs provide several ways of doing remote debugging for each language, but since Rust is not the primary language of CLion and requires a plug-in, remote debugging of Rust is currently limited to using gdbserver. It has several disadvantages from a UX perspective: There is a need to copy symbol files. Build directory can get quite heavy, especially since cargo accumulates old build files until they are cleaned with a manual command; Some interactive UI features of CLion do not work with gdbserver. For instance with local debugging one can click on a specific unit test and run it, with gdbserver that would require restarting it on the remote machine with special arguments; Need to start gdbserver. The solution to all this is using remote host toolchains that would allow the local IDE to access the remote cargo to build and run remote programs. This feature is available in PyCharm using “SSH Interpreter” and for C++ in CLion, but unfortunately it is not yet supported with Rust. For those interested in Near Protocol: we build a sharded general purpose blockchain with a huge emphasis on usability. If you like our write-ups, follow us: http://twitter.com/nearprotocol https://discord.gg/nqAXT7h https://github.com/nearprotocol/nearcore https://upscri.be/633436/
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="NFT Primitive" label="Reference" default> ```bash near call nft.primitives.near nft_transfer '{"token_id": "1", "receiver_id": "bob.near"}' --accountId bob.near --deposit 0.000000000000000000000001 ``` </TabItem> <TabItem value="Paras" label="Paras"> ```bash near call x.paras.near nft_transfer '{"token_id": "490641", "receiver_id": "bob.near"}' --accountId bob.near --deposit 0.000000000000000000000001 ``` </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```bash near call thomasettorreiv.mintbase1.near nft_transfer '{"token_id": "490641" "receiver_id": "bob.near"}' --accountId bob.near --deposit 0.000000000000000000000001 ``` </TabItem> </Tabs>
```bash near call token.v2.ref-finance.near ft_transfer_call '{"receiver_id": "v2.ref-finance.near", "amount": "100000000000000000", "msg": ""}' --gas 300000000000000 --depositYocto 1 --accountId bob.near ``` <details> <summary>Example response</summary> <p> ```bash '100000000000000000' ``` </p> </details>
--- id: balance-changes title: Balance changes sidebar_label: Balance Changes --- ## Prerequisites {#prerequisites} - [NEAR Account](https://testnet.mynearwallet.com/create) - [NEAR-CLI](/tools/near-cli) - Credentials for sender account stored locally by running [`near login`](/tools/near-cli#near-login) ### Native NEAR (Ⓝ) {#native-near} > Balance changes on accounts can be tracked by using our [changes RPC endpoint](/api/rpc/setup#view-account-changes). You can test this out by sending tokens to an account using [NEAR-CLI](/tools/near-cli#near-send) and then viewing the changes made. ## Send Tokens {#send-tokens} - Send tokens using [`near send`](/tools/near-cli#near-send) ```bash near send sender.testnet receiver.testnet 1 ``` - You should see a result in your terminal that looks something like this: ```bash Sending 1 NEAR to receiver.testnet from sender.testnet Transaction Id 4To336bYcoGc3LMucJPMk6fMk5suKfCrdNotrRtTxqDy To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/4To336bYcoGc3LMucJPMk6fMk5suKfCrdNotrRtTxqDy ``` ## View Balance Changes {#view-balance-changes} - Open the transaction URL in [NearBlocks Explorer](https://testnet.nearblocks.io/) and copy the `BLOCK HASH`. - Using the `BLOCK HASH` and the accountId, query the [changes RPC endpoint](/api/rpc/setup#view-account-changes) to view changes. **Example Query using HTTPie:** ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare \ method=EXPERIMENTAL_changes \ 'params:={ "block_id": "CJ24svU3C9FaULVjcNVnWuVZjK6mNaQ8p6AMyUDMqB37", "changes_type": "account_changes", "account_ids": ["sender.testnet"] }' ``` <details> <summary>**Example Response:**</summary> ```json { "id": "dontcare", "jsonrpc": "2.0", "result": { "block_hash": "BRgE4bjmUo33jmiVBcZaWGkSLVeL7TTi4ZxYTvJdPbB9", "changes": [ { "cause": { "tx_hash": "4To336bYcoGc3LMucJPMk6fMk5suKfCrdNotrRtTxqDy", "type": "transaction_processing" }, "change": { "account_id": "sender.testnet", "amount": "11767430014412510000000000", "code_hash": "11111111111111111111111111111111", "locked": "0", "storage_paid_at": 0, "storage_usage": 806 }, "type": "account_update" } ] } } ``` </details> --- Alternatively, you can view account balances by [querying `view_account`](/api/rpc/setup#view-account) which only requires an accountId. **Example HTTPie Request:** ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "view_account", "finality": "final", "account_id": "sender.testnet" }' ``` **Example Response:** ```json { "id": "dontcare", "jsonrpc": "2.0", "result": { "amount": "11767430683960197500000000", "block_hash": "HUiscpNyoyR5z1UdnZhAJLNz1G8UjBrFTecSYqCrvdfW", "block_height": 50754977, "code_hash": "11111111111111111111111111111111", "locked": "0", "storage_paid_at": 0, "storage_usage": 806 } } ``` **Note:** Gas prices can change between blocks. Even for transactions with deterministic gas cost the cost in NEAR could also be different. You can query the gas price for recent blocks using the [`gas_price` RPC endpoint](https://docs.near.org/api/rpc/setup#gas-price). --- :::tip Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> Ask it on StackOverflow! </a> :::
--- id: one-yocto title: Ensure it is the User (1yⓃ) --- NEAR uses a system of [Access Keys](../../../1.concepts/protocol/access-keys.md) to simplify handling accounts. There are basically two type of keys: `Full Access`, that have full control over an account (i.e. can perform all [actions](../anatomy/actions.md)), and `Function Call`, that only have permission to call a specified smart contract's method(s) that _do not_ attach Ⓝ as a deposit. When a user [signs in on a website](../../4.web3-apps/integrate-contracts.md#user-sign-in--sign-out) to interact with your contract, what actually happens is that a `Function Call` key is created and stored in the website. Since the website has access to the `Function Call` key, it can use it to call the authorized methods as it pleases. While this is very user friendly for most cases, it is important to be careful in scenarios involving transferring of valuable assets like [NFTs](../../../2.build/5.primitives/nft.md) or [FTs](../../../2.build/5.primitives/ft.md). In such cases, you need to ensure that the person asking for the asset to be transfer is **actually the user**. One direct and inexpensive way to ensure that the user is the one calling is by requiring to attach `1 yⓃ`. In this case, the user will be redirected to the wallet and be asked to accept the transaction. This is because, once again, only the `Full Access` key can be used to send NEAR. Since the `Full Access` key is only in the user's wallet, you can trust that a transaction with `1 yⓃ` was made by the user.
Marieke Flament Appointed CEO of NEAR Foundation To Spearhead Growth NEAR FOUNDATION December 16, 2021 The NEAR Foundation is thrilled to announce it has selected global executive Marieke Flament as its new CEO, effective January 1, 2022. The appointment comes at an exciting time for the NEAR ecosystem. The NEAR blockchain is a permissionless, proof-of-stake carbon-neutral blockchain designed to be super-fast, incredibly secure, and infinitely scalable. NEAR is backed by top VCs including A16Z, Pantera Capital, and Electric Capital. In October 2021, the NEAR ecosystem announced $800 million in funding initiatives targeted at accelerating growth. The announcement, which includes the $350 million in funding announced by Proximity Labs, is designed to build on the momentum in the NEAR ecosystem over the last 12 months. In addition, NEAR recently closed partnerships with Opera and The Wharton Business School, started working with crypto payment provider MoonPay to make NEAR accessible in 150 countries worldwide, and continued collaborating with Near Inc. to launch Simple Nightshade, the first step towards a fully sharded blockchain. “We are delighted to have Marieke join NEAR to help accelerate our next phase of adoption and help us realize our vision.” shared Illia Polosukhin, Co-Founder of NEAR. “Her skills and experience are the perfect blend to help NEAR reach its next phase.” Flament brings a wealth of international business experience to the role, as well as in-depth knowledge about the world of crypto and fintech. Born in France, Flament trained as a computer engineer and has worked across the globe in a diverse range of companies from the luxury giant LVMH of Louis Vuitton fame to Boston Consulting Group, Expedia’s Hotels.com, crypto giant Circle and more recently Mettle by Natwest. During her time at Circle she was Managing Director of European operations, where she took to market several products and built a user base from 0-2 million in less than 2 years. Shortly after that she became the company’s first Global CMO, leading the branding and rollout of USDC – one of the world’s most successful stablecoins. After her position at Circle, Flament became the CEO of SME banking app Mettle by Natwest, targeting the passion/creator economy. During her time in the role, she launched the app and grew the team from 50 to 250 employees. Mettle has gained widespread customer acclaim (above 4.8 app store rating) and has become one of the bank’s biggest product success stories. Flament is passionate about exploring the ways in which technology can be used to change people’s lives, and is an advocate for diversity and inclusion in finance and technology. She was recognised in the Women in FinTech Powerlist in 2017 and 2019 and she is frequently quoted by the press; including The BBC, The Telegraph, Fortune, The Financial Times, Reuters, Forbes, and City AM. “I am absolutely delighted to be joining NEAR,” said Flament. “The tech, the team, and the community are absolutely fantastic. I look forward to working with Illia and the NEAR Foundation team to help achieve NEAR’s vision and bring OpenWeb technology to millions of users. And most importantly I look forward to serving and supporting the NEAR ecosystem.” “NEAR is a unique, once-in-a-lifetime global opportunity to shape the future by democratizing access to the tools that people need to create service for everyday life,” added Flament. ”With its permissionless, proof-of-stake blockchain, NEAR has the capability to help us unlock many of the long-promised uses of the technology and to create products and services that promote greater inclusivity and reflect the needs of the people they’re designed to serve. As the CEO, I am excited to play a role in achieving the foundation’s aim and to ensure that through collaboration and openness, the blockchain can be used as a true force for good.” Since its launch in 2020, NEAR’s ecosystem has seen a surge of activity. To date, it has processed more than 50 million transactions, across more than 1.7 million accounts, and helped incubate and foster over 200 projects and 300 DAOs. “A huge thank you to Erik Trautman, who has been instrumental in helping NEAR reach those major milestones and will continue as board advisor to help advocate and grow the NEAR ecosystem,” said Polosukhin. Excitement continues to build around the potential of the NEAR blockchain. Unlike other networks, NEAR gives software developers easy access to build new crypto applications, from Non Fungible Tokens (NFTs) to decentralized finance products – and to launch new business models and consumer products. It’s also much faster than Ethereum – the world’s most used blockchain – capable of 100,000s of transactions per second, versus ETH’s 45, and charges 1000x lower transaction fees. However, instead of competing directly with Ethereum, NEAR runs in concert with it, along with other blockchains, allowing for the free flow of assets and communication between networks for the betterment of all. NEAR’s foundation aims to help evangelize, raise awareness, support, and grow this ecosystem and allocate grants on behalf of the ecosystem. To date, the foundation has allocated over $45m to new projects.
2023: NEAR In Review NEAR FOUNDATION December 20, 2023 by Illia Polosukhin While this was a tough year in the market, we’re closing 2023 on a higher note for Web3. The NEAR ecosystem has made great progress on many fronts. Here’s a recap of some highlights and accomplishments from this year and a brief look ahead at 2024. Year in Review The NEAR ecosystem has made great strides in 2023 towards realizing the vision of mainstream adoption of the Open Web in spite of tough market conditions. Four of DappRadar’s top ten apps in all of Web3 are built on the NEAR Protocol and daily active users now regularly exceed a million per day. From launching the Blockchain Operating System in February to NEAR DA in November, the NEAR ecosystem is offering solutions to builders across all Web3 networks to deliver the vision of the Open Web. With 7 million monthly active accounts, 35 million total accounts overall, and a current average of over 2 million transactions per day, the NEAR ecosystem has seen substantial growth in usage this year—and keeps outpacing its peers in terms of daily usage. A lot of exciting technology built on NEAR was also released this year to enable chain abstraction. At EthDenver in February, NEAR Day featured the debut of the Blockchain Operating System—a fully decentralized open web stack and common layer for browsing and discovering open web experiences. By making it easier to build and deploy decentralized on-chain frontends for any network, B.O.S. helps developers build more discoverable and resilient apps while hiding the blockchain infrastructure from users. Building on the benefits of the NEAR account model, the FastAuth onboarding solution lets users create an account in seconds using only an email address and device security. App developers can subsidize gas so users can start using apps immediately upon creating their account, and they only need to set up once in order to access any app on B.O.S. The team has gotten great feedback on the beta and will share some exciting next steps early next year. B.O.S. also includes NEAR QueryAPI, a fully managed, open-source, serverless infrastructure offering NEAR blockchain indexers, storage, and GraphQL endpoints. QueryAPI simplifies the indexer building experience with JavaScript and interactive debugging and eliminates the need to manage cloud infrastructure. The beta already powers 25 indexers in production. Beyond rollups using decentralized frontends, I shared the news of 3 exciting Ethereum alignment initiatives to offer NEAR technology to the modular Ethereum ecosystem and benefit the broader Open Web. The collaboration with Polygon Labs on a zkWASM prover will optimize the NEAR L1 and bring NEAR to the forefront of the zero-knowledge research space. The Foundation is working with Eigen Labs to build a fast finality layer for defragmenting Ethereum rollups and also launched NEAR DA, a cost-efficient and data availability layer compatible with L2s offering 11,000x cheaper DA than Ethereum and 30x cheaper than Celestia. NEAR reached #1 in daily active users for all of Web3 to close the year, per Artemis. 4 of the top 10 apps in all of Web3 are built on NEAR & Aurora, per DappRadar’s 30-day ranking. Looking Ahead As we look towards 2024, the ecosystem will build upon the innovations and market recognition of 2023 with some major advancements at every layer of NEAR’s open web stack, plus expand into exciting new territory on the AI and product fronts. 2024 is the year of chain abstraction: blockchains and other infrastructure will become increasingly invisible to users and developers. Just as we don’t need to know if a given website or app we’re using every day is running on Google or Amazon servers, most app users on the Open Web shouldn’t need to manage infra, toggling between accounts and wallets, bridging, or gas. This is the biggest barrier to mainstream adoption. The NEAR ecosystem has been building for chain abstraction since the very beginning with sharding and the account model, and more recently the B.O.S., FastAuth, and ETH alignment solutions. From the user perspective the NEAR blockchain functions like a single platform, but under the hood, every account and smart contract is its own logical chain. Developers today pick an ecosystem based on where they can access liquidity and users, but that will matter less if they can access users and deposit liquidity from any chain – so they can just choose the infrastructure that works best for their application. A big part of advancing chain abstraction for the Web3 space is account aggregation. In order to enable users to transact across all blockchains without needing to think about underlying infrastructure or switch networks, they need a single account from which they can navigate all of Web3. In the true spirit of Web3, this single account should be non-custodial and non-dependent on a specific wallet software or any other single service provider. In addition to FastAuth, Pagoda will launch chain signatures and intent relayers to deliver the full scope of this vision in the first half of 2024. At the protocol level, the team will launch Phase 2 of sharding, which is a big deal. TLDR: introducing stateless validation will expand the original Nightshade design, allowing us to avoid fraud proofs. As part of this transition, the state of each shard moves fully into memory, improving performance of each shard—currently 4, soon to be 5—by 10x+. Adding zkWASM on top as the next step will compress execution proofs, enabling even greater decentralization of validators. Finally, the NEAR ecosystem will make bigger strides into AI. I’ve been sharing my views on how AI and blockchains can work together with humans to improve our collective systems and individual experiences while minimizing risk and centralization. We’re working both on AI-driven governance and AI-augmented Web3 experiences to work towards the vision of user-owned AI. Stay tuned for more updates and specifics in January 2024. Thank you to every member of the NEAR community for staying the course and believing in our shared Open Web vision.
NEAR Digital Collective’s I-AM-HUMAN Welcomes Its First 1000 Verified Humans NEAR FOUNDATION June 16, 2023 NEAR Foundation is thrilled to share some inspiring news today. The I-AM-HUMAN project, a cornerstone proof-of-humanity initiative of the NEAR Digital Collective (NDC), just achieved a significant landmark of welcoming 1,000 verified community members to our growing ecosystem. This critical milestone underscores the NEAR Foundation and NDC’s commitment to fair and equitable digital governance and representation built on NEAR. The impact of I-AM-HUMAN’s 1,000 verified users What does it mean to have 1,000 verified users? Simply put, it means 1,000 verified, unique human voices; 1,000 individual perspectives; and 1,000 contributors to NEAR Foundation’s mission of democratizing the digital world. 1,000 verified community members now have the opportunity to engage in governance voting, build an on-chain reputation, drive grassroots funding, and unlock the truly transformative power of DAOs. This active engagement is helping reshape the way key decisions are made, moving away from centralized control and towards a truly decentralized, democratic governance model. Distributing voting power to the people with “Soul Bound Tokens” I-AM-HUMAN is all about fairly distributing voting power to the people. At its heart is the concept of “Soul Bound Tokens” or SBTs. These aren’t your average digital tokens —each SBT represents a real individual, flesh-and-blood human being, verified through our innovative and user-friendly proof-of-humanity identity verification process. SBTs are the digital embodiment of you, assuring that your voice counts, and making the principle of “one person, one vote” a reality in the digital realm. Minting your SBT is easy and only requires a NEAR wallet and your (adorable) human face. And don’t worry about what you look like since the image is encrypted and never seen by anyone. In fact, you always have the right to request the deletion of your data from I-AM-HUMAN and our partner Fractal. If you haven’t yet done so, give it a shot! It only takes a minute or two and we would love to have you be part of this important initiative. We’ve made sure the process of getting your unique SBT, or putting a digital stamp on your individuality, is simple and accessible. With Fractal’s help, we’ve been able to keep this process secure and respectful of your privacy rights, which for the NDC, is of paramount importance. “With the creation of the I-AM-HUMAN protocol, NDC sets a new standard for on-chain identity verification, empowering individuals to assert their humanity securely and transparently in the digital realm,” says Jane Wang, Product Lead at NDC Governance Working Group. “The I-AM-HUMAN protocol opens up a world of opportunities, from secure voting and governance participation to fair airdrops and reputation systems. We’re thankful for our partnership with Fractal, who has made the journey smooth with their field-tested identity solutions at NEAR.” Other NDC Initiatives on the horizon As NEAR Foundation and the NDC celebrate this major milestone, the commitment to innovation and improvement continues. The NDC is determined to provide an ever-improving experience for users, with initiatives underway to constantly improve user experience, strengthen data privacy, and expand our availability within the NEAR ecosystem. The NDC is actively creating a partnership roadmap for other organizations to leverage our proof-of-personhood solution, helping to empower our partners to ensure equitable decision-making within their own ecosystems. The journey to 1,000 users has been exciting, but the NDC is far from finished. Every new user brings us one step closer to NEAR’s vision of a digital world where each individual’s voice is respected, and where the democratic process isn’t just a principle, but a practice. So, if you haven’t already, we invite you to become a part of this revolutionary journey. Mint your own SBT, join our community, and make your unique mark in shaping the future of decentralized governance. The NDC extends its deepest gratitude to each and every one of you for taking the opportunity to unlock elections, governance, and community treasury with us. These first 1,000 users are opening the door for thousands more to come. For updates, follow NDC on Medium and stay connected with us on this revolutionary journey!
--- title: 4.4 The Making of the Creator Economy description: How does creator economy can challenge and change existing opportunities --- # 4.4 The Making of the Creator Economy: ‘Wrapping’ Content and Other Entertainment The application of non-fungible tokens is an extremely broad topic, each with its own business model and potential addressable market. Non-fungible tokens, leveraged for creators or types of people who originate new forms of value on a social (influencing), cultural (music, art, media), and intellectual basis (articles, blogs, and content) is known as the _creator economy._ For newcomers to crypto, the value proposition of the creator economy is best understood in reference to the opportunities available for creators in the Web 2.0 / mainstream world. The two most important questions to kick off any discussion surrounding the creator economy includes: _How does the creator economy challenge and change existing opportunities for creators?_ Similar to the paradigm shift in the transition from a siloed and controlled Web2.0 into an open and composable Web3.0, the existing creator economy is riddled with middle-men and gate-keepers. From _Taylor Swift _to _Kanye West_ to issues surrounding creator monetization on Spotify and YouTube, to high fashion, and blogging, challenges to creators today tend to fall into two buckets: * **Financial Exploitation:** When a creator is dependent upon other parties in order for them to access the value for their work. This could be via a record label, studio rights, brand partnerships, and so forth. * **Censorship:** When the work of a creator, is dependent upon other parties for the distribution, platforming, or access to the work. This varies from things like twitter, to substack, YouTube, rumble, and so forth. In both cases, the trend that the creator economy inaugurates, is a transition from centralized platforms of control, data extraction, and censorship, to open platforms or systems in which permissionless participation, value-created, and future royalties on the created value - can all stream directly back to the originator (or originators) of the work. This is the paradigm shift proposed when non-fungible tokens can be leveraged and utilized by creators. _How does the creator economy expand the market for creators, and fundamentally redefine the value of what can be created?_ This second question is not focused on the past, but rather the future of created value. A blockchain-based creator economy, fundamentally means an open, permissionless, global, and accessible economy, that moves beyond jurisdictional siloes and boundaries, and creates the opportunity for talent and creations from around the globe to talk to one another on a single ledger. From a financial perspective, the tokenization of non-fungible value, creates entirely new opportunities for how that value can be leveraged _composabley_ with other services. An NFT of a song, or an article, is not only a mechanism for directing value back to its creator - it can also be fractionalized, rented out to a DAO, collateralized for a loan, or embedded inside of a video game for maximum exposure. _A matrix to understand this process would be the following: For any NFT of the creator economy:_ * _What industry is getting disrupted?_ * _How do NFTs cause this disruption?_ * _How is the disruption composable?_ | | Creator Economy Sector / Product | | --- | --- | | **What industry is getting disrupted?** | | | **How do NFTs cause this disruption?** | | | **How is the disruption composable?** | | ## What Do We Mean by Creator Economy? Diving Into Examples. Today in crypto, the following industries are already being experimented with, and are well on their way to disruption: ## Art **“Just as NFTs give musicians more power, artists that use NFTs have complete control over their work. Art on an NFT allows artists to create and sell their work directly to collectors, bypassing traditional gatekeepers.” ([Andrew Steinwold](https://andrewsteinwold.substack.com/p/crypto-will-change-value-nfts-will))** Artists are the ‘break-through’ creative segment of the creator economy. The original launch of profile-picture collections (PFPs) was done hand in hand with the discovery of digital artwork, from the likes of _[Beeple](https://www.beeple-crap.com/everydays)_. Those who purchase the art, are the sole owners of the original, and sometimes hold a claim to the physical asset if there is one. Digital art galleries from [Norway ](https://www.versegallery.xyz/en/home/)to New York, have brought together communities of artists, collectors, and PFP members. For the future of art both on-chain and in the physical world, NFT’s have revolutionized: (1) The Buying and selling of digital art. (2) The prospect of fractional ownership of the physical artwork, including leasing and renting. (3) The buying and selling of the physical art itself. (4) The ability to govern the movement of art works to different galleries. **_Companies and Artists in This Niche:_** * **_[Beeple](https://www.beeple-crap.com/everydays)._** A digital artist who stepped into the non-fungible renaissance at scale - selling art for over 50 million dollars, and featuring on podcasts like Joe Rogan. * **_Renaissance Labs:_** Aurora’s own fractional ownership of real-world art marketplace. Allowing individuals to share in the value of the art work, and jointly decide on the movement of the art work from vault to gallery. * **_Open Sea:_** The honorable mention of the role of NFT Marketplaces, for facilitating the transfer of value between purchasers and sellers. NFT exchanges have done over 5$ billion dollars in volume in the last 4 years. ## Content, Journalism and Media Content remains one of the most low-hanging and easily monetizable areas of NFT’s that have yet to found significant product market fit. On the lowest level, is (1) the prospect of ‘wrapping’ individual pieces of content within an NFT, such that ownership is required in order to access the information it contains. This would refer to research articles, individual blogs, financial research, or digitized libraries / archives. For well-known individuals, popular writers, or academics wishing to maintain their autonomy or publish in a censorship free environment, the opportunity is to sell-directly to an audience and remove any middleman capable of controlling the content itself. Second (2), is the prospect of decentralizing content management itself - such that a media company, digital newspaper, or community of writers, could have a verifiable and reliable process for fact-checking their work. Companies like Campground and Sovereign have experimented with this, however a scalable mechanism for decentralized content management remains largely undiscovered and un-implemented. Third, (3) is the capacity to use NFT’s at slightly larger scale to coordinate membership, revenue share, or access to a community of content creators. This, goes hand in hand with (4) the ability to gate access to an author’s work or blogs, in an on-chain version of ‘Substack’. At scale such a system would also be applicable to podcasts, videos and movies. In line with the principles above, ### _Companies of Interest In This Niche:_ * **_Campground_**. * **_Steem ([Limited](https://steemit.com/))_** * **_Civil Media ([Decayed](https://civil.co/))_** ## Fashion: [Fashion in the context of the creator economy](https://www.forbes.com/sites/forbesagencycouncil/2022/10/18/nfts-the-fashion-industrys-future-baby/), refers to changes in the creation, purchase, or traceability of different fashion products around the world. The applications of NFTs to fashion are multiple, and expected to expand into the future: (1) Mirroring physical fashion items with digital widgets for the metaverse. Whereby a pair of sneakers I buy from Nike, offers me a digital equivalent for my metaverse character and any perks associated with that item. (2) Marketplaces for designs and blueprints of new fashion concepts. (3) Tracing the origin of fashion items to ensure authenticity using a IoT chip, or scanned dApp from a user. ## Music Similar to art, the ability to gate and capture the value of music opens up a new world of opportunities for the artist. From (1) The direct purchase of songs and albums from the artists themselves, to (2) ownership to the rights of the song for reuse purposes, to (3) circumventing the record label and selling direct to audience - artists face a future whereby they can increasingly customize incentives towards the release of their music. Consider for example, an artist launching a first album such that anyone who purchases it would be entitled to receiving a small percentage of royalties from future albums. Or, the early supporters are given an exclusive long-term access link that provides a direct link to the artist himself for up to X years. ### _Companies of Interest In This Niche:_ * **_Tamago._** * **_Audius._** ## Social Rights: Social rights refer to the issuance of NFT’s as representative of the community of a specific influencer, podcaster, content creator, or celebrity. The NFT guarantees the owner with a vote or a voice in determining key facets of the persons’ social presence. This might include: (A) Voting on who comes onto the podcast next, (B) Involvement in deciding where an artist tours, (C) Special access to events and fundraisers from the person involved (could be a politician, artist, comedian, etc.). Or even (D) Revenue sharing among artists participating in an event together. Interestingly this applies both digitally and physically: From a real comedian's next tour location, and to a Metaverse’s design of a new digital neighborhood. ## Practical Implementation of the Creator Economy: Is There A Regulatory Blocker? The story [of SingularDTV](https://singulardtv.com/) is most illustrative of the difficulty in scaling creator economy innovation. One of the first ICO’s on Ethereum launched with the promise of forever revolutionizing media and content creation - from magazines to movies - and in the process raised over 500mm. Less then five years later, there has been nothing to show due to a lack of visibility, lack of product market fit, and lack of relevant product stack (at the time NFTs were expensive and clunky). The story illustrates a number of questions pertaining to blockers and facilitators of the adoption of the creator economy: * Should legacy companies look to move into Web3 with their audiences and brand name? Similar to how the NY Times moved online and created a podcast with Web2? * Should stand alone influencers follow the Nelk brothers in experimenting with gated content and fan rights on directing the platform? * Will Web3 ever be able to aggregate individually monetized creations into a single uniform and friction-free subscription service? (i.e. for spotify for example)? * What clear regulatory blockers limit certain creator industries from embracing NFTs? * Does geographical location matter for the successful adoption of certain creator products using NFTs? (Leapfrog theory).
```bash near call v2.keypom.near create_drop '{"public_keys": <PUBLIC_KEYS>, "deposit_per_use": "10000000000000000000000", "nft": {"sender_id": "bob.near", "contract_id": "nft.primitives.near"}}' --depositYocto 23000000000000000000000 --gas 100000000000000 --accountId bob.near ```
NEAR Community Update: February 22, 2019 COMMUNITY February 22, 2019 Lately it’s been a blur of events as we talk to developers both in and outside of the blockchain ecosystem and learn more about what they need in a decentralized platform. This weekend, we’re at the SF Developer Week hackathon helping developers work with the platform (and awarding a number of challenge prizes). If you’re in town, stop by and say hi! Community and Events We’ve touched Denver, Boston, San Francisco and multiple locations in Asia with no sign of stopping yet. A key upcoming event actually doesn’t have a specific location — on March 5 at 4pm PT / 7pm ET, we’ll host an online Decentralized App Development Workshop where anyone can code along and see what the platform can do. If you want to host a local NEAR meetup in your city or see if we can meet with yours, reach out to [email protected]. Recent Highlights [Denver] Feb 12: Sneak Peak Workshop: NEAR DevNet with ETH Denver [SF] Feb 13: Blockchain 101 Onramp: DApp Development Basics [Denver] Feb 15–17: Judging the Eth Denver hackathon (Illia Polosukhin) [SF] Feb 19: NEAR Protocol DevNet Test Drive with ABC Blockchain Alex Skidanov speaking at SF Developer Week: Upcoming Events [San Francisco] Feb 23–24: Developer Week Hackathon [Boston] Feb 23: Harvard Business School 2019 Crypto Club (with Alex Skidanov) [Beijing] Feb 23: Blockchain 3.0 — The Evolution in Blockchain DApps [SF] Feb 26: Giving power back to developers: Preview of a new computing platform (@Github) [Oakland] Feb 27: Near Protocol — DevNet Workshop (@Oakland Developers) [SF] Feb 27: Blockchain 101 Onramp: Best Practices for Developing DApps [Shanghai] Feb 28: Blockchain 3.0 — The Evolution in Blockchain DApps [Mountainview] Feb 28: Learn Blockchain Tools and Technologies that Enable Smart Contracts [ONLINE] March 5 @ 4pm PT / 7pm ET: Decentralized App Development Workshop [Paris] March 8–10: Events around Eth Paris [Austin] March 14–16: Events around SXSW [San Jose] March 21: Blockchain Developer Meetup [SF] Mar 28: Decentralized Computing with WASM @ Github If you want to collaborate on events, reach out to [email protected] Writing and Content Alex Skidanov spoke to Justin Drake of the Ethereum Foundation in the latest installment of our Whiteboard Series about the design and implementation of Ethereum Serenity, beacon chains, shard chains, randomness, cross-shard transactions, LMD ghost and Casper FFG. Yes, it ran a little long… We’ve also translated the Beginner’s Guide to the NEAR Blockchain into Japanese. If you want to make a translation yourself, please reach out to [email protected]. Engineering Highlights Now that our single-node DevNet is active, we’re focusing on making the user experience better and the technology behind it more robust. That means continuing to build out documentation, stabilize the node and smooth out the user experience throughout the NEAR Studio IDE. Upcoming weeks will see big upgrades in all of these areas as well. The next blockchain milestone is the multi-node AlphaNet, expected out in early March. We’ve updated to a newer, simpler consensus called Nightshade. There were 40 PRs in nearcore from 8 different authors over the last couple weeks. DevNet update Initial working API for cross-contract calls using AssemblyScript. Benchmarks for the client excluding network and consensus. Launched NEAR Place app (https://app.near.ai/amsuwo78d/) as a showcase for the current development and user experience. AlphaNet update Finalized the design and implementation of a new consensus for beacon and shard chains called “Nightshade”, replacing previously used consensus “TxFlow”. See a draft of a paper for an early DAG-based version of Nightshade here, and a simplified version without a DAG here. Started integrating Nightshade with the existing infrastructure. Implemented an initial version of mempool and starting hooking it in, replacing the gossip DAG that was used previously. NEARlib update Improved API for connecting to DevNet Integration tests for connecting to DevNet Switched from Parity WASM interpreter to WASMER JIT. Got 100x raw improvement and 18x improvement when other components factored in. NEARStudio update Updated nearlib and corresponding fixes Minor fixes to templates AssemblyScript/bindgen Updated bindgen to work with latest version of AssemblyScript Fixed bug with duplicate bindings generated for encoding arrays of base types How You Can Get Involved Join us! If you want to work with one of the most talented (and humble?) teams in the world right now to solve incredibly hard problems, check out our careers page for openings. 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.
What the NEAR Foundation Does NEAR FOUNDATION July 19, 2021 The NEAR Foundation (“NF”) is a unique kind of organization. It helped to launch both a technological platform — the NEAR Protocol — and the ecosystem around it. The Foundation, which was introduced briefly last year, is a Swiss-based nonprofit, non-beneficiary organization which uses the power of its financial and operational resources to support the same mission as the overall NEAR Collective, which is the grouping of all active participants who make up and drive the NEAR ecosystem. This mission is: …to accelerate the world’s transition to open technologies by growing and enabling a community of developers and creators. In line with the core value of Openness, the goal of this post is to provide more clarity about how the NF organizes itself, how it operates, how it defines success and what vision it is working to achieve. The Vision of the NF While it shares a mission with the entirety of the NEAR Collective, the Foundation’s role in this is to realize a more specific vision: …a self-sufficient ecosystem of creators, developers, entrepreneurs, community members and tokenholders whose collaborative efforts make the NEAR ecosystem the best place to build massively impactful projects in the Open Web. This vision requires that NEAR become the best ecosystem in the world on several fronts: NEAR needs to have the best ecosystem-level clarity. This means that all participants in the ecosystem have a clear understanding of what the platform is good for, what’s going on in the ecosystem and how to access resources. Large-scale decisions that affect the community, for example large resource allocations or technical governance, are done with proper community input. NEAR needs to have the best onboarding. Within seconds of first hearing about NEAR, a prospective builder understands what they can build with NEAR and how it’s different from other options. Within the first minute, they are connected with a real human being who can help “sherpa” them through available resources. Within a few more, they are embedded in whatever communities can best support their journey by answering questions, testing products and driving early adoption. NEAR needs to have the best founder experience. When building their organization, they have easy access to the information they need to make good decisions about hiring, incorporation, compensation, legal and regulatory matters. They have easy access to a clear menu of financing options and support as they navigate them. They have access to an informed, engaged and highly competent pool of human resources for all the roles they need to hire for. NEAR needs to have the best developer experience. When building their product, devs are confident that they are building on the most reliable and effective technology possible. They have easy access to basic explanations, working examples and documentation. They clearly understand the ecosystem of tools, products and projects that are available to help them and their journey from idea to launch is rapid, iterative, painless and supported by an active, inclusive community. They are also supported by a wide range of project integrations (for example, wallets, payment processors and custody) both to help them build their product and take it to market. NEAR needs to have the best go-to-market support. When initially testing their product, builders have easy access to an engaged community of early adopters who can help them rapidly find product/market fit. During launch, this community helps them evangelize the product. Builders have access to open knowledge bases of best practices for everything from consumer onboarding to security to growth strategies. After launch, they are supported by broad access to customers, deep secondary markets and continued access to partnerships, capital and exit opportunities. The NF’s goal is to accomplish these things indirectly. Thus, rather than operating in the ecosystem as an active participant, wherever possible it will make sure this vision is realized by other members of the community in a high quality, scalable and ultimately self-sufficient manner. What does success for the NEAR ecosystem look like? Ultimately, it comes down to adoption — that the platform and its underlying protocol are in active use by a huge number of people and businesses around the world. While there are many ways to measure this, the most straightforward 3 which can be used to determine success in the next 18 months are that the NEAR ecosystem generates the most economic activity (GMV), support the highest total market cap of projects and host the most active users of any other blockchain-based ecosystem. Analogues for understanding the NF The NF’s mandate to provide support for the ecosystem, without actively operating it, doesn’t map exactly to any existing business model. It is closest to a full-service venture capital firm like a16z — its “portfolio” comprises all of the applications and companies that operate within the NEAR ecosystem. The NF’s job is to allocate them the resources they need to be successful while supporting them in whatever ways possible. All of this occurs within an extremely fast-moving, tech-forward and competitive space. There are a few key differences between the NF and a full-service VC: The “return” of the portfolio is not capital but adoption of the protocol by each of the key stakeholder groups. So the NF will place its allocations with the intention of receiving better adoption above all else. The NF operates at one level of abstraction higher than a VC firm. Rather than making bets in individual companies, it needs to operate more like a fund-of-funds model and make generalized allocation decisions across asset categories like other VC funds, DAOs, grant buckets and so on. That allows the NF to stay out of the day-to-day capital allocation game and focus on the high level ecosystem support. The NF operates at a much larger scale than a typical full service VC. Rather than just a portfolio of dozens of companies, the NF needs to support hundreds or thousands of developers, founders, integrators and beyond. So its support efforts need to scale to become fully open and community-driven wherever possible. The NF takes on some aspects of a venture accelerator as well, in that, if the ecosystem is missing a particular element, it may incubate the team which develops this particular component or business until it is ready to spin out. The NF shares another similarity to a defined-horizon VC fund — its long term mission is also to make itself completely unnecessary. In this case, that’s because a completely well-functioning antifragile ecosystem has all the components it needs to be successful regardless of the efforts of a foundation. Ideally, companies and communities combine to handle all of the governance, roadmapping and capital allocation activities that the NF handled during the early days of the ecosystem’s development. In fact, success in 5 years means that the NF has wound down its core entity and sustainably handed off each of its core functions to teams within the ecosystem which have sustainable mandates. The team of this foundation needs to combine a fanatical focus on adoption with an open source, community-first, inspiration-driven approach to creating alignment among ecosystem participants. Each person needs to be incredibly values-aligned with the 5 key NEAR values and each of its leaders will need to craft and communicate strategy both to internal teams at the NF and to the ecosystem overall. Responsibilities of the NEAR Foundation As a “portfolio manager” of the NEAR ecosystem, and inline with the vision above, NF is ultimately responsible for driving the success of the applications which make up this ecosystem via 3 major categories of activities: Awareness: Raise awareness of the NEAR technology, platform and ecosystem such that more developers, community members, enterprises and entrepreneurs build new portfolio companies and projects. This combines education, evangelism, communications, PR, tokenholder relations, analytics and more. Allocation: Spend both its discretionary (100M NEAR token endowment) and advisory (major ecosystem token buckets) tokens to capitalize the best initiatives within the ecosystem. This is primarily via a fund-of-funds level of abstraction, so the NF is allocating resources to other people who will actually deploy them “on the ground”. Its only granular allocation tool is the Grants Program, which accepts applications for small grants for a wide range of ecosystem-supportive activities, which are at least partially informed by the NF’s roadmap. Support: Create as much value as possible for ecosystem projects without actually stepping in and operating at all. This means supporting in a number of key way, including creating the operating framework and coordination so the NEAR community is well organized, well supported and capable of routing people, answers and resources to the teams that would benefit most from them. Operational Advisory: Create the self-serve resources, best practices and events which give projects the resources they need to solve problems with hiring, HR, legal, regulatory, financial and operational challenges. A key question is also what the NF is NOT doing. Except in truly extraordinary cases, the NF is… NOT going to market: NF is NOT operating GTM initiatives for any specific products or technologies to generate revenue or reach end-users unless it is a test case or early stage incubation for something that will be spun out as an independent initiative. When a project or initiative starts pushing to a market, it must be helmed by an entrepreneur and spun out. NOT developing: NF is NOT providing direct development support to deals, companies or projects in the ecosystem. This is not a development shop. NOT running a true VC or syndicate: NF is NOT allocating to specific projects or entrepreneurs outside of the Grants Program because that doesn’t offer enough leverage. NOT a lawyer, accountant, etc: NF will contribute to legal and regulatory discussions but will never be a substitute for hiring professionals in these categories. In each of these categories, NF may have some exposures but they are only temporary such that it is bootstrapping an effort or supporting an entrepreneur who can spin these things out. How NEAR’s Success is Defined The NEAR ecosystem’s success is driven by 3 key priorities, which are shared by the NF: Awareness: How many people know about and can accurately describe NEAR’s value proposition? Adoption: How much usage is the platform getting from each of its key stakeholder groups: Consumers (Monthly Active Accounts, “MAA”) Financials, (Total Value Locked, “TVL”) Developers, (Monthly Active Developers, “MAD”) Apps, (Total financing raised) Community Members, (Onchain Community Members) Credibility / “Legitness”: Do people within each stakeholder group who know about NEAR have a very high opinion of its quality and prospects for success? The NEAR ecosystem’s overall success is difficult to measure, but two metrics which represent opposite ends of the spectrum are the total market cap of projects within the ecosystem (but which can be influenced heavily by market forces) and the gross marketplace value of transactions driven by the platform (both on chain and off). How Culture and Values Apply NEAR has always been primarily driven by deeply technical people trying to apply the lessons of Silicon Valley startups to actually build something real humans want using the blockchain technology. This project wasn’t started and doesn’t continue because of commercial intent but rather to create a rippling wave of change and value creation across the application stack. Our values reflect this and everyone actually works hard to live by them. Below are the values themselves as well as the way the NF specifically embraces them and where it needs to do better: ECOSYSTEM-FIRST: always put the health and success of the ecosystem above any individual’s interest. The NF works tirelessly to create value for participants in the ecosystem. Everything from resource sharing to team vesting contracts are structured such that what matters most is the overall health of the ecosystem. OPENNESS: operate transparently and consistently share knowledge to build open communities. The NF has historically been strong in the sharing of resources and education but needs to put the time into better communication around its activities in order to better include the community. PRAGMATISM OVER PERFECTION: find the right solution not the ideal solution and beat dogmatism by openly considering all ideas. The NF doesn’t play favorites and is ultimately here to make everyone successful, regardless of where they come from. It has avoided many pitfalls of bureaucracy along the way, and has a healthy dose of pragmatism. MAKE IT FEEL SIMPLE: strive to make the complex feel simple so the technology, platform and ecosystem are accessible to all. The NF doesn’t make first party products but it is a service organization. Some of its services to teams in the ecosystem (eg routing deals or help requests or just making internal team requests for resources smoother) could be greatly simplified, which has been a focus in early summer 2021. GROW CONSTANTLY: learn, improve and fail productively so the ecosystem and the community are always becoming more effective. The NF has liberally supported team members in their personal (eg managerial) growth. Early summer 2021 efforts are focused on helping spread the resources for ecosystem participants to also learn and grow themselves, for example by contributing to the Open Web Atlas. Operating the NF The NF is a porous, open organization so many of its activities will be done as openly as possible but it still has many internal processes to keep the team aligned and performant. Its rhythm is as follows: Annually: Performance reviews across all teams (NFC, leadership, team leads, members) Review of Mission, Vision, Values and multi-year Objectives (NFC, leadership, team leads) Quarterly: Review individual team Missions and Visions (leadership, team leads) Review prior quarter’s OKRs (leadership, team leads) Submit, review and approve forward-looking quarter’s OKRs (leadership, team leads) NF Council meets officially (NFC, leadership, team leads) Monthly: Coordinate or seed the hosting of external-facing Town Hall events with the community (community team) Prepare and publish the Ecosystem Review to NFC and to the community (leadership support team) NF Council calls informally (NFC, Leadership) Bi-weekly: Internal All Hands sessions to coordinate internal teams (everyone) Review KR progress (leadership with team leads, team leads with members) Coordinate 2-week sprints (team leads with members) The Future and Scorecard of the NF The NF has provided — and will continue to provide — many of the early resources that have been helpful to the early ecosystem but its ultimate goal is to make itself completely redundant and unnecessary by establishing robust communities across the ecosystem to handle all of its core functions. As noted in the vision previously, the role of the NF is thus the role of any great entrepreneur — to scale itself out such that better teams and better leaders are able to take up the charge. It will bootstrap where necessary and then empower the ecosystem around it to improve and scale each of its areas of focus. The NF has made extraordinary progress in less than 2 years towards creating a self-sufficient ecosystem but there is still plenty to bootstrap and many more handoffs to coordinate. NF will continue to deploy resources heavily to support key efforts but it will make sure all core support activities it provides are eventually made self-sufficient and are run by great entrepreneurs with sustainable businesses. Success for the NF in 5 years thus means that it has wound down its core entity and sustainably handed off each of its core functions to teams within the ecosystem which have sustainable mandates. It’s an ambitious goal but an achievable one. In the long term, the NEAR ecosystem itself will become the hub of a global universe of blockchains which support the Open Web. While there are many paths to get there and it will ultimately be driven by the founders and developers of the NEAR ecosystem, the NF is here to guide and support their journeys all along the way.
NEAR 2019 Year in Review COMMUNITY January 8, 2020 We are excited to share with you our NEAR 2019 Year in Review. The year has passed at an accelerating speed, filled with events, community programs and lots of engineering work. We planted the seeds of a now growing global collective and iterated most of NEAR’s sharding design. While continuously marching towards mainnet, we want to take a moment to look back at NEAR 2019 Highlights. Content We launched our Whiteboard Series, which features a collection of over 30 deep-dives into various blockchain protocols. With finalising NEAR’s design, we started our Lunch & Learn Series on YouTube, providing a deep dive into the underlying mechanisms of NEAR protocol. Alex was live coding core features of the NEAR Protocol in October. Research Nightshade: Near Protocol Sharding Design Near Protocol Randomness Beacon Fast Finality and Resilience to Long Range Attacks with Proof of Space-Time and Casper-like Finality Gadget Doomslug: block confirmation with single round of communication, and a finality gadget with guaranteed liveness Events Throughout 2019, we attended, spoke at and hosted over 50 meetups and discussions. Locations included: Tokyo, Paris, Berlin, London, San Francisco, San Jose, San Mateo, Oakland, Beijing, Shanghai, Boston, and Sydney. ETH New York: we hosted two great panels and participated in more. Access some of the recordings here. Alex spoke at Web3 about the challenges of sharding. We hosted several events during and after DevCon. Check-out our events at San Francisco Blockchain Week! Community We launched three unique community programs to support mission-aligned engagement, research, projects, and development. We want to give a big thank you to everyone who got involved! Stakewars: Our incentivised testnet program; access overview and updates. The Ambassador Program: Formalising community-driven contributions. The Beta Program: Providing projects that are building on NEAR with engineering and fundraising support. Join our mailing list to hear about important developments and to learn when we’re going to be in a city near you. Our year in a gif — Goku going super Saiyan. HOW YOU CAN GET INVOLVED Join us: there are new jobs we’re hiring for 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 AMM_CONTRACT_ADDRESS = "v2.ref-finance.near"; const wallet = new Wallet({ createAccessKeyFor: AMM_CONTRACT_ADDRESS }); await wallet.viewMethod({ method: 'get_pools', args: { from_index: 0, limit: 1000 }, contractId: AMM_CONTRACT_ADDRESS, }); ``` _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ <details> <summary>Example response</summary> <p> ```js [ { 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>
NEAR Community Update: February 14th, 2020 COMMUNITY February 14, 2020 The event season begins! Starting off, you can find us at ETHDenver and Developer Week in San Francisco. Our team took extra care to create an amazing booth experience. Check-out the video below: At #ETHDenver we’re excited to bring our engineers, product, and accelerator team together with developers. If you are around, come chat with us at NEAR’s Friday ETHDenver workshop. Kendall and Illia will be talking about how to write, deploy and interact with Rust, TypeScript, and Solidity smart contracts on NEAR. You can find all the information you need about our hackathon prizes and workshops in the following blog. #DEVWEEK2020 @ilblackdragon on stage at @DeveloperWeek discussing #openweb participation. 🌎 pic.twitter.com/H295AEnidi — NEAR Protocol (@NEARProtocol) February 13, 2020 New Release: The Open Web Collective Incubator and Accelerator Many teams create exciting new projects at hackathons and then face the difficult decision of whether or not to continue them as side projects or even potentially as businesses. To help teams navigate this decision and then take the next step with their projects, we are supporting the launch of the Open Web Collective (OWC) Incubator and Accelerator. The Open Web Collective, which is supported by NEAR, is a community of crypto-native entrepreneurs and mentors who are pushing past the hype and building the projects that will bring the vision of the Open Web to reality. They are looking for hungry and talented teams who need support from ideation all the way through funding. Learn more and apply at https://openwebcollective.com/ Content Highlights We released Doomslug, our new block production technique, a month ago. As a follow-up to the paper (and to make the content more consumable), we recently released a blog post that highlights how Doomslug compares to PBFT, Tendermint, and Hotstuff. Please let us know what you think about it or if you have any open questions. How You Can Get Involved Join the NEAR Contributor Program. If you would like to host events, create content or provide developer feedback, we would love to hear from you! To learn more about the program and ways to participate, please head over to the website. If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox.
--- title: Crowd (NEAR Tasks) description: Overview of a new gig economy powered by NEAR BOS sidebar_position: 10 --- # NEAR Tasks ## Highlights * A new gig-economy platform powered by NEAR BOS that gives anyone the opportunity to quickly and easily earn $NEAR. * It is a way to bring more users into the Web3 space and understand what tasks they are willing to complete to earn crypto. ### What it is: NEAR Tasks is an exciting new platform powered by NEAR's Blockchain Operating System (BOS) that allows anyone to earn $NEAR just by completing simple tasks. Designed for creatives, remote workers, and anyone interested in participating in the gig economy, NEAR Tasks open up the crypto economy to everyone, making it easy to start earning crypto anytime, anywhere. ### Why it matters: The crypto space has felt inaccessible to much of the population. While there is often significant interest, people find it difficult to understand how they can get or earn crypto, what they can do with it, and why it matters. This has created a challenge for bringing large numbers of people into the space and continues to serve as a limit to its potential growth. To overcome this, it’s important to develop experiences that both feel familiar to potential users, and serve a real purpose for them. That’s where NEAR Tasks comes in. NEAR Tasks enables people to do what many people are already doing, earning money in the gig economy by working simple tasks. But rather than having this pass through third parties, it is a fully decentralized crypto based earning experience. The platform offers three unique experiences (see below), each focused on a specific use case, meant to demonstrate how flexible users can be when delivering work for a varying array of skill sets. Each task type can help show how motivated users are to complete work items of varying complexity in order to earn $NEAR. The goal is to have NEAR Tasks become a decentralized and self governing work distribution platform. ### Who it’s for: * Everyone - NEAR Tasks is for creatives, remote workers, and anyone interested in participating in a new, crypto based, gig economy. ### How it works: 1. Sign up * Users (also referred to as Taskers) sign up for a NEAR account using FastAuth or connect an existing NEAR Wallet. * All Tasks stats (tasks completed / earnings accumulated / quality score) are linked to a specific NEAR account. 2. Accessing tasks * Taskers access tasks associated with a scanned QR code. * They can also scroll the task feed which showcases all available task types and their associated requirements to complete. 3. Task completion * Once a task is claimed, a Tasker must complete it within the live session and upon submission, their earnings will appear as ‘pending’ until verified by another Tasker that picks up their task for review. 4. Feedback * Stats for Taskers run in the background, enabling them to see how they are doing and what improvements can be made next time - in the event a task is marked as incorrect. * To prevent spam/bad actors, Taskers must earn a minimum amount of $NEAR and have >85% quality score to withdraw funds. ### Types of tasks: * Image Labeling – data verification * Taskers are prompted to write a high level overview of an image and then select several points within the image to describe before submitting for review. The review process consists of a new user analyzing the image and descriptions provided by the initial user to determine if it’s accurate. * Writing a hot take from the conference – data aggregation * Taskers are prompted to share a brief thought about what they learned from the conference to increase information sharing (e.g. a key takeaway from a panel discussion, a conversation they had with someone in passing, something they learned at a booth, etc). The review process is to detect if the entry should be considered as spam. * Sharing a photo to twitter with specific tags – social activation * To encourage a fun and engaging way to create user generated content, Taskers are prompted to take a photo with the NEAR logo in the background, share it to twitter, tag @NEARProtocol, and use the hashtag #EarnWithNEARTasks. The review process is to ensure the NEAR logo is present in the photo and the correct tags are used. ### What’s next: * Following Consensus, our aim is to initiate an intense Beta testing phase where we will collaborate with specific user groups and gather feedback before making the platform available to everyone. * The long term goal is to establish an interactive two-sided marketplace, where tasks encompassing a variety of skill levels are provided by companies, and Taskers are matched according to their proven abilities. * As part of the long term roadmap, the $NEAR earned by Taskers will serve as an incentive to explore financial literacy content and tools, with the primary objective of encouraging users to discover practical applications for their $NEAR, rather than merely converting it to fiat currency.
--- id: marketplace title: Marketplace sidebar_label: Marketplace --- import {Github} from "@site/src/components/codetabs" In this tutorial, you'll learn the basics of an NFT marketplace contract where you can buy and sell non-fungible tokens for $NEAR. In the previous tutorials, you went through and created a fully fledged NFT contract that incorporates all the standards found in the [NFT standard](https://nomicon.io/Standards/NonFungibleToken). ## Introduction Throughout this tutorial, you'll learn how a marketplace contract could work on NEAR. This is meant to be an example and there is no canonical implementation. Feel free to branch off and modify this contract to meet your specific needs. Using the same repository as the previous tutorials, if you checkout the `8.marketplace` branch, you should have the necessary files to complete the tutorial. ```bash git checkout 8.marketplace ``` ## File structure {#file-structure} ``` market-contract └── src ├── internal.ts ├── index.ts ├── nft_callbacks.ts ├── sale.ts └── sale_views.ts ``` Usually, when doing work on multiple smart contracts that all pertain to the same repository, it's a good idea to structure them in their own folders as done in this tutorial. To make your work easier when building the smart contracts, we've also modified the repository's `package.json` file so that building both smart contracts can be easily done by running the following command. ```bash yarn build ``` This will install the dependencies for both contracts and compile them to `wasm` files that are stored in the following directory. ``` nft-tutorial-js └── build ├── nft.wasm └── market.wasm ``` ## Understanding the contract At first, the contract can be quite overwhelming but if you strip away all the fluff and dig into the core functionalities, it's actually quite simple. This contract was designed for only one thing - to allow people to buy and sell NFTs for NEAR. This includes the support for paying royalties, updating the price of your sales, removing sales and paying for storage. Let's go through the files and take note of some of the important functions and what they do. ## index.ts {#index-ts} This file outlines what information is stored on the contract as well as some other crucial functions that you'll learn about below. ### Constructor logic {#constructor-logic} The first function you'll look at is the constructor function. This takes an `owner_id` as the only parameter and will default all the storage collections to their default values. <Github language="js" start="40" end="52" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/index.ts" /> ### Storage management model {#storage-management-model} Next, let's talk about the storage management model chosen for this contract. On the NFT contract, users attached $NEAR to the calls that needed storage paid for. For example, if someone was minting an NFT, they would need to attach `x` amount of NEAR to cover the cost of storing the data on the contract. On this marketplace contract, however, the storage model is a bit different. Users will need to deposit $NEAR onto the marketplace to cover the storage costs. Whenever someone puts an NFT for sale, the marketplace needs to store that information which costs $NEAR. Users can either deposit as much NEAR as they want so that they never have to worry about storage again or they can deposit the minimum amount to cover 1 sale on an as-needed basis. You might be thinking about the scenario when a sale is purchased. What happens to the storage that is now being released on the contract? This is why we've introduced a storage withdrawal function. This allows users to withdraw any excess storage that is not being used. Let's go through some scenarios to understand the logic. The required storage for 1 sale is 0.01 NEAR on the marketplace contract. **Scenario A** - Benji wants to list his NFT on the marketplace but has never paid for storage. - He deposits exactly 0.01 NEAR using the `storage_deposit` method. This will cover 1 sale. - He lists his NFT on the marketplace and is now using up 1 out of his prepaid 1 sales and has no more storage left. If he were to call `storage_withdraw`, nothing would happen. - Dorian loves his NFT and quickly purchases it before anybody else can. This means that Benji's sale has now been taken down (since it was purchased) and Benji is using up 0 out of his prepaid 1 sales. In other words, he has an excess of 1 sale or 0.01 NEAR. - Benji can now call `storage_withdraw` and will be transferred his 0.01 NEAR back. On the contract's side, after withdrawing, he will have 0 sales paid for and will need to deposit storage before trying to list anymore NFTs. **Scenario B** - Dorian owns one hundred beautiful NFTs and knows that he wants to list all of them. - To avoid having to call `storage_deposit` everytime he wants to list an NFT, he calls it once. Since Dorian is a baller, he attaches 10 NEAR which is enough to cover 1000 sales. He now has an excess of 9 NEAR or 900 sales. - Dorian needs the 9 NEAR for something else but doesn't want to take down his 100 listings. Since he has an excess of 9 NEAR, he can easily withdraw and still have his 100 listings. After calling `storage_withdraw` and being transferred 9 NEAR, he will have an excess of 0 sales. With this behavior in mind, the following two functions outline the logic. <Github language="js" start="58" end="121" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/index.ts" /> In this contract, the storage required for each sale is 0.01 NEAR but you can query that information using the `storage_minimum_balance` function. In addition, if you wanted to check how much storage a given account has paid, you can query the `storage_balance_of` function. With that out of the way, it's time to move onto the `nft_callbacks.ts` file where you'll look at how NFTs are put for sale. ## nft_callbacks.ts {#nft_callbacks-ts} This file is responsible for the logic used to put NFTs for sale. If you remember from the [marketplaces section](/tutorials/nfts/js/approvals#marketplace-integrations) of the approvals tutorial, when users call `nft_approve` and pass in a message, it will perform a cross-contract call to the `receiver_id`'s contract and call the method `nft_on_approve`. This `nft_callbacks.ts` file will implement that function. ### Listing logic {#listing-logic} The market contract is expecting the message that the user passes into `nft_approve` on the NFT contract to be JSON stringified sale arguments. This outlines the sale price in yoctoNEAR for the NFT that is listed. The `nft_on_approve` function is called via a cross-contract call by the NFT contract. It will make sure that the signer has enough storage to cover adding another sale. It will then attempt to get the sale conditions from the message and create the listing. <Github language="js" start="6" end="73" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/nft_callbacks.ts" /> ## sale.ts {#sale-ts} Now that you're familiar with the process of both adding storage and listing NFTs on the marketplace, let's go through what you can do once a sale has been listed. The `sale.ts` file outlines the functions for updating the price, removing, and purchasing NFTs. ### Sale object {#sale-object} It's important to understand what information the contract is storing for each sale object. Since the marketplace has many NFTs listed that come from different NFT contracts, simply storing the token ID would not be enough to distinguish between different NFTs. This is why you need to keep track of both the token ID and the contract by which the NFT came from. In addition, for each listing, the contract must keep track of the approval ID it was given to transfer the NFT. Finally, the owner and sale conditions are needed. <Github language="js" start="9" end="42" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/sale.ts" /> ### Removing sales {#removing-sales} In order to remove a listing, the owner must call the `remove_sale` function and pass the NFT contract and token ID. Behind the scenes, this calls the `internallyRemoveSale` function which you can find in the `internal.ts` file. This will assert one yoctoNEAR for security reasons. <Github language="js" start="44" end="65" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/sale.ts" /> ### Updating price {#updating-price} In order to update the list price of a token, the owner must call the `update_price` function and pass in the contract, token ID, and desired price. This will get the sale object, change the sale conditions, and insert it back. For security reasons, this function will assert one yoctoNEAR. <Github language="js" start="67" end="96" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/sale.ts" /> ### Purchasing NFTs {#purchasing-nfts} For purchasing NFTs, you must call the `offer` function. It takes an `nft_contract_id` and `token_id` as parameters. You must attach the correct amount of NEAR to the call in order to purchase. Behind the scenes, this will make sure your deposit is greater than the list price and call a private method `processPurchase` which will perform a cross-contract call to the NFT contract to invoke the `nft_transfer_payout` function. This will transfer the NFT using the [approval management](https://nomicon.io/Standards/Tokens/NonFungibleToken/ApprovalManagement) standard that you learned about and it will return the `Payout` object which includes royalties. The marketplace will then call `resolve_purchase` where it will check for malicious payout objects and then if everything went well, it will pay the correct accounts. <Github language="js" start="98" end="131" url="https://github.com/near-examples/nft-tutorial-js/blob/8.marketplace/src/market-contract/sale.ts" /> ## sale_view.ts {#sale_view-ts} The final file we'll go through is the `sale_view.ts` file. This is where some of the enumeration methods are outlined. It allows users to query for important information regarding sales. ### Total supply {#total-supply} To query for the total supply of NFTs listed on the marketplace, you can call the `get_supply_sales` function. An example can be seen below. ```bash near view $MARKETPLACE_CONTRACT_ID get_supply_sales ``` ### Total supply by owner {#total-supply-by-owner} To query for the total supply of NFTs listed by a specific owner on the marketplace, you can call the `get_supply_by_owner_id` function. An example can be seen below. ```bash near view $MARKETPLACE_CONTRACT_ID get_supply_by_owner_id '{"account_id": "benji.testnet"}' ``` ### Total supply by contract {#total-supply-by-contract} To query for the total supply of NFTs that belong to a specific contract, you can call the `get_supply_by_nft_contract_id` function. An example can be seen below. ```bash near view $MARKETPLACE_CONTRACT_ID get_supply_by_nft_contract_id '{"nft_contract_id": "fayyr-nft.testnet"}' ``` ### Query for listing information {#query-listing-information} To query for important information for a specific listing, you can call the `get_sale` function. This requires that you pass in the `nft_contract_token`. This is essentially the unique identifier for sales on the market contract as explained earlier. It consists of the NFT contract followed by a `DELIMITER` followed by the token ID. In this contract, the `DELIMITER` is simply a period: `.`. An example of this query can be seen below. ```bash near view $MARKETPLACE_CONTRACT_ID get_sale '{"nft_contract_token": "fayyr-nft.testnet.token-42"}' ``` In addition, you can query for paginated information about the listings for a given owner by calling the `get_sales_by_owner_id` function. ```bash near view $MARKETPLACE_CONTRACT_ID get_sales_by_owner_id '{"account_id": "benji.testnet", "from_index": "5", "limit": 10}' ``` Finally, you can query for paginated information about the listings that originate from a given NFT contract by calling the `get_sales_by_nft_contract_id` function. ```bash near view $MARKETPLACE_CONTRACT_ID get_sales_by_nft_contract_id '{"nft_contract_id": "fayyr-nft.testnet, "from_index": "5", "limit": 10}' ``` ## Conclusion In this tutorial, you learned about the basics of a marketplace contract and how it works. You went through the [index.ts](#index-ts) file and learned about the [initialization function](#initialization-function) in addition to the [storage management](#storage-management-model) model. You then went through the [nft_callbacks](#nft_callbacks-ts) file to understand how to [list NFTs](#listing-logic). In addition, you went through some important functions needed for after you've listed an NFT. This includes [removing sales](#removing-sales), [updating the price](#updating-price), and [purchasing NFTs](#purchasing-nfts). Finally, you went through the enumeration methods found in the [`sale_view`](#sale_view-ts) file. These allow you to query for important information found on the marketplace contract. You should now have a solid understanding of NFTs and marketplaces on NEAR. Feel free to branch off and expand on these contracts to create whatever cool applications you'd like. The world is your oyster! Thanks for joining on this journey and don't forget, **Go Team!** :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `3.0.0` - NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0` :::
Vistara Lands in the NEAR Ecosystem for Seamless Base Layer Roll-up Deployment DEVELOPERS July 7, 2023 NEAR is welcoming Vistara, the groundbreaking rollup deployment framework, into the fold. Vistara is set to seamlessly integrate with the BOS for the end-to-end, multi-chain deployment of rollups. This alliance will accelerate the pace of blockchain innovation, making rollup deployment faster, more efficient, and accessible across multiple chains for all developers. Vistara stands out as a game-changing one-click rollup deployment framework that simplifies creating application-specific rollups across multiple blockchains. Streamlining the intricate rollup deployment process into a straightforward, single-click operation, Vistara will build a front-end on the BOS to make user-friendly, multi-chain rollup deployment a reality. Simplifying multi-chain roll-ups with Vistara on the BOS Existing frameworks such as Cosmos SDK and Substrate have sought to streamline certain software components in decentralized applications but often leave developers tied to one ecosystem that they must completely understand and master. Vistara will now present a unique solution by combining the BOS with backend chains like Ethereum and Celestia. Vistara’s emphasis on simplifying rollup component creation aligns with NEAR’s vision of user-centric decentralization and a serverless Web3. With this new BOS front-end integration, developers in the NEAR ecosystem and beyond can now build and deploy rollups in one convenient location. The result will be a user-friendly design that makes the deployment of a rollup as simple as selecting an option from a dropdown menu. The integration will also encourage a wider range of developers to build with rollups on the BOS with any chain, leading to a more diverse pool of innovations and robust growth. Vistara’s integration not only simplifies the process but also expands the scope for innovation. It demystifies rollup creation, making it accessible to a broader range of developers. This inclusivity fuels a more diverse pool of applications, fostering growth and vibrancy within the NEAR ecosystem. Vistara and BOS breaking base layer building barriers Developing decentralized applications on base layers can be a complex process. Coordination of node operators, high costs, and extended development times are among the major challenges. However, Vistara is designed to confront these issues directly, streamlining the process and fostering efficiency. Rollups — technologies that bundle or ‘roll up’ side-chain transactions into a single transaction — provide an effective solution. They help developers bypass the difficulties associated with building decentralized networks. Vistara leverages this rollup technology, pushing the NEAR ecosystem towards application-specific rollups. The solution effectively untangles the complexities tied to base layer dependencies, forging a development environment on the BOS that stretches beyond traditional base layer confines. With Vistara, multi-chain developers can now bring their applications to life more swiftly and efficiently than ever before. To sum up, Vistara’s user-friendly, multi-chain rollup deployment capabilities on the BOS will have a huge impact on the NEAR ecosystem and beyond. The integration will take much of the complexity out of rollup deployment for anyone, helping Web3 creators, builders, and developers bring their applications to life faster than ever.
Register for NEAR’s March Town Hall: DAOs on NEAR NEAR FOUNDATION March 30, 2022 Hello, NEAR World. 2022 is shaping up to be the year of the DAO. Join the community for NEAR’s March Town Hall on March 21, 5:00pm GMT (1:00PM EDT/10:00am PDT) for a deep dive into NEAR’s ecosystem of DAOs. NEAR Foundation CEO Marieke Flament will open the Town Hall with some updates on the ecosystem and the Foundation’s progress in advancing Web3. There will also be a flurry of news and NEAR protocol updates, including ecosystem funding and education efforts, the MetaBUILD 2 winners, news on new events, and a panel focused entirely on DAOs. There will also be talk of Ukraine, especially how DAOs have stepped up and supported humanitarian relief efforts. MetaBUILD 2 Hackathon Winners Since December, the NEAR community has been hosting the MetaBUILD 2 hackathon—the biggest one yet, with over 3,900 participants and 20+ partners. Pagoda’s Maria Yarotska will be at the March Town Hall to talk MetaBUILD 2, including how the war in Ukraine impacted the judging process. Maria will also update the community on the winning teams and projects, and will share information on upcoming hackathons. A Panel on DAOs NEAR Foundation CEO Marieke Flament will return to talk briefly about the DAO community on NEAR. There will also be a panel focused on DAOs, with surprise guests from several different Web3 platforms and DAOs. Register for the March Town Hall To join the conversation with the global NEAR community, register for the March Town Hall.
Community Update: All our Node are Belong to You COMMUNITY September 29, 2020 Hello citizens of NEARverse! This is NiMA coming to you from a NEARby planet in the Milky Chain … TL;DR: “For the first time, we can say that NEAR is officially and undeniably community operated.” – Erik “Twain” Trautman We are collectively NEARing a new chapter in the journey of the NEAR community and network. The foundation has shut down all its nodes and effectively handed over the reigns of the network to a subset of pioneering node operators from the community and our NEAR Validator Advisory Board (aka NVAB). In parallel we have also been doubling down on growing our builder community non-stop 24/7. Hack the Rainbow and our webinar series welcomed hundreds of new NEAR enthusiasts and developers to our ecosystem. We will also be sponsoring ETHOnline where we will introduce NEAR to the larger web 3 dev ecosystem with special focus on NEAR’s A++ usability. MainNet Phase II: what it means for you … NEAR’s transition to a fully community-governed permissionless network is unique and arguably a first of its kind in the blockchain space. In our Community Town Hall #1, Viktor (protocol specialist at BisonTrails) laid out a set of proposed processes and criteria for the upgrade to Phase II. A detailed overview of these criteria can be found on Github, but here we will go over some of the most important elements … Important to note is that Phase II involves two distinct actions by the validators. An on-chain vote to unlock token transfers and an upgrade of the nearcore software to enable inflationary rewards. To ensure community members can participate, the vote will not happen until 100 million of tokens are claimed by the token holders. In aggregate there needs to be 200 million of the total 750 million tokens staked. We understand that some of the participants in our recent Coinlist token sale have not yet received or claimed their tokens. Rest assured, since token transfer has not yet been unlocked for anyone. That will only happen after a successful vote to transition to Phase 2. The exact date for unlocking of tokens will be 40 days (reg. requirement) from Aug 25th or Oct 4th. Whichever is latest. In case you have already received your tokens and would like to delegate to a staking pool you can do that by following the instruction on this page. The primary method for delegation described in this doc relies on CLI (command line interface), but one of our active ecosystem members (Dokia Capital) have developed a web interface for those who are not comfortable with CLI. Lastly, we invite you to join the conversation on near.chat #validator-lounge to get to know our validators and ask all your staking related questions! Engineering Updates Our engineering team is dedicating more resources to EVM on NEAR and Rainbow Bridge which should make it even easier for web 3 projects to add support for NEAR to their projects. We made some improvements to our core testing infrastructure (1, 2, 3, 4); We have redirected more engineering resources into polishing bridge and EVM. Approximately half of the core engineering team is now working on bridge and EVM; We matched EVM gas to NEAR gas; We are actively researching the idea of adding synchronous calls and we have brainstormed several designs in the last two weeks. Edu Updates Our devX and Edu teams, in collaboration with members of our dev community, have been producing tons of educational materials and workshops during Hack the Rainbow hackathon and webinar series. Here’s a short list with direct links for your convenience 🤓 WASM v. EVM on NEAR: https://www.crowdcast.io/e/hacktherainbow/17 NEAR 102 – intro to NEAR for Web 3/Ethereum devs: https://www.crowdcast.io/e/hacktherainbow/13 NEAR Accounts and key registration 🔑 : https://www.crowdcast.io/e/hacktherainbow/7 Deep dive into ETH<>NEAR Rainbow Bridge 🌉: https://www.crowdcast.io/e/hacktherainbow/2 SkyNet (Sia) on NEAR 💥 : https://www.crowdcast.io/e/hacktherainbow/8 The State of DAOs (spoiler alert! NEAR is a perfffect match for DAOs): https://www.crowdcast.io/e/hacktherainbow/9 This week we’re reading, watching, … Watch 👁 Open Web Collective held their final demo day for the first batch of projects on Crowdcast! Read 📖 NEAR MainNet is now Community-Operated Listen 👂 Mona El Isa joins Sasha on Building the Open Web podcast to talk about her journey from a trad. hedge fund manager to building the protocol for managing onchain assets. That’s it for this update. See you in the next one! Your friends, NiMA and the NEAR team
NEAR Foundation and PipeFlare Team Up to Reshape Web3 Gaming NEAR FOUNDATION May 2, 2023 NEAR Foundation and PipeFlare, a trailblazing play-to-earn (P2E) platform, are partnering to reshape Web3 gaming by building on Aurora, NEAR’s Ethereum-compatible layer. As Web3 gaming on NEAR accelerates, PipeFlare will enable gamers to play, earn crypto, and engage socially in a decentralized environment. Collaborating with NEAR Foundation, PipeFlare aims to redefine scalability, security, and sheer enjoyment in Web3 by leveraging the EVM-compatible development capabilities of Aurora. PipeFlare is one of the industry’s most reliable Web3-enabled gaming platforms, allowing users to earn cryptocurrency through gameplay, tasks, and activities. The partnership will help create more intricate, engaging Web3 games in a secure fashion. The collaboration will most certainly attract more users to Web3 gaming, while making NEAR a top choice for game developers. Let’s delve into the PipeFlare and NEAR Foundation partnership, the advantages of the NEAR Blockchain Operating System and tech stack for Web3 gaming, and how the collaboration positively impacts the future of the NEAR decentralized gaming ecosystem. Transforming play: PipeFlare’s NEAR-driven gaming evolution Pipeflare is one of the most reputable P2E gaming sites in the industry, backed by some of the largest investors in the blockchain space like DCG and Horizen Labs. All PipeFlare transactions are published publicly as well, giving gamers more transparency and peace of mind in Web3 gaming, earning, transacting, and collecting. Gamers can enjoy playing games, collecting free cryptocurrency from PipeFlare faucets, participating in airdrops, competing in weekly leaderboards, and earning rewards through the referral program. Additionally, players can buy and sell limited-mint NFTs on PipeFlare’s NFT marketplace. PipeFlare’s exclusive Pyro NFT also brings perks like staking bonuses and a secret fourth crypto faucet to users. A dedicated support team demystifies blockchain and NFTs, while NEAR’s scalability enhances transactions without sacrificing speed or efficiency. This paves the way for PipeFlare’s explosive growth in the dynamic Web3 gaming market. As security becomes more paramount in safeguarding digital assets and identities in Web3 gaming, PipeFlare is now embracing the speed and security of NEAR infrastructure. This ensures the protection of user data and assets and provides a cutting-edge, trustworthy, and reliable Web3 gaming experience for users to explore and enjoy. Making Web3 Gaming more scalable, secure, and dev-friendly NEAR’s intuitive, developer-focused platform offers substantial advantages for PipeFlare, simplifying game development and empowering creators to craft groundbreaking Web3 gaming experiences for veteran gamers and newcomers alike. But the PipeFlare and NEAR Foundation collaboration will transcend mere technology integration. Harnessing the BOS, PipeFlare can introduce even deeper functionality to players in areas like NFTs, in-game token rewards, and community engagement. As one of the only platforms where NFTs can be ported into multiple games, PipeFlare is breaking new ground in the industry. NEAR Foundation is excited about this new portable NFT model in Web3 gaming, and will focus on the following three areas to help accelerate PipeFlare: Scalability. One of the biggest challenges facing Web3 gaming is scalability. Traditional blockchains are not designed to handle the high volume of transactions required for gaming. NEAR is a high-performance blockchain that can handle a large number of transactions per second, making it ideal for Web3 gaming. Security. Another important factor for Web3 gaming is security. Players need to be confident that their data and assets are safe when playing games on the blockchain. The BOS uses a variety of security measures to protect gamer data and ensure the protection and provenance of all digital assets. User-Friendliness. Web3 gaming needs to be user-friendly to succeed and grow in the long term. Users need to be able to easily create and manage their accounts, buy and sell NFTs, and play games. With the BOS being one of the most developer-friendly ecosystems to build on, PipeFlare is set to make big strides in Web3 gamer onboarding. To get the ball rolling, the partnership will initially focus on upgrading Pipeflare’s existing games and developing new ones using the BOS. This transition will enhance the gaming experience for users and showcase the capabilities of NEAR’s technology in the Web3 gaming space. The collaboration also marks substantial progress for the Web3 gaming industry, demonstrating that key players recognize NEAR’s potential. It also signals NEAR’s strong positioning to emerge as the premier blockchain for novel gaming experiences.
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="Paras" label="Paras"> ```js Near.call( "marketplace.paras.near", "storage_deposit", { receiver_id: "bob.near" }, undefined, 9390000000000000000 ); Near.call( "nft.primitives.near", "nft_approve", { token_id: "1e95238d266e5497d735eb30", account_id: "marketplace.paras.near", msg: { price: "200000000000000000000000", market_type: "sale", ft_token_id: "near" } } ); ``` The method `nft_approve` will call `nft_on_approve` in `marketplace.paras.near`. </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```js Near.call( "simple.market.mintbase1.near", "deposit_storage", { autotransfer: true }, undefined, 9390000000000000000 ); Near.call( "nft.primitives.near", "nft_approve", { token_id: "3c46b76cbd48e65f2fc88473", account_id: "simple.market.mintbase1.near", msg: { price: "200000000000000000000000" } } ); ``` The method `nft_approve` will call `nft_on_approve` in `simple.market.mintbase1.near`. </TabItem> </Tabs>
--- id: core title: Transfers --- import {Github} from "@site/src/components/codetabs" In this tutorial you'll learn how to implement NFT transfers as defined in the [core standards](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) into your smart contract. We will define two methods for transferring NFTs: - `nft_transfer`: that transfers ownership of an NFT from one account to another - `nft_transfer_call`: that transfers an NFT to a "receiver" and calls a method on the receiver's account :::tip Why two transfer methods? `nft_transfer` is a simple transfer between two user, while `nft_transfer_call` allows you to **attach an NFT to a function call** ::: --- ## Introduction {#introduction} Up until this point, you've created a simple NFT smart contract that allows users to mint tokens and view information using the [enumeration standards](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration). Today, you'll expand your smart contract to allow for users to not only mint tokens, but transfer them as well. As we did in the [minting tutorial](/tutorials/nfts/minting), let's break down the problem into multiple subtasks to make our lives easier. When a token is minted, information is stored in 3 places: - **tokens_per_owner**: set of tokens for each account. - **tokens_by_id**: maps a token ID to a `Token` object. - **token_metadata_by_id**: maps a token ID to its metadata. Let's now consider the following scenario. If Benji owns token A and wants to transfer it to Mike as a birthday gift, what should happen? First of all, token A should be removed from Benji's set of tokens and added to Mike's set of tokens. If that's the only logic you implement, you'll run into some problems. If you were to do a `view` call to query for information about that token after it's been transferred to Mike, it would still say that Benji is the owner. This is because the contract is still mapping the token ID to the old `Token` object that contains the `owner_id` field set to Benji's account ID. You still have to change the `tokens_by_id` data structure so that the token ID maps to a new `Token` object which has Mike as the owner. With that being said, the final process for when an owner transfers a token to a receiver should be the following: - Remove the token from the owner's set. - Add the token to the receiver's set. - Map a token ID to a new `Token` object containing the correct owner. :::note You might be curious as to why we don't edit the `token_metadata_by_id` field. This is because no matter who owns the token, the token ID will always map to the same metadata. The metadata should never change and so we can just leave it alone. ::: At this point, you're ready to move on and make the necessary modifications to your smart contract. --- ## Modifications to the contract Let's start our journey in the `nft-contract-skeleton/src/nft_core.rs` file. ### Transfer function {#transfer-function} You'll start by implementing the `nft_transfer` logic. This function will transfer the specified `token_id` to the `receiver_id` with an optional `memo` such as `"Happy Birthday Mike!"`. <Github language="rust" start="60" end="80" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/nft_core.rs" /> There are a couple things to notice here. Firstly, we've introduced a new function called `assert_one_yocto()`, which ensures the user has attached exactly one yoctoNEAR to the call. This is a [security measure](../../2.build/2.smart-contracts/security/one_yocto.md) to ensure that the user is signing the transaction with a [full access key](../../1.concepts/protocol/access-keys.md). Since the transfer function is potentially transferring very valuable assets, you'll want to make sure that whoever is calling the function has a full access key. Secondly, we've introduced an `internal_transfer` method. This will perform all the logic necessary to transfer an NFT. <hr class="subsection" /> ### Internal helper functions Let's quickly move over to the `nft-contract/src/internal.rs` file so that you can implement the `assert_one_yocto()` and `internal_transfer` methods. Let's start with the easier one, `assert_one_yocto()`. #### assert_one_yocto <Github language="rust" start="14" end="21" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/internal.rs" /> #### internal_transfer It's now time to explore the `internal_transfer` function which is the core of this tutorial. This function takes the following parameters: - **sender_id**: the account that's attempting to transfer the token. - **receiver_id**: the account that's receiving the token. - **token_id**: the token ID being transferred. - **memo**: an optional memo to include. The first thing we have to do is to make sure that the sender is authorized to transfer the token. In this case, we just make sure that the sender is the owner of the token. We do that by getting the `Token` object using the `token_id` and making sure that the sender is equal to the token's `owner_id`. Second, we remove the token ID from the sender's list and add the token ID to the receiver's list of tokens. Finally, we create a new `Token` object with the receiver as the owner and remap the token ID to that newly created object. We want to create this function within the contract implementation (below the `internal_add_token_to_owner` you created in the minting tutorial). <Github language="rust" start="96" end="132" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/internal.rs" /> Now let's look at the function called `internal_remove_token_from_owner`. That function implements the functionality for removing a token ID from an owner's set. In the remove function, we get the set of tokens for a given account ID and then remove the passed in token ID. If the account's set is empty after the removal, we simply remove the account from the `tokens_per_owner` data structure. <Github language="rust" start="71" end="94" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/internal.rs" /> Your `internal.rs` file should now have the following outline: ``` internal.rs ├── hash_account_id ├── assert_one_yocto ├── refund_deposit └── impl Contract ├── internal_add_token_to_owner ├── internal_remove_token_from_owner └── internal_transfer ``` <hr class="subsection" /> ### Transfer call function {#transfer-call-function} The idea behind the `nft_transfer_call` function is to transfer an NFT to a receiver while calling a method on the receiver's contract all in the same transaction. This way, we can effectively **attach an NFT to a function call**. <Github language="rust" start="82" end="126" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/nft_core.rs" /> The function will first assert that the caller attached exactly 1 yocto for security purposes. It will then transfer the NFT using `internal_transfer` and start the cross contract call. It will call the method `nft_on_transfer` on the `receiver_id`'s contract, and create a promise to call back `nft_resolve_transfer` with the result. This is a very common workflow when dealing with [cross contract calls](../../2.build/2.smart-contracts/anatomy/crosscontract.md). As dictated by the core standard, the function we are calling (`nft_on_transfer`) needs to return a boolean stating whether or not you should return the NFT to it's original owner. <Github language="rust" start="146" end="201" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/nft_core.rs" /> If `nft_on_transfer` returned true or the called failed, you should send the token back to it's original owner. On the contrary, if false was returned, no extra logic is needed. As for the return value of our function `nft_resolve_transfer`, the standard dictates that the function should return a boolean indicating whether or not the receiver successfully received the token or not. This means that if `nft_on_transfer` returned true, you should return false. This is because if the token is being returned its original owner, the `receiver_id` didn't successfully receive the token in the end. On the contrary, if `nft_on_transfer` returned false, you should return true since we don't need to return the token and thus the `receiver_id` successfully owns the token. With that finished, you've now successfully added the necessary logic to allow users to transfer NFTs. It's now time to deploy and do some testing. --- ## Redeploying the contract {#redeploying-contract} Using cargo-near, deploy the contract as you did in the previous tutorials: ```bash cargo near deploy $NFT_CONTRACT_ID without-init-call network-config testnet sign-with-keychain send ``` :::tip If you haven't completed the previous tutorials and are just following along with this one, simply create an account and login with your CLI using `near login`. You can then export an environment variable `export NFT_CONTRACT_ID=YOUR_ACCOUNT_ID_HERE`. ::: --- ## Testing the new changes {#testing-changes} Now that you've deployed a patch fix to the contract, it's time to move onto testing. Using the previous NFT contract where you had minted a token to yourself, you can test the `nft_transfer` method. If you transfer the NFT, it should be removed from your account's collectibles displayed in the wallet. In addition, if you query any of the enumeration functions, it should show that you are no longer the owner. Let's test this out by transferring an NFT to the account `benjiman.testnet` and seeing if the NFT is no longer owned by you. <hr class="subsection" /> ### Testing the transfer function :::note This means that the NFT won't be recoverable unless the account `benjiman.testnet` transfers it back to you. If you don't want your NFT lost, make a new account and transfer the token to that account instead. ::: If you run the following command, it will transfer the token `"token-1"` to the account `benjiman.testnet` with the memo `"Go Team :)"`. Take note that you're also attaching exactly 1 yoctoNEAR by using the `--depositYocto` flag. :::tip If you used a different token ID in the previous tutorials, replace `token-1` with your token ID. ::: ```bash near call $NFT_CONTRACT_ID nft_transfer '{"receiver_id": "benjiman.testnet", "token_id": "token-1", "memo": "Go Team :)"}' --accountId $NFT_CONTRACT_ID --depositYocto 1 ``` If you now query for all the tokens owned by your account, that token should be missing. Similarly, if you query for the list of tokens owned by `benjiman.testnet`, that account should now own your NFT. <hr class="subsection" /> ### Testing the transfer call function Now that you've tested the `nft_transfer` function, it's time to test the `nft_transfer_call` function. If you try to transfer an NFT to a receiver that does **not** implement the `nft_on_transfer` function, the contract will panic and the NFT will **not** be transferred. Let's test this functionality below. First mint a new NFT that will be used to test the transfer call functionality. ```bash near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-2", "metadata": {"title": "NFT Tutorial Token", "description": "Testing the transfer call function", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID --amount 0.1 ``` Now that you've minted the token, you can try to transfer the NFT to the account `no-contract.testnet` which as the name suggests, doesn't have a contract. This means that the receiver doesn't implement the `nft_on_transfer` function and the NFT should remain yours after the transaction is complete. ```bash near call $NFT_CONTRACT_ID nft_transfer_call '{"receiver_id": "no-contract.testnet", "token_id": "token-2", "msg": "foo"}' --accountId $NFT_CONTRACT_ID --depositYocto 1 --gas 200000000000000 ``` If you query for your tokens, you should still have `token-2` and at this point, you're finished! --- ## Conclusion In this tutorial, you learned how to expand an NFT contract past the minting functionality and you added ways for users to transfer NFTs. You [broke down](#introduction) the problem into smaller, more digestible subtasks and took that information and implemented both the [NFT transfer](#transfer-function) and [NFT transfer call](#transfer-call-function) functions. In addition, you deployed another [patch fix](#redeploying-contract) to your smart contract and [tested](#testing-changes) the transfer functionality. In the [next tutorial](/tutorials/nfts/approvals), you'll learn about the approval management system and how you can approve others to transfer tokens on your behalf. :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `4.0.13` - cargo-near `0.6.1` - NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.1.0` - Enumeration standard: [NEP181](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration), version `1.0.0` :::
--- NEP: 413 Title: Near Wallet API - support for signMessage method Author: Philip Obosi <philip@near.org>, Guillermo Gallardo <guillermo@near.org> # DiscussionsTo: Status: Approved Type: Standards Track Category: Wallet Created: 25-Oct-2022 --- ## Summary A standardized Wallet API method, namely `signMessage`, that allows users to sign a message for a specific recipient using their NEAR account. ## Motivation NEAR users want to create messages destined to a specific recipient using their accounts. This has multiple applications, one of them being authentication in third-party services. Currently, there is no standardized way for wallets to sign a message destined to a specific recipient. ## Rationale and Alternatives Users want to sign messages for a specific recipient without incurring in GAS fees, nor compromising their account's security. This means that the message being signed: 1. Must be signed off-chain, with no transactions being involved. 2. Must include the recipient's name and a nonce. 3. Cannot represent a valid transaction. 4. Must be signed using a Full Access Key. 5. Should be simple to produce/verify, and transmitted securely. ### Why Off-Chain? So the user would not incur in GAS fees, nor the signed message gets broadcasted into a public network. ### Why The Message MUST NOT be a Transaction? How To Ensure This? An attacker could make the user inadvertently sign a valid transaction which, once signed, could be submitted into the network to execute it. #### How to Ensure the Message is not a Transaction In NEAR, transactions are encoded in Borsh before being signed. The first attribute of a transaction is a `signerId: string`, which is encoded as: (1) 4 bytes representing the string's length, (2) N bytes representing the string itself. By prepending the prefix tag $2^{31} + 413$ we can both ensure that (1) the whole message is an invalid transaction (since the string would be too long to be a valid signer account id), (2) this NEP is ready for a potential future protocol update, in which non-consensus messages are tagged using $2^{31}$ + NEP-number. ### Why The Message Needs to Include a Receiver and Nonce? To stop a malicious app from requesting the user to sign a message for them, only to relay it to a third-party. Including the recipient and making sure the user knows about it should mitigate these kind of attacks. Meanwhile, including a nonce helps to mitigate replay attacks, in which an attacker can delay or re-send a signed message. ### Why using a FullAccess Key? Why Not Simply Creating an [FunctionCall Key](https://docs.near.org/concepts/basics/accounts/access-keys) for Signing? The most common flow for [NEAR user authentication into a Web3 frontend](https://docs.near.org/develop/integrate/frontend#user-sign-in--sign-out) involves the creation of a [FunctionCall Key](<](https://docs.near.org/concepts/basics/accounts/access-keys)>). One might feel tempted to reproduce such process here, for example, by creating a key that can only be used to call a non-existing method in the user's account. This is a bad idea because: 1. The user would need to expend gas in creating a new key. 2. Any third-party can ask the user to create a `FunctionCall Key`, thus opening an attack vector. Using a FullAccess key allows us to be sure that the challenge was signed by the user (since nobody should have access to their `FullAccess Key`), while keeping the constraints of not expending gas in the process (because no new key needs to be created). ### Why The Input Needs to Include a State? Including a state helps to mitigate [CSRF attacks](https://auth0.com/docs/secure/attack-protection/state-parameters). This way, if a message needs to be signed for authentication purposes, the auth service can keep a state to make sure the auth request comes from the right author. ### How to Return the Signed Message in a Safe Way Sending the signed message in a query string to an arbitrary URL (even within the correct domain) is not secure as the data can be leaked (e.g. through headers, etc). Using URL fragments instead will improve security, since [URL fragments are not included in the `Referer`](https://greenbytes.de/tech/webdav/rfc2616.html#header.referer). ### NEAR Signatures NEAR transaction signatures are not plain Ed25519 signatures but Ed25519 signatures of a SHA-256 hash (see [near/nearcore#2835](https://github.com/near/nearcore/issues/2835)). Any protocol that signs anything with NEAR account keys should use the same signature format. ## Specification Wallets must implement a `signMessage` method, which takes a `message` destined to a specific `recipient` and transform it into a verifiable signature. ### Input Interface `signMessage` must implement the following input interface: ```jsx interface SignMessageParams { message: string ; // The message that wants to be transmitted. recipient: string; // The recipient to whom the message is destined (e.g. "alice.near" or "myapp.com"). nonce: [u8; 32] ; // A nonce that uniquely identifies this instance of the message, denoted as a 32 bytes array (a fixed `Buffer` in JS/TS). callbackUrl?: string; // Optional, applicable to browser wallets (e.g. MyNearWallet). The URL to call after the signing process. Defaults to `window.location.href`. state?: string; // Optional, applicable to browser wallets (e.g. MyNearWallet). A state for authentication purposes. } ``` ### Structure `signMessage` must embed the input `message`, `recipient` and `nonce` into the following predefined structure: ```rust struct Payload { message: string; // The same message passed in `SignMessageParams.message` nonce: [u8; 32]; // The same nonce passed in `SignMessageParams.nonce` recipient: string; // The same recipient passed in `SignMessageParams.recipient` callbackUrl?: string // The same callbackUrl passed in `SignMessageParams.callbackUrl` } ``` ### Signature In order to create a signature, `signMessage` must: 1. Create a `Payload` object. 2. Convert the `payload` into its [Borsh Representation](https://borsh.io). 3. Prepend the 4-bytes borsh representation of $2^{31}+413$, as the [prefix tag](https://github.com/near/NEPs/pull/461). 4. Compute the `SHA256` hash of the serialized-prefix + serialized-tag. 5. Sign the resulting `SHA256` hash from step 3 using a **full-access** key. > If the wallet does not hold any `full-access` keys, then it must return an error. ### Example Assuming that the `signMessage` method was invoked, and that: - The input `message` is `"hi"` - The input `nonce` is `[0,...,31]` - The input `recipient` is `"myapp.com"` - The callbackUrl is `"myapp.com/callback"` - The wallet stores a full-access private key The wallet must construct and sign the following `SHA256` hash: ```jsx // 2**31 + 413 == 2147484061 sha256.hash(Borsh.serialize<u32>(2147484061) + Borsh.serialize(Payload{message:"hi", nonce:[0,...,31], recipient:"myapp.com", callbackUrl: "myapp.com/callback"})) ``` ### Output Interface `signMessage` must return an object containing the **base64** representation of the `signature`, and all the data necessary to verify such signature. ```jsx interface SignedMessage { accountId: string; // The account name to which the publicKey corresponds as plain text (e.g. "alice.near") publicKey: string; // The public counterpart of the key used to sign, expressed as a string with format "<key-type>:<base58-key-bytes>" (e.g. "ed25519:6TupyNrcHGTt5XRLmHTc2KGaiSbjhQi1KHtCXTgbcr4Y") signature: string; // The base64 representation of the signature. state?: string; // Optional, applicable to browser wallets (e.g. MyNearWallet). The same state passed in SignMessageParams. } ``` ### Returning the signature #### Web Wallets Web Wallets, such as [MyNearWallet](https://mynearwallet.com), should directly return the `SignedMessage` to the `SignMessageParams.callbackUrl`, passing the `accountId`,`publicKey`, `signature` and the state as URL fragments. This is: `<callbackUrl>#accountId=<accountId>&publicKey=<publicKey>&signature=<signature>&state=<state>`. If the signing process fails, then the wallet must return an error message and the state as string fragments: `<callbackUrl>#error=<error-message-string>&state=<state>`. #### Other Wallets Non-web Wallets, such as [Ledger](https://www.ledger.com) can directly return the `SignedMessage` (in preference as a JSON object) and raise an error on failure. ## References A full example on how to implement the `signMessage` method can be [found here](https://github.com/gagdiez/near-login/blob/1650e25080ab2e8a8c508638a9ba9e9732e76036/server/tests/wallet.ts#L60-L77). ## Drawbacks Accounts that do not hold a FullAccess Key will not be able to sign this kind of messages. However, this is a necessary tradeoff for security since any third-party can ask the user to create a FunctionAccess key. At the time of writing this NEP, the NEAR ledger app is unable to sign this kind of messages, since currently it can only sign pure transactions. This however can be overcomed by modifying the NEAR ledger app implementation in the near future. Non-expert subjects could use this standard to authenticate users in an unsecure way. To anyone implementing an authentication service, we urge them to read about [CSRF attacks](https://auth0.com/docs/secure/attack-protection/state-parameters), and make use of the `state` field. ## Decision Context ### 1.0.0 - Initial Version The Wallet Standards Working Group members approved this NEP on January 17, 2023 ([meeting recording](https://youtu.be/Y6z7lUJSUuA)). ### 1.1.0 - First Revison Important Security concerns were raised by a community member, driving us to change the proposed implementation. ### Benefits - Makes it possible to authenticate users without having to add new access keys. This will improve UX, save money and will not increase the on-chain storage of the users' accounts. - Makes it possible to authorize through jwt in web2 services using the NEAR account. - Removes delays in adding transactions to the blockchain and makes the experience of using projects like NEAR Social better. ### Concerns | # | Concern | Resolution | Status | | --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | 1 | Implementing the signMessage standard will divide wallets into those that will quickly add support for it and those that will take significantly longer. In this case, some services may not work correctly for some users | (1) Be careful when adding functionality with signMessage with legacy and ensure that alternative authorization methods are possible. For example by adding publicKey. (2) Oblige wallets to implement a standard in specific deadlines to save their support in wallet selector | Resolved | | 2 | Large number of off-chain transactions will reduce activity in the blockchain and may negatively affect NEAR rate and attractiveness to third-party developers | There seems to be a general agreement that it is a good default | Resolved | | 3 | `receiver` terminology can be misleading and confusing when existing functionality is taken into consideration (`signTransaction`) | It was recommended for the community to vote for a new name, and the NEP was updated changing `receiver` to `recipient` | Resolved | | 4 | The NEP should emphasize that `nonce` and `receiver` should be clearly displayed to the user in the signing requests by wallets to achieve the desired security from these params being included | We strongly recommend the wallet to clearly display all the elements that compose the message being signed. However, this pertains to the wallet's UI and UX, and not to the method's specification, thus the NEP was not changed. | Resolved | | 5 | NEP-408 (Injected Wallet API) should be extended with this new `signMessage` method | It is not a blocker for this NEP, but a follow-up NEP-extension proposal is welcome. | Resolved | ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
NEAR Community Update: March 8, 2019 COMMUNITY March 8, 2019 It has been enormously gratifying to sit down with some of the top teams from across the ecosystem and watch them get excited about what this platform can provide both their developers and end-users. We certainly have a long way yet to go but our goal of making blockchain development and usage intuitive is resonating in all the right places. Every week we have more to show off. We’re rapidly closing in on our multi-node AlphaNet release and are upgrading the developer tools from proofs-of-concept to professional grade. We’ve also released our new website and will soon introduce a new member of the family to help guide the user journey: Community and Events Another weekend, another hackathon! This time you can find us at ETH Paris giving away coffee and showing off our new development environment. More on that in the next update. We’ve now run dozens of in-person workshops across multiple continents and are starting to enter the online space as well to help give the community more opportunities to learn about the platform. Our first online event was the Decentralized App Development Workshop but it certainly won’t be the last. If you want to host a local NEAR meetup in your city or see if we can support yours, reach out to [email protected]. Recent Events [San Francisco] Feb 23–24: Developer Week Hackathon [Boston] Feb 23: Harvard Business School 2019 Crypto Club (with Alex Skidanov) [Beijing] Feb 23: Blockchain 3.0 — The Evolution in Blockchain DApps [SF] Feb 26: Giving power back to developers: Preview of a new computing platform (@Github) [Oakland] Feb 27: Near Protocol — DevNet Workshop (@Oakland Developers) [Shanghai] Feb 28: Blockchain 3.0 — The Evolution in Blockchain DApps [Mountainview] Feb 28: Learn Blockchain Tools and Technologies that Enable Smart Contracts [ONLINE] March 5 @ 4pm PT / 7pm ET: Decentralized App Development Workshop (video) Upcoming Events [Paris] March 8–10: Events around Eth Paris [Tokyo] March 8: NEAR at Waseda University [Tokyo] March 9: NEAR at HashHub [Beijing] March 11: NEAR at Beijing AI [Beijing] March 13: NEAR at Tsinghua University [SF] March 20: Building on a Blockchain DevNet (Workshop) [San Jose] March 21: Blockchain Developer Meetup [SF] Mar 28: Decentralized Computing with WASM @ Github [SF] Mar 29: Rust Latam conference [San Mateo] Mar 30: San Mateo HS Hackathon [Sydney] April 8: EdCon If you want to collaborate on events, reach out to [email protected] Writing and Content Aliaksandr Hudzillin wrote about Richard Stallman’s vision and how blockchain enables an open future in his piece on The Future of Software Innovation. The Whiteboard Series continues strong with several new videos: Harmony’s Rongjian Lan Interledger’s Dan Robinson Plasma Group’s Ben Jones Engineering Highlights On the application/development layer, we’ve built out the command line tools necessary to build, test and deploy apps to either a local DevNet or our hosted DevNet and upgraded the UI on our wallet. On the blockchain layer, we are finishing up what’s needed to release our multi-node AlphaNet. There were 48 PRs in nearcore from 12 different authors over the last couple of weeks. Blockchain Layer TestNet “Alpha” version is finalized: NightShade consensus runs across multiple nodes with syncing & announcement of blocks, transaction and block proposal gossiping. See documentation on how to run multiple nodes locally. Sped up BLS signature aggregation Application/Development Layer Released command line tools for local development, testing, and deployment Improved NEAR Studio UI and added more templates. Exposed cross-contract APIs in AssemblyScript and published an example with using another token contract. Released new designs for the NEAR Wallet and NEAR website. Released an image that deploys entire NEAR stack (NEARStudio, nearlib, wallet, DevNet, block explorer), which is useful for local development or continuous deployment. How You Can Get Involved Join us! If you want to work with one of the most talented teams in the world right now to solve incredibly hard problems, check out our careers page for openings. 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/
--- id: blockvote-js sidebar_label: BlockVote JS --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" # BlockVote JS Edition BlockVote JS Edition is a blockchain-based voting application built using JavaScript on the Near Protocol blockchain. The application allows users to securely cast their votes in an election and have them recorded on the blockchain, ensuring that the results are transparent and cannot be altered. ![image](/docs/assets/blockvote.png) ## Installation To install BlockVote JS Edition, follow these steps please: 1. Clone the repository to your local machine using the following command: ```bash git clone https://github.com/doriancrutcher/BlockVote-JS-Edition-Tutorial.git ``` 2. Navigate to the project directory: ```bash cd BlockVote-JS-Edition-Tutorial ``` 3. Install the required dependencies using the following command: ```bash yarn install-deps ``` 4. Start the application: ```bash yarn start ``` :::note If you don't have `yarn` installed, you can install it by running `npm install -g yarn`. ::: ## Usage This application allows users to create a poll with two candidates, and each user can only vote in a poll once. Results are shown after the vote is cast. To create a poll, follow these steps: 1. Enter the names and URL links for the two candidates in the input fields. 2. Click on the "Create Poll" button to create the poll. 3. Share the poll link with others to allow them to vote. To vote in a poll, follow these steps: 1. Click on the name of the candidate you want to vote for. 2. You will only be able to vote once in each poll. 3. After you vote, the poll results will be displayed on the screen. That's it! If you have any questions or issues while using the BlockVote JS Edition, feel free to open an issue on the [project's GitHub page](https://github.com/doriancrutcher/BlockVote-JS-Edition-Tutorial). ## Smart Contract The contract contains several view and call methods that allow users to interact with the contract, including: ### View Methods - `getUrl`: retrieves the URL link for a specific candidate based on the candidate's name and prompt. - `didParticipate`: checks whether a specific user has participated in a given prompt. - `participateArray`: retrieves the list of users who have participated in a given prompt. - `getAllPrompts`: retrieves a list of all prompts currently available in the contract. - `getVotes`: retrieves the vote tallies for a specific prompt. - `getCandidatePair`: retrieves the names of the two candidates for a specific prompt. <CodeTabs> <Language value="js" language="js"> <Github fname="contract.ts" url="https://github.com/doriancrutcher/BlockVote-JS-Edition-Tutorial/blob/main/contract/src/contract.ts" start="20" end="60" /> </Language> </CodeTabs> ### Call Methods - `addCandidatePair`: adds a candidate pair for a specific prompt to the contract's unordered map of candidate pairs. - `initializeVotes`: initializes the vote tallies for a specific prompt - `addToPromptArray`: adds a prompt to the contract's unordered set of prompts - `clearPromptArray`: clears all prompts and associated data from the contract (candidate pairs, vote tallies, and user participation) - `addVote`: casts a vote for a specific candidate in a prompt by updating the vote tally for that candidate in the contract's unordered map of vote tallies. The method takes in the prompt and the index of the candidate - `recordUser`: records the participation of a user in a specific prompt by adding the user's account ID to an array in the contract's unordered map of user participation <CodeTabs> <Language value="js" language="js"> <Github fname="contract.ts" url="https://github.com/doriancrutcher/BlockVote-JS-Edition-Tutorial/blob/main/contract/src/contract.ts" start="61" end="110" /> </Language> </CodeTabs> ## Testing When writing smart contracts, it is very important to test all methods exhaustively. In this project, you have two types of tests: unit tests and integration tests. Before digging into them, it's important to run the tests present in the dApp through the command `yarn test`. ### Unit Tests Unit tests are designed to test individual functions and methods in the smart contract. These tests are run in isolation, meaning that they do not interact with other components of the system. The purpose of unit tests is to ensure that each individual function or method behaves as expected. In this project, you can run the unit tests by executing the command `yarn test:unit`. ### Integration Tests These tests are run to ensure that the different components of the system work together as expected. In the context of a smart contract, integration tests are used to test the interactions between the contract and the blockchain. In this project, you can run the integration tests by executing the command `yarn test`. These tests use a combination of `ava` and `near-workspaces` <CodeTabs> <Language value="js" language="js"> <Github fname="contract.ts" url="https://github.com/doriancrutcher/BlockVote-JS-Edition-Tutorial/blob/main/integration-tests/src/main.ava.ts" start="6" end="92" /> </Language> </CodeTabs>
Community Update: May 22nd, 2020 COMMUNITY May 22, 2020 Our community is taking roots! The past two weeks have been as exciting as ever. After Ready Layer One we received lots of community input, ideas, and contributions, some of which we highlight below. Community contributions are critical to the success of NEAR’s ultimate community governed mainnet. A BIG shout-out to every community member who is making this possible. Join our community on Discord to be the first to receive our announcements and contribute to NEAR. Ready to Rewind Thank you to all 3903 participants who made this event possible. If you missed a talk or simply cannot get enough (neither can we -squeak-), head over to the recordings. Ready Layer One: Day 1 Ready Layer One: Day 2 Ready Layer One: Day 3 We would love to hear your thoughts on how we can improve on the next open blockchain week (if there is one). Take the Survey Validator Telegram Bot Yes, we know what you think “Yet another bot”. BUT HOLD ON — this Bot is special. It is not only created by Vadim, one of our Contributors, but it also makes the life of our validators much easier. The Bot can send NEAR tokens to existing blockchain and Telegram users. It also provides account details, a validator list and allows users to delegate tokens to their staking-pool contract. Wait — You haven’t heard of Stake Wars yet? Stake Wars Episode II is here. If you’re looking for ways to get involved in validation and testing our network, now is your time. This post discusses the unique features of validation and delegation on NEAR, and the rewards for successful participation. Flux <> NEAR Flux published their recap of the past 60 days since starting the Open Web Collective, “We have shipped over 16,000 lines of code over 214 commits. These commits include the launch of V0.2 of our protocol, the flux open-source app, and flux SDK.” Read the entire update here. Events: Time to Shine RL1 Hackathon The RL1 Hackathon has ended with 52 projects submitted & 229 participants. $7,500 in prizes were awarded. We will announce the winners soon. UW Hackathon Are you currently enrolled at a University AND want to get started developing on Blockchain? Say no more, this is your opportunity to show your skills. We have partnered with the University of Washington Blockchain Society to host a 3-day hackathon. Sign-up To learn more about the experiences of participants in previous hackathons, have a look at our recap of the Future of Blockchain Hackathon hosted by StakeZero Ventures. Engineering Update We published near-shell 0.24.0! Highlights include: Ledger support (‘–useLedgerKey’, ‘–newLedgerKey’) ‘near delete-key’ Metrics opt-in only in ‘near login’ and near ‘dev-deploy’ (to avoid messing with scripts) Content Highlight Podcast by Outlier Ventures with Illia on onboarding 99% of developers into Web3 Blog post by Felix Machart from Greenfield One on NEAR’s developments This is your chance to get started developing on NEAR with our tutorials on Exploring AssemblyScript Contracts Exploring Rust Contracts Exploring NEAR APIs How You Can Get Involved Join the NEAR Contributor Program. If you would like to host events, create content or provide developer feedback, we would love to hear from you! To learn more about the program and ways to participate, please head over to the website. If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox.
# BOS Web Engine Docs ### Local Development ``` $ pnpm start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ pnpm build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service.
Refining NEAR Foundation’s Grant Approach NEAR FOUNDATION January 3, 2023 A few weeks ago, as part of a series of blogs on the state of funding, NEAR Foundation announced it would be examining its evolving funding strategy. This is in line with the Foundation’s goal of providing a clear and concise update to continue to foster transparent communication. At this time, NEAR Foundation is actively working towards a more decentralized model of capital allocation that will initially involve the DeveloperDAO, MarketingDAO, CreativesDAO, with an additional DAO that will begin formation in Q1 of 2023. This will impact the ecosystem in the following ways: Effective immediately, NEAR Foundation will cease allocating capital directly from our inbound start-up grants program, with the exception of our current events grants, which will be handed over to the MarketingDAO when they are set up to manage them. Request events funding by following the steps outlined here. In January and February, we will be working directly with community members to outline a clear application process for funding via the DAOs. Processing time is expected to take 6-8 weeks. If you are interested in helping us form the new DAO with a focus on start-up projects, please submit your interest using this contact form. Any projects that have already received a portion of their funding and are working towards their agreed milestones will continue to be supported through the remaining milestones. Any application that is not already in the approval stage will not receive funding. However, we will do our best to redirect you to appropriate, alternative funding sources. NEAR Foundation’s goal is to empower the ecosystem to make decisions that support the strategic approach that will drive NEAR to the next phase of its roadmap, with a look ahead at new areas of product and development, as outlined in the NEAR Strategic Update and Outlook for 2023. We will continue to be as transparent as possible about the new funding strategy as it rolls out. The Foundation will communicate as often, and as frequently, as possible. We encourage the community to continue providing meaningful feedback so we can iterate more quickly as we unite to build the NEAR Ecosystem together.
# Runtime Fees Runtime fees are measured in Gas. Gas price will be discussed separately. When a transaction is converted into a receipt, the signer account is charged for the full cost of the transaction. This cost consists of extra attached gas, attached deposits and the transaction fee. The total transaction fee is the sum of the following: - A fee for creation of the receipt - A fee for every action Every [Fee](/GenesisConfig/RuntimeFeeConfig/Fee.md) consists of 3 values measured in gas: - `send_sir` and `send_not_sir` - the gas burned when the action is being created to be sent to a receiver. - `send_sir` is used when `current_account_id == receiver_id` (`current_account_id` is a `signer_id` for a signed transaction). - `send_not_sir` is used when `current_account_id != receiver_id` - `execution` - the gas burned when the action is being executed on the receiver's account. ## Receipt creation cost There are 2 types of receipts: - Action receipts [ActionReceipt](/RuntimeSpec/Receipts.md#actionreceipt) - Data receipts [DataReceipt](/RuntimeSpec/Receipts.md#datareceipt) A transaction is converted into an [ActionReceipt](/RuntimeSpec/Receipts.md#actionreceipt). Data receipts are used for data dependencies and will be discussed separately. The `Fee` for an action receipt creation is described in the config [`action_receipt_creation_config`](/GenesisConfig/RuntimeFeeConfig.md#action_receipt_creation_config). Example: when a signed transaction is being converted into a receipt, the gas for `action_receipt_creation_config.send` is being burned immediately, while the gas for `action_receipt_creation_config.execution` is only charged, but not burned. It'll be burned when the newly created receipt is executed on the receiver's account. ## Fees for actions Every [`Action`](/RuntimeSpec/Actions.md#actions) has a corresponding Fee(s) described in the config [`action_creation_config`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md). Similar to a receipt creation costs, the `send` gas is burned when an action is added to a receipt to be sent, and the `execution` gas is only charged, but not burned. Fees are either a base fee or a fee per byte of some data within the action. Here is the list of actions and their corresponding fees: - [CreateAccount](/RuntimeSpec/Actions.md#createaccountaction) uses - the base fee [`create_account_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#create_account_cost) - [DeployContract](/RuntimeSpec/Actions.md#deploycontractaction) uses the sum of the following fees: - the base fee [`deploy_contract_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#deploy_contract_cost) - the fee per byte of the contract code to be deployed with the fee [`deploy_contract_cost_per_byte`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#deploy_contract_cost_per_byte) To compute the number of bytes for a deploy contract action `deploy_contract_action` use `deploy_contract_action.code.len()` - [FunctionCall](/RuntimeSpec/Actions.md#functioncallaction) uses the sum of the following fees: - the base fee [`function_call_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#function_call_cost) - the fee per byte of method name string and per byte of arguments with the fee [`function_call_cost_per_byte`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#function_call_cost_per_byte). To compute the number of bytes for a function call action `function_call_action` use `function_call_action.method_name.as_bytes().len() + function_call_action.args.len()` - [Transfer](/RuntimeSpec/Actions.md#transferaction) uses one of the following fees: - if the `receiver_id` is an [Implicit Account ID](/DataStructures/Account.md#implicit-account-ids), then a sum of base fees is used: - the create account base fee [`create_account_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#create_account_cost) - the transfer base fee [`transfer_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#transfer_cost) - the add full access key base fee [`add_key_cost.full_access_cost`](/GenesisConfig/RuntimeFeeConfig/AccessKeyCreationConfig.md#full_access_cost) - if the `receiver_id` is NOT an [Implicit Account ID](/DataStructures/Account.md#implicit-account-ids), then only the base fee is used: - the transfer base fee [`transfer_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#transfer_cost) - [Stake](/RuntimeSpec/Actions.md#stakeaction) uses - the base fee [`stake_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#stake_cost) - [AddKey](/RuntimeSpec/Actions.md#addkeyaction) uses one of the following fees: - if the access key is [`AccessKeyPermission::FullAccess`](/DataStructures/AccessKey.md#access-keys) the base fee is used - the add full access key base fee [`add_key_cost.full_access_cost`](/GenesisConfig/RuntimeFeeConfig/AccessKeyCreationConfig.md#full_access_cost) - if the access key is [`AccessKeyPermission::FunctionCall`](/DataStructures/AccessKey.md#accesskeypermissionfunctioncall) the sum of the fees is used - the add function call permission access key base fee [`add_key_cost.function_call_cost`](/GenesisConfig/RuntimeFeeConfig/AccessKeyCreationConfig.md#full_access_cost) - the fee per byte of method names with extra byte for every method with the fee [`add_key_cost.function_call_cost_per_byte`](/GenesisConfig/RuntimeFeeConfig/AccessKeyCreationConfig.md#function_call_cost_per_byte) To compute the number of bytes for `function_call_permission` use `function_call_permission.method_names.iter().map(|name| name.as_bytes().len() as u64 + 1).sum::<u64>()` - [DeleteKey](/RuntimeSpec/Actions.md#deletekeyaction) uses - the base fee [`delete_key_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#delete_key_cost) - [DeleteAccount](/RuntimeSpec/Actions.md#deleteaccountaction) uses - the base fee [`delete_account_cost`](/GenesisConfig/RuntimeFeeConfig/ActionCreationConfig.md#delete_account_cost) - action receipt creation fee for creating Transfer to send remaining funds to `beneficiary_id` - full transfer fee described in the corresponding item ## Gas tracking In `Runtime`, gas is tracked in the following fields of `ActionResult` struct: - `gas_burnt` - irreversible amount of gas spent on computations. - `gas_used` - includes burnt gas and gas attached to the new `ActionReceipt`s created during the method execution. - `gas_burnt_for_function_call` - stores gas burnt during function call execution. Later, contract account gets 30% of it as a reward for a possibility to invoke the function. Initially runtime charges `gas_used` from the account. Some gas may be refunded later, see [Refunds](../Refunds.md). At first, we charge fees related to conversion from `SignedTransaction` to `ActionReceipt` and future execution of this receipt: - costs of all `SignedTransaction`s passed to `Runtime::apply` are computed in `tx_cost` function during validation; - `total_cost` is deducted from signer, which is a sum of: - `gas_to_balance(gas_burnt)` where `gas_burnt` is action receipt send fee + `total_send_fees(transaction.actions)`); - `gas_to_balance(gas_remaining)` where `gas_remaining` is action receipt exec fee + `total_prepaid_exec_fees(transaction.actions)` to pay all remaining fees caused by transaction; - `total_deposit(transaction.actions)`; - each transaction is converted to receipt and passed to `Runtime::process_receipt`. Then each `ActionReceipt` is passed to `Runtime::apply_action_receipt` where gas is tracked as follows: - `ActionResult` is created with `ActionReceipt` execution fee; - all actions inside `ActionReceipt` are passed to `Runtime::apply_action`; - `ActionResult` with charged base execution fees is created there; - if action execution leads to new `ActionReceipt`s creation, corresponding `action_[action_name]` function adds new fees to the `ActionResult`. E.g. `action_delete_account` also charges the following fees: - `gas_burnt`: **send** fee for **new** `ActionReceipt` creation + complex **send** fee for `Transfer` to beneficiary account - `gas_used`: `gas_burnt` + **exec** fee for created `ActionReceipt` + complex **exec** fee for `Transfer` - all computed `ActionResult`s are merged into one, where all gas values are summed up; - unused gas is refunded in `generate_refund_receipts`. Inside `VMLogic`, the fees are tracked in the `GasCounter` struct. The VM itself is called in the `action_function_call` inside `Runtime`. When all actions are processed, the result is returned as a `VMOutcome`, which is later merged with `ActionResult`. # Example Let's say we have the following transaction: ```rust Transaction { signer_id: "alice.near", public_key: "2onVGYTFwyaGetWckywk92ngBiZeNpBeEjuzSznEdhRE", nonce: 23, receiver_id: "lockup.alice.near", block_hash: "3CwEMonK6MmKgjKePiFYgydbAvxhhqCPHKuDMnUcGGTK", actions: [ Action::CreateAccount(CreateAccountAction {}), Action::Transfer(TransferAction { deposit: 100000000000000000000000000, }), Action::DeployContract(DeployContractAction { code: vec![/*<...128000 bytes...>*/], }), Action::FunctionCall(FunctionCallAction { method_name: "new", args: b"{\"owner_id\": \"alice.near\"}".to_vec(), gas: 25000000000000, deposit: 0, }), ], } ``` It has `signer_id != receiver_id` so it will use `send_not_sir` for send fees. It contains 4 actions with 2 actions that requires to compute number of bytes. We assume `code` in `DeployContractAction` contains `128000` bytes. And `FunctionCallAction` has `method_name` with length of `3` and `args` length of `26`, so total of `29`. First let's compute the the amount that will be burned immediately for sending a receipt. ```python burnt_gas = \ config.action_receipt_creation_config.send_not_sir + \ config.action_creation_config.create_account_cost.send_not_sir + \ config.action_creation_config.transfer_cost.send_not_sir + \ config.action_creation_config.deploy_contract_cost.send_not_sir + \ 128000 * config.action_creation_config.deploy_contract_cost_per_byte.send_not_sir + \ config.action_creation_config.function_call_cost.send_not_sir + \ 29 * config.action_creation_config.function_call_cost_per_byte.send_not_sir ``` Now, by using `burnt_gas`, we can calculate the total transaction fee ```python total_transaction_fee = burnt_gas + \ config.action_receipt_creation_config.execution + \ config.action_creation_config.create_account_cost.execution + \ config.action_creation_config.transfer_cost.execution + \ config.action_creation_config.deploy_contract_cost.execution + \ 128000 * config.action_creation_config.deploy_contract_cost_per_byte.execution + \ config.action_creation_config.function_call_cost.execution + \ 29 * config.action_creation_config.function_call_cost_per_byte.execution ``` This `total_transaction_fee` is the amount of gas required to create a new receipt from the transaction. NOTE: There are extra amounts required to prepay for deposit in `TransferAction` and gas in `FunctionCallAction`, but this is not part of the total transaction fee.
--- id: push-notifications title: Push Notifications --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs" Push messages enable your gateway to send notifications on desktop and mobile devices even when the users are not active. To implement push notifications, you need to: 1. Create a Service Worker 2. Ask the user for permission to send push notifications 2. Send the `client identifier` information to our notification server 3. Add logic to display the notifications :::tip Example Check our working example at https://github.com/near-examples/BOS-notifications ::: --- ## Create the Service Worker Push notifications work by having a [service worker](https://codelabs.developers.google.com/codelabs/push-notifications#2) on the client side that listens for messages from the NEAR notifications server. <CodeTabs> <Github fname="main.js" language="js" value="Create" url="https://github.com/near-examples/BOS-notifications/blob/main/app/scripts/main.js" start="16" end="22" /> </CodeTabs> Browsers readily provide native support for service workers, so you can easily check if a service worker exists, and create one if not. --- ## Subscribe to our Notifications In order to have the `service worker` display notifications, you need to subscribe it to a notifications server. A notification server is identified by its `public key`, constraining that only the server holding the `private` counterpart can push notifications to the user. <CodeTabs> <Github fname="main.js" language="js" value="Subscribe" url="https://github.com/near-examples/BOS-notifications/blob/main/app/scripts/main.js" start="44" end="50" /> </CodeTabs> :::tip Permission When you subscribe to the service, the user will be asked for permission to be sent notifications. ::: --- ## Create a Stream in our Server After you subscribe the user to a notifications server, share it with us so we can start sending you notifications! For this, make a `post` request to our server, add which account you want to be notified for, and a URL identifying your gateway. <CodeTabs> <Github fname="main.js" language="js" value="Stream" url="https://github.com/near-examples/BOS-notifications/blob/main/app/scripts/main.js" start="52" end="64" /> </CodeTabs> :::tip The `gateway` parameter is there just to help us keep track of who receives notifications. ::: --- ## Handle Notifications When the user receives a notification, the `service worker` will be triggered, and you can add logic to display the notification. <CodeTabs> <Github fname="sw.js" language="js" value="Notifications" url="https://github.com/near-examples/BOS-notifications/blob/main/app/scripts/sw.js" start="20" end="37" /> </CodeTabs> Feel free to personalize the notification as you wish, and to add logic on what to do once the notification is clicked. In our example, we just open the Post page. <CodeTabs> <Github fname="sw.js" language="js" value="Notifications" url="https://github.com/near-examples/BOS-notifications/blob/main/app/scripts/sw.js" start="39" end="51" /> </CodeTabs>
--- NEP: 177 Title: Non Fungible Token Metadata Author: Chad Ostrowski <@chadoh>, Mike Purvis <mike@near.org> DiscussionsTo: https://github.com/near/NEPs/discussions/177 Status: Final Type: Standards Track Category: Contract Created: 03-Mar-2022 Requires: 171 --- ## Summary An interface for a non-fungible token's metadata. The goal is to keep the metadata future-proof as well as lightweight. This will be important to dApps needing additional information about an NFT's properties, and broadly compatible with other token standards such that the [NEAR Rainbow Bridge](https://near.org/blog/eth-near-rainbow-bridge/) can move tokens between chains. ## Motivation The primary value of non-fungible tokens comes from their metadata. While the [core standard][NFT Core] provides the minimum interface that can be considered a non-fungible token, most artists, developers, and dApps will want to associate more data with each NFT, and will want a predictable way to interact with any NFT's metadata. ## Rationale and alternatives NEAR's unique [storage staking](https://docs.near.org/concepts/storage/storage-staking) approach makes it feasible to store more data on-chain than other blockchains. This standard leverages this strength for common metadata attributes, and provides a standard way to link to additional offchain data to support rapid community experimentation. This standard also provides a `spec` version. This makes it easy for consumers of NFTs, such as marketplaces, to know if they support all the features of a given token. Prior art: - NEAR's [Fungible Token Metadata Standard][FT Metadata] - Discussion about NEAR's complete NFT standard: #171 ## Specification ## Interface Metadata applies at both the contract level (`NFTContractMetadata`) and the token level (`TokenMetadata`). The relevant metadata for each: ```ts type NFTContractMetadata = { spec: string, // required, essentially a version like "nft-1.0.0" name: string, // required, ex. "Mochi Rising — Digital Edition" or "Metaverse 3" symbol: string, // required, ex. "MOCHI" icon: string|null, // Data URL base_uri: string|null, // Centralized gateway known to have reliable access to decentralized storage assets referenced by `reference` or `media` URLs reference: string|null, // URL to a JSON file with more info reference_hash: string|null, // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. } type TokenMetadata = { title: string|null, // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055" description: string|null, // free-form description media: string|null, // URL to associated media, preferably to decentralized, content-addressed storage media_hash: string|null, // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included. copies: number|null, // number of copies of this set of metadata in existence when token was minted. issued_at: number|null, // When token was issued or minted, Unix epoch in milliseconds expires_at: number|null, // When token expires, Unix epoch in milliseconds starts_at: number|null, // When token starts being valid, Unix epoch in milliseconds updated_at: number|null, // When token was last updated, Unix epoch in milliseconds extra: string|null, // anything extra the NFT wants to store on-chain. Can be stringified JSON. reference: string|null, // URL to an off-chain JSON file with more info. reference_hash: string|null // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. } ``` A new function MUST be supported on the NFT contract: ```ts function nft_metadata(): NFTContractMetadata {} ``` A new attribute MUST be added to each `Token` struct: ```diff type Token = { token_id: string, owner_id: string, + metadata: TokenMetadata, } ``` ### An implementing contract MUST include the following fields on-chain - `spec`: a string that MUST be formatted `nft-1.0.0` to indicate that a Non-Fungible Token contract adheres to the current versions of this Metadata spec. This will allow consumers of the Non-Fungible Token to know if they support the features of a given contract. - `name`: the human-readable name of the contract. - `symbol`: the abbreviated symbol of the contract, like MOCHI or MV3 - `base_uri`: Centralized gateway known to have reliable access to decentralized storage assets referenced by `reference` or `media` URLs. Can be used by other frontends for initial retrieval of assets, even if these frontends then replicate the data to their own decentralized nodes, which they are encouraged to do. ### An implementing contract MAY include the following fields on-chain For `NFTContractMetadata`: - `icon`: a small image associated with this contract. Encouraged to be a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs), to help consumers display it quickly while protecting user data. Recommendation: use [optimized SVG](https://codepen.io/tigt/post/optimizing-svgs-in-data-uris), which can result in high-resolution images with only 100s of bytes of [storage cost](https://docs.near.org/concepts/storage/storage-staking). (Note that these storage costs are incurred to the contract deployer, but that querying these icons is a very cheap & cacheable read operation for all consumers of the contract and the RPC nodes that serve the data.) Recommendation: create icons that will work well with both light-mode and dark-mode websites by either using middle-tone color schemes, or by [embedding `media` queries in the SVG](https://timkadlec.com/2013/04/media-queries-within-svg/). - `reference`: a link to a valid JSON file containing various keys offering supplementary details on the token. Example: "/ipfs/QmdmQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm", "https://example.com/token.json", etc. If the information given in this document conflicts with the on-chain attributes, the values in `reference` shall be considered the source of truth. - `reference_hash`: the base64-encoded sha256 hash of the JSON file contained in the `reference` field. This is to guard against off-chain tampering. For `TokenMetadata`: - `name`: The name of this specific token. - `description`: A longer description of the token. - `media`: URL to associated media. Preferably to decentralized, content-addressed storage. - `media_hash`: the base64-encoded sha256 hash of content referenced by the `media` field. This is to guard against off-chain tampering. - `copies`: The number of tokens with this set of metadata or `media` known to exist at time of minting. - `issued_at`: Unix epoch in milliseconds when token was issued or minted (an unsigned 32-bit integer would suffice until the year 2106) - `expires_at`: Unix epoch in milliseconds when token expires - `starts_at`: Unix epoch in milliseconds when token starts being valid - `updated_at`: Unix epoch in milliseconds when token was last updated - `extra`: anything extra the NFT wants to store on-chain. Can be stringified JSON. - `reference`: URL to an off-chain JSON file with more info. - `reference_hash`: Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. ### No incurred cost for core NFT behavior Contracts should be implemented in a way to avoid extra gas fees for serialization & deserialization of metadata for calls to `nft_*` methods other than `nft_metadata` or `nft_token`. See `near-contract-standards` [implementation using `LazyOption`](https://github.com/near/near-sdk-rs/blob/c2771af7fdfe01a4e8414046752ee16fb0d29d39/examples/fungible-token/ft/src/lib.rs#L71) as a reference example. ## Reference Implementation This is the technical portion of the NEP. Explain the design in sufficient detail that: - Its interaction with other features is clear. - Where possible, include a `Minimum Viable Interface` subsection expressing the required behavior and types in a target Near Contract language. (ie. traits and structs for rust, interfaces and classes for javascript, function signatures and structs for c, etc.) - It is reasonably clear how the feature would be implemented. - Corner cases are dissected by example. The section should return to the examples given in the previous section, and explain more fully how the detailed proposal makes those examples work. ## Drawbacks - When this NFT contract is created and initialized, the storage use per-token will be higher than an NFT Core version. Frontends can account for this by adding extra deposit when minting. This could be done by padding with a reasonable amount, or by the frontend using the [RPC call detailed here](https://docs.near.org/docs/develop/front-end/rpc#genesis-config) that gets genesis configuration and actually determine precisely how much deposit is needed. - Convention of `icon` being a data URL rather than a link to an HTTP endpoint that could contain privacy-violating code cannot be done on deploy or update of contract metadata, and must be done on the consumer/app side when displaying token data. - If on-chain icon uses a data URL or is not set but the document given by `reference` contains a privacy-violating `icon` URL, consumers & apps of this data should not naïvely display the `reference` version, but should prefer the safe version. This is technically a violation of the "`reference` setting wins" policy described above. ## Future possibilities - Detailed conventions that may be enforced for versions. - A fleshed out schema for what the `reference` object should contain. ## Errata - **2022-02-03**: updated `Token` struct field names. `id` was changed to `token_id`. This is to be consistent with current implementations of the standard and the rust SDK docs. The first version (`1.0.0`) had confusing language regarding the fields: - `issued_at` - `expires_at` - `starts_at` - `updated_at` It gave those fields the type `string|null` but it was unclear whether it should be a Unix epoch in milliseconds or [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). Upon having to revisit this, it was determined to be the most efficient to use epoch milliseconds as it would reduce the computation on the smart contract and can be derived trivially from the block timestamp. ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). [NFT Core]: ../specs/Standards/Tokens/NonFungibleToken/Core.md [FT Metadata]: ../specs/Standards/Tokens/FungibleToken/Metadata.md
```js const tokenContract = "token.v2.ref-finance.near"; Near.call( tokenContract, "ft_transfer", { receiver_id: "alice.near", amount: "100000000000000000", }, undefined, 1 ); ```
Open Call for NEAR Accelerator Partners NEAR FOUNDATION February 8, 2023 The NEAR blockchain is an open-source, decentralized blockchain protocol designed to be scalable, developer-friendly, and able to support a wide range of decentralized applications (dApps) and smart contracts. The NEAR Foundation is the non-profit organization behind the NEAR blockchain, responsible for the development and maintenance of the NEAR Protocol and its associated ecosystem. Since the inception of the grants program, the NEAR Foundation has committed over $90m capital and the ecosystem grew from 0 to over 1,000 teams. One of the central lessons learned during this time is that founding teams need a host of contributors in order to be successful, including mentors/advisors, subject matter specific resources (e.g. legal playbooks, go-to-market strategies, tokenomics, etc), and access to investment opportunities. NEAR Foundation is looking to partner with existing acceleration programs in two ways: Leverage the partner’s excellence and experience in running cohort-based acceleration programs. Beta test and help build a digital product being developed by NEAR that connects projects with contributors (including investors). If you’re interested in becoming a NEAR Accelerator Partner, please read the requirements below. Proposals must be submitted via Google Form by February 17th. *If you’re a startup looking for accelerator programs, NEAR Foundation is looking to engage with the best partners out there. Register your interest in the NEAR Accelerator here. NEAR Foundation’s Goal Attract the most talented early stage teams to NEAR and provide them with the right tools, knowledge, and network to successfully raise external funds at a later stage. Success metrics Quality of founder experience, as measured by an NPS score. Ability for founders that have graduated from the accelerator(s) to raise their first or next round within a year of graduation. Requirements NEAR Foundation will be assessing proposals based on the two dimensions explained below: the Accelerator Partner Requirements and the Digital Product Beta Participation Requirements. Accelerator Partner Requirements Strong sourcing capabilities in the areas of our investment thesis NEAR Foundation believes in selecting teams building projects with real world, utility-based use cases that tap into the existing pools of Web2 users and companies. They must leverage Web3 in novel ways to solve real world problems better than Web2 tech is able to. The Foundation will not be focused on specific verticals, and instead be relatively opportunistic in terms of use case (at least in the first few cohorts). DeFi and Gaming verticals would be excluded from the accelerator purview. The Foundation is focused on pre-seed and seed stage teams. We expect that teams selected for a NEAR sponsored cohort will build on NEAR and leverage NEAR Discovery. More information on NEAR Discovery here. In your response, please detail the following: Your investment thesis and the degree to which it does / does not align with our focus. Your approach to sourcing and acquiring top calibur teams. Your approach to vetting teams to ensure quality. Web3 accelerator program scope As NEAR Foundation aims to attract the best teams, we want our accelerator partner to provide a top class experience and focus on the main challenges that Web3 startups face nowadays, including but not limited to: go-to-market, token economy and launches, fundraising and pitching, marketing and comms, governance, legal, etc. This will be supplemented by the support of experts within the NEAR ecosystem. In your response, please detail the following: Program scope and sequence (learning opportunities and delivery method) Scope of advisory and mentorship services Length of program Post program services Number of cohorts and anticipated cohort size (number of projects) Geographic focus areas Delivery mode (e.g. in person, on-line, hybrid) Track record of success NEAR Foundation seeks accelerator partners that have a strong track record of success. In your response, please detail the following: Date when your program started Number of projects and cohorts that have graduated from your program Projects names per cohort Feedback from teams that have gone through your program Percent of teams that have been able to close their first or next round after graduating from your program Average and median amount that graduating teams have been able to raise post-graduation Attractive deal terms One of the most important factors in attracting high quality founders to the accelerator will be the quality of the investment terms. In your response, please detail the following: Your approach to investment (including standard allocation if applicable, percent of equity and tokens your team takes, approach to follow-on investment etc.). Cost & investment NEAR Foundation is open to various proposals in terms of costs and investments. Where we land will largely depend on the proposed value to NEAR and its ecosystem. For NEAR specific cohorts, the Foundation’s goal is for both NEAR and the Accelerator Partner to share operational cost and investment opportunity. For chain agnostic cohorts, we would be willing to provide direct technical and non-technical support from the NEAR Foundation Accelerator’s team for startups who choose NEAR as their Layer 1. In your response, please detail the following: Proposed approach (NEAR cohort vs chain agnostic or both) Proposed budget in support of the proposal: this budget should provide details about what the money will be used for (e.g. administrative costs, costs to host events, etc) i.e. P&L If applicable, propose the role the NEAR Foundation could play in terms of investment (e.g. LP / co-investor etc.) Potential startup date of the program and/or adherence to ongoing program Broader NEAR ecosystem support NEAR Foundation would like its ecosystem of startups to leverage the partner capabilities even though they are not actively participating in the accelerator (e.g., share ready-made class material, leverage investor network, connections to enterprise, etc.). In your response, please detail the following: Your perspective on providing these resources and supports to NEAR ecosystem projects that do not go through the accelerator program Additional costs that might be associated with providing these services (if applicable) Your proposal for how your services scale Digital Product Beta Participation Requirements In 2023, Pagoda, NEAR Foundation and other key ecosystem participants are increasing the integration and seamless experience for developers and end users into one common operating system that will leverage fast onboarding experience, user profiles, new chat/ social capabilities, and more. As part of this platform, the Foundation is building a founder-focused application that will be the place for both NEAR-native and non-NEAR-native projects to be discovered, find contributors and investors, and grow towards their goals. We would like to invite accelerator partners in as beta customers and builders for this application. If your organization is both an investment team and an accelerator: Agreement to use the digital product as a project “contributor,” meaning: One or more resources from your team will actively engage with projects on the platform, providing advisory services Your team will leverage the platform to identify projects for investment You will encourage founding teams from your portfolio to use to the platform (they do not need to be building on NEAR) You will actively work to improve your user experience by providing feedback to the project team and/or contributing directly to the development effort If your organization is solely an accelerator: Agreement to use the digital product as a project “contributor,” meaning: One or more resources from your team will actively engage with projects on the platform, providing advisory services You will encourage founding teams from your portfolio to use to the platform (they do not need to be building on NEAR) You will actively work to improve your user experience by providing feedback to the project team and/or contributing directly to the development effort In your response, please detail the following: Your interest and commitment in participation Your proposal for how you would engage in the beta (e.g., you will dedicate three part-time resources for the beta; you will contribute part-time engineering resource to contribute to building with us) NEAR Foundation Commitments NEAR Foundation is committed to complement the partner’s current programs with ecosystem support (technical and non-technical). Selection criteria and timelines NEAR Foundation will be assessing proposals based on the previously mentioned requirements. Acceleration partners are expected to submit their proposals by February 17, 2023 via Google Form. The NEAR Foundation review team will be conducting interviews with selected candidates between February 13-24. The review team will shortlist the partners between February 27-28 and will communicate further with the selected parties. Final approval will be provided by the NEAR Foundation Counsel. Legal Disclosure: Participation in our accelerator partners program is subject to the following terms and conditions: (1) Confidentiality: Participants will be required to keep all information and materials shared by the program confidential, unless otherwise agreed to in writing or as required by law. (2) Intellectual Property: All intellectual property created or developed by a participant during the program will remain the property of the participant, unless otherwise agreed to in writing by the participant. (3) Disclaimer of Liability: The program will not be liable for any damages arising out of or in connection with the program or the participation of any participant. (4) Governing Law: These terms and conditions will be governed by and construed in accordance with the laws of Switzerland. By participating in the program, participants agree to be bound by these terms and conditions.
Sweat Economy Launches in the USA, Opening the Door to Millions of New Web3 Users NEAR FOUNDATION October 17, 2023 Sweat Economy, creators of $SWEAT and leaders in helping the world become more active, is launching in the United States for the first time. The decision to expand into the new territory was supported by a historic on chain vote by the Sweat Economy Community, and saw more than 380,000 community members take part in the decision. The announcement will pave the way for millions of users in the United States, the Bahamas, Barbados, Botswana, Ghana, Jamaica, Pakistan, Zimbabwe, and Uganda, to be able to tokenize their physical activity within the Sweat Economy ecosystem — adding momentum to the burgeoning global movement economy. Sweat Economy is a Web3 evolution of the Web2 health & fitness app — Sweatcoin — which now has more than 145 million registered users worldwide. It started in September 2022 when the project launched its crypto token $SWEAT alongside the Sweat Wallet mobile app. $SWEAT is effectively a tokenized form of physical activity; a new asset class that did not exist up to this moment, while Sweat Wallet is the mobile application that gives you the best experience of collecting and managing your $SWEAT. To start minting $SWEAT, users need to install the Sweatcoin app, opt-in to “Walk into Crypto” and then install the Sweat Wallet app. This means that instead of earning centralized sweatcoin points, users earn $SWEAT — a crypto token that represents the value of their physical activity and is traded on 20+ exchanges worldwide. Accrued $SWEAT can then be used in various ways, including deposited into “Growth Jars” to be saved and multiplied, and unlock exclusive rewards within the ecosystem. Users can also compete in the free-to-play Sweat Hero NFT game to win additional $SWEAT, while also having the option to purchase $SWEAT in-app using the MoonPay fiat on-ramp “It’s incredible to see the progress of Sweat Economy as it enables us to achieve our mission to bring millions into the open web,” says Chris Donovan, CEO of the NEAR Foundation. “As an industry leader in tokenizing physical activity, Sweat Economy’s launch into the U.S. represents a major milestone not just for the project, but for the entire NEAR ecosystem. It also demonstrates the incredible scalability of the NEAR Protocol, which has been able to seamlessly support one of the largest consumer apps in Web3 operating at a significant scale.” Since $SWEAT launched on NEAR Protocol, it has become one of the largest Dapps in the Web3 ecosystem, with more than 20 million wallets and more than 100,000 transactions per day. The Sweat Wallet app quickly became the number one most downloaded Finance app in more than 50 countries. This follows Sweat’s success as the fastest IDO ever to sell out on the DAO Maker platform. It has become one of the largest Web3 on-ramps in history. “We are thrilled to finally bring the Sweat Economy experience to the United States and 8 other markets. Our community was making it loud and clear that they wanted and needed us there and we are happy that we finally can deliver for them,” says Oleg Fomenko, co-founder of Sweat Economy. “We are excited that residents of these countries will also be able to literally WALK INTO CRYPTO! Our global community of users has been instrumental in supporting this launch and we are thankful for their participation in the biggest ever governance vote that allocated nearly 700 million $SWEAT to the new community members in consideration for their verified physical activity. By expanding into these markets, we aim to inspire a new wave of physical activity and incentivize individuals to lead healthier lives, while paving the way for the next billion users looking to participate in the movement economy.” Sweat Economy’s announcement is another milestone as the NEAR community works hard to onboard one billion users to Web3. By choosing to build on NEAR, Sweat Economy will be well placed to leverage the protocol’s incredibly secure and infinitely scalable sharding infrastructure — unlocking the opportunity to onboard millions of potential users into a burgeoning Web3 movement economy. If you have yet to join the economy of movement, head to your mobile app store and download the Sweatcoin and Sweat Wallet apps today and see how millions of people are earning crypto just by being physically active. Join NEAR and Sweat Economy in building a healthier collective future!
NEAR Foundation Partners With Elliptic To Enhance On-Chain Security COMMUNITY February 22, 2022 The NEAR Foundation is delighted to announce it is partnering with Elliptic to help enhance security and on chain forensics. The partnership means both the NEAR blockchain and its native asset $NEAR will have access to Elliptic’s class-leading blockchain analytics and financial crime monitoring services. “NEAR’s mission is to help onboard billions of users into Web3,” says NEAR Foundation CEO Marieke Flament. “We can’t do that unless we can create a safe and secure environment for people to explore this new world. Partnering with projects like Elliptic helps us realise this goal faster.” The agreement will provide users of NEAR with full visibility of the NEAR blockchain across Elliptic’s full suite of products and services. This will initially include screening of crypto wallets and transactions on the NEAR blockchain through Elliptic’s Lens and Navigator products, with plans to incorporate Virtual Asset Providers (VASPs verification) and crime investigation capabilities through Elliptics Discovery and Forensics. “Blockchain technologies are embedded in the financial mainstream and giving businesses the tools to use them transparently is critical to their safe and secure adoption,” said Elliptic CPO John Connolly. “Working with NEAR Foundation is another important step towards providing the deepest analytical and technical insight across a broad range of blockchain technologies to ensure businesses can identify trusted partners and work with cryptoassets with confidence.” Elliptic provides compliance solutions and services for exchanges, protocols and Web3 businesses. Its analytics scan more than 500 cryptoassets and 20 billion+ data points to provide accurate, actionable insights that businesses rely on to mitigate risk and be compliant.
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="NFT Primitive" label="Reference" default> ```js const tokenData = Near.call( "nft.primitives.near", "nft_transfer", { token_id: "1", receiver_id: "bob.near" }, undefined, 1, ); ``` </TabItem> <TabItem value="Paras" label="Paras"> ```js const tokenData = Near.call( "x.paras.near", "nft_transfer", { token_id: "490641", receiver_id: "bob.near" }, undefined, 1 ); ``` </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```js const tokenData = Near.call( "thomasettorreiv.mintbase1.near", "nft_transfer", { token_id: "490641", receiver_id: "bob.near" }, undefined, 1 ); ``` </TabItem> </Tabs>
--- id: hardware-rpc title: Hardware Requirements for RPC Node sidebar_label: Hardware Requirements sidebar_position: 1 description: NEAR RPC Node Hardware Requirements --- This page covers the minimum and recommended hardware requirements for engaging with the NEAR platform as a RPC node. For testing your RPC once the node is fully sync'd, see [this example RPC request.](https://docs.near.org/api/rpc/network#node-status) ## Recommended Hardware Specifications {#recommended-hardware-specifications} | Hardware | Recommended Specifications | | -------------- |--------------------------------------------------------------------------| | CPU | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support | | CPU Features | CMPXCHG16B, POPCNT, SSE4.1, SSE4.2, AVX | | RAM | 20GB DDR4 | | Storage | 1TB SSD (NVMe SSD is recommended. HDD will be enough for localnet only ) | _Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh avx```. If the output is empty, your CPU is not supported._ ## Minimal Hardware Specifications {#minimal-hardware-specifications} | Hardware | Minimal Specifications | | -------------- |---------------------------------------------------------------------------| | CPU | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support | | RAM | 12GB DDR4 | | Storage | 500GB SSD (NVMe SSD is recommended. HDD will be enough for localnet only) | _Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh avx```. If the output is empty, your CPU is not supported._ ## Cost Estimation {#cost-estimation} Estimated monthly costs depending on operating system: | Cloud Provider | Machine Size | Linux | | -------------- | --------------- | ---------------------- | | AWS | m5.2xlarge | $330 CPU + $80 storage | | GCP | n2-standard-8 | $280 CPU + $80 storage | | Azure | Standard_F8s_v2 | $180 CPU + $40 storage | <blockquote class="info"> <strong>Resources for Cost Estimation</strong><br /><br /> All prices reflect *reserved instances* which offer deep discounts on all platforms with a 1 year commitment - AWS - cpu: https://aws.amazon.com/ec2/pricing/reserved-instances/pricing - storage: https://aws.amazon.com/ebs/pricing - GCP - cpu: https://cloud.google.com/compute/vm-instance-pricing - storage: https://cloud.google.com/compute/disks-image-pricing - Azure — https://azure.microsoft.com/en-us/pricing/calculator </blockquote> >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
Women in Web3 Changemakers: Bridget Greenwood NEAR FOUNDATION October 24, 2023 “Web3 is a marathon and a sprint at the same time,” says Bridget Greenwood, Founder of The Bigger Pie, a project helping to support women in blockchain and emerging tech. Greenwood 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. Greenwood, along with nine other outstanding candidates, is showing the industry the change women are bringing about during the advent of the Open Web. When Greenwood isn’t helping women get funding, connecting them with event organisers and experts in the field at The Bigger Pie, she is also the founder of the 200Bn Club. The 200Bn club is an investment fund and accelerator program for under-represented founders, giving them pitch coaching, mock pitches, and access to over 200 VC Partners to help them successfully gain term sheets. “There’s a lot of research that shows that women imagine solutions for a real-world problem that is much more sustainable in terms of its impact,” says Greenwood. “I think we’ve not seen enough of that in this space, and it’s what led me to start up The Bigger Pie.” But Greenwood’s journey into carving out space for more women in Web3 was anything but straightforward. Watch an extended NEAR Foundation video interview with Bridget Greenwood below. A chance encounter Before crypto, Greenwood worked as an independent financial advisor in Norfolk, a rural part of England. But found the lack of opportunity and low wages at odds with her desire to be present for her son. “I lived in a place where there wasn’t a lot of opportunity on the doorstep. So how can I earn money whilst also being present for my child?” So Greenwood turned down offers from local businesses, and joined a financial software company specialising in helping leaders navigate the online world of social media. Shortly afterwards, she “fell down the Bitcoin rabbit hole”. It was a conversation with a friend that introduced her to the idea of decentralized ledger technology. “I loved the idea of having a blockchain that is decentralised, with the ability to change, and choose where we wanted to transfer value and who was included,” says Greenwood. After that, she joined the BCB Group, which provided cryptocurrency brokerage services for institutional clients. While working at the company she saw firsthand how many brilliant, talented women were already working in the space. “I thought to myself, they don’t need any help. Right? But I thought I better ask. And I said as women in this industry, do you feel as though it’d be good to have support as a woman? Actually, the answer was yes.” Six years later, and that impromptu question has grown into a community of hundreds of women in Web3 space supporting each other. But, says Greenwood there’s still a long way to go for true equality. “When you leave out half of the population, you’re leaving out half of those experiences, and the problems they face.” For Greenwood, she is on a mission to help more women find their footing in Web3. “This is a great space to come in, because everyone’s making shit up as they go along,” she says. “Don’t worry about the fact that you’re coming in and you don’t know everything because nobody does, it moves too quickly.” Instead, says Greenwood, reach out to female founders and entrepreneurs you admire and explain why you’d like to be here. “Feel free to reach out to me and I will invite you into the Bigger Pie and share with you all of the other communities that you have. Don’t be overwhelmed, do speak up. And without you, we are not going to build a future that we want to see.”
# ExtCostsConfig ## base _type: Gas_ Base cost for calling a host function. ## read_memory_base _type: Gas_ Base cost for guest memory read ## read_memory_byte _type: Gas_ Cost for guest memory read ## write_memory_base _type: Gas_ Base cost for guest memory write ## write_memory_byte _type: Gas_ Cost for guest memory write per byte ## read_register_base _type: Gas_ Base cost for reading from register ## read_register_byte _type: Gas_ Cost for reading byte from register ## write_register_base _type: Gas_ Base cost for writing into register ## write_register_byte _type: Gas_ Cost for writing byte into register ## utf8_decoding_base _type: Gas_ Base cost of decoding utf8. ## utf8_decoding_byte _type: Gas_ Cost per bye of decoding utf8. ## utf16_decoding_base _type: Gas_ Base cost of decoding utf16. ## utf16_decoding_byte _type: Gas_ Cost per bye of decoding utf16. ## sha256_base _type: Gas_ Cost of getting sha256 base ## sha256_byte _type: Gas_ Cost of getting sha256 per byte ## keccak256_base _type: Gas_ Cost of getting keccak256 base ## keccak256_byte _type: Gas_ Cost of getting keccak256 per byte ## keccak512_base _type: Gas_ Cost of getting keccak512 base ## keccak512_byte _type: Gas_ Cost of getting keccak512 per byte ## log_base _type: Gas_ Cost for calling logging. ## log_byte _type: Gas_ Cost for logging per byte ## Storage API ### storage_write_base _type: Gas_ Storage trie write key base cost ### storage_write_key_byte _type: Gas_ Storage trie write key per byte cost ### storage_write_value_byte _type: Gas_ Storage trie write value per byte cost ### storage_write_evicted_byte _type: Gas_ Storage trie write cost per byte of evicted value. ### storage_read_base _type: Gas_ Storage trie read key base cost ### storage_read_key_byte _type: Gas_ Storage trie read key per byte cost ### storage_read_value_byte _type: Gas_ Storage trie read value cost per byte cost ### storage_remove_base _type: Gas_ Remove key from trie base cost ### storage_remove_key_byte _type: Gas_ Remove key from trie per byte cost ### storage_remove_ret_value_byte _type: Gas_ Remove key from trie ret value byte cost ### storage_has_key_base _type: Gas_ Storage trie check for key existence cost base ### storage_has_key_byte _type: Gas_ Storage trie check for key existence per key byte ### storage_iter_create_prefix_base _type: Gas_ Create trie prefix iterator cost base ### storage_iter_create_prefix_byte _type: Gas_ Create trie prefix iterator cost per byte. ### storage_iter_create_range_base _type: Gas_ Create trie range iterator cost base ### storage_iter_create_from_byte _type: Gas_ Create trie range iterator cost per byte of from key. ### storage_iter_create_to_byte _type: Gas_ Create trie range iterator cost per byte of to key. ### storage_iter_next_base _type: Gas_ Trie iterator per key base cost ### storage_iter_next_key_byte _type: Gas_ Trie iterator next key byte cost ### storage_iter_next_value_byte _type: Gas_ Trie iterator next key byte cost ### touching_trie_node _type: Gas_ Cost per touched trie node ## Promise API ### promise_and_base _type: Gas_ Cost for calling promise_and ### promise_and_per_promise _type: Gas_ Cost for calling promise_and for each promise ### promise_return _type: Gas_ Cost for calling promise_return
NEAR Protocol BigQuery Public Dataset NEAR FOUNDATION September 22, 2023 NEAR Protocol is a user-friendly, carbon-neutral blockchain, built from the ground up to be performant, secure, and unparalleled scalability. In technical terms, NEAR is a layer one, sharded, proof-of-stake blockchain built with usability in mind. In simple terms, NEAR is a blockchain for everyone. Today, we are excited to announce the NEAR BigQuery Public Dataset for anyone who wants to query blockchain data in an easy and cost-effective way. Why BigQuery Public Dataset Until now, a user’s data query needs were fulfilled by indexers. Those indexers were either supplied by NEAR Protocol or custom made. To build custom indexers required JSON files from the NEAR Lake storage layer to be transformed and loaded into a target database engine like PostgreSQL, and only then could a user execute queries against it. This approach is complex, time-consuming, and resource-draining. It requires constant monitoring to ensure databases have the most up-to-date information. NEAR BigQuery Public Dataset changes this. It provides near real-time blockchain data that can be easily queried with SQL. What we did We built the NEAR LakeHouse in Databricks. The data is loaded into raw bronze files using Databricks Autoloader, and transformed with Databricks Delta Live Tables into cleaned and enriched silver tables following the Databricks Medallion Architecture. The silver tables are then copied into the GCP BigQuery Public Dataset ready for consumption. The solution design The code is open-source and can be found in our GitHub repository: near/near-public-lakehouse To learn more about how to get started and the data available, please check our documentation: https://docs.near.org/bos/queryapi/big-query Benefits NEAR instant insights: Historic on-chain data queried at scale. Cost-effective: Eliminate the need to store and process bulk NEAR Protocol data; query as little or as much data as preferred. Easy to use: No prior experience with blockchain technology is required; bring a general knowledge of SQL to unlock insights. Conclusion NEAR BigQuery Public Dataset is now available for anyone wanting to harness blockchain data for their own needs. BigQuery can help not only developers, but broader audiences including: Users: Create queries to track NEAR Protocol assets, monitor transactions, or analyze on-chain events at a massive scale. Researchers: Use indexed data for data science tasks, including on-chain activities, identifying trends, or feeding AI/ML pipelines for predictive analysis. Startups: Use NEAR Protocol’s indexed data for deep insights on user engagement, smart contract utilization, or insights across tokens and NFT adoption. Acknowledgments We are grateful for the following contributors who helped us to deliver the NEAR BigQuery Public Dataset. NEAR Foundation/Pagoda: Eduardo Ohe, Pavel Kudinov, Jo Yang, Abhishek Anirudhan, Yad Konrad, Olga Telezhnaya, Bohdan Khorolets,Morgan McCauley, Ernesto Cejas Padilla, Rob Tsai, Damián Parrino. Google Cloud: Colleen Pimentel, Rodrigo de Freitas Vale, and Devan Mitchem. Databricks: Clayton Martin, and Alice Zhang.
A Reminder to Migrate from NEAR Wallet NEAR FOUNDATION October 12, 2023 In July, NEAR Foundation published “Embracing Decentralization: What’s Next for the NEAR Wallet”, a detailed exploration of how Pagoda is migrating NEAR Wallet from being a browser wallet into a wallet hub. As we noted at the time, this wallet evolution illustrates the substantial growth of the NEAR ecosystem, which now offers a wide range of cross-chain wallets and native wallets. As part of this wallet evolution, the NEAR Wallet is set to be discontinued on January 1, 2024. You can migrate to your wallet of choice using the automatic Wallet Transfer Wizard, integrated into the current NEAR Wallet, or manually by using your recovery phrase. Whichever path you choose, understand that your account and its assets are safe. Do not worry if you have not transferred your accounts by January 1, 2024 — the Transfer Wizard will still be available after the wallet functionality sunsets. And again, rest assured that your assets will remain secure until you import them to a new wallet. For more details on using the Transfer Wizard, visit the Migrating from NEAR Wallet page.
NEAR Community Update: February 8, 2019 COMMUNITY February 8, 2019 The NEAR DevNet is out. In this case, the blockchain is currently running on a single node but you can use the NEAR Studio online IDE to one-click deploy a sample Guest Book contract or you can try out a lightweight tutorial for building a basic game. We’ve kept the styling and functionality very minimal so far but there are a few key things to notice: You can use one click — the “Run” button — to deploy the contract immediately to the blockchain and serve it in the browser. Sharing the full URL from app.near.ai allows other people to interact with it collaboratively. The contract development language is TypeScript so anyone who knows JavaScript or even C#/Java will feel comfortable with it immediately. Tests are baked right into the templates and the “Test” button will automatically run the Jasmine test suite for you in the browser. There is a basic NEAR-hosted wallet in place as well. It doesn’t look like much visually but this is the tip of the iceberg and functionality will increase quickly over the upcoming weeks. We are running tons of workshops with developers to build community and iterate alongside our users. #movefastandshipthings This is a test caption for the image. Community and Events We’re kicked into high gear for upcoming events because we’re ready to allow our community to get their hands on real code. Those events which have been finalized are listed below but we have tours through Colorado, Europe and Asia on the horizon plus plenty of good old-fashioned Bay Area workshopping. If you want to host a local NEAR meetup in your city or see if we can meet with yours, reach out to [email protected]. Recent Highlights [SF] Blockchain 101 Onramp: The Design of Blockchain-Based Apps (DApps) (Video, Slides) [Online]: Next Generation Blockchains: Usability, Scalability and Real Business Models (Erik Trautman) Upcoming Events [Denver] Feb 12: Sneak Peak Workshop: NEAR DevNet with ETH Denver [SF] Feb 13: Blockchain 101 Onramp: DApp Development Basics [Denver] Feb 15–17: Judging the Eth Denver hackathon (Illia Polosukhin) [SF] Feb 19: NEAR Protocol DevNet Test Drive with ABC Blockchain [Boston] Feb 22: Harvard Business School 2019 Crypto Club (with Alex Skidanov) [SF] Feb 26: Giving power back to developers: Preview of a new computing platform (@Github) [Oakland] Feb 27: Near Protocol — DevNet Workshop (@Oakland Developers) [SF] Feb 27: Blockchain 101 Onramp: Best Practices for Developing DApps [Shanghai] Feb 28: NEAR Workshop (link unavailable yet) [Paris] March 8: Events around Eth Paris [Austin] March 14–16: Events around SXSW If you want to collaborate on events, reach out to [email protected] Writing and Content Alex Skidanov gave a talk on sharding at Graph Day which discussed tradeoffs in the space and I spoke about usability, scalability and real business models for next generation blockchains at Decentralized Summit. Engineering Highlights As mentioned above, we have finalized the first version of DevNet and are now on-boarding developers to try it out. Check it out at https://studio.nearprotocol.com/, where you can use a pre-configured template to deploy a smart contract in about 4 seconds. We are beginning to build out more tutorials to show off what NEAR can do and how easy it is to built apps on top of. Check out the docs or catch up with Illia and Alex at ETH Denver or on Discord to learn more. Development changes included: Built a hosted wallet with OAuth flow Switched to use protobufs for encoding transactions across nearcore and nearlib. Nearlib: updated docs, syntactic sugar for contract method calls, easy way to wait for transaction completion using promises, handle failed transactions and return readable errors through promises, get logs from node into JS console Refactored runtime and transaction/receipt processing to allow for validation of the receipt source Integrated BLS signature aggregation and verification for block production Finalized rewriting network protocol and started to build integration testing for TestNet Finally, we’re building on WASM so wanted to show our support for the developers of the project. We hope to get even more involved with great infrastructure projects in the future. How You Can Get Involved Join us! If you want to work with one of the most talented (and humble?) teams in the world right now to solve incredibly hard problems, check out our careers page for openings. 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.