text
stringlengths
46
74.6k
# Messages All message sent in the network are of type `PeerMessage`. They are encoded using [Borsh](https://borsh.io/) which allows a rich structure, small size and fast encoding/decoding. For details about data structures used as part of the message see the [reference code](https://github.com/nearprotocol/nearcore). ## Encoding A `PeerMessage` is converted into an array of bytes (`Vec<u8>`) using borsh serialization. An encoded message is conformed by 4 bytes with the length of the serialized `PeerMessage` concatenated with the serialized `PeerMessage`. Check [Borsh specification](https://github.com/nearprotocol/borsh#specification) details to see how it handles each data structure. ## Data structures ### PeerID The id of a peer in the network is its [PublicKey](https://github.com/nearprotocol/nearcore/blob/master/core/crypto/src/signature.rs). ```rust struct PeerId(PublicKey); ``` ### PeerInfo ```rust struct PeerInfo { id: PeerId, addr: Option<SocketAddr>, account_id: Option<AccountId>, } ``` `PeerInfo` contains relevant information to try to connect to other peer. [`SocketAddr`](https://doc.rust-lang.org/std/net/enum.SocketAddr.html) is a tuple of the form: `IP:port`. ### AccountID ```rust type AccountId = String; ``` ### PeerMessage ```rust enum PeerMessage { Handshake(Handshake), HandshakeFailure(PeerInfo, HandshakeFailureReason), /// When a failed nonce is used by some peer, this message is sent back as evidence. LastEdge(Edge), /// Contains accounts and edge information. Sync(SyncData), RequestUpdateNonce(EdgeInfo), ResponseUpdateNonce(Edge), PeersRequest, PeersResponse(Vec<PeerInfo>), BlockHeadersRequest(Vec<CryptoHash>), BlockHeaders(Vec<BlockHeader>), BlockRequest(CryptoHash), Block(Block), Transaction(SignedTransaction), Routed(RoutedMessage), /// Gracefully disconnect from other peer. Disconnect, Challenge(Challenge), } ``` ### AnnounceAccount Each peer should announce its account ```rust struct AnnounceAccount { /// AccountId to be announced. account_id: AccountId, /// PeerId from the owner of the account. peer_id: PeerId, /// This announcement is only valid for this `epoch`. epoch_id: EpochId, /// Signature using AccountId associated secret key. signature: Signature, } ``` ### Handshake ```rust struct Handshake { /// Protocol version. pub version: u32, /// Oldest supported protocol version. pub oldest_supported_version: u32, /// Sender's peer id. pub peer_id: PeerId, /// Receiver's peer id. pub target_peer_id: PeerId, /// Sender's listening addr. pub listen_port: Option<u16>, /// Peer's chain information. pub chain_info: PeerChainInfoV2, /// Info for new edge. pub edge_info: EdgeInfo, } ``` <!-- TODO: Make diagram about handshake process, since it is very complex --> ### Edge ```rust struct Edge { /// Since edges are not directed `peer0 < peer1` should hold. peer0: PeerId, peer1: PeerId, /// Nonce to keep tracking of the last update on this edge. nonce: u64, /// Signature from parties validating the edge. These are signature of the added edge. signature0: Signature, signature1: Signature, /// Info necessary to declare an edge as removed. /// The bool says which party is removing the edge: false for Peer0, true for Peer1 /// The signature from the party removing the edge. removal_info: Option<(bool, Signature)>, } ``` ### EdgeInfo ```rust struct EdgeInfo { nonce: u64, signature: Signature, } ``` ### RoutedMessage ```rust struct RoutedMessage { /// Peer id which is directed this message. /// If `target` is hash, this a message should be routed back. target: PeerIdOrHash, /// Original sender of this message author: PeerId, /// Signature from the author of the message. If this signature is invalid we should ban /// last sender of this message. If the message is invalid we should ben author of the message. signature: Signature, /// Time to live for this message. After passing through some hop this number should be /// decreased by 1. If this number is 0, drop this message. ttl: u8, /// Message body: RoutedMessageBody, } ``` ### RoutedMessageBody ```rust enum RoutedMessageBody { BlockApproval(Approval), ForwardTx(SignedTransaction), TxStatusRequest(AccountId, CryptoHash), TxStatusResponse(FinalExecutionOutcomeView), QueryRequest { query_id: String, block_id_or_finality: BlockIdOrFinality, request: QueryRequest, }, QueryResponse { query_id: String, response: Result<QueryResponse, String>, }, ReceiptOutcomeRequest(CryptoHash), ReceiptOutComeResponse(ExecutionOutcomeWithIdAndProof), StateRequestHeader(ShardId, CryptoHash), StateRequestPart(ShardId, CryptoHash, u64), StateResponse(StateResponseInfo), PartialEncodedChunkRequest(PartialEncodedChunkRequestMsg), PartialEncodedChunkResponse(PartialEncodedChunkResponseMsg), PartialEncodedChunk(PartialEncodedChunk), Ping(Ping), Pong(Pong), } ``` ## CryptoHash `CryptoHash` are objects with 256 bits of information. ```rust pub struct Digest(pub [u8; 32]); pub struct CryptoHash(pub Digest); ```
--- title: 3.7 Prediction Market Design description: Theory and use-cases of Prediction Markets, and the re-application of the mechanism design behind prediction markets for a wide variety of use-cases --- # 3.7 Prediction Market Design The final lecture in our DeFi series is titled ‘Prediction-Market Design’ - and very clearly not only prediction markets. Why would this be the case? Because despite prediction markets being a quiet and slowly growing DeFi product in its own right, there is much more opportunity and interest from leveraging the mechanism design surrounding ‘prediction-markets’ for a wide variety of on-chain verification use cases. This lecture as such is broken up into two parts: The ‘boring’ theory and use-cases of prediction markets, and second, the much more interesting re-application of the mechanism design behind prediction markets for a wide variety of use-cases. ## Prediction Market Mechanism Design: What Is The Value? ‘Validation’ typically refers to validation of the L1 blockchain itself, done relatively automatically through node operators running software, and delegators allocating tokens to node operators. The specific type of data that is being validated, is thus digital data, and relatively uncontroversial insofar as all of the data is being created with the next block created on-chain. Any working explorer or indexer can show the same story to all of the validator nodes, such that it is quite automated to maintain the node on the network. One step slightly more advanced than this, would be Oracles attempting to bring data on-chain for specific things like price-feeds, from APIs of real world events. Centralized Oracles, guarantee the accuracy of these price-feeds by synchronizing multiple APIs - decentralized oracles however require their own validation mechanism. One step even more advanced than this, would refer to the data that is collected from the physical world, and uploaded on-chain either manually, via a sensor, or even from a human being. How is such a system verifiable at scale? Herein lies the means by which the logic of a ‘prediction market’ can be utilized: As verification of data moving on chain becomes less quantitative, and more qualitative - that is to say, more ambiguous - and less mathematically verifiable from digital-only data - there is a need for a mechanism by which such data could be verified in a decentralized manner. _Put another way, the closer to attempting to track the physical state of a specific asset or event, the more difficult it is to verify that physical state, in a decentralized manner._ To date, prediction market mechanics are the most promising foundation, from which one could construct a decentralized, on-chain mechanism for ‘validating’ such data. ## Traditional Prediction Market Design _“Prediction markets: these have been a niche but stable pillar of decentralized finance since the launch of Augur in 2015. Since then, they have quietly been growing in adoption. Prediction markets [showed their value and their limitations](https://vitalik.eth.limo/general/2021/02/18/election.html) in the 2020 US election, and this year in 2022, both crypto prediction markets like [Polymarket](https://polymarket.com/) and play-money markets like [Metaculus](https://www.metaculus.com/questions/) are becoming more and more widely used. Prediction markets are valuable as an epistemic tool, and there is a genuine benefit from using cryptocurrency in making these markets more trustworthy and more globally accessible. I expect prediction markets to not make extreme multibillion-dollar splashes, but continue to steadily grow and become more useful over time.” ([Vitalik](https://vitalik.eth.limo/general/2022/12/05/excited.html))_ As Vitalik explains, prediction markets refer to open-markets, in which users can ‘stake’ or ‘bet’ on the outcome of a binary, ‘yes’ or ‘no’ question. The ‘decentralized’ nature of predict markets are twofold: 1. First, any user, from anywhere in the world is eligible to participate, such that there is no KYC, discrimination, or localization of participants. This, by extension, enables ‘the wisdom of the crowds’ to provide realistic predictions and foresight towards the future. See Superforcasters or the Foresight Institute for more information on this front. The ‘wisdom of the crowds’ on a particular outcome could have the CIA and the KGB betting on one outcome based on the intel they know - without even knowing it. 2. Second, the resolution and validation of the market is done by a decentralized suite of participants, all following the same incentive scheme. This is usually designed in the following manner, using the native token of the protocol: * Validators stake the native token affirming one of the two binary outcomes. * After X period of time, there is the opportunity to challenge the outcome. * After Y period of time, there is the opportunity to escalate the challenge. * Each escalation requires higher and higher amounts of tokens to be staked on an outcome. * When there is no longer an escalation, the side with the majority stake is deemed the correct outcome, and the side with the losing stake is slashed. The implicit premise in prediction market design, is that the binary outcome is clearly evident once the event has passed, and as such it is straightforward or self-evident as to what the correct outcome actually is. A non-binary question would prove to be more difficult to resolve especially if there is any room for controversy. At the end of the validation - challenge - and escalation sequence, there is typically a resolution period, in which the market resolves, and prepares to payout rewards to the correct validators. Those who have staked value on an outcome, are also rewarded for the outcome that is deemed correct. ## Augur Augur was the first dApp ever built on Ethereum, and was used briefly before the mechanism design was hijacked by an anonymous hacker by the name of _[Poyo](https://medium.com/sunrise-over-the-merkle-trees/meet-poyo-an-interview-with-augurs-most-controversial-cat-a6bccae9ffe7)_ . Poyo’s strategy was based on a loophole in the protocol design in which an infinite escalation would eventually resolve as ‘invalid’ and payout both sides of the binary market an equal amount of value (regardless of how clear the correct outcome might be). This initial flaw in the prediction market set back the development of Augur significantly, and demonstrated to many the absolute importance of sound mechanism design. On the whole the fundamental issues with Augur beyond its mechanism design also centered on the cost of fees on the Ethereum network, specifically when it came to resolving markets or bidding on outcomes. High costs and slow resolution times made the system scalability limited and painful especially for users. ## Seda Protocol & Stake GG Fast forward two years, and Seda protocol (formerly Flux), originally sought to re-test the Augur prediction market design on a cheaper, and more scalable network - our own NEAR Protocol. With the same essential mechanism design minus the fundamental flaws in Augur V1, the logic was that an affordable and quick resolution period could sustain liquid and scalable markets for decentralized forecasting. The resultant product, known as Stake.gg struggled to find active users and venture backing, so with the same mechanism design, the Seda team pivoted into a new cluster: [Decentralized Oracle design](https://docs.seda.xyz/seda-network/introduction/the-oracle-problem), using the same prediction market mechanism design. The underlying value proposition is as follows: _Unlike existing oracles, that are largely managed in a centralized manner to decide which data is connected to a specific dApp or blockchain, Flux [Seda] purports to leverage the decentralized market resolution design of Augur, in order to secure the correct amount of price and data feeds, connected to a dApp on-chain._ This design is slightly modified, as instead of a user placing value on a future outcome, it is used to whitelist _requesters_, capable of connecting Seda Oracles to on-chain mechanisms. _Requesters →_ Request a data feed from a Seda oracle, and in return for receiving this service, post a fee to validator nodes. _Validators →_ Mirror the Augur validation mechanism in staking on outcomes and competing for a share in the fee paid by requesters. _Token Holders →_ Curate the list of requesters, via DAO vote, to decide who is allowed to post validation requests. The resolution windows are meanwhile set to resolve on a recurring basis, with the fee increasing with each escalation. The design fixes Augur’s ‘Invalid’ status bug, by bringing in a final arbitrator, once 2.5% of the token supply is utilized in a resolution. _The value in understanding Flux [Seda], centers upon how the same mechanism for resolving prediction markets, can equally be utilized for ‘economically securing’ data requests as an Oracle._ ## Campground While [Campground ](https://www.campground.co/)remains in its infancy, the thesis of the project was to create a decentralized content management system, in which wrapped content, would be validated by a decentralized community of curators. Users would stake tokens, to place ‘emojis’ on certain pieces of content, with the thesis being that a nuanced conclusion could be achieved on any specific piece of content with sufficient emojis’ placed on the content over time. Content creators would then develop reputations based on the aggregate judgments placed on the content of a creator by the community of curators. The specific mechanism by which curators would ‘validate’ the quality of a content piece, would be by a prediction market mechanism of validation, challenge, and escalation from a (whitelisted) group of curators. _The value in this approach, centers upon the prospect of leveraging a prediction market mechanism, for creating a decentralized content management system surrounding reactions to content, and quality and reputation being attributed to a specific author or work over time._ ## Open Forest Protocol Last but not least, [Open Forest Protocol (OFP)](https://www.openforestprotocol.org/), leverages a similar prediction market mechanism for resolving data uploads, uploaded from forest projects seeking to generate carbon credits on the platform. However, unlike Flux Oracles and Campground curators, OFP validators have a 30 day window to validate data uploads, and a maximum of three escalations. Any validator in its current state, must be whitelisted to participate based upon their qualifying criteria. ## So what is really going on here? Modification Variables The prediction market mechanism is ultimately a mechanism from which any type of decentralized verification mechanism can be created based upon (1) The types of participants allowed to validate, (2) the timeframes for validating the ‘market’ or ‘data request’, (3) The penalties or rewards for successfully resolving an outcome. In addition, there are a number of modification variables that could add further mechanistic complexity: * (1) Visibility - between participants: Are validators allowed to see who, when, and how other validators have validated an outcome, or is this only visible after the market has resolved? * (2) Timeframes on Resolution of Market: Recurring, expanded time frames, or set timeframes for the type of request in question. * (3) Gating who can validate: Is it open to the public or are only specific parties eligible to validate based upon their background, KYC, or other criteria? * (4) Validator requirements: Are validators all using the same software, API, or price feed, or is their flexibility in terms of how a validator may come to their conclusion on the state of the data request. * (5) Penalties and Rewards for Validators: How are validators compensated for each data request? Are validators slashed, penalized or barred from the platform if they consistently resolve data requests on the wrong side of the outcome? * (6) Validator Communication: Are validators able to discuss the ongoing data request in real-time or are they intentionally siloed from one another in order to prevent collusion? It is likely in the future there will be a number of decentralized network designs that will originate based upon the prediction market logic of Augur. The variety and applicability of such a mechanism is a ‘hidden’ gem across network verticals that should be kept in mind for struggling products or industries specifically difficult to bring on-chain.
# Bridge Wallets ## Summary Standard interface for bridge wallets. ## Motivation Bridge wallets such as [WalletConnect](https://docs.walletconnect.com/2.0/) and [Nightly Connect](https://connect.nightly.app/) are powerful messaging layers for communicating with various blockchains. Since they lack an opinion on how payloads are structured, without a standard, it can be impossible for dApps and wallets to universally communicate without compatibility problems. ## Rationale and alternatives At its most basic, a wallet manages key pairs which are used to sign messages. The signed messages are typically then submitted by the wallet to the blockchain. This standard aims to define an API (based on our learning from [Wallet Selector](https://github.com/near/wallet-selector)) that achieves this requirement through a number of methods compatible with a relay architecture. There have been many iterations of this standard to help inform what we consider the best approach right now for NEAR. You can find more relevant content in the [Injected Wallet Standard](#). ## Specification Bridge wallets use a relay architecture to forward signing requests between dApps and wallets. Requests are typically relayed using a messaging protocol such as WebSockets or by polling a REST API. The concept of a `session` wraps this connection between a dApp and a wallet. When the session is established, the wallet user typically selects which accounts that the dApp should have any awareness of. As the user interacts with the dApp and performs actions that require signing, messages are relayed to the wallet from the dApp, those messages are signed by the wallet and submitted to the blockchain on behalf of the requesting dApp. This relay architecture decouples the 'signing' context (wallet) and the 'requesting' context (dApp, which enables signing to be performed on an entirely different device than the dApp browser is running on. To establish a session, the dApp must first pair with the wallet. Pairing often includes a QR code to improve UX. Once both clients are paired, a request to initialize a session is made. During this phase, the wallet user is prompted to select one or more accounts (previously imported) to be visible to the session before approving the request. Once a session has been created, the dApp can make requests to sign transactions using either [`signTransaction`](#signtransaction) or [`signTransactions`](#signtransactions). These methods accept encoded [Transactions](https://nomicon.io/RuntimeSpec/Transactions) created with `near-api-js`. Since transactions must know the public key that will be used as the `signerId`, a call to [`getAccounts`](#getaccounts) is required to retrieve a list of the accounts visible to the session along with their associated public key. Requests to both [`signTransaction`](#signtransaction) and [`signTransactions`](#signtransactions) require explicit approval from the user since [`FullAccess`](https://nomicon.io/DataStructures/AccessKey) keys are used. For dApps that regularly sign gas-only transactions, Limited [`FunctionCall`](https://nomicon.io/DataStructures/AccessKey#accesskeypermissionfunctioncall) access keys can be added/deleted to one or more accounts by using the [`signIn`](#signin) and [`signOut`](#signout) methods. While the same functionality could be achieved with [`signTransactions`](#signtransactions), that contain actions that add specific access keys with particular permissions to a specific account, by using `signIn`, the wallet receives a direct intention that a user wishes to sign in/out of a dApp's smart contract, which can provide a cleaner UI to the wallet user and allow convenient behavior to be implemented by wallet providers such as 'sign out' automatically deleting the associated limited access key that was created when the user first signed in. Although intentionally similar to the [Injected Wallet Standard](#), this standard focuses on the transport layer instead of the high-level abstractions found in injected wallets. Below are the key differences between the standards: - [Transactions](https://nomicon.io/RuntimeSpec/Transactions) passed to `signTransaction` and `signTransactions` must be encoded. - The result of `signTransaction` and `signTransactions` are encoded [SignedTransaction](https://nomicon.io/RuntimeSpec/Transactions#signed-transaction) models. - Accounts contain only a string representation of public keys. ### Methods #### `signTransaction` Sign a transaction. This request should require explicit approval from the user. ```ts import { transactions } from "near-api-js"; interface SignTransactionParams { // Encoded Transaction via transactions.Transaction.encode(). transaction: Uint8Array; } // Encoded SignedTransaction via transactions.SignedTransaction.encode(). type SignTransactionResponse = Uint8Array; ``` #### `signTransactions` Sign a list of transactions. This request should require explicit approval from the user. ```ts import { providers, transactions } from "near-api-js"; interface SignTransactionsParams { // Encoded Transaction via transactions.Transaction.encode(). transactions: Array<Uint8Array>; } // Encoded SignedTransaction via transactions.SignedTransaction.encode(). type SignTransactionsResponse = Array<Uint8Array>; ``` #### `signIn` For dApps that often sign gas-only transactions, `FunctionCall` access keys can be created for one or more accounts to greatly improve the UX. While this could be achieved with `signTransactions`, it suggests a direct intention that a user wishes to sign in to a dApp's smart contract. ```ts import { transactions } from "near-api-js"; interface Account { accountId: string; publicKey: string; } interface SignInParams { permission: transactions.FunctionCallPermission; accounts: Array<Account>; } type SignInResponse = null; ``` #### `signOut` Delete one or more `FunctionCall` access keys created with `signIn`. While this could be achieved with `signTransactions`, it suggests a direct intention that a user wishes to sign out from a dApp's smart contract. ```ts interface Account { accountId: string; publicKey: string; } interface SignOutParams { accounts: Array<Account>; } type SignOutResponse = null; ``` #### `getAccounts` Retrieve all accounts visible to the session. `publicKey` references the underlying `FullAccess` key linked to each account. ```ts interface Account { accountId: string; publicKey: string; } interface GetAccountsParams {} type GetAccountsResponse = Array<Account>; ``` ## Flows **Connect** 1. dApp initiates pairing via QR modal. 2. wallet establishes pairing and prompts selection of accounts for new session. 3. wallet responds with session (id and accounts). 4. dApp stores reference to session. **Sign in (optional)** 1. dApp generates a key pair for one or more accounts in the session. 2. dApp makes `signIn` request with `permission` and `accounts`. 3. wallet receives request and executes a transaction containing an `AddKey` Action for each account. 4. wallet responds with `null`. 5. dApp stores the newly generated key pairs securely. **Sign out (optional)** 1. dApp makes `signOut` request with `accounts`. 2. wallet receives request and executes a transaction containing a `DeleteKey` Action for each account. 3. wallet responds with `null`. 4. dApp clears stored key pairs. **Sign transaction** 1. dApp makes `signTransaction` request. 2. wallet prompts approval of transaction. 3. wallet signs the transaction. 4. wallet responds with `Uint8Array`. 5. dApp decodes signed transaction. 6. dApp sends signed transaction. **Sign transactions** 1. dApp makes `signTransactions` request. 2. wallet prompts approval of transactions. 3. wallet signs the transactions. 4. wallet responds with `Array<Uint8Array>`. 5. dApp decodes signed transactions. 6. dApp sends signed transactions.
NEAR Bringing Chainlink’s Leading Oracle Solution to its Open Web Ecosystem COMMUNITY July 30, 2020 We are excited to announce that Chainlink’s decentralized oracle network is launching on NEAR. You can view the TestNet repository and instructions, and in a few weeks developers can start building applications that are integrating real-world data into their smart contracts contracts. Our goal is to be the leading computing platform for the Open Web by providing developers with the best infrastructure for building future applications (including dApps). Chainlink is the most versatile off-chain connectivity in Web3; we recommend it as it is the industry leading oracle solution used by top DeFi teams such as Synthetix, AAVE and many others. We’re excited to collaborate with Chainlink to make decentralized oracles available to NEAR developers. Integrating Chainlink provides developers access to a large decentralized collection of security-reviewed nodes, an integration framework for connecting to any premium data source derived from credentialed APIs, multiple proven data solutions that can be quickly deployed on the NEAR blockchain, and much more. One of the first use cases for Chainlink on NEAR will be providing pricing data for DeFi applications by leveraging their Price Reference Data framework. Other use cases include Open Web applications connecting to Chainlink’s Web2 counter-parties to query their data (e.g., marketplace data for real estate, insurance, music, etc). Applications can ask for any generic data by creating a contract with the data provider nodes. The Benefits of Chainlink for NEAR Developers Without oracles, smart contracts can only be written about data generated within the blockchain (on-chain) which is largely about ownership of various pieces of data (like tokens, NFTs, digital assets or data provided from outside). Expanding to include off-chain data opens up a plethora of new applications and use cases, whether it be building crop insurance agreements for developing countries using satellite weather data, triggering options contracts based on stock market prices, or constructing trade finance automation applications that are connected to IoT and customs data. However, with this expansion in connectivity comes new attack surface area that must be secured. Fully decentralized blockchains interacting with data from centralized oracles introduces large risks to the end-to-end security and reliability of the smart contract. To prevent such centralization issues, Chainlink provides a framework for building decentralized oracle networks that source and deliver off-chain data for smart contracts in a secure and reliable manner. It allows dApps to know what’s happening in the real world while retaining the decentralized, permissionless, and deterministic guarantees of the blockchain. There are many ways NEAR developers can use Chainlink to augment the value of their dApps, including the following: Access to secure node operators – The Chainlink Network contains a large and growing number of independent, security reviewed, and Sybil-resistant node operators that can be commissioned to provide specific oracle services, many of which are operated by leading blockchain DevOps and blockchain infrastructure teams. Retrieve data from credentialed APIs – Chainlink’s modular external adapter technology gives your smart contract access to data from any paid or password protected API, enabling connections to premium data providers and permissioned enterprise backend systems. Framework for decentralization – Chainlink provides a generalized framework for deploying decentralization at both the node operator and data source levels, ensuring high availability and redundant validation to the delivery and sourcing of external data to your application. Proven solutions – Chainlink’s existing oracle design patterns already secure hundreds of millions and can be easily deployed on NEAR to allow contracts to obtain Price Reference Data and on-chain verifiable randomness, avoiding the pitfalls of trying to provision your own oracle infrastructure. TLS Verification – Chainlink is pioneering TLS verification solutions through its well-known work on TownCrier, making oracles available that preserve privacy and provide integrity to any data source. Everyone who has worked on getting NEAR to this point is extremely excited to see the community and partners get more involved in every aspect of the network’s development, operation, and ecosystem growth. This includes creating decentralized applications that are aware of off-chain events happening in everyday life and then reacting to these events through a variety of on-chain actions. The possibilities are truly limitless when combining on-chain and off-chain worlds, so we encourage developers to get creative as this field has so much untapped potential. Illia Polosukhin, Co-Founder at NEAR Protocol, explained the importance of the Chainlink integration: “Chainlink integration provides NEAR with most versatile oracle network in the market, as well as the ability to connect to any off-chain API. These are key building blocks for connecting Web2 and Open Web environments, which ultimately allows our developers to build a much wider range of applications, ranging from decentralized financial products and NFTs, to asset tokenization and insurance contracts.” About NEAR Protocol NEAR’s mission is to enable community-driven innovation to benefit people around the world. The NEAR platform is a decentralized application platform that is secure enough to manage high value assets like money or identity and performant enough to make them useful for everyday people, putting the power of Open Finance and the Open Web in their hands. Technically speaking, NEAR Protocol is a public, proof-of-stake blockchain which is built using a novel consensus mechanism called Doomslug. NEAR Protocol uses a technique called “sharding” which splits the network into multiple pieces so that the computation is done in parallel. Parallelism radically increases throughput and allows the network to scale up as the number of nodes on it increases. With NEAR, there isn’t a theoretical limit on the network’s capacity. NEAR core contributors have won multiple world championships in competitive programming and worked at major tech companies such as Google, Facebook, and Niantic. Find out more about NEAR Protocol on our website, follow us on Twitter, or join our community onDiscord. If you are curious about how to integrate with NEAR or whether it might be a good fit for your business needs, reach out to [email protected]. About Chainlink If you’re a developer and want to connect your smart contract to off-chain data and systems, visit thedeveloper documentation and join the technical discussion onDiscord. If you want to schedule a call to discuss the integration more in-depth, reach out here. Chainlink is an open source blockchain abstraction layer for building and running decentralized oracle networks that give your smart contract access to secure and reliable data inputs and outputs. It provides oracles to leading DeFi applications like Synthetix, Aave, and Kyber Network; numerous blockchains such as Ethereum, Polkadot, and Tezos; as well as large enterprises including Google, Oracle, and SWIFT.
# RuntimeFeesConfig Economic parameters for runtime ## action_receipt_creation_config _type: Fee_ Describes the cost of creating an action receipt, `ActionReceipt`, excluding the actual cost of actions. ## data_receipt_creation_config _type: [DataReceiptCreationConfig](RuntimeFeeConfig/DataReceiptCreationConfig.md)_ Describes the cost of creating a data receipt, `DataReceipt`. ## action_creation_config _type: [ActionCreationConfig](RuntimeFeeConfig/ActionCreationConfig.md)_ Describes the cost of creating a certain action, `Action`. Includes all variants. ## storage_usage_config _type: [StorageUsageConfig](RuntimeFeeConfig/StorageUsageConfig.md)_ Describes fees for storage rent ## burnt_gas_reward _type: [Fraction](RuntimeFeeConfig/Fraction.md)_ Fraction of the burnt gas to reward to the contract account for execution.
--- title: 4.3 Social Tokens description: Understanding the social value of Non-Fungible tokens --- # 4.3 Social Tokens The focus of this lecture centers on the social value of Non-Fungible tokens, as already achieved across the crypto verse through token-gated communities (social tokens) and Profile Picture communities (PFPs). However, in order to thoroughly understand the relationship between NFT’s and communities, we need to also understand the indirect effects generated by such communities. This leaves us with an interesting question we will try to answer at the end: _Are token gated communities necessary for the development of a non-fungible token market in an L1 ecosystem?_ ## What is a Token-Gated Community? To start, let’s define what is a ‘social token’: Technically, a social token could be a fungible token or a non-fungible token, that provides special access to specific benefits in which other owners of the token or NFT are also entitled to. Originally, social tokens began as being for a specific artist or creator, then they morphed into more general communities like _Seed Club_ or _Friends with Benefits._ Then they caught hold with the launch of Non-Fungible Token Profile Picture Collections (PFPs) to provide exclusive access to a specific community server - discord, telegram, or something launched by the project itself. _Token Gated Community, are an encompassing term referring to both social tokens and non-fungible tokens. The premise of a token gated community is that it ‘gates’ access to a community or individual, such that only someone in possession of the token would be able to access and participate in the community._ Two well known and highly successful token-gated communities include: ![](@site/static/img/bootcamp/mod-em-4.3.1.png) * **[Seed Club:](https://www.seedclub.xyz/)** Seed club is one of the OG token gated communities designed to create a network of builders, DAOs, and crypto-natives. It is rooted in offering builders a 12 week accelerators on the fundamentals of community building and capital formation. _“We work intensively with you over the 12 week program to refine your plans and prepare you for your capital and community formation milestones. The program culminates with Demo Day, where you get to present your project to 1,000+ prospective contributors and community members._ _We’ve run four successful cohorts to date, and currently support 60+ alumni DAOs. Our next cohort SC05 kicks off mid-September.” ([Seed Club](https://www.seedclub.xyz/))_ The interesting nature of seed club, lies in its ability to connect capital allocators (VC’s) with fresh crypto-native talent, all beneath the umbrella of its token gated community. * **[Friends with Benefits DAO: ](https://www.fwb.help/)** Friends with Benefits is one of the most successful social tokens and DAO communities. While FWB is not built around an NFT collection, they are a token gated community [providing business, lifestyle, and networking opportunities to their members](https://www.youtube.com/watch?v=38C5-9RZE7w). ![](@site/static/img/bootcamp/mod-em-4.3.2.png) FwB has grown to over 2,000 members, and 8 full time managers. As CoinDesk Reports, it is pushing the boundaries of what a ‘token gated community’ is able to offer: _“It’s still also a group chat, but its ambit is much broader: FWB is a music discovery platform, an online publication, a startup incubator and a kind of Bloomberg terminal for crypto investors. It’s setting up community hubs in major cities across the globe; it throws parties with [Yves Tumor](https://www.youtube.com/watch?v=YnZLqtNXbAM) and [Erykah Badu](https://youtu.be/YY2-mrsXgMM). And maybe most crucially, it raised $10 million in financing from the powerhouse venture capital firm Andreessen Horowitz, cementing its position as one of today’s most powerful online crypto communities. Also, it’ll cost you anywhere between $5,000 and $10,000 to join.”_ * **[VeeFriends: ](https://veefriends.com/)** Gary V’s very own NFT community build around experimenting with and understanding business models and opportunities surrounding Non-Fungible Tokens. The evolution of token gated communities has been much discussed in crypto, especially when considering how they will most likely evolve over time. In line with Balaji’s thesis on Network States discussed in Module 5, it is highly likely that the most valuable and popular token gated communities are in position to grow beyond their discord server or telegram group into a physical location somewhere (or in many parts of the world), from which they would eventually morph into entire towns or cities. ## PFP communities: Tools of Speculation or the First Step in Unlocking Non-fungible Value? Profile Picture communities (PFP) refer to communities that have all purchased the same NFT (usually art, and the size of a profile picture). Ownership of the NFT is the access key into the community discord, office space, or special events. Importantly, PFP’s differ radically from social tokens insofar as they are far more representative and public facing and to date, far less focused on special perks or enhanced benefits from being inside of the community. This has led many to take divergent opinions on PFP communities. * _Are PFPs hyped speculation on value less assets?_ * _Is there any value in PFP communities?_ * _How do PFP Communities fit into the development of an ecosystem?_ * _Can an ecosystem succeed without PFP communities?_ Below are three interesting examples of different PFP gated communities and the value inherent to them: **Bored Ape Yacht Club (BAYC)** - The Bored Ape Yacht club was originally incubated by Yuga Labs on Ethereum. As a community designed for rich people to simply hangout it has attracted interest from the highest order of celebrities including: Stephen Curry, Pipa Malmgren, Jimmy Kimmel and Justin Beiber. Notably, BAYC has an all-time sales volume of close [to $2 billion dollars](https://beincrypto.com/bored-ape-yacht-club-2-billion-sales/). ![](@site/static/img/bootcamp/mod-em-4.3.3.png) **CryptoPunks** - ETH OG’s. CryptoPunks are the oldest NFT project on Ethereum, and have been used as a status signal from other crypto OG’s. With [more than $200 million in volume from sales](https://techcrunch.com/2021/04/08/the-cult-of-cryptopunks/?guccounter=1&guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&guce_referrer_sig=AQAAAEkzFXhp4OVpKbOCJzLwkDiqNy1DUjl35jRZAmLCna8itK95eyCMlWdae91szbOYrS7SDvmlyjtMbovtC6oWKDTXHf5vQ90NLvMGfe_I6nsZ1cJPTgy9GcxI2HCkiObX85RRir7ErvspJu40By8h-UF9sZSzMBWj9E7MGf4Xw5ux), CryptoPunks are established as a lasting and blue-chip sub-culture on Ethereum. ![](@site/static/img/bootcamp/mod-em-4.3.4.png) **Full-Send MetaCard Collection:** While not an official profile picture, the Nelk boys collection deserves special attention as one of the most successful value creation and community building transitions from Web2 into Web3. Founders of the Full Send Podcast launched the MetaCard collection as a way of providing fans with exclusive access to their platform and themselves - and to have a say in who gets interviewed on the podcast. According to [NFT Now](https://nftnow.com/podcasts/how-the-nelk-boys-made-nearly-25m-on-their-first-nft-drop/) this has been one of the most successful Web2 influencer transitions into Web3 to date: _“They explained that the purpose of the project was to launch a number of branded ventures in both the physical world and metaverse, with the ultimate aim of creating a multi-faceted Full Send brand. Some of the ventures they outlined for Full Send include lounges, gyms, festivals, casinos, and restaurants. The Discord server for the collection quickly gained a massive following, bringing in [121,000 members in just about 12 hours](https://www.dexerto.com/entertainment/nelk-boys-are-making-their-own-nft-and-its-already-doing-crazy-numbers-1743039/). The project went live on January 19, and the collection sold out in minutes. The Full Send NFT was available for mint for 0.75 ETH, which was roughly equivalent to $2300 at the time of launch. With 10,000 Full Send Metacards available, the project sold for close to $25 million in total value.”_ ## How Should We Think of Communities? ### Tools for Network development, Culture Creation, and Indirect Capital Flows Into An Ecosystem One of the most important and least understood facets of token-gated communities, is their indirect and often-times unquantifiable impacts on the growth of the ecosystems they launch within. Many crypto-natives, originally turned off by the loose and unclear value proposition of profile picture NFTs, have taken significant amounts of time to realize that PFP and other forms of token gated communities can bring the following to their mothership L1 ecosystem: **Identity:** Membership in a community provides a notion of being a part of an in-group, during a time when many are isolated and lacking in community. It is a way of ‘paying your way’ into a group of people who are interested in connecting with you. **Culture:** Collaboration across a community creates a specific culture that is not only present inside of the community but also outside of the community in the surrounding ecosystem. This refers to events hosted in person, projects created by core members, and high level visibility into the community from mainstream media. **Network:** A well designed community is a combination of an alumni network, a group of like minded friends, and a group of aligned and talented individuals looking to collaborate on a vision of the future. PFP communities and token-gated social tokens - with proper management - can offer exclusive and life-changing networking opportunities - especially in an emergent industry with lots of money floating around. **Signaling:** The belief that a certain community is ‘special’ or bringing together some of the best minds, signals to the larger industry and to other like-minded individuals that there is an incentive and opportunity to benefit from joining the community. This then creates a network effect that can often translate into _a migration_ into an ecosystem - from builders to socialites. In many ways this is a kin to the _brain drain_ discussed in geopolitics. **Capital Inflows:** Last but not least, a highly successful PFP or token gated community brings significant amounts of value into the ecosystem it was launched in. This may be because membership is a coveted social symbol, or it may be over-hyped FOMO leading to significant price appreciation. Yet as BAYC has demonstrated, it has been largely new and old money that contributed to its peak volume of 500mm traded for the collection since its inception. In this sense a successful collection can put an entire ecosystem on the map. ## PFPs as the first step in the evolution of NFTs VS. The Same Problem As Governance Tokens To conclude this lecture, I would like to leave everyone with an interesting dilemma. We have said in prior lectures on the nature of governance tokens the following: _The inherent problems with governance tokens, is that they seek to tokenize a value proposition, that usually does not exist on a protocol due to its early nature, and lack of product market fit, or revenue. In short, governance tokens put the cart before the horse, insofar as they seek to offer the value of governance up to the public, for a system that has not accrued any value and by extension has no value to be governed!_ The question can now be applied to PFP and token gated communities: _Does the value of a PFP or token gated community come from the creation of the community itself? Or should the community already exist in order for a PFP or token-gated community to be successful?_ Most likely, the answer resides somewhere in the middle. Whereby the prospect of a new community with speculation attached, has the attention to increase interest and value, yet an existent base of talented and involved people who are not only in it for the speculation can ground it and keep members entertained in order for the community to grow over time.
deadmau5 Launches NFT Partnership with Mintbase and NEAR COMMUNITY December 3, 2021 deadmau5, the DJ and Producer has teamed up with rockband Portugal. the Man, Mintbase, and NEAR to release a single as an NFT. The song, titled “this is fine” is being sold as a collection of one million NFTs exclusively on the Mintbase NFT marketplace, which runs on the carbon neutral NEAR blockchain, with tokens now on sale. By releasing the song as an NFT, deadmau5 and Portugal. the Man could be the first artists to reach platinum status — selling one million copies in the US — with an NFT single release. The announcement took place in Miami during the Art Basel art fair, an annual event which draws thousands of tastemakers from the art-world, entertainment, fashion and tech. Half of the NFTs (500,000) are being sold on Mintbase for 0.25 $NEAR per piece, which is $2.19 at the time of writing. The remaining half million will be sold as additional awards with groundbreaking benefits. The ‘Ultimate Bundle’ includes 50,000 NFTs, artwork, a limited edition NFT, a merchandise pack and a highly-prized spot on the guest-list for a forthcoming deadmau5 show. The lucky fan who collects a pack of 1,000 NFTs will receive a unique, alternate color single cover art for ‘this is fine’, that was created via a generative algorithm. “NFTs aren’t really that complicated. What we are doing here is giving our millions of fans and people interested in NFT’s an easy way to get on board for an extremely reasonable price. The song is cool too,” said deadmau5. The single release kicked off with one deadmau5-wrapped bus and two NEAR-wrapped buses circling Miami for a month, inviting art week visitors and locals alike to buy the track using the QR code on its side. The buses will then go ‘on tour’ in New York and San Francisco in December and January to reach music fans and the tech curious on both coasts. For most people, buying NFTs has been a complex experience, involving additional fees, delays and multiple wallets. With NEAR and Mintbase, users will be able to buy NFTs using fiat cash instantly, with super low fees, thanks to an integration with payment rail provider, Stripe. The announcement forms part of a wider series NEAR has launched to help people get to grips with Web3 technology around the world. NEAR is on a mission to make blockchain and crypto a simpler experience that anyone can take part in. From buying NFTs, creating a DAO or joining a Guild, at NEAR it’s a simple as clicking a mouse. Find out how.
:::info Remember about fungible token precision. You may need this value to show a response of balance requests in an understandable-to-user way in your app. How to get precision value (decimals) you may find [above](#get-token-metadata). ::: ```js const tokenContract = "token.v2.ref-finance.near"; const userTokenBalance = Near.view(tokenContract, "ft_balance_of", { account_id: "bob.near", }); ``` <details> <summary>Example response</summary> <p> ```json "3479615037675962643842" ``` </p> </details>
# AccessKeyCreationConfig Describes the cost of creating an access key. ## full_access_cost _type: Fee_ Base cost of creating a full access access-key. ## function_call_cost _type: Fee_ Base cost of creating an access-key restricted to specific functions. ## function_call_cost_per_byte _type: Fee_ Cost per byte of method_names of creating a restricted access-key.
--- sidebar_label: "Credentials" --- # Credentials :::info DevConsole Please, keep in mind, currently using the AWS Credentials is the only way to access the data provided by [NEAR Lake](/tools/realtime#near-lake-indexer) ecosystem. But it is about to change with Pagoda DevConsole release. Stay tuned! ::: To access the data provided by [NEAR Lake](/tools/realtime#near-lake-indexer) you need to provide valid AWS credentials in order to be charged by the AWS for the S3 usage. ### AWS S3 Credentials To be able to get objects from the AWS S3 bucket you need to provide the AWS credentials. AWS default profile configuration with aws configure looks similar to the following: ``` ~/.aws/credentials ``` ``` [default] aws_access_key_id=AKIAIOSFODNN7EXAMPLE aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ``` [AWS docs: Configuration and credential file settings](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) #### Environment varibales Alternatively, you can provide your AWS credentials via environment variables with constant names: ``` $ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE $ AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY $ AWS_DEFAULT_REGION=eu-central-1 ```
--- id: running-a-node title: Run a Node on Linux and MacOS sidebar_label: Run a Node (Linux and MacOS) sidebar_position: 3 description: How to run a NEAR node using nearup on Linux and MacOS, with or without using Docker --- *If this is the first time for you to setup a validator node, head to our [Validator Bootcamp 🚀](/validator/validator-bootcamp). We encourage you to set up your node with Neard instead of Nearup as Nearup is not used on Mainnet. Please head to [Run a node](/validator/compile-and-run-a-node) for instructions on how to setup a RPC node with Neard.* This doc is written for developers, sysadmins, DevOps, or curious people who want to know how to run a NEAR node using `nearup` on Linux and MacOS, with or without using Docker. ## `nearup` Installation {#nearup-installation} You can install `nearup` by following the instructions at https://github.com/near-guildnet/nearup. <blockquote class="info"> <strong>Heads up</strong><br /><br /> The README for `nearup` (linked above) may be **all you need to get a node up and running** in `testnet` and `localnet`. `nearup` is exclusively used to launch NEAR `testnet` and `localnet` nodes. `nearup` is not used to launch `mainnet` nodes. See [Deploy Node on Mainnet](deploy-on-mainnet.md) for running a node on `mainnet`. </blockquote> The steps in the rest of this document will require `nearup` ## Running a Node using Docker {#running-a-node-using-docker} ### Install Docker {#install-docker} By default we use Docker to run the client. Follow these instructions to install Docker on your machine: * [MacOS](https://docs.docker.com/docker-for-mac/install/) * [Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/) ### Running `nearup` with Docker {#running-nearup-with-docker} <blockquote class="warning"> Note: `nearup` and `neard` are running inside the container. You have to mount the ~/.near folder to ensure you don't lose your data which should live on the host. </blockquote> Once `nearup` and Docker are installed (by following instructions in previous section), run: ```sh docker run -v $HOME/.near:/root/.near -p 3030:3030 --name nearup nearup/nearprotocol run testnet ``` _(If you prefer to use `localnet` then just replace `testnet` with `localnet` in the command above)_ You might be asked for a validator ID; if you do not want to validate, simply press enter. For validation, please follow the [Validator Bootcamp](/validator/validator-bootcamp). ```text Enter your account ID (leave empty if not going to be a validator): ``` #### Running in detached mode {#running-in-detached-mode} To run `nearup` in docker's detached (non-blocking) mode, you can add `-d` to the `docker run` command, ``` docker run -v $HOME/.near:/root/.near -p 3030:3030 -d --name nearup nearup/nearprotocol run testnet ``` #### Execute `nearup` commands in container {#execute-nearup-commands-in-container} To execute other `nearup` commands like `logs`, `stop`, `run`, you can use `docker exec`, ``` docker exec nearup nearup logs docker exec nearup nearup stop docker exec nearup nearup run {testnet/localnet} ``` (The container is running in a busy wait loop, so the container won't die.) #### `nearup` logs {#nearup-logs} To get the `neard` logs run: ``` docker exec nearup nearup logs ``` or, ``` docker exec nearup nearup logs --follow ``` To get the `nearup` logs run: ``` docker logs -f nearup ``` ![text-alt](/images/docker-logs.png) | Legend | | | :------- | :--------------------------------------------------------- | | `# 7153` | BlockHeight | | `V/1` | `V` (validator) or `—` (regular node) / Total Validators | | `0/0/40` | connected peers / up to date peers / max peers | ## Compiling and Running a Node without Docker {#compiling-and-running-a-node-without-docker} Alternatively, you can build and run a node without Docker by compiling `neard` locally and pointing `nearup` to the compiled binaries. Steps in this section provide details of how to do this. If [Rust](https://www.rust-lang.org/) isn't already installed, please [follow these instructions](https://docs.near.org/docs/tutorials/contracts/intro-to-rust#3-step-rust-installation). For Mac OS, make sure you have developer tools installed and then use `brew` to install extra tools: ```text brew install cmake protobuf clang llvm ``` For Linux, install these dependencies: ```text sudo apt update sudo apt install -y git binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev cmake gcc g++ python docker.io protobuf-compiler libssl-dev pkg-config clang llvm ``` Then clone the repo: ```text git clone https://github.com/near/nearcore.git cd nearcore ``` Checkout the version you wish to build: ```bash git checkout <version> ``` You can then run: ```bash make neard ``` This will compile the `neard` binary for the version you have checked out, it will be available under `target/release/neard`. Note that compilation will need over 1 GB of memory per virtual core the machine has. If the build fails with processes being killed, you might want to try reducing number of parallel jobs, for example: `CARGO_BUILD_JOBS=8 make neard`. NB. Please ensure you build releases through `make` rather than `cargo build --release`. The latter skips some optimisations (most notably link-time optimisation) and thus produces a less efficient executable. If your machine is behind a firewall or NAT, make sure port 24567 is open and forwarded to the machine where the node is going to be running. Finally, execute: ```bash nearup run testnet --binary-path path/to/nearcore/target/release ``` If you want to run `localnet` instead of `testnet`, then replace `testnet` with `localnet` in the command above. (If you’re running `localnet` you don’t need to open port 24567). You might be asked for a validator ID; if you do not want to validate, simply press enter. For validation, please follow the [Validator Bootcamp](/validator/validator-bootcamp). ```text Enter your account ID (leave empty if not going to be a validator): ``` ## Running a Node on the Cloud {#running-a-node-on-the-cloud} Create a new instance following the [Hardware requirements](hardware.md). Add firewall rules to allow traffic to port 24567 from all IPs (0.0.0.0/0). SSH into the machine. Depending on your cloud provider this may require different commands. Often simple `ssh hosts-external-ip` should work. Cloud providers may offer custom command to help with connecting to the instances: GCP offers [`gcloud compute ssh`](https://cloud.google.com/sdk/gcloud/reference/compute/ssh), AWS offers [`aws emr ssh`](https://docs.aws.amazon.com/cli/latest/reference/emr/ssh.html) and Azure offers [`az ssh`](https://docs.microsoft.com/en-gb/cli/azure/ssh?view=azure-cli-latest). Once connected to the instance, follow [the steps listed above](#compiling-and-running-a-node-without-docker). ## Success Message {#success-message} Once you have followed the steps for running a node with Docker or of Compiling without Docker, you should see messages similar to as shown below: ```text Using local binary at path/to/nearcore/target/release Our genesis version is up to date Starting NEAR client... Node is running! To check logs call: `nearup logs` or `nearup logs --follow` ``` or ```text Using local binary at path/to/nearcore/target/release Our genesis version is up to date Stake for user 'stakingpool.youraccount.testnet' with 'ed25519:6ftve9gm5dKL7xnFNbKDNxZXkiYL2cheTQtcEmmLLaW' Starting NEAR client... Node is running! To check logs call: `nearup logs` or `nearup logs --follow` ``` ## Starting a node from backup {#starting-a-node-from-backup} Using data backups allows you to sync your node quickly by using public tar backup files. There are two types of backups for available for both `testnet` and `mainnet`: - regular - archival ### Archive links {#archive-links} Download the latest snapshots from [Node Data Snapshots](/intro/node-data-snapshots). Starting node using `neard` backup data ```bash ./neard init --chain-id <chain-id> --download-genesis mkdir ~/.near/data wget -c <link-above> -O - | tar -xC ~/.near/data ./neard run ``` Starting node using `nearup` backup data: ```bash nearup run <chain-id> && sleep 30 && nearup stop dir=$HOME/.near/<chain-id>/data rm -r -- "$dir" # clean up old DB files to avoid corruption mkdir -- "$dir" wget -c <link-above> -O - | tar -xC "$dir" nearup run <chain-id> ``` In both examples, `<chain-id>` corresponds to `testnet` or `mainnet`. **Note:** Default location for `neard` data is `~/.near/data`. `nearup` stores data by default in `~/.near/<chain-id>/data.` >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 className="file-tabs"> <TabItem value="Keypom API" label="Keypom API"> ```js const dropsNumber = "2"; const keysGeneratorUrl = "https://keypom.sctuts.com/keypair/"; const rootEntrophy = "my-password"; //If not provided, the keypair will be completely random. see: https://docs.keypom.xyz/docs/next/keypom-sdk/Core/modules asyncFetch(keysGeneratorUrl + dropsNumber + "/" + rootEntrophy).then((res) => { const keyPairs = JSON.parse(res.body); const pubKeys = []; const privKeys = []; keyPairs.forEach((e) => { pubKeys.push(e.pub); privKeys.push(e.priv); }); const obj = { publicKeys: pubKeys, privKeys: privKeys, }; State.update(obj); }); ``` </TabItem> </Tabs>
NEAR and Grupo Nutresa Partner for Customer Experience Innovations in Web3 UNCATEGORIZED December 1, 2022 In a groundbreaking and innovative move, NEAR has partnered with Grupo Nutresa, one of the most important processors of food in South America, to bring Web3 to the grocery industry. This will see Grupo Nutresa building one of the first open-source loyalty points programs on NEAR with long-term aspirations to reach a million users in Colombia and Latin America. The partnership was established through the support of tech firm Peersyst. Grupo Nutresa customers will in turn gain more autonomy and control of their rewards. Customers will also get additional security and the reassurance that points will not be stolen or denied, and can be transferred more efficiently. Leveraging NEAR’s technology will also increase usability and accessibility of the rewards system as a whole, saving customers from having to create multiple accounts or different logins for multiple platforms — they just need their easy to use NEAR wallet. “We are excited to partner with one of the biggest multinationals in Latin America and help it to lead the way through its first Web3 loyalty programme,” says NEAR Foundation CEO Marieke Flament. “Leveraging NEAR’s first-rate technology, the partnership will redefine what is possible when combining retail with the latest blockchain innovation, not just in Latin America but throughout the rest of the world.” Usability is key to loyalty Rewarding customers for their support has always been a priority for the world’s top brands. Such programs not only engage customers and deliver incentives for them to return but also act as analytical tools, giving businesses insights into customers’ behaviour and preferences. With 87% of shoppers reporting they want brands to have loyalty programs and over 70% of consumers more likely to recommend a brand with a robust loyalty program, Web3 and digital wallets are pushing forward-thinking brands to explore new opportunities on platforms that are easy to use. As one of the biggest multinationals in Colombia, Grupo Nutresa manages several loyalty programs for its customers, collaborators, and providers. Those loyalty programs are now coming together into a single easy-to-use platform underpinned by blockchain technology, through support from Spanish technology company Peersyst Technology. Onboarding the masses into NEAR and Web3 Grupo Nutresa sees NEAR as the ideal partner for these types of loyalty programs. NEAR Foundation sees the Grupo Nutresa partnership as a great opportunity to onboard the masses into the NEAR and Web3 ecosystems. “Our purpose is to make people feel recognized and valued by brands. Above all, what interests us most is that this is an opportunity to help build their dreams, through a service that provides them with significant redemption options and value,” says Fabián Andrés Restrepo, Digital Transformation Leader at Grupo Nutresa. “This invitation is also addressed to companies that want to help make people’s dreams come true and reward their loyal customers, by becoming an ally of Grupo Nutresa and its portfolio of businesses. We see in NEAR an important ally for developing and implementing Grupo Nutresa’s loyalty strategy.” NEAR’s sustainability credentials also align with Grupo Nutresa’s own business strategy and deep commitment to create value for society as a whole. According to the 2021 Dow Jones Sustainability Indices, Grupo Nutresa has been voted as the most sustainable food company in the world for two consecutive years, thanks to its effective implementation of social, environmental, and economic practices.
NEAR Wallet Update: Staking and Withdrawing Tokens COMMUNITY October 12, 2020 On the journey to make blockchain-based apps accessible to everyday people, the NEAR Wallet plays a vital role for usability in the community. Usability for developers has been our priority in architecting the platform from day one, but as the MainNet gets closer to completing its final launch phase, it is important to consider usability of the tooling and user interfaces needed to support a thriving ecosystem of exchanges, applications, and integrations for NEAR users. The NEAR Wallet will make using applications and managing tokens easier than ever before. Our previous release for the NEAR Wallet this summer announced NEAR Drops, a much simpler way to onboard new users to NEAR by making it possible to send links with $NEAR attached to them so app developers can seamlessly create accounts without their users having to worry about having a $NEAR token balance. Today, we’re excited to announce a new release from the Wallet Team which makes it easier for the community to stake with NEAR Validators using a new User Interface in the NEAR Wallet. If you have a NEAR Wallet (only locked tokens supported for now), try it out! A New User Interface for Staking Key to the Proof-of-Stake model is how Validators are supported by the community via Staking. Validators earn NEAR token rewards for operating the nodes which run the network in the form of a static inflation rate of 5% each year, creating new tokens for Validators every epoch (~12 hours) as rewards. Validators must maintain a minimum amount of Stake to keep their Validator seat. Token holders are able to stake with a particular Validator they believe is performing well for the network and earn a portion of Token rewards generated by the network too. This incentivizes Token holders to stay involved with the community! With this release, the NEAR Wallet now has a staking user interface built directly into the web app. To Stake: Select “Staking” from the navigation bar (or dropdown on mobile) Click the “Select Validator” button Choose a validator Confirm your choice and select “Stake with Validator” Enter the amount of NEAR you would like to stake, and click “Submit Stake” You will need to confirm two transactions, one to select the validator, and another to deposit and stake with the validator. To Unstake: On the staking dashboard (/staking), select your current validator Click “Unstake” and confirm the transaction After 36 to 48 hours (3 full epochs), you will be able to withdraw your stake. To do so, return to the validator page, and click “Withdraw”. Monitoring Key Staking Information Not only does this interface allows you to choose Validators to stake with and see key information you need to make a staking decision like: Total Amount Staked: NEAR tokens your account has currently staked with Validators. These tokens are accumulating rewards. To access these tokens once again, you must first unstake and then withdraw them from the staking pool. Unclaimed Rewards: Token rewards that have been earned, but not withdrawn from the staking pool. Unclaimed rewards are automatically restaked, which means your “Total Amount Staked” automatically increases over time, and your rewards are compounding. Tokens Available for Withdrawal: These tokens have been unstaked and are ready to be withdrawn. Tokens Pending Release: These tokens have been unstaked, but are not yet ready to withdraw. Tokens are ready to withdraw 36 to 48 hours after unstaking. Validator Fee: This is the fee paid to the validator to stake on your behalf. This fee is only charged on your rewards earned not your total token balance staked to the Validator. Each Validator can set their own fees, so take this into consideration when deciding who to stake to. Staking features in the NEAR Wallet are new and should still be considered beta. If you have any concerns or questions about staking, check out the docs, or pose the question to the community in our Discord chat. Join the Community Join us on the journey to make blockchain accessible to everyday people who are excited for the future of the Open Web 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.
--- slug: / sidebar_position: 1 --- # BWE Alpha Test ## Welcome 🎉 Thank you for participating in the alpha test for BOS Web Engine **(actual release name TBD)**; an improved execution layer for NEAR's decentralized front-end components. Significant effort has been dedicated to this project, reaching a stage where most of the essential features are established, laying the groundwork for the development of more sophisticated and refined applications. BWE is on the verge of achieving complete parity with the former VM, while also providing substantial additional functionalities. That being said, this is an **alpha** so rough edges and bugs should be expected. We appreciate your help in identifying these issues so we can quickly move towards a stable release. 🙏 :::danger Warning Please use **non-vital NEAR accounts** during the alpha test since we have not yet initiated our security audit program. Avoid using accounts with significant balances, elevated permissions, or sentimental addresses. ::: --- ## Timeline BWE alpha test begins on Feb 26, 2024 and runs for several weeks as we perform rigorous testing both internally and with community members such as yourself. 🙏 --- ## How to get involved - [Test](#test) - [Ask Questions & Get Support](#support) - [Give Feedback](#give-feedback) --- ### Test Using the [BWE Sandbox IDE](https://bwe-sandbox.near.dev), try any of the following: - Write components that aren't possible to build using the current VM - Write components that test the limits of BWE - Migrate your existing components from the VM to BWE - Migrate vanilla React components to BWE - Test npm package imports :::tip npm Package Support A wide variety of npm packages should work out of the box with BWE, especially non-UI packages. See the [npm section of our imports documentation](/alpha/building-decentralized-frontends/imports#npm) for full details. **Note:** You can attempt to import any npm package, but not all will work due to the sand boxed environment. We are using this testing period to determine which packages will work and cataloging them in docs. ::: :::warning Not Supported Yet - `useRef` (refs not exposed to outer application) - `useContext` - `<canvas>` and other Web APIs - development with local code editor and bos-loader ::: :::info Not Planned to be Supported - Direct DOM manipulation - Interoperability between BWE and the previous VM ::: We'd love to see what you build and hear about your experience! Please share what you build with us and the community! 🙏 --- ### Support The BWE team will be available in Telegram and GitHub Discussions to answer any questions you might have and assist in troubleshooting. - [Telegram Group](https://t.me/+IlVl5uEsGH83YTEx) - [GitHub Discussions](https://github.com/near/bos-web-engine/discussions) --- ### Give Feedback There are three main avenues for giving feedback. Please choose whichever is most convenient for you: - [BWE Feedback Form](https://forms.gle/5w16G5wix4ezWx4y5) - Easy google feedback form - [GitHub Discussions](https://github.com/near/bos-web-engine/discussions/new?category=alpha-test-feedback) - Alpha feedback section of BWE's GH Discussions - [GitHub Issues](https://github.com/near/bos-web-engine/issues/new) - Found a bug, performance issue, or have a feature request? [File it here.](https://github.com/near/bos-web-engine/issues) The more info the better, but don't let that be a blocker from filing one! If you only have time to file something quick, please do so and we can follow up for more details later 🙂 :::tip We are looking for feedback in the following areas: - Performance - Syntax - Documentation - Level of effort to migrate components to BWE - Missing capabilities - Overall developer experience (DevX) :::
--- sidebar_position: 2 title: Callbacks --- # Callbacks NEAR Protocol is a sharded, proof-of-stake blockchain that behaves differently than proof-of-work blockchains. When interacting with a native Rust (compiled to Wasm) smart contract, cross-contract calls are asynchronous. Callbacks are used to either get the result of a cross-contract call or tell if a cross-contract call has succeeded or failed. ## Calculator Example A callback method can be declared in your contract class as a regular method decorated with the `call({})` decorator. Be sure to pass in the `privateFunction: true` option to the decorator. This will ensure that the method is only callable by the contract itself. For example, let's assume the calculator is deployed on `calc.near`, we can use the following: ```js @NearBindgen({}) export class CalculatorCallerContract { @call({}) sum_a_b({ a, b }) { let calculatorAccountId = "calc.near"; // Call the method `sum` on the calculator contract. // Any unused GAS will be attached since the default GAS weight is 1. // Attached deposit is defaulted to 0. return NearPromise .new(calculatorAccountId) .functionCall("sum", { a, b }, BigInt(0), BigInt(100000000000000)); } @call({ privateFunction: true }) sum({ a, b }) { return a + b; } } ``` ## Allowlist Example Next we'll look at a simple cross-contract call that is made to an allowlist smart contract, returning whether an account is in the list or not. The common pattern with cross-contract calls is to call a method on an external smart contract, use `.then` syntax to specify a callback, and then retrieve the result or status of the promise. The callback will typically live inside the same, calling smart contract. There's a special decorator parameter used for protecting the callback function, which is [`privateFunction: true`](https://docs.rs/near-sdk-core/latest/near_sdk_core/struct.AttrSigInfo.html#structfield.is_private). We'll see this pattern in the example below. The following example demonstrates two common approaches to callbacks using the high-level cross-contract approach with `NearPromise`. ```js @NearBindgen({}) export class ExtAllowlist { // ... @call({}) is_allowlisted({ staking_pool_account_id }) { return this.allowlist.get(staking_pool_account_id) != null; }; } ``` After creating the class, we'll show a simple flow that will make a cross-contract call to the allowlist smart contract, asking if the account `idea404.testnet` is allowlisted. ```js @NearBindgen({}) export class Contract { @call({}) xcc_query_allowlist() { // Call the method `is_allowlisted` on the allowlisted contract. Static GAS is only attached to the callback. // Any unused GAS will be split between the function call and the callback since both have a default unused GAS weight of 1 // Attached deposit is defaulted to 0 for both the function call and the callback. return NearPromise .new("allowlist.near") .functionCall("is_allowlisted", { staking_pool_account_id: "idea404.testnet" }, BigInt(0), BigInt(100000000000000)) .then("internalCallbackMethod", {}, BigInt(0), BigInt(100000000000000)); } @call({ privateFunction: true }) internalCallbackMethod() { assert(near.promiseResultsCount() === BigInt(1), "Error: expected 1 promise result"); let result = JSON.parse(near.promiseResult(0)); return result; } ``` The syntax begins with `NearPromise.new(<someAccountId>)` which initializes the async call to the designated `<someAccountId>`. Subsequent calls to this program in this account are invoked using `.functionCall()`. The `.functionCall()` method takes in the following parameters: - `functionName`: the name of the method to call on the contract - `args`: the arguments to pass to the method - `amount`: the amount of Ⓝ to attach to the call - `gas`: the amount of GAS units to attach to the call There are a couple things to note when doing these function calls: 1. You can attach a deposit of Ⓝ, in yoctoⓃ to the call by specifying the `amount` parameter. This value is defaulted to 0 (1 Ⓝ = 1000000000000000000000000 yoctoⓃ, or 1^24 yoctoⓃ). 2. You can attach an amount of GAS units by specifying the `gas` method. This value is defaulted to 0.
--- id: introduction title: Chain Abstraction sidebar_label: Introduction --- Do you know how your favorite apps are built and which database they use?. Chances are not, since we choose apps based on their functionality, and not their underlying tech. We believe that **same should be true for blockchain apps**, users should be able to enjoy an application, without the underlying tech hampering their experience. The user experience should be so good, that they don't realize they're using a blockchain. ![img](/docs/assets/welcome-pages/chain-abstraction-landing.png) To help make this a reality, NEAR provides a set of services that allow to **abstract away** the blockchain from the user experience. This means that users can use blockchain-based application - both in NEAR and **other chains** - without needing to understand the technical details. --- ## Abstraction services Through a combination of multiple technologies, NEAR allows to create a seamless flow, in which users can use their email to create an account, use such account without acquiring funds, and even control accounts across multiple chains. This is achieved through a combination of multiple services: - **Relayers**: A service that allows developers to subsidize gas fees for their users. - **FastAuth**: A service that allows users to create and recover accounts using their email address through multi-party computation (MPC). - **Multi-chain signatures**: A service that allows users to use their NEAR account to sign transactions in other chains. --- ## A holistic view The combination of these services allows to create a **seamless** user experience, in which users can use blockchain-based applications without realizing they are using a blockchain. Users will simply login with an email, and a **zero-fund** account will be created for them. No seed phrases to remember, no private keys to safe keep, and no need to acquire funds. Once having their account, apps can ask the user to create meta-transactions and send them to any relayer. The relayer will pass the transaction to the network, attaching NEAR to pay for the execution fees. The transaction will then be executed as if the user had sent it, since the relayer is only there to attach NEAR to the submission. If the user wants to interact with other blockchain, they can use their account to interact with a multi-chain signature relayer, which will relay the transaction to the right network, covering GAS fees. As an example, this would allow users to collect NFTs across different chains, without ever needing to explicitly create an account or acquire crypto. All with just a single email login.
--- sidebar_position: 1 sidebar_label: "Setup" --- # Setup Alerts & Triggers :::warning Please be advised that these tools and services will be discontinued soon. ::: ## Setting up E-mail alerts 1. Navigate to [console.pagoda.co](https://console.pagoda.co) and log-in 2. Navigate to the <kbd>Alerts</kbd> tab <img width="20%" src="/docs/pagoda/setup1.png" /> 3. Select a target address for the alert to listen to <img width="60%" src="/docs/pagoda/setup2.png" /> 4. Select one of the following conditions to listen for <img width="60%" src="/docs/pagoda/setup3.png" /> 5. Select email as the destination to send alerts to and enter an email address to send the alert to <img width="60%" src="/docs/pagoda/setup4.png" /> 6. This email address will need to be verified before it can be used as a valid alert destination. <img width="60%" src="/docs/pagoda/setup5.png" /> 7. Be sure that the email destination is toggled on as shown below and click "Create Alert" to finish setting up your email alert <img width="60%" src="/docs/pagoda/setup6.png" /> ## Setting up Telegram alerts Follow the steps above to begin setting-up telegram alerts. When selecting the destination select Telegram and follow these steps to authorize Alerts <img width="60%" src="/docs/pagoda/setup7.png" /> ### Private Message Alerts 1. On the device that is logged into the telegram aclick "Open Telegram" or scan the QR code. <img width="60%" src="/docs/pagoda/setup8.png" /> 2. by Telegram. Hit "Send Message" to continue <img width="40%" src="/docs/pagoda/setup9.png" /> 3. Once inside the chat, hit "Start" to begin receiving alerts at this destination <img width="60%" src="/docs/pagoda/setup10.png" /> ### Group message alerts For group chats, add `PagodaDevConsoleBot` and copy the message you see in your on-screen modal and send it in the chat that includes`PagodaDevConsoleBot` to authorize the group chat destination <img width="70%" src="/docs/pagoda/setup11.png" /> ## Setting up Event Log Alerts You can listen to on-chain events occurring to contracts that follow NEPs standards like NEP-171 (NFTs), NEP-141 (fungible tokens), or NEP-145 (storage management). All NEAR NEPs can be found on the [Nomicon NEAR site](https://nomicon.io/Standards/). To set-up an alert for an event, for example `nft_transfer` from [NEP-171 version 1.1.0](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core): 1. Follow the steps above to begin setting up an alert. 2. Select the "Event Logged" condition, 3. Type the event name `nft_transfer`, 4. The standard `nep171`, and 5. Add the version `1.1.0` as seen below <img width="80%" src="/docs/pagoda/setup12.png" /> > Note that input fields are case sensitive, and the standards field must be written in the format `nep123` not `NEP-123` ## Setting up Function Call Specific Alerts More generally, Pagoda Console makes it easy to generate alerts based on specific function calls. Simply follow the steps above, select the "Function Called" condition, and type the method name **exactly** as it appears in the contract code or the contract's [ABI](https://github.com/near/abi) <img width="80%" src="/docs/pagoda/setup13.png" />
Project Spotlight: TessaB- Blockchain for the Mobile Phone Industry CASE STUDIES March 3, 2021 Hi NEARverse, we’d like to introduce you to the TessaB project solving a real world problem within the secondhand mobile phone industry with blockchain via the Glyde Marketplace. Below is a Q&A with TessaB’s CEO, Flavio Mansi. TessaB CEO Flavio Mansi Background Tell us a few things about your company. What inspired you to start it? PCS Wireless founded TessaB in 2018 to enable a new, innovative ecosystem for pre-owned mobile devices and related services backed by a blockchain technology platform. I was part of the PCS Wireless team and previously served as President of its subsidiary IGWT Block. Today, as CEO of TessaB Corp. my goal is to leverage the TessaB blockchain platform we have built, as well as PCS Wireless’s proven track record in the secondary wireless market, to develop a more transparent and secure ecosystem for new and pre-owned phones and related services starting with our newly launched platform: The Glyde Marketplace (Glyde). Who is on your team? We have a robust and multi-faceted team. Please check them out on our website: https://www.tessab.com/the-team/ Have you received outside funding from notable investors or advisors? Up until this point we have self-funded this project but expect to attract external capital in the next quarter or two, once the business units we are building on top of our TessaB blockchain platform continue gaining traction. The Blockchain Factor Why did you decide to build your project with blockchain technology? TessaB is using a blockchain technology stack to solve the issues of trust and transparency. Blockchain provides a more transparent, and secure ecosystem for new and pre-owned phones and related services. The biggest barrier to purchasing a used phone is lack of confidence in the condition of the phone the buyer will receive. That is why we have selected blockchain and other innovative technologies to create a more efficient and trustworthy marketplace for used phones. Enter NEAR Why did you choose to build on NEAR? We teamed up with NEAR Protocol for layer one of the blockchain to provide the foundation for a fairer marketplace for both individual consumers and businesses, one in which transactions are more transparent and, as a result, prices more accurately reflect the quality and value of the device. With Glyde, business rules programmed into smart contracts to guide dispute mediation when the condition of a phone a buyer receives does not match the condition the seller posted to a phone listing, minimizing the need for subjective decision-making. How did NEAR help you solve some of your key challenges? The two biggest challenges with any main chain protocols for blockchain eg. Bitcoin, Ethereum right now is scalability and cost to record transactions. NEAR protocol helps a lot in both of those problems via the sharding concept. NEAR is 100 times faster than Ethereum and more than 1000 times cheaper. There were a few more factors we were looking for such as: Popularity: Number of dApps on the platform and developers in their community Contract Complexity: How robust is their development infrastructure? WASM compatibility: Web-Assembly was another important factor for reuse and compatibility with other languages in future development. The wallet is mobile & web compatible, custodial & non-custodial options. Since we had plans for our own Token for our ecosystem, the protocol needed to be compatible with various wallet solutions. Cost of creating a user account: Since we had to create an account for every user, the cost of creating an account was also very important. NEAR was at the top of our selection matrix. On the Personal Side What is your motto / favorite quote? “Parco en la adulación y abundante en la crítica” which roughly translates to “limited on adulation and extensive on criticism”. What is your current state of mind? We are delighted with the official launch of The Glyde Marketplace this past November with a mission of solving issues within the used mobile phone market. Right now, there is an average of seven middlemen between a customer who trades in a phone and its next owner. Our goal is to eliminate these inefficiencies and also instill trust between buyers and sellers. Looking to the Future What are your plans for the future? What’s the next big milestone you want to achieve? Our goal is for Glyde to usher in the future of buying and selling used phones. We do this by harnessing new technologies to provide buyers and sellers a higher level of transparency and security, thereby allowing consumers to cut out the many industry middlemen who needlessly drive up prices. TessaB is disrupting a massive industry. The global market for used phones is huge, forecast to be worth $67 billion by 2023 according to William Stofega, Program Director, Mobile Device Technology and Trends at IDC and we hope to be a part of that market as the industry for second hand phones grows. What is it that excites you the most about blockchain and the Open Web? I’m most excited about Blockchain’s ability to revolutionize industries, societies, and create new communities. Blockchain enables programmable digital agreements (eliminating the need for human intermediaries), provides verifiable data, and facilitates a new level of trust and transparency to various industry markets. With our new Glyde marketplace, we’re combining the power of Blockchain with mobile diagnostics, machine learning, and artificial intelligence to revolutionize an industry plagued by lack of transparency and ambiguity. The fusion of these emerging technologies will cultivate a fully transparent, trustworthy peer-to-peer marketplace. Our diagnostics benefit consumers tremendously as we are harnessing the power of smart contracts to ensure transactions include verifiable data for both parties. This act of good faith via the blockchain, will create a historical record of each device any time diagnostics are run. This will allow for us to assess and predict the value and lifespan of devices more accurately, providing cost-efficiency and more transparency around what devices should really be bought and sold. Overall, our goal is to provide more value for a phone you are selling and more insights for a second-hand phone you may be looking to purchase. TessaB and NEAR Keep up to date with TessaB and The Glyde Marketplace on our socials via LinkedIn and don’t forget our Twitter. NEAR invites you to join us on the journey to make blockchain accessible to everyday people who are excited for the future of the Open Web. If you’re a developer, be sure to sign up for our developer program and join the conversation in our Discord chat. You can also keep up to date on future releases, announcements, and event invitations by subscribing to our newsletter or following us on our Twitter for the latest news on NEAR.
--- id: how-it-works title: How QueryAPI works sidebar_label: How it works --- QueryApi is a streaming indexer implementation that executes custom indexing logic written by developers on the NEAR blockchain. QueryApi allows hosted execution of complex queries (ones that can’t be answered by a [simple RPC](../../../5.api/rpc/introduction.md) or [Enhanced API](https://docs.pagoda.co/api) call), data hosting, and its exposure via GraphQL endpoints. ## Components involved The QueryApi implementation integrates many different components in a single and streamlined solution. In a high-level overview, the main components are: :::info Components `NEAR Protocol` -> `NEAR Lake` -> `Coordinator` -> `Runner` -> `Database` -> `API` ::: ### Detailed overview An in-depth, detailed overview of the QueryApi components: [![QueryAPI](/docs/qapi-components.png)](/docs/qapi-components.png) ### Description - **Protocol:** the underlying NEAR Layer-1 Blockchain, where data `Blocks` and `Chunks` are produced. - **NEAR Lake:** an indexer which watches the Layer-1 network and stores all the events as JSON files on AWS S3. Changes are indexed as new `Blocks` arrive. - **Coordinator:** the QueryApi coordinator indexer filters matching data `Blocks`, runs historical processing threads, and queues developer's JS code to be indexed with these matched blocks. - **Runner:** executes the user's indexer code, which outputs the data to the database. - **Database:** a Postgres database where the developer's indexer data is stored, using a logical DB per user, and a logical schema per indexer function. - **API:** a Hasura server running on Google Cloud Platform exposes a GraphQL endpoint so users can access their data from anywhere. ## Historical backfill When an indexer is created, two processes are triggered: - real-time - starts from the block the indexer was registered (`block_X`), and will execute the indexer function on every matching block from there on. - historical - starts from the configured `start_from_block` height, and will execute the indexer function for all matching blocks up until `block_X`. The historical backfill process can be broken down in to two parts: _indexed_, and _unindexed_ blocks. **Indexed** blocks come from the `near-delta-lake` bucket in S3. This bucket is populated via a DataBricks job which streams blocks from NEAR Lake, and for every account, stores the block heights that contain transactions made against them. This processed data allows QueryAPI to quickly fetch a list of block heights that match the contract ID defined on the Indexer, rather than filtering through all blocks. NEAR Delta Lake is not updated in real time, so for the historical process to close the gap between it and the starting point of the real-time process, it must also manually process the remaining blocks. This is the **unindexed** portion of the backfill. ## Provisioning In summary, QueryAPI provisioning consists of the following steps: 1. Create `database` in [Postgres](#postgres), named after account, if necessary 2. Add `database` to Hasura 3. Create `schema` in `database` 4. Run DDL in `schema` 5. Track all tables in `schema` in [Hasura](#hasura) 6. Track all foreign key relationships in `schema` in [Hasura](#hasura) 7. Add all permissions to all tables in `schema` for account :::note This is the workflow for the initial provisioning. Nothing happens for the remaining provisions, as QueryAPI checks if it has been provisioned, and then skips these steps. ::: :::info To check if an Indexer has been provisioned, QueryAPI checks if both the `database` and `schema` exist. This check is what prevents the app from attempting to provision an already provisioned indexer. ::: ### Low level details There are two main pieces to provisioning: [Postgres](#postgres) and [Hasura](#hasura). #### Postgres The dynamic piece in this process is the user-provided `schema.sql` file, which uses Data Definition Language (DDL) to describe the structure of the user's database. The `schema` DDL will be executed within a new Postgres Schema named after the account + function name. For example, if you have an `account.near` and `my_function`, the schema's name will be `account_near_my_function`. Each schema exists within a separate virtual database for that account, named after the account, i.e. `account_near`. #### Hasura After creating the new schema, Hasura is configured to expose this schema via a GraphQL endpoint. First, the database is added as a data source to Hasura. By default, all tables are hidden, so to expose them they must be "tracked". Foreign keys in Postgres allow for nested queries via GraphQL, for example a `customer` table may have a foreign relationship to an `orders` table, this enables the user to query the orders from a customer within a single query. These are not enabled by default, so they must be "tracked" too. Finally, necessary permissions are added to the tables. These permissions control which GraphQL operations will be exposed. For example, the `SELECT` permission allows all queries, and `DELETE` will expose all delete mutations. A role, named after the account, is used to group these permissions. Specifying the role in the GraphQL request applies these permissions to that request, preventing access to other users data. ## Who hosts QueryAPI [Pagoda Inc.](https://pagoda.co) runs and manages all the infrastructure of QueryAPI, including NEAR Lake nodes to store the data in JSON format on AWS S3. - NEAR Lake indexing is hosted on AWS S3 buckets. - Coordinator and Runners are hosted on GCP. - Hasura GraphQL API server is hosted on GCP. :::caution Pricing QueryAPI is currently free. Pagoda doesn't charge for storage of your indexer code and data as well as running the indexer, but usage pricing will be introduced once QueryApi is out of beta. :::
NEAR, MetaBUILD 2, and Brave Head to ETHDenver COMMUNITY February 15, 2022 NEAR will be at ETHDenver, as will our MetaBUILD 2 Hackathon, and the Brave browser. The mission: support the global community of developers in building a multi-bridge, multi-chain world! The NEAR community, in partnership with Brave, will give attendees at ETHDenver, the world’s largest and longest-running Ethereum event, the chance to take part in MetaBUILD to reimagine gaming on the world’s biggest crypto browser. Brave currently has over 54 million monthly active users and recently launched the Brave Wallet, a browser-native crypto wallet. The team is challenging ETHDenver and MetaBUILD hackers to formulate new ways of issuing game skins for the simple, yet addictive, Dino game, available on the Brave browser. Hackers have the choice to either use one of NEAR’s ecosystem’s NFT platforms or develop their own smart contract to complete the task. For this MetaBUILD 2 challenge, Brave is putting up a bounty of $20,000 $BAT. This $BAT Match is just one of many fun and creative MetaBUILD 2 challenges driving applicant demand. Both MetaBUILD and ETHDenver empower the global developer community to build leading decentralized Web3 technologies, so we encourage hackers to submit their projects to both hackathons. When MetaBUILD 2 launched on December 22, 2021, there were 300 participants. To inspire and reward MetaBUILD 2 hackers, we announced $1,000,000 in prize money across 35 sponsor challenges to be awarded to winning projects and development teams—from building decentralized storage and game development to NFT marketplaces and more! As of today, there are over 3,500 applications—all taking advantage of NEAR’s easy-to-build infrastructure, and bringing their own unique ideas and skills to the task of building with NEAR and the cross-chain Open Web and Metaverse. To satisfy hackathon applicant demand, we’re extending MetaBUILD 2 until February 21st, which coincides with the last day of ETHDenver. That means you’ve got more time to submit your ideas for NEAR, the Open Web, or the Metaverse. More MetaBUILD Hacking at ETHDenver Means More Cross-Chain Collabs For the Open Web to be fully realized, cross-chain collaborations are absolutely vital. With blockchain platforms working as allies, the future is bright and anything is possible. Most crucially, users and developers will be able to move assets, projects, and experiences without friction back and forth across blockchain platforms. By collaborating, tools and products like atomic swaps will preserve privacy across blockchains, instead of exposing identities in transit. More upsides to collaboration between NEAR, Ethereum, and other blockchains include efficiency gains in areas like transaction speeds, security, and sustainability. In other words, cross-chain collaboration will help expand and supercharge decentralized app ecosystems, changing the Internet as we know it—for the better. Reimagine Gaming, DeFi, and NFTs for Cross-Chain Future NEAR is designed to be simple to use, no matter what ecosystem you’re coming from. This simplicity also makes it an ideal platform for cross-chain collaboration projects. For MetaBUILD, participants can use Rust, Web Assembly, or other familiar programming languages to build DeFi, Web3, Gaming, Digital Art/Collectibles, as well as infrastructure apps and tools. You can even migrate an existing Ethereum Virtual Machine (EVM) app to the NEAR ecosystem. Gaming will be a big focus for the NEAR ecosystem in 2022. After the successful rollout of sharding last year—and an aggressive roadmap designed to increase speed, scalability, and security this year—the gaming ecosystem has flourished. With some 30 gaming titles either launched or due to launch in the coming months, it’s never been a better time to jump into the space. And what better way of taking part in NEAR’s gaming ecosystem than by entering NEAR and Brave’s $BAT Match? Or maybe you want to build an NFT marketplace? Aurora, an Ethereum scaling solution on NEAR, is challenging MetaBUILD 2 participants to hack together an NFT marketplace on its platform. Aurora has experienced massive growth since launching in May 2021, which makes this one of the most popular MetaBUILD challenges. Migrate your ETH project onto NEAR using Aurora and the Rainbow Bridge. NFT marketplaces Paras and Mintbase are also offering NFT challenges. And lastly, but not leastly, there are opportunities for hackers to build solutions for blockchain oracles, governance, or even for The Graph’s explorer. Check out the full list of MetaBUILD 2 sponsor challenges and get hacking for a cross-chain future! You can visit NEAR and Brave at ETHDenver during the main conference at the Sports Castle (Shill Zone, Floor 2, Booth P5). Also, don’t miss talks by Sampson, Senior Developer Relations Specialist at Brave, and Luke Mulks, VP of Business Operations at Brave, at the NEAR Lounge, located on the 3rd floor of the Jonas Bros Building on February 15-17th during BUILD week. Talks will also be livestreamed.
NEAR at NVIDIA GTC 2024: A Recap of Illia’s Appearance COMMUNITY March 25, 2024 At NVIDIA GTC 2024––the flagship conference of the AI hardware supercompany in San Jose, California––the spotlight was on the intersection of AI, blockchain, and the next era of open web innovation. Among the distinguished speakers was Illia Polosukhin, co-founder of NEAR Protocol, who contributed his insights into how AI models will evolve and how blockchain and token economies can play key roles. Polosukhin is the only blockchain industry founder to speak at the NVIDIA event. The “Transforming AI” panel was hosted by Jensen Huang, CEO and co-founder of NVIDIA. Appearing on the panel were all but one of the co-authors of the landmark 2017 research paper “Attention is All You Need,” which introduced the Transformer architecture that revolutionized natural language processing. That lineup of coauthors has gone on to work on projects such as OpenAI, Inceptive, and Essential AI. The group’s conversation explored the practical applications of blockchain technology, with Illia touching on programmable money and its impact on both the current and future states of digital economies. By addressing the challenges and opportunities presented by the convergence of AI and blockchain, Illia offered a grounded perspective on the potential for these technologies to facilitate a more decentralized and efficient open web. Illia’s insights also highlighted NEAR’s commitment to leveraging Web3 technologies for broader adoption and innovation across a range of future tech use cases. Jensen himself noted that he thinks “NEAR is very cool.” From Accelerated Computing to AI and the Blockchain Jensen kicked off the panel by providing context around the evolution of computing power and the potential of generative AI as the next industrial revolution. After a round of introductions, Illia dove into the beginnings of his research at Google and the unique challenges that brought AI to the forefront during that time. “The team and I were working on simple question answering. You’d go to Google, you ask a question, and it should give you an answer,” Illia recounted. “But Google has very low latency requirements, so if you want to ship actual models that read search results, like tons of documents, you need something that can process that quickly. And models at the time just couldn’t do that.” After publishing the paper and leaving Google to explore new opportunities, Illia first worked on NEAR as an AI startup, then pivoted when he and co-founder Alex Skidanov recognized an opportunity in the blockchain space they first encountered as users. They recognized a clear need in the space back in 2018: to make blockchain technology accessible and intuitive for everyday use. Illia discussed with the panel how that realization led him to the concept of programmable money, and subsequently built NEAR Protocol to address blockchain scalability and usability challenges, creating a shift towards a more user-friendly open web economy. The Genesis of NEAR and Programmable Money Illia further discussed how his shift from pure AI research to Web3 was driven by the concept of programmable money, not just for cross-border payments but for a range of powerful use cases. This was a direct response to the challenges of coordinating on complex networks and the increasing demand for scalable blockchain solutions. The result is a platform that can handle large transaction volumes without compromising speed or security. “NEAR has the most users in the world in the blockchain space,” Illia explained. “We’re talking about multiple millions of daily users who don’t even know they’re using blockchain. But they’re actually interfacing with programmable money and programmable value. And now we’re bringing back some of those AI tools to generate more data.” He then highlighted the need for a shift in how creators are rewarded in an emerging age of generative AI, suggesting that the century-old copyright system must evolve. With artists and creators now leveraging tools like Midjourney and OpenAI for everything from visual art to storytelling, the panel agreed that copyright laws will need an overhaul sooner than later. Integrating AI for Fairer User and Creator Economies With the generative age already underway, Illia further unpacked how NEAR will be central to this new AI-enabled creator economy. “The way we’re rewarding creators right now is broken,” Illia continued. “And the only way to fix that is to leverage programmable money, programmable value, and blockchain. You need the basic primitive of programmable money because it’s what allows users and groups to coordinate people at scale.” Illia’s vision extends to building a version of the open web where programmable value underpins a positive feedback loop, fostering a novel economy enriched by equitable participation. For example, he noted that NEAR is exploring ways for users to contribute their own data, which can help improve AI models. These initiatives demonstrate how tomorrow’s AI economy could benefit both creators and users by allowing more participation and collaboration underpinned by Web3 infrastructure and incentives. “I strongly believe that the way we’re going to make progress towards software eating the world to machine learning is eating software,” Illia argued. “And the most direct way is to teach machines to code, so you’re able to actually generate software and transform everyone’s access.” Throughout his appearance at NVIDIA GTC 2024, Illia underscored NEAR’s pivotal role in bridging the gap between the open web, programmable money, and AI. By advocating for a reimagined copyright framework and more equitable creator compensation models, Illia presented an accessible and compelling vision for NEAR at the forefront of tomorrow’s user and creator centric AI economy. While this was just a brief glimpse of the emerging AI+Web3 ecosystem on NEAR, it was met with a wave of excitement from the NEAR community and served as a reminder for the whole Web3 space about Illia’s and NEAR’s early roots in the world of AI.
--- title: 2.8 Legal Pathways and Project Design description: Pragmatic expectations on the implications of different legal pathways --- # 2.8 Legal Pathways and Project Design This final lecture is a practical lecture at root, that seeks to ground expectations on the implications of different legal pathways taken by projects building in an L1 ecosystem. It is an understatement to say that crypto is a gray zone area. The focus however is not legal council nor legal advice: It is practical insights that must be considered based upon the type of project in question, and the different legal jurisdictions that a project might choose. In this sense, the goal is to be able to understand the _implications_ of the different legal decisions a project might take - from a crypto perspective. ## Initial Considerations: Location and Fundraise Structure While many entrepreneurs are quick to understand traditional equity raise strategies, crypto challenges cross-over entrepreneurs (from Web2 or whatever other industry into Web3) with its complex legal framework. If a company is intending to launch a token as a part of their project, they must either clarify the status of their token with the SEC _or_ file for an exemption (under a Reg. D filing) - this is if the project is launching from the United States or if it intends to raise in relation to USA investors. The problem from a glance is actually twofold: 1. What happens if a project is not sure if they would like to launch a token or not? 2. Does the type of vehicle impact a project’s ability to get investors to be able to participate in their project? Both of these questions must be carefully considered _before a project moves forward with a specific approach_. To date there are three primary legal raise strategies that most projects fall into: (1) SAFT - or simple agreement for future tokens, (2) Token SAFE and Warrant → Simple Agreement for Future Equity (capable of being converted into tokens), and (3) Equity. ## SAFT A Simple Agreement for Future Tokens (SAFT) is a investment contract that was originally popular from 2017 to 2021, used to sell tokens to investors in the pre-sale of a project, prior to its public launch (ICO). A SAFT is a type of agreement between an investor and a project or company that is issuing a cryptocurrency or token. The SAFT is designed to provide investors with the rights to receive tokens at a future date, once the token is fully developed and released on the market. The terms of the SAFT typically outline the rights and obligations of both the investor and the issuing company, as well as the conditions under which the tokens will be delivered to the investor. The SAFT is intended to provide a simple and straightforward way for investors to participate in a pre-sale or ICO, while also ensuring that the issuing company is able to develop and release its tokens in a responsible and compliant manner. In practice, a SAFT is a guarantee for tokens, and only tokens. There is no control an investor may possess over the behavior of the company, the management of funds, and so forth unless it is specified in a side letter or in the SAFT itself. This type of vehicle is ideal for protocols, or projects whereby the team intends to cede ultimate control over to the community later in time, and whereby they have a clear crypto-economics already developed. When compared with a token SAFE and warrant, a SAFT is less constraining for a project, but requires a clearer and more sophisticated crypto-economic design. The danger of a SAFT is that if the company structures offshore or through a Swiss Foundation (with a relevant token categorization from its regulatory body FINMA), then the project could in principle launch a token with limited responsibility in the long term, and then proceed to refuse to cede ownership of the private keys controlling the core facets of the protocol. ## Token SAFE and Warrant A SAFE (simple agreement for future equity) is a type of investment contract that is often used in crowdfunding campaigns, particularly in the tech industry. A SAFE is similar to a convertible note in that it provides investors with the right to receive equity in a company at a later date, typically when the company raises a certain amount of funding or reaches a specific valuation. However, unlike a convertible note, a SAFE does not accrue interest or have a maturity date. A warrant is a financial instrument that gives the holder the right, but not the obligation, to purchase a specified number of shares of stock at a specified price within a specified time period. In the context of a crypto fundraising, a token warrant would be issued to an investor along with a SAFE for the right to tokens at a future date - if such a token would be launched. Technically, the warrant would give the investor the right to purchase additional tokens of the company's stock at a future date, typically at a discounted or fixed price. In practice, the company transfers the money ahead of time, and owns the right to a certain amount of tokens, whenever they are to be created. The combination of a token SAFE and a warrant can provide investors with an attractive investment opportunity from a tax and legal perspective, as the investing entity does not actually control or own the tokens themselves - but rather they ability to redeem their investment for tokens at a later date (should a token be launched). A token SAFE and Warrant structure can, however, be a danger for investors, despite its tax and legal benefits: Because crypto is centered upon the fundamental design of monetary systems built into smart contracts, the nature of the token is extremely important from an investment perspective. With a token SAFE and Warrant however, teams have the ability to sell investors on a vision or product _without specifying how that product or vision will be connected to a clear token-economic design_. As such, investors often create massive blunders insofar as they invest in a promising concept or prototype, and then come to find the token design is not able to accrue any of its value! For projects, a token SAFE and Warrant is sometimes (sadly) used to kick the can down the road for the design of their crypto-economic system: A project can quickly and easily raise funds without needing to get into the nitty-gritty of how their open, permissionless system is leveraged to accrue value. ## Traditional Equity Vehicles Holding Tokens Offshore Last but not least, there is the option of creating a traditional equity investment vehicle. This is characteristically used for infrastructure, security, custody, and on-ramp projects that may or may not intend to launch a token. This is similar to traditional tech investing, and largely depends on the jurisdiction in which the entity intends to operate. Popular destinations include the Cayman Islands, Switzerland, Hong Kong, Singapore, as well as Antigua and Barbuda. If there is a potential for the nature of the project to intersect with the regulation of the United States as it pertains to token design and functionality, it is best for the company to be structured offshore. From an investment perspective, traditional equity vehicles are often-times used to allow more legacy investors or corporations to invest or participate in a token sale, by holding the tokens inside of an offshore company, and selling equity of that company to the corporation in question. **Hypothetical Example:** KDDI is a Japanese corporation that has set up an offshore entity. A protocol then would sign a SAFT or SAFE with that offshore entity, from which it could deploy tokens. These tokens would then be owned (once-removed) by KDDI, such that they would be able to control them through the Cayman Entity. However on KDDI’s balance sheet it simply shows an equity investment in a Cayman entity. ## Token Considerations and Jurisdictions Without touching too much upon the field of crypto-economics, projects and investors must also always consider the legal implications and designation of a token that a project launches. According to Swiss regulation there are three types of tokens: 1. Utility Tokens. 2. Payment Tokens. 3. Security Tokens. To receive this designation, a project would need to structure an LLC or Foundation inside of Switzerland and register their supposed token design for approval from FINMA. Any entity launching a token from offshore, would not need to worry about their token designation, unless they intended to sell or launch to the United States market of investors and retail users (discussed below). Offshore entities would only be limited by the jurisdiction they launch within - which to date has zero regulations on token designations. It would then be a question for exchanges or custodians wishing to list that token if it is acceptable within specific jurisdictions. From an investor’s point of view, the investor must understand the roadmap and development timeline of the project, as well as the utility of the token they may be investing in. This is surprisingly not done frequently or well. ## Governance Tokens and their Critics One strategy that has been leveraged by founders revolves around ‘governance tokens’. The strategy is quite straightforward: If a token is going to be receiving value from an external source, it is most likely to be considered a security token. This would apply to most fee-sharing protocols relevant to Decentralized Finance and NFT marketplaces. Teams then do the following: * Launch Governance Token Offshore (or as Anonymous Team). * ‘Decentralize’ the protocol after the token has been launched (and even listed on an exchange). * Add fee accrual to the governance token, as a protocol wide decision or vote, such that it functions as a security token, even though it is considered as being created for governance. Often times, however, this strategy is not developed fully or to its completion, resulting in the launch of a token that merely has rights to vote on mechanical changes to the protocol over time. Vitalik as been outspoken on the silly nature of value capture in these token designs: ![](@site/static/img/bootcamp/mod-em-2.8.1.png) ## Regulation D filing and sales in the United States Regulation D is a rule under the Securities Act of 1933 that provides an exemption from the registration requirements of the Act. This allows a company to raise capital from investors without having to register their securities with the Securities and Exchange Commission (SEC). In the context of token offerings, a company would use a Regulation D to offer and sell tokens without having to register the offering with the SEC. This can be a useful way for companies to raise capital while still complying with the law. However, it's important to note that there are limitations and requirements that must be met in order to qualify for the exemption under Regulation D. For example, the tokens being offered must be offered only to accredited investors, and there are limits on the amount of money that can be raised through a Regulation D offering. Details aside, a Regulation D filing is necessary for most projects intending to offer their token to accredited investors inside of the United States. If a project is selling to USA investors, they have a choice to comply with the Reg D filing requirements, or to simply launch as an anonymous team. In the former case, the project is responsible (despite most likely being structured offshore), in the latter case the investors are taking on additional risk, investing in a protocol or project that is not legally structured or compliant in the USA. ## Takeaways Amidst all of the legal mumbo-jumbo there are some very practical takeaways from investors and projects to understand: 1. If your project has a token, you must think carefully about (1) If you are launching it offshore or through some regulated jurisdiction (like Switzerland), (2) If you will raise as SAFT, Token SAFE and Warrant, or Equity - and the implications of that for your crypto-economics. (3) If you are selling to USA investors, and you intend to comply with the minimum registration requirements from the SEC. 2. Investors need to look carefully at the crypto-economic design, rights to the company, and designation of the token. Otherwise they may be investing in vaporware! 3. Projects must understand the timeframes and implications of (1). Certain types of tokens cannot be listed on certain exchanges, while selling to USA investors under a Reg. D filing may have a limitation on where and when the token can be offered to retail at a later point. 4. At the end of the day, there is no ‘global jurisdiction’. The FTX fallout, 3AC going to Dubai, and limited reach from governments, shows that in the crypto space, a lack of global regulation and coordination leaves the door open to maneuverability on behalf of projects and founders, that has been hitherto unprecedented.
--- title: Developer Enablement description: Overview of the Development Platform on NEAR BOS sidebar_position: 4 --- # Developer Enablement: The Developer Platform ## Highlights: * The BOS development platform removes complexity enabling any developer interested in open-source and decentralization, to build, deploy, and host serverless backend services for web apps. * The BOS development platform creates an accessible entry point for BOS with a comprehensive set of tools and capabilities to get developers started quickly agnostic of underlying smart contract blockchain ### What it is: Developer enablement is responsible for the developer platform; A set of tools and capabilities that help remove the barriers around Web3 and make it possible for developers of all backgrounds to start building on the BOS. Created for every developer who values open-source and decentralization, the BOS offers developers a way to quickly build composable apps, build complete projects using current workflows, seamlessly onboard users, get feedback from real users, and increase discoverability. The development platform allows anyone with coding experience to start building on the BOS from day one, providing a more accessible space for Web3 development. ### Why it matters: The current Web3 space can feel like a walled garden, with access being limited to those already in the know. Getting up to speed on blockchain development can feel intimidating, complex, and time-consuming, particularly for people who are new to the field, but also for those trying to move between projects or chains. This complexity keeps many developers from working in the space, limiting the development of new apps and experiences and the overall adoption of Web3. By providing a full suite of easy-to-use development tools and capabilities, including the ability to build full projects in Javascript, the developer platform solution helps overcome these challenges. Developers can compose applications with confidence using community-generated and validated components, as well as build their own reputations by publishing their own components and applications. They can also build complete projects locally using their current workflows with the VS Code extension, and seamlessly deliver projects using decentralized front-ends with low fees and transparent policies. Both NEAR and Ethereum blockchains are supported. ### Who it’s for: * Component developers - Anyone interested in building reusable components that can be shared with other developers and facilitate the growth of an open web can get started creating from day one. * Application developers - Developers, and anyone curious about Web3 who has some coding experience, can quickly build applications by remixing components for specific use cases and unique audiences. ### How it works: * Developer Workflow * Discover a component via search, understand the component from the component details, fork the component, remix and modify the component in the sandbox, and save and publish the component on-chain to the community. * Components * Built by developers for other developers or end users, components can range in size from a tiny button all the way to large applications composed of many other components that solve a detailed end-user use case. Components are stored on the NEAR blockchain and written using JSX (JavaScript with ReactJS). * Viewer * Responsible for the UI (the gateway) which exposes the ability to log in, build, and interact with components. Including injecting into components the needed RPC libraries (e.g Pagoda or ETH RPCs). * VM * This enables developers with modules, functions, pure javascript, and select javascript APIs. * Gateways * A specific implementation of the virtual machine for building an application that requires functionality not currently supported by the near.org VM & viewer. In order to deliver their specific use case, they can fork or reference the VM/Viewer, make changes, and serve their own gateway at their own URL. Current Gateways include bos.gg, near.org, near.social, and cantopia.pages.dev * Sandbox * The in-browser IDE where a developer builds, modifies, saves, and publishes their components, allowing for a quick time to delight for new developers looking to decentralize front ends and remix components. * Cross-Chain Ethereum Support * Read and write to Ethereum smart contracts from a decentralized front-end running on the BOS using ethers.js. Using remote NEAR accounts, developers can use their existing funded Ethereum accounts to deploy components. ### What’s coming next * Design system (component library, frontend development stack, documentation, and pattern library) * Reputation, badges, and rewards
--- NEP: 0418 Title: Remove attached_deposit view panic Author: Austin Abell <austin.abell@near.org> DiscussionsTo: https://github.com/nearprotocol/neps/pull/418 Status: Approved Type: Standards Track Category: Tools Version: 1.0.0 Created: 18-Oct-2022 Updated: 27-Jan-2023 --- ## Summary This proposal is to switch the behavior of the `attached_deposit` host function on the runtime from panicking in view contexts to returning 0. This results in a better devX because instead of having to configure an assertion that there was no attached deposit to a function call only for transactions and not view calls, which is impossible because you can send a transaction to any method, you could just apply this assertion without the runtime aborting in view contexts. ## Motivation This will allow contract SDK frameworks to add the `attached_deposit == 0` assertion for every function on a contract by default. This behavior matches the Solidity/Eth payable modifier and will ensure that funds aren't sent accidentally to a contract in more cases than currently possible. This can't be done at a contract level because there is no way of checking if a function call is within view context to call `attached_deposit` conditionally. This means that there is no way of restricting the sending of funds to functions intended to be view only because the abort from within `attached_deposit` can't be caught and ignored from inside the contract. Initial discussion: https://near.zulipchat.com/#narrow/stream/295306-pagoda.2Fcontract-runtime/topic/attached_deposit.20view.20error ## Rationale and alternatives The rationale for assigning `0u128` to the pointer (`u64`) passed into `attached_deposit` is that it's the least breaking change. The alternative of returning some special value, say `u128::MAX`, is that it would cause some unintended side effects for view calls using the `attached_deposit`. For example, if `attached_deposit` is called within a function, older versions of a contract that do not check the special value will return a result assuming that the attached deposit is `u128::MAX`. This is not a large concern since it would just be a view call, but it might be a bad UX in some edge cases, where returning 0 wouldn't be an issue. ## Specification The error inside `attached_deposit` for view calls will be removed, and for all view calls, `0u128` will be set at the pointer passed in. ## Reference Implementation Currently, the implementation for `attached_deposit` is as follows: ```rust pub fn attached_deposit(&mut self, balance_ptr: u64) -> Result<()> { self.gas_counter.pay_base(base)?; if self.context.is_view() { return Err(HostError::ProhibitedInView { method_name: "attached_deposit".to_string(), } .into()); } self.memory_set_u128(balance_ptr, self.context.attached_deposit) } ``` Which would just remove the check for `is_view` to no longer throw an error: ```rust pub fn attached_deposit(&mut self, balance_ptr: u64) -> Result<()> { self.gas_counter.pay_base(base)?; self.memory_set_u128(balance_ptr, self.context.attached_deposit) } ``` This assumes that in all cases, `self.context.attached_deposit` is set to 0 in all cases. This can be asserted, or just to be safe, can check if `self.context.is_view()` and set `0u128` explicitly. ## Security Implications This won't have any implications outside of view calls, so this will not affect anything that is persisted on-chain. This only affects view calls. This can only have a negative side effect if a contract is under the assumption that `attached_deposit` will panic in view contexts. The possibility that this is done _and_ has some value connected with a view call result off-chain seems extremely unlikely. ## Drawbacks This has a breaking change of the functionality of `attached_deposit` and affects the behavior of some function calls in view contexts if they use `attached_deposit` and no other prohibited host functions. ## Future possibilities - The Rust SDK, as well as other SDKs, can add the `attached_deposit() == 0` check by default to all methods for safety of use. - Potentially, other host functions can be allowed where reasonable values can be inferred. For example, `prepaid_gas`, `used_gas` could return 0. ## Decision Context ### 1.0.0 - Initial Version The initial version of NEP-418 was approved by Tools Working Group members on January 19, 2023 ([meeting recording](https://youtu.be/poVmblmc3L4)). #### Benefits - This will allow contract SDK frameworks to add the `attached_deposit == 0` assertion for every function on a contract by default. - This behavior matches the Solidity/Eth payable modifier and will ensure that funds aren't sent accidentally to a contract in more cases than currently possible. - Given that there is no way of checking if a function call is within view context to call `attached_deposit` conditionally, this NEP only changes a small surface of the API instead of introducing a new host function. #### Concerns | # | Concern | Resolution | Status | | - | - | - | - | | 1 | Proposal potentially triggers the protocol version change | It does not trigger the protocol version change. Current update could be considered a client-breaking change update. | Resolved | | 2 | The contract can assume that `attached_deposit` will panic in view contexts. | The possibility that this is done _and_ has some value connected with a view call result off-chain seems extremely unlikely. | Won't Fix | | 3 | Can we assume that in all view calls, the `attached_deposit` in the VMContext always zero? | Yes, there is no way to set `attached_deposit` in view calls context | Resolved | ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
NEAR Tasks Launches AI Marketplace on NEAR to Revolutionize the Future of Work NEAR FOUNDATION November 16, 2023 The convergence of AI and Web3 captured the tech industry’s imagination in 2023 — but few ideas have actually become a working reality. An exciting exception is NEAR Tasks, a global gigs marketplace poised to reshape AI training while leveraging the power of NEAR blockchain. Officially launched at NEARCON 2023 with its first product beta launching this week, NEAR Tasks is a self-service platform where anyone can easily list and complete AI requests, setting a new standard for quality data labeling. Unlocking the Power of AI and Web3 NEAR Tasks envisions a future where AI and Web3 technologies complement each other, fostering an ecosystem driven by transparency and efficiency. This symbiotic relationship aims to streamline task matching, review processes, and manage data quality more effectively at scale. Implemented on the NEAR Protocol, NEAR Tasks utilizes on-chain tasker IDs, smart contracts for automated payments, and $NEAR transactions for global payments with minimal fees. This ensures accountability, motivates high-quality outcomes, and addresses the challenge of underpaid workers in the AI sector. NEAR Tasks in a Nutshell In the age of AI, despite popular narratives about LLMs replacing a range of human jobs, human intelligence actually becomes even more important: as models get more complex, they need human expertise for fine-tuning models and increasing subject matter specialization. This user-friendly platform seamlessly connects task listing, work review, and crypto rewards, propelling AI model training into a new era through direct human feedback loops and a flexible self-service marketplace. For business clients and AI builders, NEAR Tasks provides a self-service, plug-and-play solution, liberating users from the constraints of costly managed service options. Blockchain integration on NEAR facilitates efficient data labeling by verified human experts, who can build reputation and get paid in real time for contributing quality work to the platform. For taskers, the NEAR Tasks marketplace offers a transparent path to monetizing their skills and knowledge, unlocking new revenue streams in the ever-evolving AI labor frontier, and changing the future of digital work. There are more than a billion participants in the global on-demand gig economy today, showing the need for more opportunities as well as greater specialization for those with particular training or expertise. With more reliable identity verification for accounts, faster work review, and the ability to pay taskers with crypto, taskers can get paid more reliably and work at the pace they wish — making the gig economy more supportive to specialized workers. In his introduction to NEAR Tasks at NEARCON in Lisbon, Senior Engineer Momo Araki pointed out: “There’s an interdependence for the system to work properly. You have to reform the central inspection principle wielded by task providers, and maintain sybil-resistance so workers can’t spoof the platform. It’s loosely analogous to a ‘proof-of-work’ model, where work performed well also translates to earning reputation, which leads to accessing further opportunities.” Incorporating more trust into a tasks marketplace in this way also produces better results for the AI builders and businesses trying to refine their models. A Fair and Transparent Platform for AI Training In an AI landscape where autonomy often overshadows human involvement, NEAR Tasks recognizes the vital role of a global workforce responsible for data labeling and validation. The platform introduces on-chain digital IDs for taskers, ensuring transparency and accountability. Transactions exclusively conducted in $NEAR guarantee rapid global payments with minimal fees, directly confronting the issue of underpaid AI workers in what is known in the industry as “AI sweatshops.” “Human intelligence forms the base of artificial intelligence, and it’s time we give AI tasks the recognition they deserve as legitimate jobs in the AI economy,” says Catherine Yushina, Head of Operations at NEAR Tasks. AI Is NEAR At NEARCON 2023, NEAR Co-Founder Illia Polosukhin — an AI researcher himself and co-creator of transformers, the architecture powering today’s major LLMs like ChatGPT — named AI as one of the core verticals for the NEAR ecosystem heading into 2024. From transforming governance and business operations with AI agents to provable provenance for data and content, as well as novel marketplaces like NEAR Tasks and hybrid human-AI working environments, we’re at the very beginning of an exciting revolution that will change the ways we work, collaborate, transact, research, and govern ourselves. More news is coming before the end of 2023 to position NEAR as the leader at the intersection of AI and Web3. Join the AI + Blockchain Movement If you want to be part of this transformative AI and blockchain convergence shaping the human intelligence market, sign up for the NEAR Tasks waitlist — currently at more than 48,000 applicants. The marketplace opens for public access in Q1 of 2024. You can also reach out to the team directly to request entry into the current Beta. Drop them an email at [email protected] to express your interest by Monday, November 20. For more information about NEAR Tasks, please visit https://neartasks.ai/. Follow along on social media: Twitter: https://twitter.com/near_tasks LinkedIn: https://www.linkedin.com/company/98907399
The NEAR Foundation’s Vision for the Future NEAR FOUNDATION June 24, 2022 The past several weeks have been challenging for many within crypto. This downturn is also very different from the previous 2018/2019 crypto winter as it is occurring against the backdrop of surging inflation, rising interest rates and global instability. Crypto isn’t immune to these shocks, but the crypto ecosystem is more robust than it was three years ago. There is more capital than ever flowing into projects, an increasing amount of top talent, and a maturing of the infrastructure that provides a better foundation for more projects to flourish. The NEAR Foundation has always focused on diligent and conservative treasury management, and as an ecosystem, we are therefore well-positioned to weather this storm. There has never been a better time to build on NEAR. A bear market is not a time to pause, it is a time to build, invest and organize to succeed – it is a time to put our best foot forward and execute at pace. To better serve and address the needs of the growing NEAR ecosystem we have made a couple of structural changes to the NEAR Foundation organization, which are described below. NEAR Foundation Mission The mission of the Foundation is to foster the conditions by which an ecosystem can flourish, assisting and aiding others to reimagine business, creativity, and community in their own ways. The Foundation exists to help inspire and empower people to join the ecosystem, by acting as a trusted party and gateway into this new world. It is one part of a larger puzzle. To help visualize how the Foundation interacts with the NEAR ecosystem we have developed a new mental model which is the basis for our internal OKRs, priority settings, and team priorities. NEAR Foundation is a centralized organization championing decentralization as part of a decentralized ecosystem. Over time, NEAR Foundation’s role will continue to evolve as new funds emerge via ecosystem and regional funds, and as the community takes on more and more. NEAR Foundation Changes To best foster the conditions needed for the NEAR Ecosystem to continue its tremendous growth, we are reorganizing our teams alongside our key principles: Adopting a functionally aligned organizational structure across the Foundation, operating in a more streamlined way. Combining all our efforts on growing and supporting our community under one “Community Team”, to continuously focus and help address the needs of our growing ecosystem. Creating a product/engineering organization under new Product and Engineering leadership, which will enable us not only to re-purpose our website (the key entry point to the NEAR ecosystem) but also to have more perspective on products built in the ecosystem and be able to address technical queries for our partners more effectively. To achieve this, we have created 16 new open positions for roles that help the Foundation achieve its mission. If you want to join us, or our ecosystem please check out – https://careers.near.org/jobs As part of this reorganization, 17 team members will be leaving the NEAR Foundation. Most of these will move their skills into the NEAR ecosystem, joining one of the 600+ projects building the future of the web. Others will join NEAR hub and other community-led projects. Seeing friends and colleagues leave an organization is never easy. We are extremely grateful for their immense contribution, continued support, and participation in the NEAR ecosystem. This is not a downsize, but a reorganization to better serve the needs of the ecosystem. We are very well positioned to succeed in the bear market. NEAR Foundation has always focused on diligent and conservative treasury management, and as an ecosystem we are therefore well-positioned to weather the storm. No better time to build on NEAR! We are confident that being well organized is the first step in that direction and we are confident that our new structure is setting us up for success.
--- sidebar_label: "Python tutorial" --- # NEAR Lake indexer basic tutorial :::info Source code for the tutorial [`frolvanya/near-lake-raw-printer`](https://github.com/frolvanya/near-lake-raw-printer): source code for the tutorial on how to create an indexer that prints block height and number of shards ::: Recently we have [published a Python version of the NEAR Lake Framework](https://pypi.org/project/near-lake-framework/) on pypi.org We want to empower you with a basic tutorial on how to use the Python Package. Let's get started! ## Create a project Create an indexer project: ```bash mkdir near-lake-raw-printer && cd near-lake-raw-printer touch main.py ``` ## Install dependencies Install `near-lake-framework` ```bash pip3 install near-lake-framework ``` ## Import `near-lake-framework` In the `main.py` file let's import the necessary dependencies: ```python title=main.py from near_lake_framework import near_primitives, LakeConfig, streamer ``` We've imported the main function `streamer` which will be called to actually run the indexer, `near_primitives` and `LakeConfig` type we need to contruct. ## Create a config Add the instantiation of `LakeConfig` below: ```python title=main.py config = LakeConfig.mainnet() config.start_block_height = 69030747 config.aws_access_key_id = os.getenv("AWS_ACCESS_KEY_ID") config.aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY") ``` Just a few words on the config, function `mainnet()` has set `s3_bucket_name`, `s3_region_name` for mainnet. You can go to [NEAR Explorer](https://nearblocks.io) and get **the most recent** block height to set `config.start_block_height`. ## Starting the stream Let's call `streamer` function with the `config`: ```python title=main.py stream_handle, streamer_messages_queue = streamer(config) while True: streamer_message = await streamer_messages_queue.get() print(f"Block #{streamer_message.block.header.height} Shards: {len(streamer_message.shards)}") ``` And an actual start of our indexer in the end of the `main.py` ```python title=main.py loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` ## All together ```python title=main.py import asyncio import os from near_lake_framework import LakeConfig, streamer, near_primitives async def main(): config = LakeConfig.mainnet() config.start_block_height = 69030747 config.aws_access_key_id = os.getenv("AWS_ACCESS_KEY_ID") config.aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY") stream_handle, streamer_messages_queue = streamer(config) while True: streamer_message = await streamer_messages_queue.get() print(f"Block #{streamer_message.block.header.height} Shards: {len(streamer_message.shards)}") loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` That's it. Now we run `main.py` ```bash python3 main.py ``` You should see something like the following: ```bash Received 400 blocks from S3 Block #69030747 Shards: 4 Block #69030748 Shards: 4 Block #69030749 Shards: 4 Block #69030750 Shards: 4 Block #69030751 Shards: 4 Block #69030752 Shards: 4 Block #69030753 Shards: 4 Block #69030754 Shards: 4 ``` You can stop the indexer by pressing CTRL+C :::danger Credentials To be able to access the data from [NEAR Lake](/tools/realtime#near-lake-indexer) you need to provide credentials. Please, see the [Credentials](../../lake-framework/running-near-lake/credentials.md) article ::: You can find the [source code for this tutorial on the GitHub](https://github.com/frolvanya/near-lake-raw-printer).
NEAR Foundation Launches NEAR DA to Offer Secure, Cost-Effective Data Availability for ETH Rollups and Ethereum Developers NEAR FOUNDATION November 8, 2023 NEAR Foundation just announced the rollout of the NEAR Data Availability (NEAR DA) layer. Part of the NEAR Open Web Stack, NEAR DA is a groundbreaking innovation that offers robust, cost-efficient data availability for ETH rollups and Ethereum developers. NEAR DA is set to launch with a number of first users, including Madara by StarkNet, Caldera, Fluent, Vistara, Dymension RollApps, and Movement Labs. Let’s take a brief look at NEAR DA to explore why it’s such an exciting and significant development for NEAR, Ethereum, and the larger effort to build a truly open web. NEAR DA — paving the way for modular blockchain development With NEAR DA, ETH rollups and Ethereum developers get cost-effective, reliable data availability. 100kB of calldata on NEAR will cost $0.0033 as of September 2023, while the same calldata on Ethereum L1 will run users $26.22. That’s 8,000 times cheaper! NEAR DA will help developers reduce costs and enhance the reliability of their rollups, while keeping the security of Ethereum. High quality projects launching an app-chain or L2 will also be able to get NEAR DA support. Illia Polosukhin, co-founder of NEAR Protocol, and newly announced CEO of NEAR Foundation said: “Offering a data availability layer to Ethereum rollups highlights the versatility of NEAR’s tech while also helping founders from across Web3 deliver great products that bring us closer to mainstream adoption of the Open Web.” “NEAR’s L1 has been live with 100% uptime for more than three years, so it can offer true reliability to projects looking for secure DA while also being cost-effective,” Polosukhin added. “NEAR provides great solutions to developers no matter which stack they’re building on and now that includes the Ethereum modular blockchain landscape.” Expanding NEAR’s Open Web Stack By opening up its blockchain for data availability, NEAR Protocol is expanding its offerings to deliver a modular blockchain development framework. This will let Web3 developers and founders continue building on Ethereum while leveraging NEAR’s state-of-the-art tech for one part of the stack, depending on their requirements. NEAR DA expands the capabilities of NEAR’s Open Web Stack, a common entry point where developers and users alike can easily build, browse, and discover Web3 products and platforms. This includes FastAuth onboarding to an account in seconds with zero crypto or seed phrases required, as well as the ability to create decentralized frontends from a library of thousands of components. Developers and founders building on Ethereum rollups interested in using NEAR DA can visit near.org/data-availability to get started.
Astro Launches on NEAR To Supercharge DAO Communities COMMUNITY October 11, 2021 Astro, the platform for online communities to gather, vote, and govern has launched on NEAR. Astro is the next evolution of SputnikDAO, the hub for decentralized autonomous organizations (DAOs) operating on NEAR with a host of new features, more flexibility, and a friendly UI. If you’re a community looking to create, collaborate, and govern, Astro is the tool for you. What is Astro? Astro is a platform for On Chain Communities (OCC). OCC are groups of people that prove their membership and coordinate decisions through a series of smart contracts. Each vote is verified by the blockchain, and funds are distributed based on voting decisions. With Astro, DAOs will be able to retain more autonomy and, importantly, cast the net further in regards to governance through increased flexibility and the introduction of governance tokens. Curious to know more about Astro? We’re hosting an AMA on October 12, 2021 at 7 am PST / 10 am EST / 4pm CEST. Register for the AMA and submit your questions to the Astro team. Find out more about it here. What is a DAO? A DAO is a business structure where control is spread out, across the team members instead of being centered around one authority figure. Think of a DAO as being a machine with one purpose, to carry out a set of instructions determined by pre-written smart contracts. A community can adapt a DAO and program it according to its own goals. So the code can be used to create a set of rules, or a governance structure by which the community agrees to abide by. Tokens are used to help people vote on topics such as fund allocation. The more a member contributes to a community, the more his/her/their vote can be increased. Why start a DAO? Think of DAOs as a toolbox that allows anyone to create a business structure that is designed to be simple and flexible. As a result, DAOs come in all shapes and sizes. From flat to hierarchical, from open to anyone to members-only; you get to decide how you want to govern your community. For example: Grants Giving – Vote and collectively decide what people and projects to fund. For businesses – Keep track of owners’ equity and elect managers to make day-to-day decisions. For investors – Pool funds and vote on strategy and transactions. For clubs of any kind – Elect leaders and decide where to spend group funds. Astro makes DAOs simple. DAOs are quick to set up, global, customisable and transparent. Astro can help you create your own DAO in minutes.
--- id: contribute-faq title: Contributor FAQ sidebar_label: Contributor FAQ sidebar_position: 6 --- ### How can I get involved? {#how-can-i-get-involved} It depends what you are excited about doing! Do you want to develop on NEAR? Build tutorials? Answer questions? Expand our documentation? We recommend you to have a look at our [NEAR Community Page](https://near.org/ecosystem/community). If you are looking for something a little different, or you have questions, please reach out to the team on [Discord](http://near.chat/). ### How do I report a security vulnerability? {#how-do-i-report-a-security-vulnerability} The most up-to-date information about security vulnerability reporting is provided [in the core repo](https://github.com/near/nearcore/blob/master/SECURITY.md). ### Does NEAR have a bug bounty program available? {#does-near-have-a-bug-bounty-program-available} While we currently do not have a bug bounty program, you can contribute to our development of resources through the [NEAR Community](https://near.org/ecosystem/community). Additionally, we have hosted several hackathons; for future events sign-up to our newsletter and follow us on Discord. ### Are articles (not NEAR specific) allowed to be shared on Discord or Telegram? {#are-articles-not-near-specific-allowed-to-be-shared-on-discord-or-telegram} Links to educational content are allowed to be shared in the channels. If you are uncertain, please message an admin or somebody from the Team first; either on Telegram or [Discord](http://near.chat/). ### How are you building your community? {#how-are-you-building-your-community} We are actively working on expanding our community. If you have any suggestions, or you want to help out, please get in touch on [Discord](http://near.chat/). For long-term engagement, please have a look at our Contributor Program. If you want to build on NEAR, please check out our [contribution guidelines](https://github.com/near/nearcore/blob/master/CONTRIBUTING.md). :::note Got a question? **[Ask it on StackOverflow!](https://stackoverflow.com/questions/tagged/nearprotocol)** :::
--- sidebar_position: 2 --- # Styling (CSS) ## CSS Modules You can currently style BWE components with CSS modules. Each component has an associated CSS file which is saved on-chain alongside component source code. In the sandbox, a CSS module is created automatically for every component. Two syntaxes are supported for CSS modules imports. In the component `Foo.tsx`, you can use either of the following: ```tsx import s from './Foo.module.css'; ``` ```tsx import s from './styles.module.css'; ``` :::warning Although the second example above is what you will find in our starter code, we recommend using the pattern from the first example since it may be the only version that is allowed once local code editor support is implemented. ::: ### Features #### CSS Nesting CSS Nesting is supported. Here is an example of using it to style child elements and pseudo-classes: ```css .entry { padding: 1rem; > input { width: 20rem; } > button { background-color: #33b074; &:hover { background-color: #2f7c57; } &:active { background-color: #174933; } } } ``` ### Learn from Our Examples From the sandbox, use the search icon in left sidebar to pull up `webengine.near` components like `webengine.near/SocialFeedPage` ## CSS-in-JS We have CSS-in-JS support [on our roadmap](https://github.com/near/bos-web-engine/issues/7), but it is not yet available.
Music and Blockchain: The Future of Decentralized Streaming Music COMMUNITY April 22, 2022 As the decentralized economy expands, it’s no surprise that musicians are turning to the blockchain. NFTs, digital autonomous organizations (DAOs), Metaverse events, and more are transforming artistic visions into new and immersive experiences. On NEAR, decentralized streaming music platforms will be one part of the future music industry landscape. Community-driven instead of centralized like Spotify and YouTube, these platforms give artists more freedom to express themselves with built-in legal infrastructure support. But what does this decentralized streaming future look like for musicians? Establishing better streaming rights for musicians In a Web3 world, artists have more control over what they create. With decentralized streaming music, that will mean fewer intermediaries taking a cut of a musician’s revenue. “Artists who release through DAOrecords hold 100% of their IP—meaning that they can do anything they want with it,” says Jason “Vandal” Schadt, CEO at DAOrecords. “We have acted primarily as a distributor, helping to facilitate the release of Audio NFTs through our storefronts across a variety of chains,” he adds. “What I find very exciting is that we’re able to minimize the friction and need for legal contracts through the use of automated royalty splits built into the smart contracts we deploy.” DAOrecords has begun designing smart contracts with an approach similar to artists registering their songs officially, then sharing the revenue like they would with the performing rights societies that distribute royalties. “As we do this, it’s important that we only work with the rights holders directly in order to ensure that there is no infringement happening,” says Vandal. And if artists are part of DAO-based labels, like DAORecords, other interesting possibilities emerge with decentralized streaming. “The artists under the DAO label would actually own a slice of the label and have voting rights in where the [streaming] money goes,” says Amber Stoneman, CEO of Minting Music. “The label hasn’t ever been transparent, so blockchain is a way for that to happen on the ground level with producers and label owners.” At its core, decentralization is about using smart contracts to create the platforms, tools, resources, and legal structures for art to flourish on its own terms. This vision inspired Stoneman to create Minting Music, which brings blockchain to the music industry in a practical way. “I saw a lot of flaws in the platform transparency and gatekeeping that connects fans and artists,” says Stoneman. “After diving into NFTs, Web3 and crypto, I started to see how blockchain could solve a lot of music industry problems.” One of Stoneman’s goals is to enable a world where fans can buy and trade music via NFTs to create long-term revenue for the artists. “I see streaming being on-chain, payments being made to artists based on actual listeners and streams instead of the current Spotify model,” she says. “We see real royalty payments happening in real time.” Bringing transparency to royalty splits Clarian North, Founder of Tamago, a decentralized streaming music platform building on NEAR, also sees blockchain tackling royalty transparency. “Transparency is a big problem musicians and content creators are faced with when it comes to royalty payouts,” says North. “The digital age has made it exponentially harder for artists, managers, and labels to track every play and purchase.” For North, it’s clear how smart contracts can play a pivotal role in the streaming music future. Musicians will be able to track all transactions related to material in a transparent and immutable format. This will help to fairly balance and unblock the monetization flow back to content creators. Remix royalties will be no different. When a producer takes on a remix, North says, it creates a different perspective, audience, and sound than the original recording. Remixers generally earn a flat fee and occasionally get a royalty, although this is rare. The more hands original material goes through, the better chance it has to be consumed by larger audiences. But then tracking the royalties becomes more complex. Smart contracts could change this by simplifying royalty payments. “Having a network of data which is universally accessible and cannot be manipulated is therefore extremely beneficial for keeping exponential and viral pathways clean and unblocked in terms of making sure the content creators of the original material get their fair and transparent share,” he adds. Strangeloop Studios, which just launched Spirit Bomb, a label for decentralized virtual artists, is also hopeful about royalty transparency. Ian Simon, Co-founder of Strangeloop Studios, believes that NFTs will be a key ingredient in decentralized streaming music. “I think we’re still in the early stages of seeing all the ways that Web3 could disrupt some of the anachronistic practices of the music industry,” says Simon. “A lot of very smart people are focusing on royalty structures and overall transparency, and forcing a lot of obfuscated backroom deals out into the open. The NFT space assumes co-ownership, which is a philosophical sea change in acknowledging the value of all creative contributors, and one I’m very excited about.” Dismantling the artist-fan divide When music isn’t completely dictated by centralized forces, like major labels, mainstream media, and Web2 streaming platforms, artists are free to pursue the aesthetics that matter to them. This gives birth to genres and cultures like Hip Hop, Techno, Indie Rock, and more. As such, it forms the basis for collaborations, remix culture, and continued creativity into new media and forms. This thinking led to the inception of Endlesss.fm, a music software platform with NEAR integration. Endless enables artists and audiences to connect in a more spontaneous and visceral way. “Endlesss transforms media from a product we consume alone into a journey we undertake together with those we resonate with,” says Tim Shaw, also known as Tim Exile, who is a passionate, lifelong musician. “Immediately this will provide a more lean-forward engaged experience for fans.” “In the long run, this will dismantle the artist-fan divide,” he adds. “We will all become participants in communities. Some will be more involved in cultural production than others. But, we won’t think of it as a metaphorical barrier between the crowd and the artists.” Web3 will also enable musicians (and other creatives) to own and control the way their work shows up online. “Web3 inverts the relationship between platforms and individuals,” says Exile. “In Web2, we all rent our relationship with platforms. Platforms can throw us out at any point and we lose everything with no recourse. In Web3, platforms rent their relationship with us sovereign digital individuals. If platforms cease to add value to our digital lives, we can take our identities elsewhere.” Ultimately, Exile envisions a future in which Web2 and Web3 co-exist. “The streaming model works very well in a Web2 world where you pay for convenient access to media,” he says. “In Web3, the value proposition for media is about association. Which media do you choose to put your time, effort, and money into creating, collecting and trading? What does the aggregation of all the media you’ve associated with say about you? How can you experience the visceral sense of who you are by experiencing the things you’ve decided to align yourself with?” Supporting an expansive and authentic music industry The pandemic and other global crises have triggered a shift in the way humans engage with the physical world. This transition inspired the formation of Muti Collective, a Portugal-based community that helps artists blend the digital and physical worlds. Co-founded by Tabea and smokedfalmon, but operated collectively as a DAO, one of the group’s objectives is to incentivize a cultural movement in rural Portugal. “Given that most venues closed during the pandemic, it was the main resource to promote arts in the digital space,” says smokedfalmon. “It brought up a lot of questions regarding streaming revenues and how little the creators are actually paid on [Web2] streaming platforms.” By using Web3 spaces like Cryptovoxels and NEARhub, people can actually interact with the event while seeing the stream. DAOs give the group a better handle over collective finances, transparency, and democracy within the community. “People are generally skeptical in the beginning but curious, and need 1:1 onboarding to really get into it,” says Tabea. “Once they receive support for one of their projects, they engage a lot more.” “Also, the system of a DAO is not very common yet in the groups we are working with,” she adds. “But, once they understand how it works, they get more engaged. They discover more of the ecosystem and create their own path.” The road ahead Music in Web3 is all about creating, experimenting, and pushing boundaries. It’s also about pursuing long-term visions and continually manifesting the infrastructure to get there. With NEAR, musicians have a super fast, low-cost, and secure platform to get them to where they want to be. What artists and musicians need most is the power of ownership, which creates choice and enables self expression. Beyond decentralized streaming music’s freedom, it empowers creators with the tools they need to release their works on their terms. Blockchain, and DAOs in particular, facilitate an ecosystem experience in which parties can collaborate fairly and specify terms. Participants ranging from artists to record labels, fans, buyers, and secondary buyers are all welcome in this space. Decentralization has the potential to bring the music industry into a more enhanced state. The future of music on the blockchain is already in motion. Check out the complete series on Blockchain Music: Part 1: Music and Blockchain: Introducing the Future of Sound Part 2: Music and Blockchain: Building a Record Label on the Blockchain Part 3: Music and Blockchain: The Rise of the New Musician Part 4: Music and Blockchain: The Future of Decentralized Streaming Music
--- id: serialization title: Notes on Serialization --- Smart contracts need to be able to **communicate complex data** in a simple way, while also **reading and storing** such data into their states efficiently. To achieve such simple communication and efficient storage, smart contracts morph the data from their complex representation into simpler ones. This process of translating **complex objects into simpler single-value** representations is called **serialization**. NEAR uses two serialization formats: [JSON](https://www.json.org/json-en.html) and [Borsh](https://borsh.io/). 1. [JSON](https://www.json.org/json-en.html) is used to serialize the contract's input/output during a function call 2. [Borsh](https://borsh.io/) is used to serialize the contract's state. --- ## Overview of Serialization Formats Lets give a quick overview of both serialization formats, including their pros and cons, as well as an example on how their serializations look like. <hr className="subsection" /> ### [JSON](https://www.json.org/json-en.html): Objects to Strings #### Features - Self-describing format - Easy interoperability with JavaScript - Multiple implementations readily available - But... it is not efficient both in computational times and resulting size #### Example ```js Example{ number: i32 = 2; arr: Vector<i32> = [0, 1]; } // serializes to "{\"number\": 2, \"arr\": [0, 1]}" ``` <hr className="subsection" /> ### [Borsh](https://borsh.io/): Objects to Bytes #### Features - Compact, binary format built to be efficiently (de)serialized - Strict and canonical binary representation - Less overhead: it does not need to store attributes names - But... it is necessary to know the schema to (de)serialize the data #### Example ```js Example{ number: i32 = 2; arr: Vector<i32> = [0, 1]; } // serializes into [2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] ``` --- ## Serializing Input & Output NEAR contracts can implement methods that both take and return complex objects. In order to handle this data in a simple way, JSON serialization is used. Using JSON makes it easier for everyone to talk with the contracts, since most languages readily implement a JSON (de)serializer. #### Example Let's look at this example, written only for educational purposes: ```rust #[derive(Serialize)] #[serde(crate = "near_sdk::serde")] pub struct A { pub a_number: i32, pub b_number: u128 } #[derive(Serialize)] #[serde(crate = "near_sdk::serde")] pub struct B { pub success: bool, pub other_number: i32 } pub fn method(&self, struct_a: A): B { return B{true, 0} } ``` #### Receiving Data When a user calls the `method`, the contract receives the arguments encoded as a JSON string (e.g. `"{\"a_number\":0, \"b_number\":\"100\"}"`), and proceed to (de)serialize them into the correct object (`A{0, 100}`) . #### Returning Data When returning the result, the contract will automatically encode the object `B{true, 0}` into its JSON serialized value: `"{\"success\":true, \"other_number\":0}"` and return this string. :::caution JSON Limitations Since JSON is limited to `52 bytes` numbers, you cannot use `u64`/`u128` as input or output. JSON simply cannot serialize them. Instead, you must use `Strings`. The `NEAR SDK RS` currently implements the `near_sdk::json_types::{U64, I64, U128, I128}` that you can use for input / output of data. ::: --- ## Borsh: State Serialization Under the hood smart contracts store data using simple **key/value pairs**. This means that the contract needs to translate complex states into simple key-value pairs. For this, NEAR contracts use [borsh](https://borsh.io) which is optimized for (de)serializing complex objects into smaller streams of bytes. :::tip SDK-JS still uses json The JavaScript SDK uses JSON to serialize objects in the state, but the borsh implementation should arrive soon ::: #### Example Let's look at this example, written only for educational purposes: ```rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct Contract { string: String, vector: Vector<u8> } #[near_bindgen] impl Contract { #[init] pub fn init(string: String, first_u8: u8) -> Self { let mut vector: Vector<u8> = Vector::new("prefix".as_bytes()); vector.push(&first_u8); Self { string, vector } } pub fn change_state(&mut self, string: String, number: u8) { self.string = string; self.vector.push(&number); } } ``` #### Empty State On Deploy If we deploy the contract into a new account and immediately ask for the state we will see it is empty: ```bash near view-state $CONTRACT --finality optimistic # Result is: [] ``` #### Initializing the State If we initialize the state we can see how Borsh is used to serialize the state ```bash # initialize with the string "hi" and 0 near call $CONTRACT init '{"string":"hi", "first_u8":0}' --accountId $CONTRACT # check the state near view-state $CONTRACT --utf8 --finality optimistic # Result is: # [ # { # key: 'STATE', # value: '\x02\x00\x00\x00hi\x01\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix' # }, # { key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00', value: '\x00' } # ] ``` The first key-value is: ```js key: 'STATE' value: '\x02\x00\x00\x00hi\x01\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix' ``` Since the `Contract` has a structure `string, Vector<u8>` the value is interpreted as: ```bash [2, 0, 0, 0, "h", "i"] -> The `string` has 2 elements: "h" and "i". [1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, "prefix"] -> The Vector has 1 element, and to see the values search for keys that start with (the 6 bytes prefix): "prefix" ``` Then, the second key-value shows the entries of the `Vector` denoted by the `"prefix"` string: ```js key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00' value: '\x00' ``` #### Modifying the State If we modify the stored string and add a new number, the state changes accordingly: ```bash near call $CONTRACT change_state '{"string":"bye", "number":1}' --accountId $CONTRACT # Result is # [ # { # key: 'STATE', # value: '\x03\x00\x00\x00bye\x02\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00prefix' # }, # { key: 'prefix\x00\x00\x00\x00\x00\x00\x00\x00', value: '\x00' }, # { key: 'prefix\x01\x00\x00\x00\x00\x00\x00\x00', value: '\x01' } # ] ``` We can see that the `STATE` key changes to reflect the storage of the new string (`bye`), and that the vector now has 2 elements. At the same time, a new key-value was added adding the new vector entry: the `1u8` we just added. <hr className="subsection" /> <!-- We should see where to move/replicate this --> ### Deserialization Error When somebody invokes a smart contract method, the first step for the contract is to deserialize its own state. In the example used above, the contract will start by reading the `STATE` key and try to deserialize its value into an object `Contract{string: String, vector: Vector<u8>}`. If you deploy a contract into the account with a different Contract structure, then the contract will fail to deserialize the `STATE` key and panic `Cannot deserialize the contract state`. To solve this, you can either: 1. Rollback to the previous contract code 2. Implement a method to [migrate the contract's state](../release/upgrade.md)
--- id: deploy title: NEAR CLI - Basics sidebar_label: Deploying and Using --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; After your contract is ready you can deploy it in the NEAR network for everyone to use it. Let us guide you on how to use the [NEAR CLI](../../../4.tools/cli.md) to deploy your contract and call its methods. :::info On this page, we will only cover the basics of NEAR CLI. For more information visit the [NEAR CLI documentation page](../../../4.tools/cli.md). ::: --- ## Deploying the Contract Thanks to the `NEAR CLI` deploying a contract is as simple as: 1. Compiling the contract to wasm (done automatically through `yarn build` in our templates). 2. [Create an account](../../../4.tools/cli.md#near-create-account) and [deploy the contract](../../../4.tools/cli.md#near-deploy) into it using `NEAR CLI`. #### Create an Account and Deploy <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash # Create a new account pre-funded by a faucet & deploy near create-account <accountId> --useFaucet near deploy <accountId> <route_to_wasm> # Get the account name cat ./neardev/dev-account ``` </TabItem> <TabItem value="near-cli-rs"> ```bash # Automatically deploy the wasm in a new account near account create-account sponsor-by-faucet-service <my-new-dev-account>.testnet autogenerate-new-keypair save-to-keychain network-config testnet create near contract deploy <my-new-dev-account>.testnet use-file <route_to_wasm> without-init-call network-config testnet sign-with-keychain ``` </TabItem> </Tabs> #### Deploy in an Existing Account <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash # login into your account near login # deploy the contract near deploy <accountId> <route_to_wasm> ``` </TabItem> <TabItem value="near-cli-rs"> ```bash # login into your account near account import-account using-web-wallet network-config testnet # deploy the contract near contract deploy <accountId> use-file <route_to_wasm> without-init-call network-config testnet sign-with-keychain send ``` </TabItem> </Tabs> :::tip You can overwrite a contract by deploying another on top of it. In this case, the account's logic will change, but the state will persist ::: :::info By default `near-cli` uses the `testnet` network. Define `NEAR_ENV=mainnet` to deploy into `mainnet`. ::: :::info Naming Convention for Public-Facing Methods Once the contract is deployed to the network, anyone and any other contract (i.e., any other account on NEAR) can interact with it by calling its methods. Furthermore, any transactions involving the contract will also be included in the network's data stream, which means its activity can also be visible to any who listens to particular events. Considering this, we advise to name methods using `snake_case` in all SDKs as this is compatible with the remainder of the NEAR ecosystem which is predominantly comprised of Rust contracts. ::: --- ## Initializing the Contract If your contract has an [initialization method](../anatomy/anatomy.md#initialization-functions) you can call it to initialize the state. This is not necessary if your contract implements `default` values for the state. <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash # Call the initialization method (`init` in our examples) near call <contractId> <initMethod> [<args>] --accountId <accountId> ``` </TabItem> <TabItem value="near-cli-rs"> ```bash # Call the initialization method (`init` in our examples) near contract call-function as-transaction <contractId> <initMethod> json-args [<args>] prepaid-gas '30 TeraGas' attached-deposit '0 NEAR' sign-as <accountId> network-config testnet sign-with-keychain send ``` </TabItem> </Tabs> :::info You can initialize your contract [during deployment](#deploying-the-contract) using the `--initFunction` & `--initArgs` arguments. ::: --- ## Calling the Contract Once your contract is deployed you can interact with it right away using [NEAR CLI](../../../4.tools/cli.md). <hr className="subsection" /> ### View methods View methods are those that perform **read-only** operations. Calling these methods is free, and do not require to specify which account is being used to make the call: <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash near view <contractId> <methodName> ``` </TabItem> <TabItem value="near-cli-rs"> ```bash near contract call-function as-read-only <contractId> <methodName> text-args '' network-config testnet now ``` </TabItem> </Tabs> :::tip View methods have by default 200 TGAS for execution ::: <hr className="subsection" /> ### Change methods Change methods are those that perform both read and write operations. For these methods we do need to specify the account being used to make the call, since that account will expend GAS in the call. <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash near call <contractId> <methodName> <jsonArgs> --accountId <yourAccount> [--deposit <amount>] [--gas <GAS>] ``` </TabItem> <TabItem value="near-cli-rs"> ```bash near contract call-function as-transaction <AccountId> <MethodName> json-args <JsonArgs> prepaid-gas <PrepaidGas> attached-deposit <AttachedDeposit> sign-as <AccountId> network-config testnet sign-with-keychain send ``` </TabItem> </Tabs>
--- title: 5.1 Decentralized Autonomous Organizations (DAOs) description: The DAO revolution and its promise of change for data, users, and value --- # 5.1 Decentralized Autonomous Organizations (DAOs) _“A DAO is a capitalized organization in which a software protocol informs its operation, placing automation at its center and humans at its edges like how DeFi is programmable money, and NFTs are programmable media, DAOs are programmable organizations of people. The promise of DAOs and crypto-economics more generally is to be able to establish collective intelligences at scale. The defining attribute that makes DAO’s different from past organizations is the use of the blockchain as a root of trust such that the inputs and outputs from decisions that matter are immutable and auditable.” - [Riva Tez on Vitalik on DAOs ](https://www.youtube.com/watch?v=Srl9tHz9OQA)_ We have seen up until this point, how the systematic inversion of crypto is applicable to the very nature of value, fungible value and by extension decentralized science, as well as non-fungible value for creators, communities, and artists (among others. The focus of this module, outlines another field that is ripe for disruption from the web3 paradigm - namely - Governance - and to be specific, coordination and collaboration mechanisms. This was originally subsumed under the heading of Decentralized Autonomous Organizations or (DAOs) but as time has gone on, new terms like On-Chain Organizations, and Network States have also emerged in this area. Now, an entire sub-industry focused on governance has emerged: This encapsulates tooling for DAOs (to allow users and builders to create their own), protocol governance, treasury governance, and community governance. In parallel to these developments, there is avid interest from legacy industries on how on-chain governance can be used to disrupt and re-create a number of processes - from politics, to scientific funding decisions, to institutional governance. ## The What and How of DAOs For our purposes the DAO revolution has the promise of changing the manner in which data, users, value, and systems are managed - outside of the usual legal and institutional wrappers. With DAO’s we outsource governance and management itself into the domain of software. **Let’s start with the _What:_** **What is governed on-chain?** * **Communities of Users:** Organize together to make decisions together, share capital, work on common projects, or engage in some other activity (RAID DAO, DCD). * **Treasuries and Pooled Value:** To manage value, revenue, investments. * **Protocols including token issuance:** To manage emissions, rates, access, open-sourcing, and gating of assets or code bases. * **Rules and Mechanics for dApps and Systems - Games, Network States:** For allowing engagement with a system be it a game, country, or agency (similar to community but more structured). So in essence, the _what_ encompasses broadly things like human systems, revenue, stored value, and mechanics or levers of on-chain systems. And now we get to the really incredible benefit of DAOs and OO’s which is the _How_. If we get a little technical, on NEAR DAOs are created according to a specific set of rules and logic, encompassed by the term ‘DAO Factory’. What this means is that it is up to the user to program their organization with specific rules, policies, and procedures as they see fit. We are only at the very beginning of this product’s emergence. If you are familiar with Vitalik and his writings, DAOs used to be token weighted - meaning the more tokens an account held the more its vote weight would be. Those rules have now been superseded. On NEAR we can design a DAO or an Organization to an increasingly complex logic: **Vote Policy:** * Token Weight * Role Weight **Permissions:** * Councils with specific permissions. ** Approve ** Deny ** Move to Vote ** Call a specific function ![](@site/static/img/bootcamp/mod-em-5-multiple.png) And as an open-source library these functions are naturally growing by the day! Okay so we have spoken on a high level about the what and the how of DAOs - as an equally powerful product that is entirely complementary and different to NFTs. What, simply put, is the improvement or promise of DAOs and OO’s? * **Simplification -** Creating a new channel to move value or coordinate a process that has become bureaucratic. Molecule DAO for investing in BioTech. * **Velocity of value -** Automating the flow into and from a DAO, using software. So that fees from one exchange can automatically go into a DAO to finance a forest project. * **Transparency of fund distribution -** Organizations, political parties, governments, budgets are all done transparently on-chain. Value flows are visible. * **Co-ownership -** Building ownership and management power into the organization itself. * **Access (this is akin to people getting more financial access than ever via Crypto vs accredited investor rules → i.e. to a sports team, or a scouting agency).** Retail participation in any type of process - globally. * **Organize, Act, Coordinate in Networks.** Global participation, non-discrimination, minimal rules and bureaucracy, easy access, and streamlined value flows. ![](@site/static/img/bootcamp/mod-em-5.1.2.png) ## The Evolution of DAOs and the DAO Landscape Today _“A DAO is a capitalized organization in which a software protocol informs its operation, placing automation at its center and humans at its edges like how DeFi is programmable money, and NFTs are programmable media, DAOs are programmable organizations of people.”_ As we circle this overarching definition of a DAO and the promise it holds for governance, we are also going to be looking at the evolution of DAOs themselves as a tech stack. This starts, first and foremost with the original DAO as launched (and hacked) by Ethereum. Early stage DAOs, were heavily token denominated in terms of voting power and decision making. **Vertically:** In the past two years, we have seen DAOs evolve in the following ways: * **Token-based voting** * **Token Delegation-voting to protocol politicians** * **Role based Voting** In the future, if we are truly going to place automation at the center and humans at the edges, we are going to be also including: * **Reputation Based Governance (Soul bound)** * **Automated function calls** * **Smart contract based tipping points and levers** * **AI governed roles** * **Legal Wrappers and Jurisdictional Compliance** * **DAO to DAO governance **- System to System governance** The point of this spectrum is to indicate where we are today, and where this is looking to evolve in the future. This is the vertical development of DAOs. ![](@site/static/img/bootcamp/mod-em-5.1.3.png) **Horizontally:** The horizontal development of DAOs refers to the scope from which we believe DAOs will reach beyond its small niche of theory and cyberspace. “_The promise of DAOs and crypto-economics more generally is to be able to establish collective intelligences at scale.”_ What have DAOs encompassed up until this point, and how do we see it evolving? * **Protocol DAOs:** DAOs in charge of governing the mechanics of an L1 protocol, including inflation, gas fees, and so forth. * **Treasury DAOs:** DAOs in charge of managing the treasury of a protocol and any revenue that may accrue into the treasury. * **Investment DAOs:** DAOs devoted to collectively investing funds from a community or set of actors who have put funds into the DAO. * **Community DAOs:** DAOs representative of a group of individuals engaging in common activities and sharing resources, time allocation, or rewards. #### Where do we see this technology evolving into the future? * **Network States.** * **Institutional Governance via DAO.** * **Scientific Research and Learning.** The thesis here is that the businesses, organizations, and systems of tomorrow will be running this graphic on some type of on-chain organization. ## DAO Landscape and Tooling Today ![](@site/static/img/bootcamp/mod-em-5.1.4.png) ![](@site/static/img/bootcamp/mod-em-5.1.5.png) _The promise of DAOs and crypto-economics more generally is to be able to establish collective intelligences at scale. The defining attribute that makes DAO’s different from past organizations is the use of the blockchain as a root of trust such that the inputs and outputs from decisions that matter are immutable and auditable.”_ What is important to understand, is that as a framework of DAOs is designed to harmonize with the existing product stack of crypto - meaning a successful DAO will most likely depend upon the quality of the account structure of the L1 chain it is built on, have the capacity to manage fungible token contracts, non-fungible access points, and other DAO communities. But the trend is clear: As the crypto product stack emerges, more users onboard to Web3, and more tools exist for plugging and playing with different governance frameworks, we will be moving towards this idea of _establishing collective intelligences at scale._ ### Top DAO Tooling Infrastructures This is a light overview of some of the most known DAO tooling infrastructures - if you are at a conference talking to someone they will probably ask if it is an Aragorn fork, if you are into Tendermint and the Cosmos ecosystem people will want to see if you know about DAO DAO, and then of course on NEAR, we have Pagoda’s incubated Astro DAO. **Aragon (Ethereum / EVM) - the OG DAO tooling:** [https://aragon.org/how-to/build-your-dao-tooling-stack](https://aragon.org/how-to/build-your-dao-tooling-stack) Aragon is the OG DAO tooling framework on Ethereum, that has shipped a number of innovative DAO related products, usually geared towards crypto-native and internet users (reddit communities). The list below is a quick overview of some of the spin-up products on Aragon today: ![](@site/static/img/bootcamp/mod-em-5.1.6.png) The App and Client is specifically focused on governance and the ability to launch a DAO and token, as well as set parameters for users - whitelist, time delay, collateralize proposals, etc. and to set governance agreements. Aragon Voice meanwhile pertains to the nature of proposals - and how to create, pass, and set a vote policy for your DAO. Those interested in these topics further, and how Aragon is looking at the future of DAOs should refer [to their blog. ](https://blog.aragon.org/) ![](@site/static/img/bootcamp/mod-em-5.1.7.png) ![](@site/static/img/bootcamp/mod-em-5.1.8.png) ## Sputnik/Astro (NEAR) The entire next lecture is devoted to the design of Sputnik and Astro as well as the opportunity present for DAO tooling on NEAR and Aurora. For now we can say the following: the power of Sputnik V2 is that it creates an extremely customizable set of governance parameters by leveraging the NEAR Account model, and a combination of highly customizable proposal-kinds (essentially what can be done by users in a governance framework on NEAR). Astro meanwhile, is the dressed up and more User-friendly interface of Astro, that makes the Sputnik logic easy to interact with as a user. Astro has additionally added open-source libraries of ‘actions’ that any DAO could make use of, in a similar way to how Wordpress had ‘widgets’ that any person designing a website could leverage for their own. This is such that remote accounts on NEAR, are in principle able to participate in DAO governance from another L1 ecosystem. Or, conversely, that an account with no access keys, could be automated to behave and fulfill certain function calls only when specific inputs are connected. **DAO DAO(Cosmos) - [https://daodao.zone/](https://daodao.zone/) / [https://docs.daodao.zone/docs/recipes/diversify-treasury](https://docs.daodao.zone/docs/recipes/diversify-treasury)** DAO DAO is a clever and necessary mention, largely because it is IBC enabled. So in reference to our earlier discussion on the Universe of Chains and the World of Dapps, DAO DAO is DAO tooling for the entire cosmos ecosystem - such that someone can manage a treasury on one Cosmos L1, and still engage with the token / governance of another chain in parallel. And in a similar vein to how Astro has an open-source library, DAO DAO has so-called _recipes_, or existing ways of structuring your treasury. ![](@site/static/img/bootcamp/mod-em-5.1.9.png) **Tribute Labs (Ethereum) - [https://tributelabs.xyz/](https://tributelabs.xyz/) / [https://tributedao.com/docs/tutorial/extensions/creating-an-extension](https://tributedao.com/docs/tutorial/extensions/creating-an-extension)** We mention Tribute Labs in this very cursory overview, because of its integration of the OpenLaw stack with Ethereum governance tools. In short, Tribute Labs offers a DAO tooling kit that bridges the gap between existing regulatory frameworks, and the cyber-world of DAO tooling. ![](@site/static/img/bootcamp/mod-em-5.1.10.png) What we see from all of these examples, is that DAO tooling today is such that it largely centers around vote policy, and proposals from which certain recipes or existing strategies can be easily implemented by someone building the DAO. What has not been done, is customizing these libraries around the ever expanding vertical and horizontal use-cases that we referenced above. ## Conclusion We are at a point in the roll-out of DAOs, where only very early on infrastructure development has taken place, with the bulk of innovation depending on the state of the L1 Ecosystem (the account model, the oracle access, storage capacities, smart contract libraries), existing dApps and communities (protocols to govern, treasuries, investment DAOs, etc.) and new use-cases and designs that have yet to have been invented. Many are building what they believe to be _‘The Wordpress of DAOs?”_ but as we will see, there is much more customization available, that can be specified for specific verticals, libraries, and use-cases - both in a specific L1 ecosystem or for cross-chain use. We are only at the very beginning.
--- NEP: 141 Title: Fungible Token Standard Author: Evgeny Kuzyakov <ek@near.org>, Robert Zaremba <@robert-zaremba>, @oysterpack DiscussionsTo: https://github.com/near/NEPs/issues/141 Status: Final Type: Standards Track Category: Contract Created: 03-Mar-2022 Replaces: 21 Requires: 297 --- ## Summary A standard interface for fungible tokens that allows for a normal transfer as well as a transfer and method call in a single transaction. The [storage standard][Storage Management] addresses the needs (and security) of storage staking. The [fungible token metadata standard][FT Metadata] provides the fields needed for ergonomics across dApps and marketplaces. ## Motivation NEAR Protocol uses an asynchronous, sharded runtime. This means the following: - Storage for different contracts and accounts can be located on the different shards. - Two contracts can be executed at the same time in different shards. While this increases the transaction throughput linearly with the number of shards, it also creates some challenges for cross-contract development. For example, if one contract wants to query some information from the state of another contract (e.g. current balance), by the time the first contract receives the balance the real balance can change. In such an async system, a contract can't rely on the state of another contract and assume it's not going to change. Instead the contract can rely on temporary partial lock of the state with a callback to act or unlock, but it requires careful engineering to avoid deadlocks. In this standard we're trying to avoid enforcing locks. A typical approach to this problem is to include an escrow system with allowances. This approach was initially developed for [NEP-21](https://github.com/near/NEPs/pull/21) which is similar to the Ethereum ERC-20 standard. There are a few issues with using an escrow as the only avenue to pay for a service with a fungible token. This frequently requires more than one transaction for common scenarios where fungible tokens are given as payment with the expectation that a method will subsequently be called. For example, an oracle contract might be paid in fungible tokens. A client contract that wishes to use the oracle must either increase the escrow allowance before each request to the oracle contract, or allocate a large allowance that covers multiple calls. Both have drawbacks and ultimately it would be ideal to be able to send fungible tokens and call a method in a single transaction. This concern is addressed in the `ft_transfer_call` method. The power of this comes from the receiver contract working in concert with the fungible token contract in a secure way. That is, if the receiver contract abides by the standard, a single transaction may transfer and call a method. Note: there is no reason why an escrow system cannot be included in a fungible token's implementation, but it is simply not necessary in the core standard. Escrow logic should be moved to a separate contract to handle that functionality. One reason for this is because the [Rainbow Bridge](https://near.org/blog/eth-near-rainbow-bridge/) will be transferring fungible tokens from Ethereum to NEAR, where the token locker (a factory) will be using the fungible token core standard. Prior art: - [ERC-20 standard](https://eips.ethereum.org/EIPS/eip-20) - NEP#4 NEAR NFT standard: [near/neps#4](https://github.com/near/neps/pull/4) Learn about NEP-141: - [Figment Learning Pathway](https://web.archive.org/web/20220621055335/https://learn.figment.io/tutorials/stake-fungible-token) ## Specification ### Guide-level explanation We should be able to do the following: - Initialize contract once. The given total supply will be owned by the given account ID. - Get the total supply. - Transfer tokens to a new user. - Transfer tokens from one user to another. - Transfer tokens to a contract, have the receiver contract call a method and "return" any fungible tokens not used. - Remove state for the key/value pair corresponding with a user's account, withdrawing a nominal balance of Ⓝ that was used for storage. There are a few concepts in the scenarios above: - **Total supply**: the total number of tokens in circulation. - **Balance owner**: an account ID that owns some amount of tokens. - **Balance**: an amount of tokens. - **Transfer**: an action that moves some amount from one account to another account, either an externally owned account or a contract account. - **Transfer and call**: an action that moves some amount from one account to a contract account where the receiver calls a method. - **Storage amount**: the amount of storage used for an account to be "registered" in the fungible token. This amount is denominated in Ⓝ, not bytes, and represents the [storage staked](https://docs.near.org/docs/concepts/storage-staking). Note that precision (the number of decimal places supported by a given token) is not part of this core standard, since it's not required to perform actions. The minimum value is always 1 token. See the [Fungible Token Metadata Standard][FT Metadata] to learn how to support precision/decimals in a standardized way. Given that multiple users will use a Fungible Token contract, and their activity will result in an increased [storage staking](https://docs.near.org/docs/concepts/storage-staking) burden for the contract's account, this standard is designed to interoperate nicely with [the Account Storage standard][Storage Management] for storage deposits and refunds. ### Example scenarios #### Simple transfer Alice wants to send 5 wBTC tokens to Bob. Assumptions - The wBTC token contract is `wbtc`. - Alice's account is `alice`. - Bob's account is `bob`. - The precision ("decimals" in the metadata standard) on wBTC contract is `10^8`. - The 5 tokens is `5 * 10^8` or as a number is `500000000`. ##### High-level explanation Alice needs to issue one transaction to wBTC contract to transfer 5 tokens (multiplied by precision) to Bob. ##### Technical calls 1. `alice` calls `wbtc::ft_transfer({"receiver_id": "bob", "amount": "500000000"})`. #### Token deposit to a contract Alice wants to deposit 1000 DAI tokens to a compound interest contract to earn extra tokens. ##### Assumptions - The DAI token contract is `dai`. - Alice's account is `alice`. - The compound interest contract is `compound`. - The precision ("decimals" in the metadata standard) on DAI contract is `10^18`. - The 1000 tokens is `1000 * 10^18` or as a number is `1000000000000000000000`. - The compound contract can work with multiple token types. <details> <summary>For this example, you may expand this section to see how a previous fungible token standard using escrows would deal with the scenario.</summary> ##### High-level explanation (NEP-21 standard) Alice needs to issue 2 transactions. The first one to `dai` to set an allowance for `compound` to be able to withdraw tokens from `alice`. The second transaction is to the `compound` to start the deposit process. Compound will check that the DAI tokens are supported and will try to withdraw the desired amount of DAI from `alice`. - If transfer succeeded, `compound` can increase local ownership for `alice` to 1000 DAI - If transfer fails, `compound` doesn't need to do anything in current example, but maybe can notify `alice` of unsuccessful transfer. ##### Technical calls (NEP-21 standard) 1. `alice` calls `dai::set_allowance({"escrow_account_id": "compound", "allowance": "1000000000000000000000"})`. 2. `alice` calls `compound::deposit({"token_contract": "dai", "amount": "1000000000000000000000"})`. During the `deposit` call, `compound` does the following: 1. makes async call `dai::transfer_from({"owner_id": "alice", "new_owner_id": "compound", "amount": "1000000000000000000000"})`. 2. attaches a callback `compound::on_transfer({"owner_id": "alice", "token_contract": "dai", "amount": "1000000000000000000000"})`. </details> ##### High-level explanation Alice needs to issue 1 transaction, as opposed to 2 with a typical escrow workflow. ##### Technical calls 1. `alice` calls `dai::ft_transfer_call({"receiver_id": "compound", "amount": "1000000000000000000000", "msg": "invest"})`. During the `ft_transfer_call` call, `dai` does the following: 1. makes async call `compound::ft_on_transfer({"sender_id": "alice", "amount": "1000000000000000000000", "msg": "invest"})`. 2. attaches a callback `dai::ft_resolve_transfer({"sender_id": "alice", "receiver_id": "compound", "amount": "1000000000000000000000"})`. 3. compound finishes investing, using all attached fungible tokens `compound::invest({…})` then returns the value of the tokens that weren't used or needed. In this case, Alice asked for the tokens to be invested, so it will return 0. (In some cases a method may not need to use all the fungible tokens, and would return the remainder.) 4. the `dai::ft_resolve_transfer` function receives success/failure of the promise. If success, it will contain the unused tokens. Then the `dai` contract uses simple arithmetic (not needed in this case) and updates the balance for Alice. #### Swapping one token for another via an Automated Market Maker (AMM) like Uniswap Alice wants to swap 5 wrapped NEAR (wNEAR) for BNNA tokens at current market rate, with less than 2% slippage. ##### Assumptions - The wNEAR token contract is `wnear`. - Alice's account is `alice`. - The AMM's contract is `amm`. - BNNA's contract is `bnna`. - The precision ("decimals" in the metadata standard) on wNEAR contract is `10^24`. - The 5 tokens is `5 * 10^24` or as a number is `5000000000000000000000000`. ##### High-level explanation Alice needs to issue one transaction to wNEAR contract to transfer 5 tokens (multiplied by precision) to `amm`, specifying her desired action (swap), her destination token (BNNA) & minimum slippage (<2%) in `msg`. Alice will probably make this call via a UI that knows how to construct `msg` in a way the `amm` contract will understand. However, it's possible that the `amm` contract itself may provide view functions which take desired action, destination token, & slippage as input and return data ready to pass to `msg` for `ft_transfer_call`. For the sake of this example, let's say `amm` implements a view function called `ft_data_to_msg`. Alice needs to attach one yoctoNEAR. This will result in her seeing a confirmation page in her preferred NEAR wallet. NEAR wallet implementations will (eventually) attempt to provide useful information in this confirmation page, so receiver contracts should follow a strong convention in how they format `msg`. We will update this documentation with a recommendation, as community consensus emerges. Altogether then, Alice may take two steps, though the first may be a background detail of the app she uses. ##### Technical calls 1. View `amm::ft_data_to_msg({ action: "swap", destination_token: "bnna", min_slip: 2 })`. Using [NEAR CLI](https://docs.near.org/docs/tools/near-cli): ```shell near view amm ft_data_to_msg \ '{"action": "swap", "destination_token": "bnna", "min_slip": 2}' ``` Then Alice (or the app she uses) will hold onto the result and use it in the next step. Let's say this result is `"swap:bnna,2"`. 2. Call `wnear::ft_on_transfer`. Using NEAR CLI: ```shell near call wnear ft_transfer_call \ '{"receiver_id": "amm", "amount": "5000000000000000000000000", "msg": "swap:bnna,2"}' \ --accountId alice --depositYocto 1 ``` During the `ft_transfer_call` call, `wnear` does the following: 1. Decrease the balance of `alice` and increase the balance of `amm` by 5000000000000000000000000. 2. Makes async call `amm::ft_on_transfer({"sender_id": "alice", "amount": "5000000000000000000000000", "msg": "swap:bnna,2"})`. 3. Attaches a callback `wnear::ft_resolve_transfer({"sender_id": "alice", "receiver_id": "compound", "amount": "5000000000000000000000000"})`. 4. `amm` finishes the swap, either successfully swapping all 5 wNEAR within the desired slippage, or failing. 5. The `wnear::ft_resolve_transfer` function receives success/failure of the promise. Assuming `amm` implements all-or-nothing transfers (as in, it will not transfer less-than-the-specified amount in order to fulfill the slippage requirements), `wnear` will do nothing at this point if the swap succeeded, or it will decrease the balance of `amm` and increase the balance of `alice` by 5000000000000000000000000. ### Reference-level explanation NOTES: - All amounts, balances and allowance are limited by `U128` (max value `2**128 - 1`). - Token standard uses JSON for serialization of arguments and results. - Amounts in arguments and results have are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of `2**53`. - The contract must track the change in storage when adding to and removing from collections. This is not included in this core fungible token standard but instead in the [Storage Standard][Storage Management]. - To prevent the deployed contract from being modified or deleted, it should not have any access keys on its account. #### Interface ##### ft_transfer Simple transfer to a receiver. Requirements: - Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes - Caller must have greater than or equal to the `amount` being requested Arguments: - `receiver_id`: the valid NEAR account receiving the fungible tokens. - `amount`: the number of tokens to transfer, wrapped in quotes and treated like a string, although the number will be stored as an unsigned integer with 128 bits. - `memo` (optional): for use cases that may benefit from indexing or providing information for a transfer. ```ts function ft_transfer( receiver_id: string, amount: string, memo: string | null ): void; ``` ##### ft_transfer_call Transfer tokens and call a method on a receiver contract. A successful workflow will end in a success execution outcome to the callback on the same contract at the method `ft_resolve_transfer`. You can think of this as being similar to attaching native NEAR tokens to a function call. It allows you to attach any Fungible Token in a call to a receiver contract. Requirements: - Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes - Caller must have greater than or equal to the `amount` being requested - The receiving contract must implement `ft_on_transfer` according to the standard. If it does not, FT contract's `ft_resolve_transfer` MUST deal with the resulting failed cross-contract call and roll back the transfer. - Contract MUST implement the behavior described in `ft_resolve_transfer` Arguments: - `receiver_id`: the valid NEAR account receiving the fungible tokens. - `amount`: the number of tokens to transfer, wrapped in quotes and treated like a string, although the number will be stored as an unsigned integer with 128 bits. - `memo` (optional): for use cases that may benefit from indexing or providing information for a transfer. - `msg`: specifies information needed by the receiving contract in order to properly handle the transfer. Can indicate both a function to call and the parameters to pass to that function. ```ts function ft_transfer_call( receiver_id: string, amount: string, memo: string | null, msg: string ): Promise; ``` ##### ft_on_transfer This function is implemented on the receiving contract. As mentioned, the `msg` argument contains information necessary for the receiving contract to know how to process the request. This may include method names and/or arguments. Returns a value, or a promise which resolves with a value. The value is the number of unused tokens in string form. For instance, if `amount` is 10 but only 9 are needed, it will return "1". ```ts function ft_on_transfer(sender_id: string, amount: string, msg: string): string; ``` ### View Methods ##### ft_total_supply Returns the total supply of fungible tokens as a string representing the value as an unsigned 128-bit integer. ```js function ft_total_supply(): string ``` ##### ft_balance_of Returns the balance of an account in string form representing a value as an unsigned 128-bit integer. If the account doesn't exist must returns `"0"`. ```ts function ft_balance_of(account_id: string): string; ``` ##### ft_resolve_transfer The following behavior is required, but contract authors may name this function something other than the conventional `ft_resolve_transfer` used here. Finalize an `ft_transfer_call` chain of cross-contract calls. The `ft_transfer_call` process: 1. Sender calls `ft_transfer_call` on FT contract 2. FT contract transfers `amount` tokens from sender to receiver 3. FT contract calls `ft_on_transfer` on receiver contract 4. [receiver contract may make other cross-contract calls] 5. FT contract resolves promise chain with `ft_resolve_transfer`, and may refund sender some or all of original `amount` Requirements: - Contract MUST forbid calls to this function by any account except self - If promise chain failed, contract MUST revert token transfer - If promise chain resolves with a non-zero amount given as a string, contract MUST return this amount of tokens to `sender_id` Arguments: - `sender_id`: the sender of `ft_transfer_call` - `receiver_id`: the `receiver_id` argument given to `ft_transfer_call` - `amount`: the `amount` argument given to `ft_transfer_call` Returns a string representing a string version of an unsigned 128-bit integer of how many total tokens were spent by sender_id. Example: if sender calls `ft_transfer_call({ "amount": "100" })`, but `receiver_id` only uses 80, `ft_on_transfer` will resolve with `"20"`, and `ft_resolve_transfer` will return `"80"`. ```ts function ft_resolve_transfer( sender_id: string, receiver_id: string, amount: string ): string; ``` ### Events Standard interfaces for FT contract actions that extend [NEP-297](nep-0297.md) NEAR and third-party applications need to track `mint`, `transfer`, `burn` events for all FT-driven apps consistently. This extension addresses that. Keep in mind that applications, including NEAR Wallet, could require implementing additional methods, such as [`ft_metadata`][FT Metadata], to display the FTs correctly. ### Event Interface Fungible Token Events MUST have `standard` set to `"nep141"`, standard version set to `"1.0.0"`, `event` value is one of `ft_mint`, `ft_burn`, `ft_transfer`, and `data` must be of one of the following relevant types: `FtMintLog[] | FtTransferLog[] | FtBurnLog[]`: ```ts interface FtEventLogData { standard: "nep141"; version: "1.0.0"; event: "ft_mint" | "ft_burn" | "ft_transfer"; data: FtMintLog[] | FtTransferLog[] | FtBurnLog[]; } ``` ```ts // An event log to capture tokens minting // Arguments // * `owner_id`: "account.near" // * `amount`: the number of tokens to mint, wrapped in quotes and treated // like a string, although the number will be stored as an unsigned integer // with 128 bits. // * `memo`: optional message interface FtMintLog { owner_id: string; amount: string; memo?: string; } // An event log to capture tokens burning // Arguments // * `owner_id`: owner of tokens to burn // * `amount`: the number of tokens to burn, wrapped in quotes and treated // like a string, although the number will be stored as an unsigned integer // with 128 bits. // * `memo`: optional message interface FtBurnLog { owner_id: string; amount: string; memo?: string; } // An event log to capture tokens transfer // Arguments // * `old_owner_id`: "owner.near" // * `new_owner_id`: "receiver.near" // * `amount`: the number of tokens to transfer, wrapped in quotes and treated // like a string, although the number will be stored as an unsigned integer // with 128 bits. // * `memo`: optional message interface FtTransferLog { old_owner_id: string; new_owner_id: string; amount: string; memo?: string; } ``` ### Event Examples Batch mint: ```js EVENT_JSON:{ "standard": "nep141", "version": "1.0.0", "event": "ft_mint", "data": [ {"owner_id": "foundation.near", "amount": "500"} ] } ``` Batch transfer: ```js EVENT_JSON:{ "standard": "nep141", "version": "1.0.0", "event": "ft_transfer", "data": [ {"old_owner_id": "from.near", "new_owner_id": "to.near", "amount": "42", "memo": "hi hello bonjour"}, {"old_owner_id": "user1.near", "new_owner_id": "user2.near", "amount": "7500"} ] } ``` Batch burn: ```js EVENT_JSON:{ "standard": "nep141", "version": "1.0.0", "event": "ft_burn", "data": [ {"owner_id": "foundation.near", "amount": "100"}, ] } ``` ### Further Event Methods Note that the example events covered above cover two different kinds of events: 1. Events that are not specified in the FT Standard (`ft_mint`, `ft_burn`) 2. An event that is covered in the [FT Core Standard][FT Core]. (`ft_transfer`) Please feel free to open pull requests for extending the events standard detailed here as needs arise. ## 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-141: - [Minimum Viable Interface](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/fungible_token/core.rs) - The [Core Fungible Token Implementation](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/fungible_token/core_impl.rs) - [Optional Fungible Token Events](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/fungible_token/events.rs) - [Core Fungible Token tests](https://github.com/near/near-sdk-rs/blob/master/examples/fungible-token/tests/workspaces.rs) ## Drawbacks - The `msg` argument to `ft_transfer` and `ft_transfer_call` is freeform, which may necessitate conventions. - The paradigm of an escrow system may be familiar to developers and end users, and education on properly handling this in another contract may be needed. ## Future possibilities - Support for multiple token types - Minting and burning ## History See also the discussions: - [Fungible token core](https://github.com/near/NEPs/discussions/146#discussioncomment-298943) - [Fungible token metadata](https://github.com/near/NEPs/discussions/148) - [Storage standard](https://github.com/near/NEPs/discussions/145) ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). [Storage Management]: ../specs/Standards/StorageManagement.md [FT Metadata]: ../specs/Standards/Tokens/FungibleToken/Metadata.md [FT Core]: ../specs/Standards/Tokens/FungibleToken/Core.md
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs className="file-tabs"> <TabItem value="Near CLI" label="Near CLI"> ```bash # This command creates a key pair locally in .near-credentials with an implicit account as the accountId (hash representation of the public key) near generate-key ``` **Example response:** ```bash Key pair with ed25519:33Vn9VtNEtWQPPd1f4jf5HzJ5weLcvGHU8oz7o5UnPqy public key for an account "1e5b1346bdb4fc5ccd465f6757a9082a84bcacfd396e7d80b0c726252fe8b3e8" ``` </TabItem> <TabItem value="Keypom API" label="Keypom API"> ```bash export NUMBER_OF_DROPS=2 curl https://keypom.sctuts.com/keypair/$NUMBER_OF_DROPS/rootEntrophy ``` </TabItem> </Tabs>
--- id: registering-accounts title: Registering Accounts sidebar_label: Registering Accounts --- import {Github} from "@site/src/components/codetabs" In the previous tutorial, you looked at how to mint an initial circulating supply of tokens and how you could log events as per the [events standard](https://nomicon.io/Standards/Tokens/FungibleToken/Event). You then deployed the contract and saw the FTs in your wallet balance. In this tutorial, you'll learn about the [storage management](https://nomicon.io/Standards/StorageManagement) standard and how you can register accounts in your FT contract in order to prevent a malicious party from draining your contract of all its funds. ## Introduction Whenever a new person receives any fungible tokens, they're added to the `accounts` lookup map on the contract. By doing this, you're adding bytes to the contract. If you made it so any user could receive FTs for free, that system could easily be abused. Users could essentially "drain" the contract of all it's funds by sending small amounts of FTs to many accounts. For this reason, you'll want to charge users for the information they're storing and the bytes they're using on the contract. This way of charging users, however, should be standardized so it works across all contracts. *Enter the [storage management](https://nomicon.io/Standards/StorageManagement) standard* <img width="65%" src="/docs/assets/fts/storage-standard-meme.png" /> ### Storage Management Standard The storage management standard is a set of rules that govern how a contract should charge users for storage. It outlines functions and behaviors such that all contracts implementing the standard are interoperable with each other. The 3 functions you'll need to implement are: - **`storage_deposit`** - Allows a user to deposit some amount of storage to the contract. If the user over deposits, they're refunded for the excess $NEAR. - **`storage_balance_of`** - Query for the storage paid by a given user - **`storage_balance_bounds`** - Query for the minimum and maximum amount of storage needed to interact with a given contract. With these functions outlined, you could make a reasonable assumption that the flow would be: 1. If a user doesn't exist on the contract, they need to deposit some storage to cover the bytes they use. 2. Once the user deposits $NEAR via the `storage_deposit` function, they're free to interact with the contract. You might be asking yourself what the deposit amount should be. There are two ways you can go about getting this information: - Dynamically calculate the bytes every individual user would take up in the `storage_deposit` function by inserting them into `accounts` map, measuring the bytes, and then removing them from the map after. - Calculate the bytes for inserting a largest possible account ID once upon initializing the contract and simply charge every user the same amount. For the purpose of simplicity, we'll assume the second method. ## Modifications to the Contract This "bytes for longest account ID" should be stored in the contract's state such that we can pull the value during the `storage_deposit` function and ensure the user attaches enough $NEAR. Open the `src/lib.rs` file and add the following code to the `Contract` struct. If you're just joining us now, you can find the skeleton code for this tutorial in the `3.initial-supply` folder. <Github language="rust" start="21" end="35" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/lib.rs" /> You'll now need a way to calculate this amount which will be done in the initialization function. Move to the `src/internal.rs` file and add the following private function `measure_bytes_for_longest_account_id` which will add the longest possible account ID and remove it while measuring how many bytes the operation took. It will then set the `bytes_for_longest_account_id` field to the result. <Github language="rust" start="36" end="45" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/internal.rs" /> You'll also want to create a function for "registering" an account after they've paid for storage. To do this, you can simply insert them into the `accounts` map with a balance of 0. This way, you know that any account currently in the map is considered "registered" and have paid for storage. Any account that attempts to receive FTs must be in the map with a balance of 0 or greater. If they aren't, the contract should throw. <Github language="rust" start="29" end="34" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/internal.rs" /> Let's also create a function to panic with a custom message if the user doesn't exist yet. <Github language="rust" start="5" end="14" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/internal.rs" /> Now when you call the `internal_deposit` function, rather than defaulting the user's balance to `0` if they don't exist yet via: ```rust let balance = self.accounts.get(&account_id).unwrap_or(0); ``` You can replace it with the following: <Github language="rust" start="16" end="27" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/internal.rs#L16-L27" /> With this finished, your `internal.rs` should look as follows: ```rust use near_sdk::{require}; use crate::*; impl Contract { pub(crate) fn internal_unwrap_balance_of(&self, account_id: &AccountId) -> Balance { ... } pub(crate) fn internal_deposit(&mut self, account_id: &AccountId, amount: Balance) { ... } pub(crate) fn internal_register_account(&mut self, account_id: &AccountId) { ... } pub(crate) fn measure_bytes_for_longest_account_id(&mut self) { ... } } ``` There's only one problem you need to solve with this. When initializing the contract, the implementation will throw. This is because you call `internal_deposit` and the owner doesn't have a balance yet. To fix this, let's modify the initialization function to register the owner before depositing the FTs in their account. In addition, you should measure the bytes for the registration in this function. <Github language="rust" start="66" end="106" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/lib.rs" /> ### Implementing Storage Standard With this finished, you're now ready to implement the storage management standard. If you remember, the three functions you'll be implementing, we can break each down into their core functionality and decide how to proceed. - **`storage_balance_bounds`** - Query for the minimum and maximum amount of storage needed to interact with a given contract. Since you're creating a fungible token contract and the storage price won't change (unless the $NEAR cost per byte changes), the minimum and maximum storage costs should be the same. These values should be equal to the amount of bytes for the longest account ID you calculated in the `measure_bytes_for_longest_account_id` function multiplied by the current $NEAR price per byte. Switch to the `src/storage.rs` file to get started. <Github language="rust" start="119" end="129" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/storage.rs" /> - **`storage_balance_of`** - Query for the storage paid by a given user. As we mentioned earlier, you can tell if somebody has paid for storage by checking if they're in the `accounts` map. If they are, you know that they've paid the amount returned by `storage_balance_bounds`. <Github language="rust" start="131" end="138" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/storage.rs" /> - **`storage_deposit`** - Allows a user to deposit some amount of storage to the contract. If the user over deposits, they're refunded for the excess $NEAR. In order to implement this logic, you first need to get the attached deposit. You'll also need to ensure that the user hasn't already paid for storage (i.e. they're in the `accounts` map). If they are, simply refund the caller for the $NEAR they attached to the call. If the user isn't registered yet, you should get the storage cost by calling `storage_balance_bounds` and make sure they've attached enough to cover that amount. Once this if finished, you can register them and refund any excess $NEAR. <Github language="rust" start="78" end="117" url="https://github.com/near-examples/ft-tutorial/blob/main/4.storage/src/storage.rs" /> With this finished, you're ready to build and deploy the contract! ## Deploying the contract {#redeploying-contract} Since the current contract you have is already initialized, let's create a sub-account and deploy to again. ### Creating a sub-account Run the following command to create a sub-account `storage` of your main account with an initial balance of 25 NEAR which will be transferred from the original to your new account. ```bash near create-account storage.$FT_CONTRACT_ID --masterAccount $FT_CONTRACT_ID --initialBalance 25 ``` Next, you'll want to export an environment variable for ease of development: ```bash export STORAGE_FT_CONTRACT_ID=storage.$FT_CONTRACT_ID ``` Using the build script, build the deploy the contract as you did in the previous tutorials: ```bash cd 3.initial-supply && ./build.sh && cd .. && near deploy $STORAGE_FT_CONTRACT_ID out/contract.wasm ``` ### Initialization {#initialization} Now that the contract is deployed, it's time to initialize it and mint the total supply. Let's once again create an initial supply of 1000 `gtNEAR`. ```bash near call $STORAGE_FT_CONTRACT_ID new_default_meta '{"owner_id": "'$STORAGE_FT_CONTRACT_ID'", "total_supply": "1000000000000000000000000000"}' --accountId $STORAGE_FT_CONTRACT_ID ``` If you now query for the storage paid by the owner, you should see that they're registered! ```bash near view $STORAGE_FT_CONTRACT_ID storage_balance_of '{"account_id": "'$STORAGE_FT_CONTRACT_ID'"}' ``` This should return a struct. The Total amount is roughly `0.00125 $NEAR` to register and the user has 0 available $NEAR since it's all being used up to pay for registration. ```bash { total: '1250000000000000000000', available: '0' } ``` You can also query for the storage balance required to interact with the contract: ```bash near view $STORAGE_FT_CONTRACT_ID storage_balance_bounds ``` You'll see that it returns the same amount as the `storage_balance_of` query above with the min equal to the max: ```bash { min: '1250000000000000000000', max: '1250000000000000000000' } ``` ## Conclusion Today you went through and created the logic for registering users on the contract. This logic adheres to the [storage management standard](https://nomicon.io/Standards/StorageManagement) and is customized to meet our needs when writing a FT contract. You then built, deployed, and tested those changes. In the [next tutorial](5.transfers.md), you'll look at the basics of how to transfer FTs to other users.
--- id: query-data title: Accessing and Querying Historical data sidebar_label: Access & Query Historical data --- In this article, you'll find a high-level overview about the two most common use-cases for blockchain indexing, and how they can be solved using NEAR [QueryAPI](intro.md) and [BigQuery](../big-query.md). ## Overview Building a blockchain indexer depends on the kind of historical blockchain data that you want to access and query. Let's consider these two most common blockchain indexing use cases: - an indexer doing [blockchain analytics](#analytics), reporting, business intelligence, and big-data queries. - an indexer built as a backend for a [web3 dApp](#webapps) building interactive and responsive UIs, that tracks interactions over a specific smart contract. :::tip Want to learn more about indexing? Check the [Introduction to Indexers](../../../1.concepts/3.advanced/indexers.md) article. ::: ## Analytics When building a Blockchain analytics solution, you'll be creating queries to track NEAR assets, monitor transactions, or analyze on-chain events at a massive scale. Handling that huge amount of data in an optimal way so you can provide accurate results quickly requires a well designed solution. Near [BigQuery solution](../big-query.md) provides instant insights, and let you access Historical on-chain data and queries at scale. It also eliminates your need to store and process bulk NEAR protocol data; you can just query as little or as much data as you want. BigQuery does not require prior experience with blockchain technology. As long as you have a general knowledge of SQL, you'll be able create queries and unlock insights about transactions, smart contract utilization, user engagement, trends, and much more. :::tip Learn more about BigQuery in [this article](../big-query.md). ::: ### Analytics use cases Common Blockchain analytics use cases that can be managed with [BigQuery](../big-query.md): - create queries to track NEAR assets - monitor transactions - analyze on-chain events at a massive scale. - use indexed data for data science tasks, including on-chain activities - identifying trends - feeding AI/ML pipelines for predictive analysis - use NEAR's indexed data for deep insights on user engagement - smart contract utilization - insights across tokens and NFT adoption. ## WebApps Building Web3 apps that handle historical blockchain data require dedicated solutions that manage the data and reduce the latency of requests, as it's not possible to scan the whole blockchain when a user makes a request. For example, if your dApp needs to keep track of minted NFTs from a specific smart contract, you'll need to keep historical data related to that contract, the NFTs, and all the transactions in an optimized way so the dApp can provide fast responses to the user. A simple solution for developers building [NEAR Components](../../3.near-components/what-is.md) is using [QueryAPI](intro.md), a fully managed solution to build indexer functions, extract on-chain data, store it in a database, and be able to query it using GraphQL endpoints. In the NFT example, with QueryApi you can create an indexer that follow the activity of your `my-nft-contract.near` smart contract, records all activities related to it (such as minting and transfers), and provides simple endpoints to communicate with your dApp, when your application needs to display all the minted NFTs, or the related transactions to a specific NFT. QueryApi can also reduce app development time, by letting you auto-generate [NEAR component code](index-function.md#create-a-bos-component-from-query) straight from a GraphQL query. By creating the boilerplate code, you can use it to render a UI and publish your new NEAR component. :::tip Learn more about QueryAPI in this [Overview article](intro.md). ::: ### dApp use cases For a technical implementation deep-dive, check these QueryAPI tutorials: build/near-data-infrastructure/lake-framework/building-indexers/nft-indexer - [NFTs Indexer](../lake-framework/building-indexers/nft-indexer.md): an indexer that keeps track of newly minted NFT on Near blockchain. - [Posts Indexer](../../../3.tutorials/near-components/indexer-tutorials/posts-indexer.md): this indexer keeps track of every new NEAR Social post found on the blockchain. - [Social Feed Indexer](../../../3.tutorials/near-components/indexer-tutorials/feed-indexer.md): this indexer keeps track of new posts, comments, and likes on NEAR Social, so a social feed can be rendered quickly.
--- id: predeployed-contract title: Pre-deployed Contract sidebar_label: Pre-deployed Contract --- > Learn how to easily create your own non-fungible tokens without doing any software development by using a readily-available NFT smart contract. ## Prerequisites To complete this tutorial successfully, you'll need: - [A NEAR Wallet](https://testnet.mynearwallet.com/create) - [NEAR-CLI](/tools/near-cli#setup) ## Using the NFT contract ### Setup - Log in to your newly created account with `near-cli` by running the following command in your terminal: ```bash near login ``` - Set an environment variable for your account ID to make it easy to copy and paste commands from this tutorial: ```bash export NEARID=YOUR_ACCOUNT_NAME ``` :::note Be sure to replace `YOUR_ACCOUNT_NAME` with the account name you just logged in with including the `.testnet` (or `.near` for `mainnet`). ::: - Test that the environment variable is set correctly by running: ```bash echo $NEARID ``` ### Minting your NFTs NEAR has deployed an NFT contract to the account `nft.examples.testnet` which allows users to freely mint tokens. Using this pre-deployed contract, let's mint our first token! - Run this command in your terminal, however you **must replace the `token_id` value with an UNIQUE string**. ```bash near call nft.examples.testnet nft_mint '{"token_id": "TYPE_A_UNIQUE_VALUE_HERE", "receiver_id": "'$NEARID'", "metadata": { "title": "GO TEAM", "description": "The Team Goes", "media": "https://bafybeidl4hjbpdr6u6xvlrizwxbrfcyqurzvcnn5xoilmcqbxfbdwrmp5m.ipfs.dweb.link/", "copies": 1}}' --accountId $NEARID --deposit 0.1 ``` :::tip You can also replace the `media` URL with a link to any image file hosted on your web server. ::: <details> <summary>Example response: </summary> <p> ```json Log [nft.examples.testnet]: EVENT_JSON:{"standard":"nep171","version":"nft-1.0.0","event":"nft_mint","data":[{"owner_id":"benjiman.testnet","token_ids":["TYPE_A_UNIQUE_VALUE_HERE"]}]} Transaction Id 8RFWrQvAsm2grEsd1UTASKpfvHKrjtBdEyXu7WqGBPUr To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/8RFWrQvAsm2grEsd1UTASKpfvHKrjtBdEyXu7WqGBPUr '' ``` </p> </details> - To view tokens owned by an account you can call the NFT contract with the following `near-cli` command: ```bash near view nft.examples.testnet nft_tokens_for_owner '{"account_id": "'$NEARID'"}' ``` <details> <summary>Example response: </summary> <p> ```json [ { "token_id": "0", "owner_id": "dev-xxxxxx-xxxxxxx", "metadata": { "title": "Some Art", "description": "My NFT media", "media": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Olympus_Mons_alt.jpg/1024px-Olympus_Mons_alt.jpg", "media_hash": null, "copies": 1, "issued_at": null, "expires_at": null, "starts_at": null, "updated_at": null, "extra": null, "reference": null, "reference_hash": null }, "approved_account_ids": {} } ] ``` </p> </details> ***Congratulations! You just minted your first NFT token on the NEAR blockchain!*** 🎉 👉 Now try going to your [NEAR Wallet](https://testnet.mynearwallet.com) and view your NFT in the "Collectibles" tab. 👈 --- ## Final remarks This basic example illustrates all the required steps to call an NFT smart contract on NEAR and start minting your own non-fungible tokens. Now that you're familiar with the process, you can jump to [Contract Architecture](/tutorials/nfts/js/skeleton) and learn more about the smart contract structure and how you can build your own NFT contract from the ground up. ***Happy minting!*** 🪙 :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `3.0.0` - NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0` :::
--- sidebar_position: 2 --- # Integration Tests We place integration tests in JS in a separate directory at the same level as `/src`, called `/integration-tests` ([read more](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#integration-tests)), placing this folder within a `/tests` folder at root-level that contains the unit tests folder would also be plausible. Refer to this folder structure below: ```sh ├── package.json ⟵ contains `dependencies` for contract and `devDependencies` for workspaces-js tests ├── src │ └── index.js ⟵ contract code ├── node_modules └── integration-tests ⟵ integration test directory └── tests.js ⟵ integration test file ``` A sample configuration for this project's `package.json` is shown below: ```json { "name": "simple-example", "version": "0.1.0", "description": "Simple json file example", "main": "index.js", "type": "module", "license": "MIT", "directories": { "test": "test" }, "scripts": { "build": "near-sdk-js build", "test": "ava" }, "dependencies": { "near-sdk-js": "0.6.0" }, "devDependencies": { "ava": "^4.3.3", "near-workspaces": "^3.2.2" }, "ava": { "files": [ "test/**/*.ava.js" ], "require": [], "failFast": false, "timeout": "2m", "failWithoutAssertions": true, "environmentVariables": {}, "verbose": true, "nodeArguments": [] } } ``` The `tests.js` file above will contain the integration tests. These can be run with the following command from the same level as the test `package.json` file: npm test <!-- TODO: add snippets of code, living everywhere spread across docs -->
--- id: fastnear-api title: FastNEAR API sidebar_label: FastNEAR API --- A fast RPC for the NEAR blockchain, based on [Redis](https://redis.io/) and [LMDB](https://www.symas.com/lmdb). ## About FastNEAR [Fast-Near](https://github.com/fastnear/fast-near) aims to provide the fastest RPC implementation for NEAR Protocol using high-performance storage backends: - in-memory storage in Redis. - SSD optimized storage using LMDB. It is optimized for `view` call performance and ease of deploy and scaling. :::info Note about data sync FastNear doesn't sync with the NEAR blockchain on its own. Data needs to be loaded either from [NEAR Lake](https://github.com/near/near-lake-indexer) or from [Near State Indexer](https://github.com/vgrichina/near-state-indexer). ::: --- ## FastNEAR API The [FastNEAR API server](https://github.com/fastnear/fastnear-api-server-rs) provides a low-latency RPC API for wallets and explorers. ### Supported APIs #### Public Key - Public Key to Account ID mapping. - Full Access Public Key to Account ID mapping. - Any Public Key to Account ID mapping. #### Account ID - Account ID to delegated staking pools (validators). - Account ID to fungible tokens (FT contracts). - Account ID to non-fungible tokens (NFT contracts). #### Token ID - Token ID to top 100 accounts by balance (for FT contracts). :::tip V1 API [Click here](https://github.com/fastnear/fastnear-api-server-rs?tab=readme-ov-file#api-v1) to see the complete list of API endpoints and usage examples. :::
--- NEP: 21 Title: Fungible Token Standard Author: Evgeny Kuzyakov <ek@near.org> DiscussionsTo: https://github.com/near/NEPs/pull/21 Status: Final Type: Standards Track Category: Contract Created: 29-Oct-2019 SupersededBy: 141 --- ## Summary A standard interface for fungible tokens allowing for ownership, escrow and transfer, specifically targeting third-party marketplace integration. ## Motivation NEAR Protocol uses an asynchronous sharded Runtime. This means the following: Storage for different contracts and accounts can be located on the different shards. Two contracts can be executed at the same time in different shards. While this increases the transaction throughput linearly with the number of shards, it also creates some challenges for cross-contract development. For example, if one contract wants to query some information from the state of another contract (e.g. current balance), by the time the first contract receive the balance the real balance can change. It means in the async system, a contract can't rely on the state of other contract and assume it's not going to change. Instead the contract can rely on temporary partial lock of the state with a callback to act or unlock, but it requires careful engineering to avoid dead locks. ## Rationale and alternatives In this standard we're trying to avoid enforcing locks, since most actions can still be completed without locks by transferring ownership to an escrow account. Prior art: ERC-20 standard NEP#4 NEAR NFT standard: nearprotocol/neps#4 For latest lock proposals see Safes (#26) ## Specification We should be able to do the following: - Initialize contract once. The given total supply will be owned by the given account ID. - Get the total supply. - Transfer tokens to a new user. - Set a given allowance for an escrow account ID. - Escrow will be able to transfer up this allowance from your account. - Get current balance for a given account ID. - Transfer tokens from one user to another. - Get the current allowance for an escrow account on behalf of the balance owner. This should only be used in the UI, since a contract shouldn't rely on this temporary information. There are a few concepts in the scenarios above: - **Total supply**. It's the total number of tokens in circulation. - **Balance owner**. An account ID that owns some amount of tokens. - **Balance**. Some amount of tokens. - **Transfer**. Action that moves some amount from one account to another account. - **Escrow**. A different account from the balance owner who has permission to use some amount of tokens. - **Allowance**. The amount of tokens an escrow account can use on behalf of the account owner. Note, that the precision is not part of the default standard, since it's not required to perform actions. The minimum value is always 1 token. ### Simple transfer Alice wants to send 5 wBTC tokens to Bob. Assumptions: - The wBTC token contract is `wbtc`. - Alice's account is `alice`. - Bob's account is `bob`. - The precision on wBTC contract is `10^8`. - The 5 tokens is `5 * 10^8` or as a number is `500000000`. #### High-level explanation Alice needs to issue one transaction to wBTC contract to transfer 5 tokens (multiplied by precision) to Bob. #### Technical calls 1. `alice` calls `wbtc::transfer({"new_owner_id": "bob", "amount": "500000000"})`. ### Token deposit to a contract Alice wants to deposit 1000 DAI tokens to a compound interest contract to earn extra tokens. Assumptions: - The DAI token contract is `dai`. - Alice's account is `alice`. - The compound interest contract is `compound`. - The precision on DAI contract is `10^18`. - The 1000 tokens is `1000 * 10^18` or as a number is `1000000000000000000000`. - The compound contract can work with multiple token types. #### High-level explanation Alice needs to issue 2 transactions. The first one to `dai` to set an allowance for `compound` to be able to withdraw tokens from `alice`. The second transaction is to the `compound` to start the deposit process. Compound will check that the DAI tokens are supported and will try to withdraw the desired amount of DAI from `alice`. - If transfer succeeded, `compound` can increase local ownership for `alice` to 1000 DAI - If transfer fails, `compound` doesn't need to do anything in current example, but maybe can notify `alice` of unsuccessful transfer. #### Technical calls 1. `alice` calls `dai::set_allowance({"escrow_account_id": "compound", "allowance": "1000000000000000000000"})`. 1. `alice` calls `compound::deposit({"token_contract": "dai", "amount": "1000000000000000000000"})`. During the `deposit` call, `compound` does the following: 1. makes async call `dai::transfer_from({"owner_id": "alice", "new_owner_id": "compound", "amount": "1000000000000000000000"})`. 1. attaches a callback `compound::on_transfer({"owner_id": "alice", "token_contract": "dai", "amount": "1000000000000000000000"})`. ### Multi-token swap on DEX Charlie wants to exchange his wLTC to wBTC on decentralized exchange contract. Alex wants to buy wLTC and has 80 wBTC. Assumptions - The wLTC token contract is `wltc`. - The wBTC token contract is `wbtc`. - The DEX contract is `dex`. - Charlie's account is `charlie`. - Alex's account is `alex`. - The precision on both tokens contract is `10^8`. - The amount of 9001 wLTC tokens is Alex wants is `9001 * 10^8` or as a number is `900100000000`. - The 80 wBTC tokens is `80 * 10^8` or as a number is `8000000000`. - Charlie has 1000000 wLTC tokens which is `1000000 * 10^8` or as a number is `100000000000000` - Dex contract already has an open order to sell 80 wBTC tokens by `alex` towards 9001 wLTC. - Without Safes implementation, DEX has to act as an escrow and hold funds of both users before it can do an exchange. #### High-level explanation Let's first setup open order by Alex on DEX. It's similar to `Token deposit to a contract` example above. - Alex sets an allowance on wBTC to DEX - Alex calls deposit on Dex for wBTC. - Alex calls DEX to make an new sell order. Then Charlie comes and decides to fulfill the order by selling his wLTC to Alex on DEX. Charlie calls the DEX - Charlie sets the allowance on wLTC to DEX - Alex calls deposit on Dex for wLTC. - Then calls DEX to take the order from Alex. When called, DEX makes 2 async transfers calls to exchange corresponding tokens. - DEX calls wLTC to transfer tokens DEX to Alex. - DEX calls wBTC to transfer tokens DEX to Charlie. #### Technical calls 1. `alex` calls `wbtc::set_allowance({"escrow_account_id": "dex", "allowance": "8000000000"})`. 1. `alex` calls `dex::deposit({"token": "wbtc", "amount": "8000000000"})`. 1. `dex` calls `wbtc::transfer_from({"owner_id": "alex", "new_owner_id": "dex", "amount": "8000000000"})` 1. `alex` calls `dex::trade({"have": "wbtc", "have_amount": "8000000000", "want": "wltc", "want_amount": "900100000000"})`. 1. `charlie` calls `wltc::set_allowance({"escrow_account_id": "dex", "allowance": "100000000000000"})`. 1. `charlie` calls `dex::deposit({"token": "wltc", "amount": "100000000000000"})`. 1. `dex` calls `wltc::transfer_from({"owner_id": "charlie", "new_owner_id": "dex", "amount": "100000000000000"})` 1. `charlie` calls `dex::trade({"have": "wltc", "have_amount": "900100000000", "want": "wbtc", "want_amount": "8000000000"})`. - `dex` calls `wbtc::transfer({"new_owner_id": "charlie", "amount": "8000000000"})` - `dex` calls `wltc::transfer({"new_owner_id": "alex", "amount": "900100000000"})` ## Reference Implementation The full implementation in Rust can be found there: https://github.com/nearprotocol/near-sdk-rs/blob/master/examples/fungible-token/src/lib.rs NOTES: - All amounts, balances and allowance are limited by U128 (max value `2**128 - 1`). - Token standard uses JSON for serialization of arguments and results. - Amounts in arguments and results have are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of `2**53`. Interface: ```rust /******************/ /* CHANGE METHODS */ /******************/ /// Sets the `allowance` for `escrow_account_id` on the account of the caller of this contract /// (`predecessor_id`) who is the balance owner. pub fn set_allowance(&mut self, escrow_account_id: AccountId, allowance: U128); /// Transfers the `amount` of tokens from `owner_id` to the `new_owner_id`. /// Requirements: /// * `amount` should be a positive integer. /// * `owner_id` should have balance on the account greater or equal than the transfer `amount`. /// * If this function is called by an escrow account (`owner_id != predecessor_account_id`), /// then the allowance of the caller of the function (`predecessor_account_id`) on /// the account of `owner_id` should be greater or equal than the transfer `amount`. pub fn transfer_from(&mut self, owner_id: AccountId, new_owner_id: AccountId, amount: U128); /// Transfer `amount` of tokens from the caller of the contract (`predecessor_id`) to /// `new_owner_id`. /// Act the same was as `transfer_from` with `owner_id` equal to the caller of the contract /// (`predecessor_id`). pub fn transfer(&mut self, new_owner_id: AccountId, amount: U128); /****************/ /* VIEW METHODS */ /****************/ /// Returns total supply of tokens. pub fn get_total_supply(&self) -> U128; /// Returns balance of the `owner_id` account. pub fn get_balance(&self, owner_id: AccountId) -> U128; /// Returns current allowance of `escrow_account_id` for the account of `owner_id`. /// /// NOTE: Other contracts should not rely on this information, because by the moment a contract /// receives this information, the allowance may already be changed by the owner. /// So this method should only be used on the front-end to see the current allowance. pub fn get_allowance(&self, owner_id: AccountId, escrow_account_id: AccountId) -> U128; ``` ## Drawbacks - Current interface doesn't have minting, precision (decimals), naming. But it should be done as extensions, e.g. a Precision extension. - It's not possible to exchange tokens without transferring them to escrow first. - It's not possible to transfer tokens to a contract with a single transaction without setting the allowance first. It should be possible if we introduce `transfer_with` function that transfers tokens and calls escrow contract. It needs to handle result of the execution and contracts have to be aware of this API. ## Future possibilities - Support for multiple token types - Minting and burning - Precision, naming and short token name. ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
NEAR Foundation Transparency Report: Q2 2023 NEAR FOUNDATION July 10, 2023 Hello, NEAR World! Welcome to NEAR Foundation’s Transparency Report. Published quarterly, the Transparency Report explores the NEAR ecosystem’s progress, as well as the latest technology news and updates from the NEAR ecosystem. The Q2 edition of the Transparency report features a NEAR Foundation Treasury report and a variety of exciting updates on the recently announced Blockchain Operating System (BOS), the NEAR ecosystem’s thriving projects, and NEAR Foundation’s Web2.5 strategy. You’ll also get the latest on NEAR Horizon Accelerator, NDC, NEAR’s Web2 → Web3 partnerships, and more. NEAR Foundation Treasury Update At the end of Q2 2023, NEAR Foundation’s treasury totaled $0.9b, which included $349M fiat reserves, 315M NEAR ($435M at a closing price of $1.38) and $90M in Loans and Investments. Total treasury holdings declined $0.2B in the quarter, led by a fall in the price of NEAR to $1.38 from $1.99. Net $16M fiat and 1m NEAR was deployed in Q2. The NEAR Foundation has continued to adopt a highly responsible approach to treasury management in order to minimize the risk of loss in a turbulent market, while continuing capital deployment to fulfill its mission. Exposure to non-NEAR assets therefore has been limited, with fiat reserves held in highly rated Swiss bank accounts. NEAR Foundation continues to maintain sufficient resources and runway to thrive in a multi-year market downturn, deploying capital in a targeted and responsible manner to help the NEAR ecosystem thrive and remain vibrant. As a result, the NEAR Foundation is in an extremely strong position to continue to support the ongoing growth and development of the NEAR Protocol and ecosystem. A recap of NEAR’s go-forward strategy Since the Q1 transparency report, the industry has faced some significant headwinds, such as the SEC action against Binance and Coinbase. (You can see our response to the SEC action here.) Amidst a turbulent market, the NEAR Foundation’s vision and mission remain the same: we believe in building a better web — the open web — and our mission is to foster the adoption of the open web by supporting the self-sustainable growth of a decentralized NEAR ecosystem. As mentioned in the Q1 transparency report, to effectively move closer towards our collective vision, the NEAR Foundation has focused on 3 core strategies: NEAR is the Blockchain Operating System (BOS): the open web is only possible with an open operating system, which only NEAR can deliver. NEAR is a thriving, decentralized ecosystem: the open web will lead to a safer, fairer, and censorship-resistant digital world. NEAR is where Web2 goes to become Web3: the open web will be the next generation of the internet, and will only reach mainstream if users from Web2 are migrated from Web3. To achieve these strategies, NEAR Foundation is focused on two different approaches to bringing more users to NEAR. It begins with NEAR Foundation’s top-down approach to partnerships led by a world-class business development team. By working with major applications and brands with substantial, established communities, NEAR Foundation is partnering on real use cases that drive engagement on the BOS. High-traction use-cases for partnerships have primarily been around loyalty — especially across sports, gaming and retail. Q2 saw a flurry of high profile announcements, including MarbleX, Shemaroo, Alibaba Cloud, Cosmose, and Skoda. There has also been a focus on bringing projects from other Web3 ecosystems onto the BOS, and many are leveraging the decentralized frontend component of BOS, including brands like Galxe. Q2 has also seen NEAR Foundation’s bottom-up, grassroots approach continue in full swing. Decentralization is a core principle of the Foundation — it is key to the success of NEAR, as it creates a more fair and inclusive ecosystem for devs and end users alike, and continues to empower more activity in the wider community. The Foundation has supported the successful transition of the Marketing & Creatives DAO into the NDC, becoming fully autonomous entities funded by the NDC itself. The Foundation has also been supporting the NDC to be fully autonomous with its own treasury, and to take control of key community ceremonies like the Town Hall and Ecosystem Roundtable. NEAR Horizon is also a key part of the bottom-up approach, providing projects with much needed acceleration support. This quarter, Horizon launched with a bang at Consensus, and has started supporting its first batch of projects. NEAR Horizon has partnered with some top backers and service providers to ensure projects have the right resources to grow. Although not directly responsible for it, NEAR Foundation believes the overall development of the Blockchain Operating System itself — a common layer for discovering and creating open web experiences, across all blockchains — is key to enabling the ecosystem to thrive. The BOS is built on top of NEAR’s scalable, cost-effective, sustainable Layer 1. The layer 1 itself also has an ambitious roadmap to continue its groundbreaking development. The Foundation has been working closely with Pagoda and DevHub to ensure that the BOS supports the entire ecosystem and puts the builder at the heart of everything it does. Q2 Ecosystem OKR performance Throughout Q2, the ecosystem has experienced several areas of growth towards its OKRs. While the ecosystem met many of its goals, there is always work to be done. Our north star metric, Monthly Active Accounts, was at 1.1M at the end of Q2, 100k shy of the 1.2M target. We’ve seen continued strong traction from SWEAT, who are still the largest partner on NEAR in terms of MAA. The slight miss to the goal can mainly be attributed to longer than anticipated lead times in partnerships going from announcement to mainnet. The TL;DR on ecosystem OKR performance this quarter (see below for more detailed analysis): NEAR is the BOS Successful launch and migration of near.org on to the BOS — this was done at Consensus with a huge activation. Sustained growth in the NEARProtocol Twitter following, hitting 1.9M followers — slightly short of the 2.2M target. A 3X increase in our Share of Voice to 15%, a huge uplift versus the target, driven primarily by the BOS launch and key partnership announcements. 16,000 active accounts on near.org since its launch in April. NEAR is a thriving decentralized ecosystem Marketing & Creatives DAO now fully transitioned to the NDC. NDC v1 Governance is about to be rolled out after hitting its key milestone of over 1,000 humans now participating. NPS in the community remains around 30, despite a target to grow to 40. NEAR Horizon launched successfully its MVP with over 110 projects now on the platform External capital raising for projects on NEAR remains a challenge, driven mainly by the current climate. NEAR is where web2 comes to become web3 42 new strategic partners have been signed in Q2, including the announcement of 7 flagship deals and over 15 tier 2 deals. The challenge here remains the lag between announcement and launch on mainnet. OKR1: NEAR is the BOS NEAR’s Blockchain Operating System is key to the creation and maintenance of a thriving ecosystem. A common layer for creating and discovering open web experiences, the BOS is designed to be used across all blockchains — all in one browser. In this way, the entire open web can become integrated and truly composable on a global level. The BOS is an operating system designed specifically for the open web — built atop the layer 1 NEAR Protocol. Usable by any blockchain or dApp, the BOS allows the effortless creation and distribution of innovative decentralized apps across any blockchain. On the BOS, developers can build quickly using existing components in languages they already know, like Javascript, as well as leverage its social network to find, connect, and build communities on NEAR and beyond. The NEAR Protocol itself, the Layer 1, is a core part of the BOS tech stack and continues to be developed as the scalable, cost-effective, and simple backend to any Web3 tech stack. After a strong soft launch for the BOS at ETHDenver, in Q2 we saw the BOS launch fully at Consensus, transforming near.org into a full BOS gateway — meaning that the entire site is now on chain, utilizing the full benefit of the BOS tech stack. The launch was incredibly well received, seeing a solid amount of coverage across media outlets such as Bloomberg, CoinMarketCap and Coindesk, as well as a strong increase in SOV across social platforms. Near.org now has over 6,800 components from around 100 active developers, along with over 12,000 accounts. What this means is that NEAR now has over 1% of existing community members on the near.org gateway, and we continue to see members of the ecosystem onboarding to BOS, contributing and using applications. Aside from near.org component builders, from the latest Electric Capital report, there are over 500 active developers within the NEAR ecosystem. The NEAR DevHub continues to make progress evolving how developers interact with the BOS, through the launch of bounties, and support across ETHGlobal hackathon events such as ETHPrague and ETHWaterloo. NEAR DevHub is a decentralized community platform, built on the BOS, for NEAR developers to contribute to the ecosystem and stay informed about the latest news. It enables anyone to share ideas, match solutions, and access technical support and funding. NEAR Foundation also announced NEARCON 2023, which is set to return to Lisbon this November, the planning of which is already building on last year’s huge success. The nearcon.org site is now live, marking the first fully decentralized event site built on the BOS. Nearcon.org makes it possible to buy your tickets in NEAR or Fiat, and see all the upcoming information for this year’s event. Although the NEARProtocol handle will come close to 2.2M followers in Q2, there has been a conscious strategy to slow down this acquisition to focus more on engagement based activity beyond just Twitter. Our conviction — based on data analytics — is that we now have a large % of high quality, relevant followers who can keep up-to-date with NEAR news and the ecosystem. The NEARProtocol Twitter handle also saw a huge uplift in Share of Voice, achieving over 15% in June — a key metric for measuring awareness and engagement of NEAR in relation to our competitor set. This measure takes the top 1,000 influencers in Web3 and measures how many times NEAR is mentioned versus other Web3 ecosystems. This has been primarily driven by the BOS narrative itself, but also from some of the high profile partnership announcements and events. OKR2: NEAR is a thriving decentralized Ecosystem NEAR Foundation continues to make great progress in its mandate to support the decentralization of the NEAR ecosystem since the last transparency report. The NEAR Foundation remains deeply committed to supporting the decentralization of the NEAR ecosystem. By decentralizing, NEAR ensures that power lies with the community upon which the vibrant ecosystem thrives, and gives the worldwide community a voice in the future of blockchain and Web3. NEAR Digital Collective (NDC) Since the last transparency report the NDC, along with support from the Foundation, has made excellent progress with the NDC being open to funding requests, the launch of “I Am Human” for voting integrity, and purpose trusts set up for Marketing and Creatives DAOs, which will allow for greater autonomy of the DAO community. We talk about these initiatives in more detail below. The NDC — the largest decentralization project in the NEAR ecosystem to date — is bringing together users, developers, and creators throughout the ecosystem with its innovative framework of governance. By developing this framework, it allows any member of the network to have a say in how NEAR is run by combining transparency, collective decision making, evolving governance models, and self-determination in a completely new way. As part of its V1 Governance and in a partnership with Fractal, the NDC launched the I Am Human initiative, a “proof-of-personhood” where participants can get verified through a quick and simple process and mint a “Soul Bound Token”. This will facilitate integrity and fairness of the on-chain voting system, ensuring that each person can only vote once. By mid-June, the I Am Human Protocol verified over 1,000 people — a remarkable achievement for the NDC and decentralization. In Q1, the NDC launched the Community Treasury with a budget of 5.7 million NEAR to support the development of the NEAR ecosystem. Following this launch, the Governance Working Group (GWG) and Legal Working Group (LWG) worked together on a set of terms and conditions to foster transparency and accountability of contributors requesting funding from the NDC. The process is now live. The NEAR Community Treasury wallet is viewable here. Moving forward, the NDC will focus on increasing engagement and creating an even bigger impact on the community. It currently has a “Run for Office” call for contributors who want to participate in its governance and leadership. This is a great opportunity for motivated individuals to help build the open web we all believe in. The NEAR Foundation is working with the GWG (Governance Working Group) and LWG (Legal Working Group) to provide educational tools to members of the community who are thinking of building (or scaling their existing projects) on the NEAR protocol. Keep an eye out for announcements! In the meantime, to learn more about the NDC and to participate in the projects and discussions, please see here. Grassroots DAO funding activity The three core grassroots DAOs remain the key source of funding for anyone looking to build in the NEAR ecosystem. Confirming the NEAR Foundation efforts to decentralize operations and promote autonomy of the ecosystem, CreativesDAO now has set up its own community treasury via a Guernsey purpose trust similar to the NDC, and started allocating funding again. The DAO is now able to request funding directly to the NDC, making the process community-owned in its entirety. Marketing DAO followed suit and its community treasury has recently been set up. Find more details in the announcement here. In addition to the trust, the MarketingDAO Charter has now been published, outlining its governance rules. DevHub has also started the process of establishing its community treasury and we will have more developments in the near future. In the meantime, NEAR Foundation and DevHub worked together on automated flow for funding requests which greatly reduced completion time. NEAR Foundation recognises the exceptional work of the NDC and core DAOs. The Foundation will continue to support decentralization initiatives and the growth and development of the NEAR community. NEAR Horizon NEAR Horizon is an early stage accelerator, coordinated by the NEAR Foundation, that’s revolutionizing how founders and builders find support in Web3. The mission of NEAR Horizon is to attract high-quality founders to build on NEAR and support their growth by facilitating connections with the right resources all in one place. The NEAR Horizon strategy consists of three main components: the Horizon dApp, partnerships, and easily accessible content resources. Horizon dApp Horizon has seen significant growth since launching April 26th, 2023. Over 160 projects and 30 contributors have produced 1,000+ transactions. The newly added service providers (sourced from the initial RFP in Q1) all bring a unique blend of talent, expertise, and innovative solutions, contributing to the diverse and vibrant ecosystem of NEAR Horizon. Another exciting feature of Horizon is the Learn section. Founders at all stages can take advantage of a curated list of resources to best help where they need it the most, such as: Business Fundamentals, Growth and Marketing, Recruiting and Legal, and Technical areas. Horizon Partnerships For founders looking for additional support and guidance throughout their Horizon journey, the platform will also be equipped with programs facilitated through a NEAR Foundation partner, providing mentorship, business resources, and a direct line to startup capital. These programs are available through a wide range of industry leading groups including Antler, Brinc, FabricX, CV Labs, Blockchain Founders Group, Decasonic and Dragonfly amongst others. Regardless of the path founders choose to take, NEAR Horizon will provide them with the support they need when they need it most to accelerate the growth of their Web3 projects built on NEAR. Our educational program partners design hackathons, fellowships, and educational content for students, early-career engineers, and current founders. We are excited to be partnered with Encode Club and Major League Hacking, who have both kicked off their various initiatives with NEAR Horizon in Q2. In addition to working with a few chain-agnostic acceleration programs with a goal of bringing new projects to the growing NEAR ecosystem, we’ve also partnered with Outlier Ventures and Startup Wiseguys to facilitate a NEAR-specific acceleration program. The first Outlier Ventures cohort is set to kick off in July, and we look forward to bringing an update to the Q3 report. We are also partnering with Web3 communities, DAOs, and incubators to provide workshops and resources to current and aspiring founders such as the NYC demo day in partnership with Banyan Collective, and another exciting Grants Demo Day hosted by Mintbase at the end of June. Horizon was proud to host Pitch and Networking events at both Consensus and Collision, including fantastic speakers from Decasonic, Fabric, Press Start Capital and others. Over 100 projects applied to pitch and more than 500 people registered to attend and network. The NEAR Horizon team is continuing to expand our community through founder experiences, engaging over 100 founders to-date. The Horizon team hosts weekly office hours, AMAs with service providers, and product demo days for founders to source live feedback on their products. To stay current on all the activities of NEAR Horizon follow us on NEAR.social @nearhorizon.near or on twitter. OKR3: Web2 → Web3 The NEAR Foundation BD team exceeded its goal in H1 2023 by bringing 74 partners to the NEAR blockchain versus a goal of 27. The 48 partnerships closed in Q2 also marked a significant increase from the 26 in Q1. The majority of these partners were considering other chains yet chose NEAR due to its focus on bridging Web2 with Web3, usability, conservative approach, and strong partner support. Number of partnerships Actual Goal (set in Jan ‘23 based on prior year #) Q1 26 10 Q2 48 17 Total 74 27 In Q1 and Q2, BD had a targeted approach to focus on five main areas that we believe are uniquely unlocked by Web3: loyalty & rewards, social and the creator economy, gaming and the metaverse, sustainability, and infrastructure. The NEAR Foundation continues to partner with startups, as well as enterprises and governments. 16 of the 74 closed partnerships were with enterprises or governments. Category # of Partnerships (Q1 + Q2) Loyalty & rewards 19 Social/creator economy 12 Gaming/metaverse 12 Sustainability 6 Infrastructure 18 Other 7 Loyalty and rewards: Loyalty is a focus for us because loyalty in Web2 is broken. From sports teams to movie studios there is a common problem. They lack a direct relationship with their customers. Simultaneously, consumers and fans are seeking new ways to demonstrate and be rewarded for their patronage. Web3 helps loyalty programs shift to open ecosystems, enables brands to build direct relationships with customers, and fosters composability among loyalty programs. Notable partnerships: Cosmose AI — Loyalty-based shopping app that enables users to buy with crypto in order to lower transaction fees for both merchants and consumers. Cosmose represents a practical and real-world use case with initial traction in Singapore. Santo Spirit — Tequila brand of Sammy Hagar and Guy Fieri is launching a loyalty program on NEAR that includes virtual tastings, autographed collectibles and mystery NFTs for patrons. Tokenproof — Tokenproof powers custom, token-gated experiences for some of the most notable Web3 communities and the biggest Web2 brands via gated Shopify storefronts and real world interactive experiences. Creator economy: The NEAR Foundation has partnered with a number of entrepreneurs in the creator economy. These builders are using Web3 to give creators greater ownership and control, new monetization and royalty channels, and novel ways to interact with their community. Similarly, we are excited about new blockchain-based decentralized social networks and closed 2 partners who are building exclusively on NEAR (not yet announced). Notable Partnerships: SLiC Images — A digital rights-management platform for independent photographers and videographers to license and monetize their content founded and led by former NBA all-star Baron Davis and built on Mintbase technology. ARterra — ARterra is leveling up fan engagement tools for game developers, individual creators, and brands via its Web3-based battle pass, quest, and duel systems that integrate seamlessly with Web2 platforms such as Discord, Youtube Gaming, and Twitch, as well as Web3 games. Djooky — Djooky is a music streaming and discovery tool that combines an online music competition with a marketplace. Musicians can participate directly in the marketplace or get discovered by voting fans who earn rewards for being talent scouts during the quarterly competitions. Gaming and Metaverse: This is another focus area since Web3 unlocks new forms of digital ownership and in-game economies. In gaming, while not exclusively focused on Korea, we are spending considerable effort there given Korea’s history as a pioneer in gaming monetization, and Korean studios’ deep expertise in Web3, especially compared to other regions. Notable partnerships: Netmarble — One of the largest game publishers worldwide is bringing a suite of Web3 games to NEAR. Vortex — Web3 subsidiary of INVEN, the “Reddit of Korea” and largest game media community in Korea with over 7M monthly active users is building exclusively on NEAR. PipeFlare — A provider of 17 casual Web3 games is transitioning from another chain to integrate exclusively with NEAR. Sustainability: The NEAR Foundation continues to back entrepreneurs and governments trying to solve environmental problems by leveraging the blockchain. Web3 can support supply chain transparency, verification and proof of green initiatives, and carbon credit systems. Notable partnerships: SankalpTaru — One of the largest sustainability NGOs in India is leveraging the blockchain to bring accountability and transparency to afforestation activities. They have planted over 3.5 million trees and supported over 30,000 farmers. Raigarh District Administration — This district in India launched a blockchain based monitoring system for tracking industrial corporate social responsibility afforestation activities. In addition to the government participation, over 50 industry participants are involved in the initiative. Flow Carbon— One of the pioneering climate technology companies, they are working towards bringing carbon credits onto the blockchain. Carbon offsetting will become more accessible and transparent to major institutional players through leveraging the power of blockchain technology. Infrastructure: This is an important focus for NEAR Foundation partnerships as it serves as the building blocks for new use cases. We aim to foster an environment that empowers builders through innovative infrastructure that helps projects better prototype and develop, communicate, and scale. Alibaba Cloud — Alibaba Cloud is collaborating with NEAR Foundation to provide Remote Procedure Call (RPC) as a service to NEAR ecosystem projects. In addition, Alibaba Cloud will focus on multi-chain data indexing which helps drive the adoption of the Blockchain Operating System (BOS) through supporting interoperability across different blockchains. Urbit — An operating system designed to run peer-to-peer apps. Combined with the BOS, we hope to build the world’s first fully decentralized development environment. Fractal — One of the leading Web3 native identity infrastructure providers, Fractal will build important decentralized identity frameworks for the BOS. Supporting Existing Partners During Q2, the BD team also made significant progress in implementing the NEAR Foundation’s product strategy centered around the Blockchain Operating System (BOS). Workshops targeting both new potential partners and existing partners were organized, aiming to educate on the new BOS product strategy. These workshops were attended by 80% of our partners and have helped build awareness and understanding in the ecosystem about the potential of BOS in the market. Our existing partners have played a crucial role in driving our success in Q2. By collaborating closely with them and supporting their initiatives, we have achieved significant milestones and further strengthened our ecosystem. Identifying successes: SWEAT — The number 1 free app in over 60 countries which rewards users daily steps with a new-generation currency, launched a highly successful USDT campaign that acquired over 300K monthly active users (MAUs). Plans for supporting SWEAT’s launch in the US during Q3/Q4 are in place. Additionally, the testing and launch of Web3 new products, such as the Swap Feature and NFT game, are currently underway, aimed at further engaging new users. Cosmose AI — A $500M global platform that predicts and influences how people shop, secured approval from smartphone manufacturers to launch the Web3 version of their Lockscreen product, scheduled for Q4 2023. This is a significant milestone as Cosmose AI continues to apply web3 principles to further advance the AI-driven retail ecosystem. Next up in Q3 will be the launch of their cash back product (Kai-Kai) on mainnet. PlayEmber — Amobile game studio built on NEAR and backed by Big Brain Holdings, Shima Capital and others, received approval from both App Store and Google Play for the launch of the new version of their app, responsible for 51K MAUs, doubling their pre-app store listing numbers. Mintbase — A leading NFT marketplace built on NEAR celebrated the impact of their grantees on the ecosystem, highlighting their progress and achievements supported by the Mintbase Grants Program. 13 projects have been successfully nurtured through this program: NiftyRent, Namesky, QSTN, Explorins,Ailand, PWX, WallID Roketo, Gorilla Shops, Cootoo, SLIC Images, Puzzle Task, and Everything. Geographical Focus The NEAR Foundation has taken an international approach to BD focusing on North America, EMEA, and Asia, specifically Korea, India, and Singapore. While the environment in North America remains uncertain for many entrepreneurs and enterprises due to ongoing concerns around regulation, we are continuing to see strong interest in Web3 in EMEA and Asia. BD will continue to prioritize these regions in 2023. Location # of Partnerships (Q1 + Q2) North America 29 EMEA 14 Asia 29 Other 2 We have always had an international footprint, and continue to foster communities around the world to thrive. NEAR community hubs generate local awareness and onboard new users, as well as support projects building on NEAR. Led by local entrepreneurs, and operating as independent legal entities, these hubs are crucial in helping NEAR Foundation reach its missions and objectives around the world. NEAR Foundation has been supporting, through grants, two types of Regional Hub models — community hubs and partnership hubs. The goal of the community regional hubs is to build local community presence in regions, specifically targeted towards builders and those who want to get involved in NEAR’s decentralized ecosystem, as well as to build brand awareness in those regions. Partnership hubs have the specific mandate to forge deep relationships with partners in the region to build on the BOS. Starting with partnership hubs, NEAR Foundation made significant strides in expanding its presence in India and Korea during Q2, securing pivotal deals and paving the way for further geographic expansion. Korea We achieved significant progress in Korea with strategic wins, strengthening our position in what we consider a leading blockchain market. In Q1/ Q2, we closed 9 partnerships focused on gaming, entertainment and infrastructure to increase NEAR’s awareness and traction for chain adoption. Gaming is especially interesting in Korea due to the large audience, established game studios and blockchain expertise. Being a key part of the strategy, gaming has strong blockchain use cases with digital ownership, in-game economies and monetization models. We partnered with top Korean gaming industry leaders such as Netmarble’s MARBLEX, the blockchain-powered subsidiary of the well-established developer and publisher of mobile games, and Vortex Gaming, the Web3 subsidiary of Korea’s largest gaming community INVEN, to drive future growth. In addition to gaming, we announced an exciting business partnership with Mirae Asset, a subsidiary of Asia’s largest financial group, Mirae Asset Global (headquartered in South Korea), to develop Web3 technology. Xangle, a leading South Korean crypto data and research platform, has added metrics for NEAR Protocol and the Sweat Economy to make information on the NEAR ecosystem more accessible in the region. With the deals signed, partnership announcements, community activations and development activities, we are very excited for the future opportunities in Korea. India In India, we have achieved noteworthy progress on multiple fronts. In Q1/ Q2, we closed 12 partnerships focused on government, sustainability, entertainment, and the infrastructure space. Industry leading partnerships such as Skoda and Shemaroo, will act as lighthouse partnerships for the region. In addition to the enterprise use cases, NEAR enabled sustainability and impact projects with SankalpTaru and District administration Raigarh (State of Chhattisgarh) to bring transparency, traceability, and accountability in afforestation initiatives. We continue to engage with the developer community in India and raise awareness about BOS. We achieved substantial media coverage in India, further consolidating the brand awareness. In addition, we are engaging think tanks and government bodies by conducting/participating in Web3 workshops and brainstorming sessions to bridge the awareness gap. Building stronger connections with the NEAR ecosystem After efforts in generating and implementing feedback from the NEAR community, NEAR Foundation’s Community Team has kicked off several initiatives that have been driving engagement, including: Actively leveraging NEAR platforms such as the Official NEAR Discord, Telegram, and NEARProtocol Twitter, the NEAR Foundation Community Team has been running regular Twitter Spaces and AMAs with many NEAR projects to continuously surface the many amazing things being built on NEAR throughout the wider network. NEAR Foundation’s commitment to transparency and stronger community connections continues through bi-weekly live Town Halls. These sessions, which take place every other Wednesday at 3:00 pm UTC on the NEARProtocol YouTube channel, provide an open platform for the NEAR Foundation leadership team to share progress on OKRs and for the core teams to deliver updates. NEAR ecosystem project teams and NEAR Foundation partners also have the opportunity to showcase what they’re actively building on NEAR. In the endeavor to further engage and boost community interaction, a Town Hall Hub has recently been developed on the BOS. This portal aims to serve as an open forum for all discussions, recommendations, and dialogues surrounding the Town Halls. It’s not just about receiving updates — it’s also about giving the NEAR community the power to shape and participate in these conversations. To boost active community participation and drive engagement, the Foundation’s Community Team has been running weekly Quiz Night events on the NEAR Protocol Telegram. This initiative is designed to not only drive community engagement but also to create a cohesive and informed community, deeply aligned with NEAR Foundation’s mission and vision. We’ve put together a concise report on the recent success and feedback this initiative has received, which you can check out here. NEAR in the press Q2 saw a number of top news stories from NEAR’s thriving ecosystem. NEAR was covered in over 300 articles across the globe in Q2, including over 20 tier 1 stories in outlets including TechCrunch, CoinDesk, Forbes Journal du Coin , Entrepreneur India, Business Insider Africa, Yahoo Finance Yahoo Japan, Korea Herald, New Economy Japan and Bloomberg. NEAR also appeared in over 40 tier 2 publications in outlets including the Block, City AM, Blockworks, and Cointelegraph. Headlines included BOS going live, the launch of Horizon, and the Women in Web3 Changemakers list, as well as coverage from many of our partnership announcements, ecosystem hubs, and progress from many of NEAR Protocol’s ecosystem projects. Stories that made an impact included Cosmose AI partnering with NEAR protocol, collaborations with Alibaba, Skoda India, Vortex Gaming and Mirae Asset in Korea, and the launch of SailGP’s Web3 driven app The Dock, as well as Santos Spirit Tequila’s NFT. To find out more about NEAR Foundation’s and the NEAR ecosystem’s press coverage you can check out the monthly roundups below: NEAR Foundation PR Roundup for April NEAR Foundation PR Roundup for May NEAR Foundation PR Roundup for June Ecosystem Highlights NEAR Ecosystem on BOS With the announcement and launch of the Blockchain Operating system earlier this year, we have seen a splash of developments from projects both in and outside of the NEAR ecosystem building on BOS and deploying widgets and front ends. In Q2 we have seen both existing and new NEAR projects building on BOS, including Harmonic Guild, Flipside, Satori, Pikespeak, Genadrop, NEARWEEK, and others. These amazing teams are building components ranging from audio/video distribution platforms, data & analytics dashboard tools, no-code multi-chain NFT creation & minting tools, DAO tools, and news & media. We also saw an incredible example of BOS’s interoperability with Zavodil’s composable multi-chain app that seamlessly integrates with any connected blockchain wallet. Also in Q2, Galxe — a leading Web3 community building platform with over 10 million unique users to date — also deployed a component on BOS with the aim of bringing a seamless onboarding experience for SPACE ID’s referral program, “Voyage Season 2”. This integration makes Galxe the first major Web3 partner utilizing NEAR’s BOS for its offerings, simplifying the process for users to register .bnb domains and participate in the SPACE ID Voyage program through near.org. NEAR’s BOS promotes collaboration among builders by allowing them to fork and build reusable on-chain widgets, deploy decentralized front ends, as well as discover other dApps, components, and communities — all on one platform. This makes it easier for builders to create multi-chain experiences, extending NEAR beyond just being another Layer 1 network and transforming it into a decentralized OS that fosters collaboration across ecosystems. NEAR Ecosystem Project Updates In Q2, the NEAR ecosystem continued to see projects pushing large developments as well as launching on NEAR in verticals ranging from DeFi and payment solutions, to gaming and infrastructure. A few examples follow. ChangeNOW, a leading cryptocurrency payment gateway, stepped up their game by incorporating NEAR, opening up new avenues for businesses to transact using NEAR tokens. Meanwhile, WOOFi DEX made its debut into on-chain derivatives on NEAR, rolling out the beta version of its perpetual futures powered by Orderly Network. The platform offers users the convenience of centralized exchanges coupled with the self-custody benefits of decentralized exchanges, shaping the future of on-chain derivatives trading. Further diversifying NEAR’s ecosystem, Namesky launched on NEAR Mainnet in Q2. Leveraging NEAR Protocol’s default feature of unique named wallets, Namesky acts as a marketplace for buying and selling NEAR accounts as NFTs using audited contracts, akin to having Ethereum Name Service (ENS) on NEAR. Expanding NEAR’s cross-chain relationships, Duel Network (originally a BSC project) expanded their presence on NEAR with the launch of Duel Soccer. This integration not only broadens NEAR’s ecosystem but also elevates Duel Network’s visibility across multiple chains. In the realm of security/trust, Gatenox, a specialized Web3 KYC platform, integrated with NEAR, making its KYC services available to NEAR-based projects, offering an extra layer of trust and safety. Overall, although there were no projects on NEAR fundraising in Q2, the NEAR ecosystem continued to see growth, innovation, and cross-chain integration. AI, ChatGPT, and NEAR As interest in AI and ChatGPT continues to grow, we are observing increasingly innovative developments bridging between ChatGPT and NEAR. Among the pioneers working on these developments is Peter Salomonson, a seasoned NEAR builder. Salomonson has integrated NEAR with ChatGPT to create a unique widget that enables users to generate, play, and download their own custom drum beats. The Mintbase team is also adding to NEAR x ChatGPT developments by developing a versatile plugin for NEAR smart contracts and widgets. Mintbase’s integration — developed by team member Luis — is capable of writing, compiling, and deploying contracts, and it can also generate user interfaces based on the contracts’ ABI as well as deploy these interfaces as BOS widgets. These developments are a testament to the continued growth, innovation, and vibrancy of the NEAR ecosystem. They also underscore the origin story of NEAR and its deeply rooted connection with AI. Before co-founding NEAR Protocol, Illia Polosukhin had a rich history in the AI space, having worked on Google’s TensorFlow. When Illia and Alex Skidanov founded NEAR in 2017, it was originally conceived as a machine learning platform. In fact, at the time it was known as Near.ai. This background has informed NEAR’s belief in the intersection of blockchain and AI, and the potential for these technologies to work in harmony to create decentralized, intelligent systems that can drive innovation and empower individuals. For more insights on this topic, here are some recent articles featuring Illia and NEAR Foundation CEO Marieke Flament, in which they discuss the intersection of AI and blockchain and the potential of these technologies to revolutionize various industries: “Illia Polosukhin: Building Near’s Blockchain, Embedding AI”: This article discusses Illia Polosukhin’s journey to blockchain success and his work on NEAR’s blockchain, including the integration of AI. “Blockchain and AI: at the crossroads”: In this article, Marieke Flament, CEO of the NEAR Foundation, discusses the intersection of blockchain and AI, and how these technologies can be used to create a more equitable and open digital world. A Look Ahead Looking ahead to Q3, the NEAR Foundation is continuing its current strategic focus. In addition, we have worked closely with the ecosystem to paint a more complete picture of what a fully functioning Web3 ecosystem should look like, which is more of a multi pronged approach: The overarching framework is made up of three models: Participants Model — the Participants are the entities that take action within the ecosystem. This looks at three core audiences: Developers, Businesses, and Accounts. Developers build applications for Businesses, who in turn create experiences for the Accounts who interact with them. Each audience is important to monitor as each is dependent on each other. Monetization Model — the Monetization model is the lifeblood of the ecosystem, much like an economy is for a country. Monitoring how capital flows in and out, as well as the transaction volume within the ecosystem, is important to show how prosperous and active participants are within the economy. Public Goods Model — the Public Goods model underpins the framework, making it like the roads and power supply for a city. At the core is the protocol itself, but it also looks at validators and the overall health of the network. NEAR Foundation has primarily focused on the Participants Model to date, but it’s important we have observability and an aligned ecosystem approach to all metrics within all of these three models. To support this, the NEAR Foundation has helped create the Champions Sync — a collective of key ecosystem participants who are responsible for rallying the ecosystem around areas of the model that need attention. This is still in the early stages, and more about the model and action taken will be circulated shortly. NEAR Foundation will continue to focus on unique use cases that drive the adoption of Web3 technology. Our commitment to maintaining a high bar for partnerships and a disciplined approach to capital allocation will remain the cornerstone of our success. The Foundation will also continue in its bottom up support, being at the service of the community to help empower participants to get involved. We will also continue to support projects to thrive through the NEAR Horizon program. As NEAR continues to drive forward into uncertain market conditions, it’s more important than ever to prioritize the things that matter and stay true to our vision to create the Open Web. This NEAR Foundation Transparency Report (the “Report“) is provided for informational purposes only. The information contained herein is provided on an “as is” basis, and the NEAR Foundation makes no representations or warranties, express or implied, regarding the accuracy, completeness, or reliability of the information contained in this Report. The NEAR Foundation, its affiliates, directors, employees, and agents, shall not be held liable for any errors, omissions, or inaccuracies in the information provided herein. NEAR Foundation reserves the right to update, modify, or amend any information contained in this Report without prior notice. This Report is not intended to provide financial, investment, legal, tax, or any other professional advice. Readers should consult with their own professional advisors before making any decisions based on the information contained in this Report.
Refer-and-Earn 2022 Q2 Report NEAR FOUNDATION October 12, 2022 NEAR’s ever-growing and engaged community is one of the ecosystem’s greatest strengths. Remember the NEAR Foundation Grants team’s Refer-and-Earn bonus scheme? A number of NEAR community members participated in Refer-and-Earn in early 2022, resulting in grants for dozens of exciting projects currently building on the NEAR ecosystem. To demonstrate the power of the NEAR community, the Grants team just published its Refer-and-Earn Q2 2022 Report. Let’s take a look at the qualified projects currently building without limits that emerged from the Grants team’s Refer-and-Earn program. Refer-and-Earn: Q2 Qualified Projects The NEAR ecosystem is the beneficiary of a number of your recommendations and referrals. A total of 26 quality projects emerged from Refer-and-Earn—each aligning with the NEAR Foundation’s Grants program objectives. In no particular order, here are the Q2 2022 qualified projects: Ref finance Roco Finance Lazy Learning Noft Games Atocha Protocol Bast.gg Omnia Defi KwikTrust BlockHealth Marnotaur Exxaverse Mambo Heritage NEAR mates NFT Design Work The Gorilla Squad Pawn Protocol PureFi Solely NFT Kyoto protocol Deepwaters Bumper Finance Dojo Finance Loozr bit brawl Blockperks Boundless Pay The Grants team has reached out to all Refer-and-Earn referrers. Thanks to your help and support, the Grants team is able to support innovative projects such as those listed above. Start referring projects to NEAR Grants today The Grants team would like to extend an invite to those yet to participate in the Refer-and-Earn program. To get started, head over to the NEAR Grants Program Referral Initiative page. Please note that only projects receiving a grant directly from NEAR Foundation will be eligible for the Refer-and-Earn bonus. Only the first recorded referral will be paid out—duplicate records will not be considered. NEAR Foundation no longer supports DeFi-related projects. All referrals are calculated at the end of each quarter and only eligible referrals will be contacted. Please contact [email protected] for additional information or inquiries.
NEAR Foundation Unlocks Web3 B2B Solutions with SK Inc. C&C Strategic Partnership NEAR FOUNDATION September 20, 2023 The NEAR Foundation is joining forces with SK Inc. C&C, a global leader in the IT industry, to help Web3 businesses expand in the region. The collaboration brings together two teams committed to helping companies find the right Web3 tools to make their business grow. NEAR Foundation and SK Inc. C&C agree to carry out joint research, share and support partners in both ecosystems and collaborate on marketing and raising awareness. “I am very pleased to collaborate with a leading company in South Korea’s IT industry like SK Inc.C&C. This partnership is expected to serve as a significant milestone, leading to the emergence of various use cases and the creation of a user-centric ecosystem,” says Marieke Flament, CEO of NEAR Foundation. The partnership with SK Inc. C&C will leverage the NEAR Foundation’s network to strengthen its technological and business growth, connecting with SK Inc. C&C’s local corporate clients to accelerate the recruitment of outstanding companies in the Korean market. “Various attempts are being made to discover Web3 services connected with public blockchains across various industries, including public, financial, manufacturing, and distribution sectors. Starting with NEAR Protocol, we will strengthen our collaboration with already market-validated public blockchain companies and embark on expanding the Web3 service ecosystem,” says Cheol Choi, Head of the Web3 and Convergence Group at SK Inc.C&C SK Inc. C&C provides consulting services, enterprise resource planning (ERP) solutions, intelligent transportation systems (ITSs), geographic information systems (GISs), billing solutions as well as other systems and solutions used in telecommunications, financial, logistics, energy and chemical industries. The company is active in the United States, China, the Middle East and other markets in addition to South Korea. Asia in focus South Korea has become a major hub for the NEAR Community. Since launching in November of 2022, NEAR Korea Hub has hit a number of major milestones in the Korean Web3 industry. The Hub has significantly contributed to the expansion of the Web3 ecosystem over the past 6 months by forming partnerships with leading domestic technology companies, offering generous developer support, and forging long-term relationships with college blockchain clubs. The partnership with SK Inc. C&C forms part of a wider strategy to help support Asia’s role in mainstream adoption of Web3 and Open Web technologies. The NEAR Foundation’s support of ecosystems across Asia culminated in its recent NEAR APAC conference that took place in Ho Chi Minh City, Vietnam. “NEAR Protocol is actively making moves to conquer the Korean market. As evidenced by the management team’s visit to Korea during Korea Blockchain Week (KBW), where discussions were held with leading companies in various industries, we expect significant results initially led by SK Inc. C&C,” says Scott Lee, General Manager, NEAR Korea.
Filecoin Launches Collaboration with NEAR to Accelerate the Growth of the Web3 Stack COMMUNITY August 10, 2021 In July 2021, Textile launched the Filecoin-NEAR bridge, taking the first step to provide simple, permissionless storage for smart contracts on NEAR — a sharded layer 1 blockchain protocol for building user-friendly decentralized applications. The novel storage bridge creates a seamless way for NEAR applications, smart contracts, or NFTs to integrate Filecoin-based storage of any form of data. In addition, to encourage utilisation of the bridge, storage costs on Filecoin via the bridge have been and will be provided free. Today we are excited to deepen the collaboration between the Filecoin ecosystem and the NEAR ecosystem with the launch of a $300,000 joint grants program designed to support developers interested in exploring new opportunities at the intersection of these two protocols. Upon receiving a grant, projects will also gain access to the global collectives of both NEAR and Filecoin to support product development and user growth. About NEAR: A Developer Friendly, Sharded, Proof-of-Stake Public Blockchain NEAR is a decentralized application platform built to bridge the users of today’s Internet to the blockchain-based web of the future. NEAR is a PoS layer 1 blockchain platform, built with UX and DevX in mind. NEAR’s novel sharding mechanism, Nightshade, parallelizes computation on chain and automatically increases capacity when needed, resulting in theoretically infinite scalability. NEAR Protocol is built by a world-class team of engineers and entrepreneurs, who have won two ICPC world championships and medals, Google Code Jam and TopCoder. NEAR is backed by A16Z, Pantera Capital, Electric Capital, Coinbase Ventures, Blockchain.com, and Baidu Ventures. To learn more about NEAR, please visit their official website or follow their Twitter and Telegram. More than just Storage: Filecoin offers a unique Web3 Building Block Filecoin is a decentralized peer-to-peer data network, allowing anyone to store or validate data within its network. Under the hood, all Filecoin nodes use the InterPlanetary File System (IPFS), one of the most widely-used data distribution protocols for Web3. The Filecoin Network offers the following features that make it attractive for both Web2 and Web3 use cases and developers. Content Addressable Data — Filecoin is a decentralized storage network built on content addressable data at the heart of Web3. Verifiable Storage with Proofs — The Filecoin blockchain verifies that all data is continuously stored on the network every 24 hours; proof of this can be bridged to other smart contract systems. Decentralized Storage at Scale — The Filecoin network is onboarding more than 1PiB of storage capacity every hour. Flexible Storage Options — A global network of storage providers, each offering different features and local optimizations, allow for maximal composability and emergence. Filecoin brings a unique building block to the Web3 ecosystem and the intersection of NEAR and Filecoin promises new applications and use cases. You can learn more about business opportunities on Filecoin in this video. Joint Grants for Filecoin and NEAR Application Development Filecoin and NEAR are offering a $300,000 grant pool to developers. Any project that demonstrates or enables integrations between Filecoin and NEAR are encouraged to apply and all eligible projects will receive funding towards further development. Here are some potential areas of exploration: Decentralized Storage SDK + Demonstration app: An SDK for NEAR users to seamlessly employ Filecoin’s decentralized storage network, along with a demonstration application. The accompanying demonstration application should showcase the functionality of the SDK, as well as serve as a reference architecture for other NEAR developers. Database APIs: Database overlays to make interacting with raw storage on Filecoin easier and more efficient. New Web3 Applications: Novel Web3 interactions such as Data Bounties, DataDAOs, Verifiable Computation, Perpetual Storage, Layer 2 Protocols, etc., leveraging verifiable storage on Filecoin, smart contract abilities on NEAR, and data bridge built by Textile. DeFi applications that interact with textile.io or other reputation indexes for Filecoin storage providers. These applications can also utilize the Aurora Bridge. If you would like to participate in the Filecoin-NEAR Grant Program, please apply here by October 31, 2021 for consideration. Submissions will be reviewed on a rolling basis, so early submissions are encouraged.
NEAR partners with Ceramic on cross-chain identity and dynamic data storage COMMUNITY May 28, 2021 Partnership with Ceramic brings streaming data and cross-chain identity protocols to NEAR developers. Developers building on NEAR Protocol now have a powerful way to manage user identities and dynamic off-chain data in their applications. Ceramic, the decentralized network for data stream processing, now supports NEAR wallets. NEAR is currently hosting an Open Web Community Hackathon with a prize for integrating IDX profiles on Ceramic with a NEAR Sputnik DAO. To participate, check out the hackathon prize! Blockchain, Data, & Identity: a full stack for Web3 developers NEAR offers developers the most dev-friendly and end-user accessible infrastructure for building decentralized apps and services. Great Web3 and DeFi apps require more than a smart contract platform. They also need sophisticated, scalable, and dependable data management infrastructure for app builders using smart contracts. Ceramic provides advanced database-like features such as mutability, version control, access control, and programmable logic. It is also the foundation for IDX, Web3’s first cross-chain identity model. With the integration of Ceramic on NEAR Protocol, developers on NEAR can: Build data-rich user experiences and social features on fully decentralized tech Give users cloud-like backup, sync, and recovery without running a centralized server Publish content on the open web without the need to anchor IPFS hashes on-chain Leverage interoperable profiles, social graphs and reputations across the Web3 ecosystem Ceramic now supports NEAR wallets Starting today, developers building applications on NEAR can easily add support for Ceramic and IDX in their application with a seamless user experience. NEAR key pairs have been added as a supported signing and authentication method for Ceramic’s data streams, so users can now perform transactions on Ceramic with their existing NEAR wallets. Developers have already started combining NEAR and Ceramic to create new applications such as NEAR Personas, which links a NEAR wallet to a DID. About Ceramic: Decentralized data streams Ceramic provides developers with database-like functionality for storing all kinds of dynamic, mutable content. This finally gives developers a Web3 native way to add critical features like rich identities (profiles, reputation, social graphs), user-generated content (posts, interactions), dynamic application-data, and much more. Ceramic’s unique stream-based architecture is designed to handle any type of data model at web-scale volume and latency. Built on top of open standards including IPFS, libp2p, and DIDs and compatible with any raw storage protocol like Filecoin or Arweave, all information stored on Ceramic exists within a permissionless cross-chain network that lets developers tap into an ever growing library of identities and data while using their preferred stack. IDX: Cross-chain identity and user-centric data Identity is the first use case enabled by Ceramic’s building blocks for open source information. IDX (identity index) is a cross-chain identity protocol that inherits Ceramic’s properties to provide developers with a user-centric replacement for server-siloed user tables. By making it easy to structure and associate data to a user’s personal index, IDX lets applications save, discover, and route to users’ data. The IDX SDK makes it simple to manage users and deliver great data-driven experiences using the same NEAR keys and wallets as developers and users are already relying on. Users can also link multiple keys, from any wallet and multiple blockchains, to the same identity. This is essential to developers who want to serve users over time, as it enables key rotation, data interoperability across accounts, and rich cross-chain profiles, reputations and experiences. Getting started with Ceramic on NEAR NEAR is currently hosting an Open Web Community hackathon! There is a prize for integrating IDX profiles on Ceramic with theSputnik DAO platform, built on NEAR. For more information, head to the NEAR Forum. To install NEAR, start with our documentation. To add IDX to your project, follow this installation guide. To use Ceramic for streams without IDX, follow this installation guide. Regardless of which option you choose, you should also select 3ID Connect as your DID wallet during the authentication process which handles the integration with NEAR wallets. For questions or support, join the Ceramic Discord and the NEAR Discord.
A Platform for Interactive Collectibles by Renowned Artists COMMUNITY April 24, 2020 Art existed since the dawn of time, but the majority of people don’t own art due to prohibitively expensive cost of it. It’s viewed as a luxury. Private collections and public galleries existed for centuries, but the mainstream ownership of art never quite happened. As the Internet became mainstream, various forms of entertainment became digitized: notably books, music, publications, and movies. As a result, in many of these industries, the power shifted from old guard like Warner Brothers to new guard like Netflix. Art ownership didn’t quite become mainstream in its digital form, partially due to the lack of digital scarcity. As younger generation artists try to utilize new digital channels (Instagram) Artsy) to monetize their work, the Internet still feels like a place to advertise your offline work. It’s bizarre since it feels like we are not in 2020, and instead 25 years back. As it might be obvious, the younger generation is showing less affection for physical art and museums. Museums are attracting audiences 35-44, but not connecting with younger audiences, 18-24. There was a 16% increase in visitors between 35 and 44 and a 23% decrease in visitors between the ages of 18 to 24 recently. On the supply side of the market, it is very hard to become an artist that can get paid well due to a lot of issues with high priced art not being liquid. How can you enable the mass market ownership of digital art while providing more sustainable livelihood to artists? Introduction to Snark.Art For the longest time, the question of scarcity of supply of digital art was driving the question of whether digital art is marketable, as galleries were deciding on how to use online channels in distributing their physical art. Sooner or later, however, the art market had to move online. What was holding off the move to online art ever since the beginning of the Internet was the digital scarcity? With the creation of programmable platforms like Ethereum, one of the branches of experimentation focused on non-fungible tokens, such as digital assets within games and digital art. For the first time ever, the concept of digital scarcity was explored. As OpenSea and other marketplaces start to get to seven-eight digit annual volumes, digital art is inevitably a piece of this larger digital asset pie. Digital art is now scarce and secured through the use of blockchain technology. Snark.art is pioneering the evolution of this trend, adding both interactivities to otherwise simple experiences & bringing the vast network of artists into this new world. Snark.art is creating a digital art platform for artists to enable the production and selling of digital assets, management of their community, and enabling the liquidity through the secondary marketplace post the initial sale. It leads to two major advantages to artists: the ability to tap into younger demographics (by selling cheaper pieces to much larger audiences) & enabling liquidity in the marketplace that wasn’t liquid prior to this. For example, Snark.art worked with top artists like Eve Sussman who was able to distribute over 1,400 pieces of art at $120 each, leading to well over $150,000 in proceeds to the artist. An experiment in ownership and collective interaction, the piece can be reassembled and screened at will by the community of collectors. As an additional effect, the process creates a unique community of buyers who now can participate in the screening by combining their pieces to be able to see the full picture. Why Blockchain: The blockchain serves primarily three functionalities in this case: creating digital scarcity, creating divisible components that are now accessible to the mass market, and opening up secondary markets to bring liquidity in previously illiquid markets. In this case, the liquid markets over time will be able to sustain the livelihood of artists who previously wouldn’t be able to make a living while pursuing their passions. As the next generation blockchains launch in 2020, they bring both usabilities of mainstream web applications and scalability needed for the interactivity part of the experiences. As a result, we will move past simple non-fungible token experiences (e.g. CryptoKitties success in 2017) and develop the use cases unexplored before. The ideal state of the ecosystem is to enable blockchain-based marketplace with the economy on top of it, which allows artists to monetize their work directly and have the ability of the community to not only have partial ownership in future economies of digital art forms but also dictate the direction of community-owned and operated web service.
# Multi Token Enumeration :::caution This is part of the proposed spec [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) and is subject to change. ::: Version `1.0.0` ## Summary Standard interfaces for counting & fetching tokens, for an entire Multi Token contract or for a given owner. ## Motivation Apps such as marketplaces and wallets need a way to show all tokens owned by a given account and to show statistics about all tokens for a given contract. This extension provides a standard way to do so. While some Multi Token contracts may forego this extension to save [storage] costs, this requires apps to have custom off-chain indexing layers. This makes it harder for apps to integrate with such Multi Token contracts. Apps which integrate only with Multi Token Standards that use the Enumeration extension do not even need a server-side component at all, since they can retrieve all information they need directly from the blockchain. Prior art: - [ERC-721]'s enumeration extension - [Non Fungible Token Standard's](../NonFungibleToken/Enumeration.md) enumeration extension ## Interface The contract must implement the following view methods: // Metadata field is optional if metadata extension is implemented. Includes the base token metadata id and the token_metadata object, that represents the token specific metadata. ```ts // Get a list of all tokens // // Arguments: // * `from_index`: a string representing an unsigned 128-bit integer, // representing the starting index of tokens to return // * `limit`: the maximum number of tokens to return // // Returns an array of `Token` objects, as described in the Core standard, // and an empty array if there are no tokens function mt_tokens( from_index: string|null, // default: "0" limit: number|null, // default: unlimited (could fail due to gas limit) ): Token[] {} // Get list of all tokens owned by a given account // // Arguments: // * `account_id`: a valid NEAR account // * `from_index`: a string representing an unsigned 128-bit integer, // representing the starting index of tokens to return // * `limit`: the maximum number of tokens to return // // Returns a paginated list of all tokens owned by this account, and an empty array if there are no tokens function mt_tokens_for_owner( account_id: string, from_index: string|null, // default: 0 limit: number|null, // default: unlimited (could fail due to gas limit) ): Token[] {} ``` The contract must implement the following view methods if using metadata extension: ```ts // Get list of all base metadata for the contract // // Arguments: // * `from_index`: a string representing an unsigned 128-bit integer, // representing the starting index of tokens to return // * `limit`: the maximum number of tokens to return // // Returns an array of `MTBaseTokenMetadata` objects, as described in the Metadata standard, and an empty array if there are no tokens function mt_tokens_base_metadata_all( from_index: string | null, limit: number | null ): MTBaseTokenMetadata[] ``` ## Notes At the time of this writing, the specialized collections in the `near-sdk` Rust crate are iterable, but not all of them have implemented an `iter_from` solution. There may be efficiency gains for large collections and contract developers are encouraged to test their data structures with a large amount of entries. [ERC-721]: https://eips.ethereum.org/EIPS/eip-721 [storage]: https://docs.near.org/concepts/storage/storage-staking
--- id: integrate-contracts title: Integrating Contracts --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs" import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; To integrate NEAR to your frontend, you will leverage two tools: 1. `Wallet Selector`: Enables the user to select their preferred NEAR wallet in your dApp. 2. `NEAR API JS`: A suit of tools to interact with the NEAR RPC. Using those tools you will implement the following flow: 1. **Setup** a wallet selector. 1. Load the wallet selector **on start-up**. 2. Ask the user to **sign-in** using a NEAR wallet. 2. **Call methods** in the contract. --- ## Adding NEAR API JS and Wallet Selector In order to use `near-api-js` and the `wallet-selector` you will need to first add them to your project. The wallet selector has multiple wallet packages to select from, [see in their website](https://github.com/near/wallet-selector#installation-and-usage). ```bash npm install \ near-api-js \ @near-wallet-selector/core \ @near-wallet-selector/my-near-wallet \ @near-wallet-selector/ledger \ @near-wallet-selector/modal-ui ``` <details> <summary>Using `near-api-js` in plain HTML</summary> You can add `near-api-js` as a script tag in your html. ```js <script src=" https://cdn.jsdelivr.net/npm/near-api-js@3.0.4/lib/browser-index.min.js "></script> ``` </details> --- ## Create a Wallet Object In our examples we implement a [`./near-wallet.js`](https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js) module, where we abstracted the `wallet selector` into a `Wallet` object to simplify using it. To create a wallet, simply import the `Wallet` object from the module and initialize it. This `wallet` will later allows the user to call any contract in NEAR. <CodeTabs> <Language value="js" language="ts"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/layout.js" start="18" end="25" /> <Github fname="near-wallet.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js" start="35" end="56" /> </Language> </CodeTabs> Under the hood (check the `near-wallet` tab) you can see that we are actually setting up the wallet selector, and asking it if the user logged-in already. During the setup, we pass a hook to the wallet selector, which will be called each time a user logs in or out. <details markdown="1"> <summary> Setting customs RPC endpoints </summary> If you want to use a user-defined RPC endpoint with the Wallet Selector, you need to setup a [network options](https://github.com/near/wallet-selector/tree/main/packages/core#options) object with the custom URLs. For example: <CodeTabs> <Language value="js" language="ts"> ```js title="index.js" const CONTRACT_ADDRESS = process.env.CONTRACT_NAME; const my_network = { networkId: "my-custom-network", nodeUrl: "https://rpc.custom-rpc.com", helperUrl: "https://helper.custom-helper.com", explorerUrl: "https://custom-explorer.com", indexerUrl: "https://api.custom-indexer.com", }; const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS, network: my_network }); ``` </Language> </CodeTabs> :::tip You can find the entire Wallet Selector [API reference here](https://github.com/near/wallet-selector/blob/main/packages/core/docs/api/selector.md). ::: </details> #### Function Call Key When instantiating the wallet you can choose if you want to **create a [FunctionCall Key](../../1.concepts/protocol/access-keys.md#function-call-keys-function-call-keys)**. If you create the key, then your dApp will be able to **automatically sign non-payable transactions** for the user on the specified contract. --- ## Calling View Methods Once the wallet is up we can start calling view methods, i.e. the methods that perform read-only operations. Because of their read-only nature, view methods are **free** to call, and do **not require** the user to be **logged in**. <CodeTabs> <Language value="js" language="ts"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/pages/hello-near/index.js" start="12" end="25" /> <Github fname="near-wallet.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js" start="81" end="94" /> </Language> </CodeTabs> The snippet above shows how we call view methods in our examples. Switch to the `near-wallet` tab to see under the hood: we are actually making a **direct call to the RPC** using `near-api-js`. :::tip View methods have by default 200 TGAS for execution ::: --- ## User Sign-In / Sign-Out In order to interact with non-view methods it is necessary for the user to first sign in using a NEAR wallet. Signing in is as simple as requesting the `wallet` object to `signIn`, the same simplicity applies to signing-out. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/components/navigation.js" start="9" end="23" /> <Github fname="near-wallet.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js" start="58" end="72" /> </Language> </CodeTabs> When the user clicks in the button, it will be asked to select a wallet and use it to login. <hr className="subsection" /> ### Function Call Key If you instantiated the `Wallet` passing an account for the `createAccessKeyFor` parameter, then the wallet will create a [FunctionCall Key](../../1.concepts/protocol/access-keys.md#function-call-keys-function-call-keys) and store it in the web's local storage. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/layout.js" start="22" end="22" /> </Language> </CodeTabs> By default, such key enables to expend a maximum of `0.25Ⓝ` on GAS calling methods in **the specified** contract **without prompting** the user to sign them. If, on the contrary, you do not create an access key, then the user will be asked to sign every single transaction (except calls to `view methods`, since those are always free). :::tip Please notice that this only applies for **non-payable** methods, if you attach money to any call the user will **always** be redirected to the wallet to confirm the transaction. ::: --- ## Calling Change Methods Once the user logs-in they can start calling change methods. Programmatically, calling change methods is similar to calling view methods, only that now you can attach money to the call, and specify how much GAS you want to use. It is important to notice that, if you ask for money to be attached in the call, then the user will be redirected to the NEAR wallet to accept the transaction. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/pages/hello-near/index.js" start="33" end="33" /> <Github fname="near-wallet.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js" start="106" end="122" /> </Language> </CodeTabs> Under the hood (see `near-wallet` tab) we can see that we are actually asking the **wallet** to **sign a FunctionCall transaction** for us. :::tip Remember that you can use the `wallet` to call methods in **any** contract. If you did not asked for a function key to be created, the user will simply be prompt to confirm the transaction. ::: <hr className="subsection" /> ### Wallet Redirection If you attach money to a change call, then the user will be redirected to their wallet to accept the transaction. After accepting, the user will be brought back to your website, with the resulting transaction hash being pass as part of the url (i.e. `your-website.com/?transactionHashes=...`). If the method invoked returned a result, you can use the transaction hash to retrieve the result from the network. Assuming you created the `near` object as in the [example above](#connecting-to-a-contract), then you query the result by doing: <CodeTabs> <Language value="js" language="js"> <Github fname="utils.js" url="https://github.com/near-examples/hello-near-examples/blob/main/frontend/src/wallets/near-wallet.js" start="132" end="140" /> </Language> </CodeTabs> --- ## Handling Data Types When calling methods in a contract, or receiving results from them, you will need to correctly encode/decode parameters. For this, it is important to know how the contracts encode timestamps (u64) and money amounts (u128). ##### Time The block timestamp in a smart contract is encoded using nanoseconds (i.e. 19 digits: `1655373910837593990`). In contrast, `Date.now()` from javascript returns a timestamp in milliseconds (i.e 13 digits: `1655373910837`). Make sure to convert between milliseconds and nanoseconds to properly handle time variables. ##### Money Smart contracts speak in yocto NEAR, where 1Ⓝ = 10^24yocto, and the values are always encoded as `strings`. - Convert from NEAR to yocto before sending it to the contract using `near-api-js.utils.format.parseNearAmount(amount.toString())`. - Convert a response in yoctoNEAR to NEAR using `near-api-js.utils.format.formatNearAmount(amount)` :::tip If the contract returns a `Balance` instead of a `U128`, you will get a "scientific notation" `number` instead of a `string` (e.g. `10^6` instead of `"1000000"`). In this case, you can convert the value to NEAR by doing: ```js function formatAmount(amount) { let formatted = amount.toLocaleString('fullwide', { useGrouping: false }) formatted = utils.format.formatNearAmount(formatted) return Math.floor(formatted * 100) / 100 } ``` ::: --- ## Leveraging NEAR API JS NEAR API JS does not limit itself to simply calling methods in a contract. In fact, you can use it to transform your web-app into a rich user experience. While we will not cover these topics in depth, it is important for you to know that with NEAR API JS you can also: - **[Sign and verify messages](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/verify-signature.js)**: this is very useful to prove that a message was created by the user. - **[Create batch transactions](https://github.com/near/near-api-js/tree/master/packages/cookbook/transactions/batch-transactions.js)**: this enables to link multiple [actions](../../1.concepts/protocol/transaction-anatomy.md#actions) (e.g. multiple function calls). If one of the transactions fails, then they are all reverted. - **[Create accounts](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts/create-testnet-account.js)**: deploy accounts for your users! Check the [cookbook](/tools/near-api-js/cookbook) to learn how to supercharge your webapp.
--- sidebar_position: 5 --- # Optimization The options presented here can lead to decreased security and should only be used with clear understanding of the implications. ## Trust Mode The default trust model of BWE is to encourage risk-free composability by sandboxing all embedded BWE components by default. There are cases where this might not be necessary, such as: - embedding your own components - embedding components from other developers you trust - embedding components you have audited for malicious behavior and are locked to a specific version If a component does not need to be sandboxed, you can change the `trust` mode on the embed and the component will be directly executed in the same container instead of having a separate sandboxed iframe created for it. This can yield significant performance improvements for pages which render many components (e.g. social feeds). There are two modes for loading a Component: **sandboxed** (default) and **trusted**. These modes make it possible to define the boundaries within Component trees, granting developers more control over the balance of performance and security in their applications. ### Sandboxed Sandboxed Components are run in a dedicated container, independent of their parent Component's context. All communication between parent and child (e.g. re-rendering, `props` method invocation) is handled via `postMessage` communication through the outer application. If no trust modes are specified, every Component is sandboxed in a separate container. ### Trusted When a Component is loaded as **trusted**, the parent Component inlines the child Component definition into its own container and renders it as a child DOM subtree. In short, embedding a component as trusted removes some application overhead but gives the embedded component the ability to read or manipulate the parent component's state and DOM. ### Usage By default, Components are loaded in **sandboxed** mode. To change the loading policy, configure the `trust` prop with a desired `mode` property The following modes are supported: - **sandboxed** (default): load this Component in its own container - **trusted**: load this Component within the parent Component - **trusted-author**: extends the **trusted** mode by inlining this Component and all descendant Components from the same author #### Sandboxed ```jsx import Foo from 'near://bwe-demos.near/Foo' // ... {/* omitting the `trust` prop would have the same behavior */} <Foo trust={{ mode: "sandboxed" }} src="ex.near/Parent" /> ``` #### Trusted ```jsx import Foo from 'near://bwe-demos.near/Foo' // ... <Foo trust={{ mode: "trusted" }} src="ex.near/Parent" /> ``` #### Trusted Author ```jsx import Foo from 'near://bwe-demos.near/Foo' // ... {/* Root Component */} <Foo trust={{ mode: "trusted-author" }} src="ex.near/Parent" /> {/* Parent Component */} <> {/* trusted: same author */} <Foo src="ex.near/X" id="x-implicit" /> {/* trusted: same author, explicitly trusted; note that descendants of Y authored by ex.near will still be trusted */} <Foo src="ex.near/Y" trust={{ mode: "trusted" }} id="y" /> {/* sandboxed: explicitly sandboxed, same author behavior is overridden */} <Foo src="ex.near/X" trust={{ mode: "sandboxed" }} id="x-sandboxed" /> {/* sandboxed: different author, no trust specified */} <Foo src="mal.near/X" id="x-mal" /> </> ``` ### Notes - The root Component is always loaded as **sandboxed**. - The `trust` prop must be specified as an object literal with literal values; i.e. the value may not contain any variables or be returned from a function. Loading happens prior to rendering, so the trust must be statically parseable. Any Component renders with a `trust` value that cannot be parsed statically are treated as **sandboxed**.
--- id: maintenance title: Node Update and Network Upgrade sidebar_label: Node Update and Network Upgrade sidebar_position: 2 description: NEAR Node Update and Network Upgrade --- ## Nearcore Releases {#updating-a-node} As a decentralized network, every update to NEAR Protocol needs some coordination between end users, platforms, developers, and validators. NEAR merges nearcore updates from nearcore release on Github: https://github.com/near/nearcore/releases. For each nearcore release, the release notes indicate the nature of the release: ``` CODE_COLOR: CODE_YELLOW_MAINNET // This field indicates the release tag (see below). RELEASE_VERSION: 1.23.0 // This field indicates the nearcore version. PROTOCOL_UPGRADE: TRUE // This indicates that is a protocol upgrade and therefore a required upgrade. DATABASE_UPGRADE: TRUE // This field indicates that database migration is needed. SECURITY_UPGRADE: FALSE // This field indicates this release does not contain a security upgrade. ``` ## Nearcore Release Schedule {#nearcore-planned-updates} The nearcore release schedule is shown on the public [NEAR Community Google Calendar](https://calendar.google.com/calendar/u/0/embed?src=nearprotocol.com_ltk89omsjnc2ckgbtk6h9157i0@group.calendar.google.com). Typically, `testnet` and `mainnet` releases are five weeks apart to allow nearcore to be tested thoroughly on `testnet` before promotion to `mainnet`. From time to time, due to changes in engineering calendar and the nature of the release, release dates may change. Please refer to the [NEAR Community Google Calendar](https://calendar.google.com/calendar/u/0/embed?src=nearprotocol.com_ltk89omsjnc2ckgbtk6h9157i0@group.calendar.google.com) for the most updated release dates. - `testnet` Wednesday at 15:00 UTC. The release tag is mapped with `x.y.z-rc.1` - `mainnet` Wednesday at 15:00 UTC. The release tag is mapped with `x.y.z` <blockquote class="warning"> <strong>Heads up</strong><br /><br /> `betanet` provides cutting-edge testing grounds for validators, with daily updates and frequent hard-forks. For more information on nodes that are running on `betanet`, please see the [betanet analysis group on the governance forum](https://gov.near.org/t/betanet-analysis-group-reports/339). </blockquote> ## Nearcore Emergency Updates {#nearcore-emergency-updates} We may issue a `[CODE_YELLOW_TESTNET]` or `[CODE_YELLOW_MAINNET]` if the network is suffering minor issues, or a new software release introduces incompatibilities and requires additional testing. NEAR Protocol team will use the tag `[CODE_RED_TESTNET]` or `[CODE_RED_MAINNET]` in the Validator Announcement channel on [Discord](https://discord.gg/xsrHaCb), followed by email instructions for coordination. Some updates may follow a confidential process, as explained on [nearcore/SECURITY.md](https://github.com/near/nearcore/blob/master/SECURITY.md) docs. NEAR's team will be mostly active on [Github](https://github.com/near/nearcore), and with limited participation on Discord and Telegram. ## Runtime Alerts {#runtime-alerts} To keep our network healthy and minimize the damage of potential incidents, the NEAR team would like to establish a process with which we communicate updates and emergency situations with validators so that they can respond promptly to properly sustain the operations of the network. To this end, we propose that we use different tags in important messages to validators so that they can be easily picked up by automated systems on validators’ end. The tags we propose are as follows: `[CODE_RED_<network_id>]` where `<network_id>` is either `MAINNET` or `TESTNET`. This represents the most dire and urgent situation. Usually it means that the network has stalled or crashed and we need validators to take **immediate** actions to bring the network up. Alternatively it could mean that we discovered some highly critical security vulnerabilities and a patch is needed as soon as possible. If it is about mainnet, we expect that validators will react immediately to such alerts, ideally within 30 minutes. `[CODE_YELLOW_<network_id>]` where `<network_id>` is either `MAINNET` or `TESTNET`. This represents a less urgent announcement. Usually it means the release of a protocol change or a fix of a moderate security issue. In such cases, validators are not expected to take immediate actions but are still expected to react within days. `[CODE_GREEN_<network_id>]` where `<network_id>` is either `MAINNET` or `TESTNET`. This usually means some general announcement that is more informational or doesn’t require actions within a short period of time. It could be an announcement of a release that improves performance or a fix some minor issues. Call-to-actions for technical teams if the network is stalling and there's the need to coordinate a manual node restart. Such messages begin with `[CODE_RED_BETANET]` or `[CODE_RED_TESTNET]`, and will be posted in the read-only Validator Announcement channel on [Discord](https://discord.gg/xsrHaCb). The same message may be repeated in other channels, to have higher outreach. >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
# Applying chunk ## Inputs and outputs Runtime.apply takes following inputs: * trie and current state root * *validator_accounts_update* * *incoming_receipts* * *transactions* and produces following outputs: * new state root * *validator_proposals* * *outgoing_receipts* * (executed receipt) *outcomes* * *proof* ## Processing order * If this is first block of an epoch, dispense [epoch rewards](../Economics/Economic.md#validator-rewards-calculation) to validators (in order of *validator_accounts_update.stake_info*) * Slash locked balance for malicious behavior (in order of *validator_accounts_update.slashing_info*) * If [treasury account](../Economics/Economic.md#protocol-treasury) was not one of validators and this is first block of an epoch, dispense treasury account reward * If this is first block of new version or first block with chunk of new version, apply corresponding migrations * If this block do not have chunk for this shard, end process early * Process [transactions](Transactions.md) (in order of *transactions*) * Process local [receipts](Receipts.md) (in order of *transactions* that generated them) * Process delayed [receipts](Receipts.md) (ordered first by block where they were generated, then first local receipts based on order of generating *transactions*, then incoming receipts, ordered by *incoming_receipts* order) * Process incoming [receipts](Receipts.md) (ordered by *incoming_receipts*) When processing receipts we track gas used (including gas used on migrations). If we use up gas limit, we finish processing the last receipt and stop to process delayed receipts, and for local and incoming receipts we add them to delayed receipts. * If any of the delayed receipts were processed or any new receipts were delayed, update indices of first and last unprocessed receipts in state * Remove duplicate validator proposals (for each account we only keep last one in receipts processing order) Please note that local receipts are receipts generated by transaction where receiver is the same as signer of the transaction ## Delayed receipts In each block we have maximal amount of Gas we can use to process receipts and migrations, currently 1000 TGas. If any incoming or local receipts are not processed due to lack of remaining Gas, they are stored in state with key <pre>TrieKey::DelayedReceipt { id }</pre> where id is unique index for each shard, assigned consecutively. Currently sender does not need to stake any tokens to store delayed receipts. State also contains special key <pre>TrieKey::DelayedReceiptIndices</pre> where first and last ids of delayed receipts not yet processed are stored.
NEAR Balkans’ Tekuno and Mastercard Team Up for Gamified NFT Experience NEAR FOUNDATION April 7, 2023 NEAR Foundation is thrilled to announce that Tekuno, one of the most innovative NEAR Balkans Hub projects, recently teamed up with Mastercard to serve up an incredibly unique real-life NFT experience. Attendees at the recent Money Motion (MoMo) Fintech conference in Zagreb, Croatia got a taste of how Web3 and NEAR can help brands reach new audiences with blockchain gamification. Mastercard, a leader in global payment systems, enabled the Tekuno team and NEAR Balkans to realize this ground-breaking experience with NFTs. The NFT activation provided MoMo visitors with a gamified experience through which they could gather evidence of their participation at the conference and various NFTs — a concept called Proof of Doings (PODs). These PODs had time and space restrictions, so participants could only pick them up during a particular period of the conference. PODs demonstrated a novel use case of how NFTs can be used to gamify real life, while strengthening Mastercard’s brand as forward-thinking in the loyalty and payments space. Behind the Tekuno and Mastercard partnership The city of Zagreb, Croatia, recently hosted the first edition of an exclusive FinTech conference called Money Motion. With Mastercard as one of the conference organizers and NEAR Balkans as a sponsor, this presented the perfect opportunity for collaboration. Before the conference, NEAR Balkans Hub’s Product Lab was ready to launch Tekuno, a blockchain as a service (BaaS) platform for NFT experiences. A user-friendly product for seamless onboarding of mass audiences to Web3, the Tekuno platform makes blockchain knowledge a preference rather than a requirement. Tekuno can be used for a variety of campaigns and experiences, including loyalty programs, marketing activations and events, CRM, HR initiatives, and much more. The technology does this through the creation of secure and transparent Proof-of-Doings (PODs) in the form of digital collectibles (NFTs) to attest and reward a wide range of activities. For the “Experience the Motion” campaign, Tekuno was used as proof-of-attendance. How MoMo attendees claimed NFT PODs In “Experience the Motion”, MoMo attendees proved their attendance by collecting a total of 5 different NFT PODs. These PODs were exclusive — attendees could only claim them at specific times during the conference.Attendees claimed their PODs by simply scanning QR codes at several predefined locations — the entrance, speakers presentations and panels, and the NEAR Balkans booth. The PODs functioned as a prize raffle gateway, which attendees entered by following certain rules. MoMo attendees competed for a number of exciting prizes, including: exclusive Mastercard merchandise; a special 1–2–1 session with Christian Rau, Senior Vice President Crypto and Fintech Enablement Mastercard Europe; an invitation to a Web3 NEAR educational workshop, VIP access tickets for conference party; and the grand prize — a Mastercard Priceless.com experience at Chiavalon, Istria, an olive oil making and tasting experience for two. NEAR Balkans and Mastercard campaign results The “Experience the Motion” ultimately reached more than 14,000 people on social media, and was available for over 1,000 attendees over two days of the conference. Tekuno’s user-friendly technology made it possible to distribute more than 500 PODs to more than 200 unique collectors. Feedback from the attendees regarding the NFT experience and rewards was overwhelmingly positive. Participants found the Tekuno platform to be intuitive and easy to navigate. Participants were able to easily open accounts, allowing them to follow the challenges and collect the PODs for a chance at winning exciting prizes. “This is the most seamless experience I have ever had with a Web3 app, and I’ve experimented with many, trust me,” said Vlaho Hrdalo, Lawyer and Chairman of UBIK — Croatian Association for Blockchain and Cryptocurrency. Nikola Škorić, the CEO of Electrocoin, Gold sponsor of the conference, added: “‘Experience the Motion ’ — the NFT activation made possible by Mastercard and organized by NEAR Balkans and Tekuno for the Money Motion conference, engaged our audience in an authentic and fun way that brought extra value to the conference while rewarding the luckiest ones.” “We’re happy that Money Motion is a place of technology adoption and that brands see us as a great partner for such activities,” Škorić added. Driving engagement with NFTs As Mastercard and NEAR Balkans noted, many attendees, who ranged from fintech professionals to regional bank representatives, retail marketing leads, and others were particularly interested in Tekuno’s various use-cases. Indeed, it demonstrated the real-world applications and versatility of NFTs, helping traditional industries see the value in Web3 integrations. Gea Kariž, Marketing Director at Mastercard Croatia, shared her insights on the successful collaboration between Mastercard, Money Motion, Tekuno, and NEAR Balkans. ‘’Our collaboration with the Tekuno and NEAR Balkans teams provided Mastercard HR with a seamless and exceptional entrance into the Web3 domain,” said Kariž. “Through this activation, we not only gained significant brand visibility but also reinforced our commitment to embracing blockchain and other cutting-edge technologies.” “The added value of this campaign was the deep engagement we experienced with our end-users, fostering a strong sense of community around our brand and further solidifying our position as a forward-thinking and innovative company,” Kariž added. The NEAR Balkans General Manager, Ida Pandur, was similarly inspired by the partnership — especially as it aligns with NEAR Foundation’s Web2.5 strategy of onboarding the masses with real use cases in Web3. ‘’We at NEAR Balkans are committed to help and enable mass adoption of Web3 and decentralization into everyday lives,” said Pandur. “The way we do it is by educating, enabling and partnering with innovative organizations to bring Web3 to users in simple, value added, use cases. We are happy to have been working with Mastercard and use Tekuno, which is one of the best Web2→Web3 tools UX wise to bring it to life at MoneyMotion and from the interest we see across the region, it’s just getting started.’’ Sally Meouche-Grawi, CEO of Tekuno, noted that the campaign illustrated how Tekuno demonstrated that Web3 products can be user-friendly. “We’re trying to make it as user friendly as possible, but it’s still realistically a Web3 product, but it’s a Web3 product that is easy to use,” said Meouche-Grawi. “And this is what a lot of these products are critically lacking, which is the easy onboarding experience.” “So, we are trying to set the standard… to show how we can create a Web3 product that any average user can actually use,” Meouche-Grawi added. “Because from my experience when it comes to Web3 products they are usually developed by developers for developers, this is the trend and we are trying to break it.’’
Open Call for Feedback on NEAR Protocol Validator Delegation Proposals COMMUNITY September 14, 2023 Validators are the backbone of the NEAR Protocol, playing an integral role in upholding the network’s core values now and into the future. Validators ensure that NEAR Protocol remains scalable, user-friendly, secure, trustworthy, and most importantly, decentralized. NEAR validators provided community feedback on how to improve the validator experience, and we collectively listened. Responses suggested that routes to secure funding were unclear, and that existing delegations from the NEAR Foundation lacked transparency. The result of the community feedback process is a new NEAR Protocol Validator Delegation Proposal and an open call RFP to coordinate the NEAR Protocol Institutional Validator Programme. The RFP will be open until Monday September 24th, 2023. Drafted in collaboration with a number of ecosystem participants — Meta Pool, Banyan Collective, DevHub, Pagoda, Proximity, Validator Community, and NEAR Foundation — this proposal creates a framework for a refreshed validator delegation structure. It clearly defines a number of expectations for validators, aims to align incentives, assigns ownership, and enhances transparency around securing funding support. The proposal’s framework addresses three delegation tracks — community validators, institutional validators, and 100% fee project validators — with the goals of improving transparency, strengthening the Nakamoto coefficient of the NEAR Protocol, and increasing validator selection at custody providers: Community Validators — Individual participants or smaller entities within the NEAR Protocol ecosystem who choose to operate validator nodes. They are strong advocates of NEAR Protocol’s principles and values, and actively contribute to the decentralization and security of the blockchain. The proposal addresses issues that Community Validators face, including resource constraints, rewards, vulnerability to attacks, and limited influence, building on new proposals for Community validators put forward in June. Institutional Validators — Typically large entities, such as companies, financial institutions, or well-established organizations. They often have significant resources and stake in the NEAR Protocol, which allows them to operate powerful and reliable infrastructure to maintain the blockchain. This proposal addresses concerns around institutional validators such as network centralization, lack of community inclusivity, and inequality in influence. 100% Fee Project Validators — A track to support growth activities resulting in onboarding of users to the NEAR Protocol, and continued engagement through retention programmes. Firstly, check out the full NEAR Protocol Validator Delegation Proposal and provide any feedback publicly here. Your feedback is greatly appreciated to improve the proposal. Secondly, since this is an open call RFP to run the NEAR Protocol Institutional Validator programme, please return any applications to [email protected]. Additionally, Restaking is coming to NEAR courtesy of Octopus Network. Under Octopus 2.0, $NEAR stakers will have the ability to secure appchains with their staked $NEAR. Find out more here Many thanks for your continued support to improve the validator experience and help secure the NEAR Protocol.
# Trie API Here we provide a specification of trie API. After this NEP is merged, the cases where our current implementation does not follow the specification are considered to be bugs that need to be fixed. --- ```rust storage_write(key_len: u64, key_ptr: u64, value_len: u64, value_ptr: u64, register_id: u64) -> u64 ``` Writes key-value into storage. ###### Normal operation - If key is not in use it inserts the key-value pair and does not modify the register; - If key is in use it inserts the key-value and copies the old value into the `register_id`. ###### Returns - If key was not used returns `0`; - If key was used returns `1`. ###### Panics - If `key_len + key_ptr` or `value_len + value_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`. (When we say that something panics with the given error we mean that we use Wasmer API to create this error and terminate the execution of VM. For mocks of the host that would only cause a non-name panic.) - If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`; ###### Current bugs - `External::storage_set` trait can return an error which is then converted to a generic non-descriptive `StorageUpdateError`, [here](https://github.com/nearprotocol/nearcore/blob/942bd7bdbba5fb3403e5c2f1ee3c08963947d0c6/runtime/wasm/src/runtime.rs#L210) however the actual implementation does not return error at all, [see](https://github.com/nearprotocol/nearcore/blob/4773873b3cd680936bf206cebd56bdc3701ddca9/runtime/runtime/src/ext.rs#L95); - Does not return into the registers. --- ```rust storage_read(key_len: u64, key_ptr: u64, register_id: u64) -> u64 ``` Reads the value stored under the given key. ###### Normal operation - If key is used copies the content of the value into the `register_id`, even if the content is zero bytes; - If key is not present then does not modify the register. ###### Returns - If key was not present returns `0`; - If key was present returns `1`. ###### Panics - If `key_len + key_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`; - If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`; ###### Current bugs - This function currently does not exist. --- ```rust storage_remove(key_len: u64, key_ptr: u64, register_id: u64) -> u64 ``` Removes the value stored under the given key. ###### Normal operation Very similar to `storage_read`: - If key is used, removes the key-value from the trie and copies the content of the value into the `register_id`, even if the content is zero bytes. - If key is not present then does not modify the register. ###### Returns - If key was not present returns `0`; - If key was present returns `1`. ###### Panics - If `key_len + key_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`; - If the registers exceed the memory limit panics with `MemoryAccessViolation`; - If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`; ###### Current bugs - Does not return into the registers. --- ```rust storage_has_key(key_len: u64, key_ptr: u64) -> u64 ``` Checks if there is a key-value pair. ###### Normal operation - If key is used returns `1`, even if the value is zero bytes; - Otherwise returns `0`. ###### Panics - If `key_len + key_ptr` exceeds the memory container it panics with `MemoryAccessViolation`; --- ```rust storage_iter_prefix(prefix_len: u64, prefix_ptr: u64) -> u64 ``` DEPRECATED, calling it will result result in `HostError::Deprecated` error. Creates an iterator object inside the host. Returns the identifier that uniquely differentiates the given iterator from other iterators that can be simultaneously created. ###### Normal operation - It iterates over the keys that have the provided prefix. The order of iteration is defined by the lexicographic order of the bytes in the keys. If there are no keys, it creates an empty iterator, see below on empty iterators; ###### Panics - If `prefix_len + prefix_ptr` exceeds the memory container it panics with `MemoryAccessViolation`; --- ```rust storage_iter_range(start_len: u64, start_ptr: u64, end_len: u64, end_ptr: u64) -> u64 ``` DEPRECATED, calling it will result result in `HostError::Deprecated` error. Similarly to `storage_iter_prefix` creates an iterator object inside the host. ###### Normal operation Unless lexicographically `start < end`, it creates an empty iterator. Iterates over all key-values such that keys are between `start` and `end`, where `start` is inclusive and `end` is exclusive. Note, this definition allows for `start` or `end` keys to not actually exist on the given trie. ###### Panics: - If `start_len + start_ptr` or `end_len + end_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`; --- ```rust storage_iter_next(iterator_id: u64, key_register_id: u64, value_register_id: u64) -> u64 ``` DEPRECATED, calling it will result result in `HostError::Deprecated` error. Advances iterator and saves the next key and value in the register. ###### Normal operation - If iterator is not empty (after calling next it points to a key-value), copies the key into `key_register_id` and value into `value_register_id` and returns `1`; - If iterator is empty returns `0`. This allows us to iterate over the keys that have zero bytes stored in values. ###### Panics - If `key_register_id == value_register_id` panics with `MemoryAccessViolation`; - If the registers exceed the memory limit panics with `MemoryAccessViolation`; - If `iterator_id` does not correspond to an existing iterator panics with `InvalidIteratorId` - If between the creation of the iterator and calling `storage_iter_next` any modification to storage was done through `storage_write` or `storage_remove` the iterator is invalidated and the error message is `IteratorWasInvalidated`. ###### Current bugs - Not implemented, currently we have `storage_iter_next` and `data_read` + `DATA_TYPE_STORAGE_ITER` that together fulfill the purpose, but have unspecified behavior.
Toward a Better Planet: Green NFTs CASE STUDIES June 8, 2021 After the boom of decentralized finance in 2020, the blockchain industry has turned its attention to NFTs. Artists, celebrities, and blockchain enthusiasts alike are minting, buying, and selling NFTs. But NFTs aren’t without controversy. Many people are against them because: Minting an NFT costs so much gas it becomes unviable for smaller artists. NFTs run on technology that has a large, negative impact on the environment. These are concerns that can both be addressed. The NEAR Foundation is excited to announce Green NFTs, a project where several environmentally conscious artists create art that will be put up for sale in a South Pole store on Mintbase. Half of the proceeds from these artworks will go to the artist and the other half will go to a selection of certified climate action projects developed by South Pole, an award-winning project developer. South Pole projects range from protecting a strategic wildlife corridor in Zimbabwe and empowering local communities to generating renewable energy and helping create the circular economy with efficient waste disposal. While cutting carbon is the science underpinning their projects, building a socially just world is at the heart of what they do. “We need to think about our impact on nature and take decisions that offset our impact. There aren’t that many crypto-art initiatives that are ethical and green, but NEAR and Mintbase fit the bill.” – Barbara Tosti, artist Collaborating For the Greater Good Because Mintbase is built on NEAR, creating a store and minting NFTs is affordable, fast, and scalable. Anyone can mint NFTs and sell them for whatever price they want, even if that’s less than ten dollars. Previously, gas fees would have made that economically unviable, but NFTs shouldn’t be a rich people’s game. That’s not all. Artist collaborations have become much easier, because Mintbase allows anyone to easily split both the revenue and royalties of a piece of art. All you need to do is define who gets what percentage. The smart contract will do the rest. Consider how this encourages novelists to write a book together, musicians to compose music together, and artists to work together with climate organizations for the greater good. Built on Carbon-Neutral Technology Green NFTs are only possible because the underlying infrastructure is carbon-neutral. The NEAR Foundation has been working together with South Pole to measure and offset its carbon footprint, and South Pole recently awarded the NEAR protocol its climate-neutral product label. NEAR purchased carbon offsets from South Pole’s certified climate action projects to compensate for all direct and indirect emissions associated with the blockchain. Importantly, the NEAR protocol uses a proof-of-stake consensus mechanism instead of a proof-of-work consensus mechanism, which means that the NEAR protocol’s carbon emissions only amount to a fraction of any proof-of-work blockchain. Measuring the carbon footprint of any blockchain is still a new field with many gray areas. Developments and changes to current methodologies can be expected as the field develops over time. But it’s important to start measuring today and iterate until we get it right instead of waiting for the perfect solution. “The environment should be at the core of any technological product. I lost interest in crypto-art when I learned about its environmental impact, but NEAR is on the right path to dealing with this problem.” – Riccardo Torresi, artist A Step in the Right Direction NFTs needn’t be expensive to create and they needn’t be bad for the climate. Instead, when the infrastructure is clean and when the incentives are aligned properly, they can be a force for good. Linking NFT art and their proceeds to real projects with measurable climate benefits can nudge NFT creators and buyers toward valuable social and environmental causes. The Green NFT project is one of the first examples of how this can be made possible. We believe it’s a step in the right direction, and hope to see many other projects contributing in similar ways for the greater good in the NEAR future. Keep your eyes out on our social media channels for an announcement on where you’ll be able to see and buy art from the Green NFT project. “Nobody is without sin when it comes to their carbon footprint. But, while I don’t think anybody can be perfect, you can try to make better individual choices, particularly when the right solutions are already out there.” – Zeitwarp, artist As well as storing carbon, forests provide innumerable benefits to humans and wildlife alike. This picture shows a sunset over the Kariba Forest Protection project.
Ready Layer One Rewind COMMUNITY May 27, 2020 In the backdrop of a global pandemic, economic shutdowns, work from home mandates, uncertainty and anxiety, crashing markets, tens of millions of unemployment filings, and money printers around the world going BRRRR — there was a need for solutions, and a need for unity. The vision of the technology we are developing is one that reroutes power back to the people. But that type of world changing vision can only be achieved with wide scale community coordination. So the NEAR team went to work calling up our friends at various other protocols. Soon, a coalition emerged: Celo, Cosmos, Polkadot, Protocol Labs, Solana, Tezos and NEAR. We envisioned workshops with members from various teams discussing standards, opportunities to contribute resources and expertise for the collective good of the space, and laying the foundations for future development. More than that — we wanted an opportunity, in these isolating times, to connect with others who also believe that we can rewrite our trajectory. Designed with our unique global circumstances in mind and executed in 5 weeks, Ready Layer One is proof that collaboration is greater than competition. The Founders and Core Team members from every major Layer 1 ecosystem joined over 3900 other brilliant minds for the 3-day Ready Layer One; an intersection between a hackathon, a conference, a masterclass seminar and a vaguely anarchist festival for developers and builders of a decentralized web. The event was designed for participants to choose their own adventure: hop in and out of a variety of ongoing sessions, be randomly matched with other participants for a 1:1 video chat or host their own pop-up workshop! While the group chats, the memes, and the friends we made were most of the fun — we’ve done our best to capture the spirit by recording all the various presentations, workshops and sessions. And now, we’re sharing those with you! Our Favorite Moments from RL1 👾 Day 1: We kicked things off with NEAR’s Erik Trautman and Illia Polosukhin announcing NEAR Mainnet! Alex Skidanov (NEAR), Anatoly Yakovenko (Solana), Justin Drake (Ethereum Foundation), Christopher Goes (Cryptium Labs), Jesse Walden (Mediachain Labs), and Karl Floersch (Optimism) discuss the importance of composability, explore the various approaches from leading protocols and how composability will impact developers. Anna Rose from Zero Knowledge podcast and Tarun Chitra begin the process of unpacking the opportunities and challenges for privacy and privacy tech post-quarantine. Vitalik Buterin discusses weaponized interdependence, the progression of control over resources vs control over networks, and control as liability. He makes a case for 2020 being the decade of Systempunks in his presentation: Cryptography and Cryptocurrency In Context: The Next Decade Illia Polosukhin, Marek Olszewski, Sam Williams, Dietrich Ayala, and Curtis Spencer discuss various web3 projects building developer communities and how to grow the interest among traditional developers in programmable web. ⚡ Day 2: Unchained LIVE with Laura Shin, Illia Polosukhin (NEAR), Zaki Manian (Cosmos), Robert Habermeier (Polkadot) and Arthur Brietman (Tezos). An assembly of protocol teams: NEAR, Polkadot, Cosmos and Golem come together to address Wasm in trustful vs trustless environment, metering, performance and safety, Wasm in Wasm, languages for the smart contracts. Ashley Tyson from NEAR Protocol and Douglas Rushkoff, author of Team Human, discuss the velocity of money and how to build technology that enhances human cooperation. 🛸 Day 3: Data Availability Roundtable with Mustafa al-Bassam, Jeff Burdges (Polkadot), Dankrad Feist (Ethereum Foundation) and Alex Skidanov (NEAR Protocol) Crypto Cycles of Innovation: a fireside chat with Chris Dixon of Andreessen Horowitz and Robert Hackett of Fortune Magazine James Prestwich of Summa on Working Cross Chain: reviewing cross-chain communication basics and examples of it working in the wild. Get Involved: NEAR is hosting several hackathons and has weekly community events. You can find a full list in our events calendar. If you would like to get involved contributing to NEAR’s technical or community efforts, please have a look at the contributor program. We look forward to seeing you get involved. Have questions? Join our Community Chat.
--- title: 2.2 Ethereum 1.0 / Ethereum 2.0 description: The origins, history, success, and future trajectory of the Ethereum Network --- # 2.2 Ethereum 1.0 / Ethereum 2.0 (the road to it) It is only fitting that in our discussions of the L1 landscape we start with the most successful and most renowned L1 ecosystem - namely Ethereum. In this overview we are going to understand the origins, history, success, and future trajectory of the Ethereum Network - as well as some of the larger criticisms and challenges to the L1 that Haseeb likens to the ‘New York’ of crypto. As we will do for each L1, here is a fast ‘fact-sheet’ overview of the fundamental design of Ethereum 1.0: | | ETH 1.0 | | --- | --- | | Block Time | 15s | | Tx Finality | 3 min | | TPS | 15 | | Avg Tx Fee | ~$21 | | Languages | Solidity | | Number of Validators | 10k | What are we looking at when we look at Ethereum? We are looking at the very first smart-contract platform. Essentially the first time a blockchain has been programmed to securely execute and verify application code. Unlike Bitcoin, one is able to use the logic of Ethereum to program decentralized applications on top - in ETH’s native programming language - Solidity. ![](@site/static/img/bootcamp/mod-em-2.2.1.png) But as the ‘first of its’ kind’ there has always been questions about the scalability of the design of the Ethereum Network - this specifically has to do with the cost of gas on the network required to pay for transactions. ![](@site/static/img/bootcamp/mod-em-2.2.2.png) Why is this the case? To put it simply, Ethereum was not designed to sustain a high throughput of transactions - initially. As we can see above it is capable of processing roughly 15 transactions per second, with an average fee of 21$. Many have asked: Is this how much it should cost to participate in the future of finance? In the open-source crypto-economic systems of the world? This is a glaring issue that we will return to - as a means of discussing potential challenges to ETH and solutions. ## The DAO Hack When Ethereum originally launched in 2015 it was not without setbacks. The DAO hack, as it came to be known was a hack of one of the first dApps on ETH, that defined the future of the network and set a precedent on network management: ![](@site/static/img/bootcamp/mod-em-2.2.3.png) * [Gemini on the DAO HACK. ](https://www.gemini.com/cryptopedia/the-dao-hack-makerdao#section-origins-of-the-dao) In short, the Ethereum community decided to fork the original Ethereum chain, so as to restore the stolen funds. This led to the creation of Ethereum and Ethereum Classic. The important takeaway from this story, is that despite the programmability of blockchains, they are ultimately governed by the community of participants in the network - and if the community can come to consensus on a specific decision to make - whether that be to fork the chain, mint new tokens, burn tokens, or block certain accounts access - it is in principle possible to do. ## Understanding the Power of Ethereum As Ethereum was the first major Layer 1 smart contract platform, they have been home to the most successful dApps, as well as the most value locked on the platform. ![](@site/static/img/bootcamp/mod-em-2.2.4.png) They have however been somewhat delayed in the implementation of their roadmap, leading to much discussion about the future of Ethereum. What we are referring to here is what is known as the ‘Merge’ as well as ETH’s sharding and roll-up plan. Our focus on Ethereum is going to be twofold: First, what challenging _scaling_ issues have resulted in, and secondly, the ETH roadmap that may or may not fix these issues. ## Solidity and the EVM Solidity is the turing-complete programming language of the Ethereum Network. ## Scalability Challenges for Ethereum Scalability as discussed above, refers to the ability for a network to sustain a high-throughput of transactions or activities. Due to the original design of the ETH network, it was not launched to accommodate millions of users in a cost-efficient manner. The result is that with high demand, but limited throughput on the network, the cost of gas spikes, making it highly expensive to pay for basic services in the network - gas costs. This made many question the usability of ETH - how can crypto bank the unbanked, and offer new financial and creative services to the world if it costs an average of 21$ to simply have an action on-chain. The reaction to the scalability challenges of ETH have been twofold: Loyal Etherians have committed to building scalability solutions connected to the Mother-layer of ETH. Originally this was known as plasma scalability solutions, sidechains, and rollups. Today rollups have been a clear answer, with only one ‘side-chain’ harnessing the narrative (Polygon) which we will speak of after. Let’s zoom in on Roll-ups for a second as you will most likely hear a lot about roll-ups in the future. ### What is the idea behind roll-ups? That a separate protocol can be used to quickly process transactions, and then bundle those transactions into a larger transaction that is processed by the ETH main chain. So in essence, we are outsourcing transaction throughput to other software that is still nevertheless built on the ETH main chain. Analogously you can think of roll-ups a bit like skyscrapers - they are ways of managing space such that you can compact a lot of people into an area. Except for crypto, we are not talking about people as much as we are talking about transaction costs. Popular roll-ups today include Arbitrum, Optimism, and Starkware. What is the critique of roll-ups? This is known as ‘Death by A million cuts’. On the Ethereum main-chain, we have a single platform, in which all dApps are being processed by the same network. With rollups we have a separate network, processing transactions more quickly than the main network, and sending bundled confirmations of those transactions to the main network. The challenge that ensues is how dApps built on different roll-ups are able to communicate quickly and easily with one another. For example, if I am sending money from one roll-up to another, I need to either use a bridge between the two, or, take my money off of the first roll-up, bring it down to the mother-chain, and then move it up to the next chain. In a similar vein, if I am looking at the infrastructure available for my dApp, the infrastructure provider - call it an Oracle, Storage, On-Ramp, Custodian, must now offer there services to not just Ethereum but also the specific roll-up terminals. This makes it more difficult for money and users to switch between applications. We will learn later on about the composability thesis, and that one of the strongest value propositions from an L1 ecosystem is the ability for value to intermingle composably. This is not possible in the current design of a roll-up centric scalability approach. In the word’s of Vitalik: _“These facts taken together lead to a particular conclusion: the Ethereum ecosystem is likely to be all-in on rollups (plus some plasma and channels) as a scaling strategy for the near and mid-term future.”_ Does this mean Ethereum is doomed? Not at all, it has simply provided inspiration for others, to try to build alternative L1 ecosystems that may rival Ethereum and solve the scalability problem that has congested its network so deeply. This is what we will be focusing on in the following lectures: What other L1 ecosystems exist, and how do these ecosystems represent the ‘state’ of crypto today? ## The ETH Roadmap Into The Future Vitalik has written quite openly about plans for scaling the future of the Ethereum network. Most recently he has even outlined the various strategies for Ethereum into the future that we will summarily address now: ![](@site/static/img/bootcamp/mod-em-2.2.5.png) While Vitalik has intended this roadmap to be executed in parallel, let’s take them each one at a time: **The Merge:** The Merge was a long awaited update for the ETH network that transitioned it away from a proof of work consensus mechanism, and moved it to a proof of stake design. In successfully completing this milestone, Ethereum is no longer energy intensive, and has become net deflationary - as fees from the network are now being burned making issuance deflationary over time. **The Surge:** To scale the entire Ethereum Network to 100,000 Transactions per second using rollups, primarily optimistic rollups, and ZK-EVMs. This strategy was outlined in detail by Vitalik in [his blog here, ](https://ethereum-magicians.org/t/a-rollup-centric-ethereum-roadmap/4698)and essentially confirms to everyone that the future of scalability of Ethereum, is largely going to be through different types of roll-ups that progressively improve in their design over time. **The Scourge:** “Ensure reliably and credibly neutral transaction inclusion and avoid centralization and other protocol risks from MEV.” The Scourge is all about balancing out risk of centralization in nodes on the Ethereum network, specifically as it relates to algorithms and machines running to optimize block space for DeFi purposes. **The Verge:** “Verifying blocks should be super easy - Download N Bytes of data, perform a few basic computations, verify a SNARK and you're done.” The Verge seeks to expand the ease with which anyone can participate as a validator on the network - specifically as ‘Chunk producers’ and ‘Chunk producers using ZK-rollup designs. **The Purge:** “Simplify the protocol, eliminate technical debt and limit costs by participating in the network by clearing old history.” The purge has to do with managing and simplifying memory on Ethereum, such that there is an expiration of old transactions, gas mechanics can be simplified, and there is a serialization of transaction types. **The Splurge:** “Fix everything else”. Perfecting the EVM and abstracting out accounts. Interestingly, the original vision for Ethereum 2.0 was a fully sharded Ethereum main-chain. While this goal seems to have been substituted for Zk-Sync / Optimistic rollup optionality instead, the composability losses of this move remain to be fully understood or discussed. ## World of Dapps vs. Universe of Chains The original vision grounding ETH 1.0 is clearly a World of dApps chain - that is to say, Ethereum is supposedly a cloud environment to support the development of a host of decentralized applications - on a single composable platform. However, in light of its scalability issues, it is unclear what kind of a network an Ethereum of the future will look like with multiple isolated roll-ups, that are not natively composable. ## Summary of Ethereum Ethereum is the home to DeFi and the original smart contract platform from which NFTs were first launched. It is now a proof of stake blockchain, that is net deflationary - which leaves many with high hopes for its future. That being said, the inability for the main-network to scale, and the delays until reaching ETH 2.0 have made others also look at other L1s for building successful dApps. All of that being said, Haseeb has routinely referred to Ethereum as the ‘New York’ of crypto - the legacy city of an emerging country, the largest, the most affluent, and also the most expensive to be a part of. Ethereum remains the home of the largest DeFi applications, NFT Communities, and crypto-natives in all of crypto. It is an extremely successful L1 that appears to possess staying power into the future.
```js const AMM_CONTRACT_ADDRESS = "v2.ref-finance.near"; const wallet = new Wallet({ createAccessKeyFor: AMM_CONTRACT_ADDRESS }); await wallet.viewMethod({ method: 'get_deposits', args: { account_id: "bob.near" }, 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> ```json { "token.v2.ref-finance.near": "0", "wrap.near": "0" } ``` </p> </details>
--- id: introduction title: Fungible Tokens Zero to Hero sidebar_label: Introduction --- > In this _Zero to Hero_ series, you'll find a set of tutorials covering every aspect of a fungible token (FT) smart contract. > You'll start by interacting with a pre-deployed contract and by the end you'll have built a fully-fledged FT smart contract that supports every extension of the standards. --- ## Prerequisites To complete these tutorials successfully, you'll need: - [Rust](/build/smart-contracts/quickstart#prerequisites) - [A NEAR testnet account](https://testnet.mynearwallet.com) - [NEAR-CLI](/tools/near-cli#setup) :::info New to Rust? If you are new to Rust and want to dive into smart contract development, our [Quick-start guide](../../2.build/2.smart-contracts/quickstart.md) is a great place to start. ::: --- ## Overview These are the steps that will bring you from **_Zero_** to **_Hero_** in no time! 💪 | Step | Name | Description | | ---- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | [Pre-deployed contract](/tutorials/fts/predeployed-contract) | Receive FTs without the need to code, create, or deploy a smart contract. | | 2 | [Contract architecture](/tutorials/fts/skeleton) | Learn the basic architecture of the FT smart contract and compile the code. | | 3 | [Defining a Token](/tutorials/fts/defining-a-token) | Flesh out what it means to have a FT and how you can customize your own | | 4 | [Circulating Supply](/tutorials/fts/circulating-supply) | Learn how to create an initial supply and have the token show up in your wallet. | | 5 | [Registering Accounts](/tutorials/fts/registering-accounts) | Explore how you can implement and understand the storage management standard to avoid malicious users from draining your funds. | | 6 | [Transferring FTs](/tutorials/fts/transfers) | Learn how to transfer FTs and discover some of the true powers that the core standard brings | | 7 | [Marketplace](/tutorials/fts/marketplace) | Learn about how common marketplaces operate on NEAR and dive into some of the code that allows buying and selling NFTs by using Fungible Tokens | <!-- 1. [Events](/tutorials/fts/events): in this tutorial you'll explore the events extension, allowing the contract to react on certain events. 1. [Marketplace](/tutorials/fts/marketplace): in the last tutorial you'll be exploring some key aspects of the marketplace contract. --> --- ## Next steps Ready to start? Jump to the [Pre-deployed Contract](/tutorials/fts/predeployed-contract) tutorial and begin your learning journey! If you already know about fungible tokens and smart contracts, feel free to skip and jump directly to the tutorial of your interest. The tutorials have been designed so you can start at any given point! :::info Questions? 👉 Join us on [Discord](https://near.chat/) and let us know in the `#development` channels. 👈 We also host daily [Office Hours](https://pages.near.org/developers/get-help/office-hours/) live where the DevRel team will answer any questions you may have. 🤔 Monday – Friday 11AM – 12PM Pacific (6PM – 7PM UTC) :::
--- title: 4.2 NFT Lending, Fractionalization and Time-Scarcity description: What can we do with non-fungible or intangible assets? --- # 4.2 NFT Lending, Fractionalization and Time-Scarcity In this lecture, the focus is really on zooming into three of the most clearly established use-cases of non-fungible tokens, which also have significant room to grow into the future. While last lecture focused a large amount on the foundations of NFTs as well as the _what_ and _how_ behind them and their many different forms - this lecture asks the question _so what?_ What can we do with this non-fungible or intangible asset class that is suspected of being valued at around $77 trillion dollars? And what are the implications of this _so what_ on how we might expect our world to change in the future? From a high level we are going to be zooming in on the lending of NFTs, the fractionalization of NFTs, and the notion of ‘time-scarce’ NFTs. Each use-case explains a fundamental direction of this technology's development into the future - and most importantly - each use-case is relevant for any growing NFT ecosystem on an L1 blockchain. ## NFT Lending The concept of NFT lending can be broken down into a number of sub-areas: * **Peer to Peer NFT Lending**: This refers to ‘orderbook’ style lending of an NFT, from which one user can loan out their NFT to another user, in exchange for a loan of value. This requires a potential lendee to find a matching lender in order to be successful. If the lendee cannot repay the loan by the date it is supposed to, then the NFT that was loaned as collateral is offered to the lender at large discount. NFTfi is the best example of this type of product that currently exists. _“NFTfi, one of the larger services, had its public beta launch in June 2020. It did $300,000 in loans in its first year, $14 million in 2021 and $150 million so far in 2022, with $37 million in loans [outstanding](https://dune.com/rchen8/NFTfi). Its loans range from 30 to 180 days in duration. The loans are paid back all at once, like a traditional bullet loan.” ([Protocol](https://www.protocol.com/fintech/nft-lending-crypto#toggle-gdpr))_ ![](@site/static/img/bootcamp/mod-em-4.2.1.png) * **Peer to Protocol NFT Lending:** Peer to protocol lending operates similar to a decentralized exchange - communally pooled liquidity is utilized from which owners of NFT’s are eligible to lend out their NFT to the protocol itself at a specific rate. BendDAO is most prominent of these protocols, with a number of ‘bluechip’ NFTs collateralized. With such protocols it is up to the design of the protocol to decide at what point an NFT is liquidated due to a drop in value. * **Non-Fungible Debt Positions:** These are just another way of saying, lending to a protocol for stable value, backed by a US Dollar. In simple terms, the NFT can be used to get a certain rate of USD. The assumption is that the NFT is whitelisted by the platform, and has established some threshold of value. * **Renting and Leasing NFTs:** Unlike collateralization and liquidation, renting and leasing on places like reNFT, establishes ‘tenancy’ from which a smart contract is used to manage the transfer of the NFT from one wallet into the other, until the tenancy is over. Such a rental market is fascinating insofar as it creates a further avenue of use for NFT’s beyond having to own each one. For example, I could leverage one specifically for an upcoming event that I need to access, or use it to showcase a certain profile as a social media growth strategy. * **Centralized Lending on NFTs:** Genesis trading (prior to its insolvency) as well as Nexo, were both centralized custodians that allowed users to take out direct loans for collateralizing their NFTs. * **[Hypothetical] Loaning out non-fungible value for another type of non-fungible value.** While this specific service does not exist yet, the premise is that a community, DAO, or platform could allow certain NFT’s to be locked and loaned out in turn for other NFTs. _Idea - An all in 1 product offering all 5 NFT lending services._ _Requirement - Price discovery and sufficient Oracle Infrastructure._ **Presuppositions:** In order for a lending market to develop around NFT’s, there are specific incentives and presuppositions required: **Ecosystem Liquidity:** Our ‘tech tree’ understanding of the evolution of the crypto product stack would suggest that sufficient liquidity would be required on the L1 ecosystem as a whole, in order allow for sufficient price discovery within the NFTs themselves, as well as collateral for lending upon them. **The incentive to borrow for Users –** Users lock up their NFT, from which they are required to pay interest on the loan, and cannot utilize the NFT while the loan is outstanding. They do however receive direct cash for their NFT, which can be used in the event of a liquidity squeeze or for immediate capital relief. From a high level, users with some form of intangible value, now have the ability to withdraw temporary fungible value, using the non-fungible value as collateral. **The Incentive to Lend Capital from Lenders –** From the lenders perspective the theory is straightforward: Earn interest on your capital, with the guarantee that if the owner of the NFT default’s you are able to acquire the NFT at a massive discount. The elephant in the room for lenders, is the need to have fair price discovery on the form of non-fungible value. Which in virtue of being non-fungible, is not often easy to do. **There is Established and Clarified Value for the NFT in Question –** Many of these lending platforms only offer loans to ‘whitelisted’ ‘bluechip’ NFT collections. This is another way of saying that the space as a whole is young, and insufficient value or attention has been given so as to create realistic price discovery for stable lending markets. Until there is established and clarified value for the NFT’s in question, there is limited opportunity to lend off of them. **Relevant Oracle Infrastructure to Supply Pricing:** The final point - and also one that is a potential vulnerability - is the need for reliable 24/7 Oracle infrastructure to support the management of value, and liquidation thresholds for the NFTs being loaned in question. Without such infrastructure no NFT lending is possible. **_The ‘So What’ for Lending NFTs:_** Bearing in mind the nature and presuppositions for NFT lending, there are a number of ‘so-what’ takeaways from the service that further expand the value proposition inherent to non-fungible tokens: * _More financial tools for the average person:_ Today, only certain assets can be collateralized for a loan - usually your house as a last resort. With the lending of NFT’s the playing field is drastically expanded for both individuals and institutions - capital can now be accessed, for things like academic research, music, art, or even an NFT indicating a certain consistent behavior. The macro result is a better way of moving capital between individuals and institutions. * _Huge aggregation opportunities for bundling and baskets of non-fungible value:**_ Second, the prospect of being able to aggregate bundles or baskets of non-fungible value, from which loans can then be taken out, further expands the idea of creating accessible value from fractions of other types of value. Instead of requiring the entire NFT for a loan, you can intertwine, the multiple bunches of NFTs. * _A re-focus on capacities - return of guilds? Capacities are tradeable now for anything else:_ Expanding the types of value that can be credited, expands the types of activities that can be used to generate value. Businesses and communities can now spring up and thrive off of the re-sale, and lending of their intangible value - should a market sufficiently large enough develop. For artists, this is a huge lifeline in a traditionally impoverished industry. The larger principle at play, is that certain capacities or ‘skills’ are now financially productive. * _A new system for generating credit - running parallel to the archaic system:_ Piggy backing off of the latter point, the opportunity to ‘exit’ the old financial system grows with the ability to take out loans off of non-fungible value. * _Secondary incentives for participants across the product stack:_ Implicit in this entire discussion is the underlying premise that due to the fact that crypto is composable, there are new incentives for users of any product that may contain an NFT inside of it. Whether that be a metaverse, play2 earn game, liquidity for DeFi projects, or something else, the implication is that there is further value to be unlocked downstream. Example: Play a game, earn a rare item and then make money loaning the item out over time. Looking ahead, it’s likely that in the future, non-fungible lending will expand such that more types of non-fungible value are eligible for a loan, with certain loan rates expanding to rival existing mainstream lenders (potentially to even include mortgages). Lending of Non-Fungible value remains in its infancy. ## Fractionalization Fractionalizing NFT’s - and creating fractional NFT marketplaces by extension - refers to the capacity to split up an NFT into different pieces, such that each individual piece can be independently owned, yet with the value maintained as a proportion of the composite piece as a whole. There are three primary benefits of NFT fractionalization: * **Expanding Access to Ownership of Non-fungible value (fractional Art via Ren DAO).** The first benefit of fractionalization refers to the notion of fractional ownership: That many people can own the same non-fungible asset - in proportions and pieces. This entails benefiting in value accrual of the non-fungible asset (if the price where to go up), benefiting from the access, benefits, or value capture derived from the NFT (for example, if it allowed access to an event, gave out streams of benefits, or yielded value on a recurring basis). From the product’s angle, fractionalization of NFT’s also allows for the placement of fractions into other products - games containing pieces of art for example. Fractional ownership is thus leveraged for incentives within other products and for users. * **Expanding Decision Making on the Uses of Non-fungible Value (deciding where to put a piece of art, where to place a movie clip, where to share an article):** As Non-Fungibles develop as an asset class, the creators of the value hold significant decision making power over how future ownership of the non-fungible may determine decision making power over the object. This applies to artists and their art, musicians and their music, communities and their voting on events and locations, and even movie or media producers on who has a right to license the film. Fractionalization of NFT’s means that this decision making power is fractionalized like stock-options can be for fungible assets. It is essentially collective decision making over the fate of an intangible asset. Previously the valuation of the intangible asset would not have been possible at scale - now it is not only possible but possible to be managed by a collective of stakeholders invested in the future of the asset. * **Expanding Financial Granularity of non-fungible value (real estate baskets going long and short on certain houses):** This last value proposition is directly on the level of financial products - fractionalization of NFT’s allows for further financialization of intangible value. Baskets of different NFT’s can be created, from which financial positions can be taken (for example, real estate on the lower east side, Harlem and Bronx). The value accrues to the asset as a whole, from which the fraction is a part. Participants however do not need to possess the entire non-fungible asset, in order to benefit from its upside. Once more, the success of any fractional NFT marketplace is dependent upon underlying price discovery and value discovery with the original NFT collection or class itself. There cannot be fractional ownership of an asset that is not valued by a larger market. ## Time-Scarcity with NFTs: The final category for this lecture is an interesting one, largely because of its non-monetary basis. Time-scarce NFT’s refer to Non-fungible tokens that are rewarded or accessed only after the specific amount of elapsed time has passed. Beyond simply ‘putting the time in’ there is no way to game the system to access the NFT. The interesting thing about time-scarce NFT’s is that they invert the characteristic value logic with NFT’s: Usually an NFT is a representation of some form of value - that is to say, it designates the value inherent in something else - for example a piece of art. With time-scarce NFT’s however, we are dealing with the NFT itself, becoming the indicator of value. The value is generated, in the NFT itself, due to the fact that the only way to create the NFT in the first place is from ‘putting the time’ into something. From a high level, time-scarce NFT’s are a return to a ‘class system’ of sorts, from which individuals, groups, and collectives, can be identified based upon their skill, stature or involvement in a specific activity. An easy way of thinking about this, is to imagine the black-belt system in martial arts, becoming applicable across the domains of expertise on the internet. Time-scarce NFT’s back this activity, providing successful users capable of obtaining them with status, access, and new opportunities. _Some of the Areas Most Open for Use of Time-scarce NFTs Include:_ * **Game Items:** Playing the game or doing a certain activity in the game generates an item designating your skill or mastery, from which you are given special access to areas, weapons, tools, or other players. * **Community Membership - Guild Achievement:** Inside of different online communities (or real world communities) the time-scarce NFT designates your rights to earning dividends from the collective group, right to days off, or to designate you with a specific role (such as in the military). * **Learning Commitment / Mastery:** For learning, recognition of certain skills, or mastery in a particular area, time-scarce NFT’s have the opportunity to replace diplomas’ and certifications in the mainstream world. The important qualification and difference is that such NFT’s are most likely to be awarded based upon specific on-chain verifiable metrics, such that any user of the future could verify that the holder of the NFT did participate sufficiently to earn it. For learning, mastery designations, and time invested in certain topic areas, time-scarce NFT’s hold a large promise for the future of science, research, and bestowing titles in the world. * **Forest Project NFTs:** A real example of time-scarce NFT’s being utilized are those on Open Forest Protocol: Each forest project uploads data from their NFT, from which the validation result is written into the NFT meta data. Notably, they can only receive carbon credits on their second data upload, meaning they must successfully manage their forest for 6 months before becoming eligible. The NFT, which is untradeable, then reflects the status of the forest over time. Drilling into fractionalization, lending, and time-scarcity demonstrates to us that non-fungible tokens are an extremely flexible technology. In order to fully carve out these benefits, however, a prospective user or builder must have an original understanding of potential non-fungible use-cases, as well as where the market is at today.
Unsolved Problems in Blockchain Sharding DEVELOPERS December 12, 2018 In the first part of the series we provided motivation for blockchain sharding and discussed some core concepts. In this post we will discuss some more advanced aspects of sharding, including its two biggest unsolved challenges: data availability and data validity. Intro The core idea in sharded blockchains is that most participants operating or using the network cannot validate blocks in all the shards. As such, whenever 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 the participant cannot necessarily be certain that the state with which they interact is the result of some valid sequence of blocks and that such sequence of blocks is indeed the canonical chain in the shard. A problem that doesn’t exist in a non-sharded blockchain. We will first present a simple solution to this problem that has been proposed by many protocols and then analyze how this solution can break and what attempts have been made to address it. The supposed simple solution The naive solution to data validity is the following: let’s say we assume that the entire system has on the order of thousands 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 ⅓ failing for practical purposes can be assumed to be zero. ⅓ is an important threshold. There’s a family of consensus protocols, called BFT consensus protocols, that guarantees that for as long as fewer than ⅓ of participants fail, either by crashing or by acting in some way that violates the protocol, the consensus will be reached. With this assumption of honest validator percentage, if the current set of validators 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 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 solution is also certain that the current chain is the only chain in the shard. This simple solution doesn’t work if we assume that the validators can be corrupted adaptively, which is not an unreasonable assumption (see here to learn more about adaptive corruption). Adaptively corrupting 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 have certainty in the validity of a block, we must know that at any point in history no shard in the system has a majority of validators colluding; with adaptive adversaries, we no longer have certainty. As we discussed in the previous part, colluding validators can exercise two basic malicious behaviors: create forks, and produce invalid blocks. Malicious forks can be addressed by blocks being cross-linked to the Beacon chain that is generally designed to have significantly higher security than the shard chains. Producing invalid blocks, however, is a significantly more challenging problem to tackle. Data Validity Consider the following figure on which Shard #1 is corrupted and a malicious actor produces invalid block B. Suppose in this block B 1000 tokens were minted out of thin air on Alice’s account. The malicious actor then produces valid 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. Some simple approaches to tackle this problem are: 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. For validators in Shard #2 to validate some large number of blocks preceding 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 undirected graph in which each shard is connected to several other shards, and only allow cross-shard transactions between neighboring shards (e.g. this is how Vlad Zamfir’s sharding essentially works, and similar idea is used in Kadena’s Chainweb). If a cross-shard transaction is needed between shards that are not neighbors, such transaction is routed through multiple shards. In this design a validator in each shard is expected to validate both all the blocks in their shard as well as all the blocks in all the neighboring shards. Consider a figure below with 10 shards, each having four neighbors, and no two shards requiring more than two hops for a cross-shard communication: Shard #2 is not only validating its own blockchain, but also blockchains of all the neighbors, including Shard #1. So if a malicious actor on Shard #1 is attempting to create an invalid block B, then build block C on top of it and initiate a cross-shard transaction, such cross-shard transaction will not go through since Shard #2 will have validated the entire history of Shard #1 which will cause it to identify invalid block B. While corrupting a single shard is no longer a viable attack, corrupting a few shards remains a problem. On the following figure 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: 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 two major directions of properly solving data validity: fishermen and cryptographic proofs of computation. Fisherman 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’s 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 way smaller than that of receiving a full block. With this approach for as long as there’s at least one honest validator in the shard, the system is secure. This is the dominant approach (besides pretending the problem doesn’t exist) among the proposed protocols today. This approach, however, has two major disadvantages: 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 invalid. Introducing such a period would significantly slow down the cross-shard transactions. The existence of the challenge protocol creates a new vector of attacks when malicious nodes spam with invalid challenges. An obvious 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 partial solution, as it might still be beneficial for the adversary to spam the system (and burn the deposits) with invalid challenges, for example to prevent the valid challenge from a honest validator from going through. These attacks are called Griefing Attacks. Neither of the fisherman’s two problems has a satisfactory solution, but using fisherman is still strictly better than having the possibility of an invalid block being finalized. Succinct Non-interactive Arguments of Knowledge The second solution to multiple-shard corruption is to use some sort of cryptographic constructions that allow one 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. zk-SNARKs, zk-STARKs 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. E.g. Coda Protocol, that uses zk-SNARKs specifically to prove that all the blocks in the blockchain are valid, said in one of the interviews that it can take 30 seconds per transaction to create a proof (this number is probably smaller by now). 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 built for, but 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 who compute zk-SNARKs to run on special hardware without reducing the decentralization of the system. The challenges of zk-SNARKs, besides performance, are: Dependency on less-researched and less-time-tested cryptographic primitives; “Toxic waste” — zk-SNARKs 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; Extra complexity introduced into the system design; zk-SNARKs only work for a subset of possible computations, so a protocol with a Turing-complete smart contract language wouldn’t be able to use SNARKs to prove the validity of the chain. While many protocols are looking into using zk-SNARKs long term, I do not know any planning to launch with them besides Coda. 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 parts of the state and transactions they are interested in. Now if a majority of full nodes collude, they can produce a block, valid or invalid, and send its hash to the light nodes, but never disclose the full content of the block. There are various ways they can benefit from it. For example, consider the figure below: There are three blocks: the previous, A, is produced by honest validators; the current, B, has validators colluding; and the next, C, will be also produced by honest validators (the blockchain is depicted in the bottom right corner). 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 the money to you). Confident the transaction is finalized, you provide the service. However, the validators never distribute the full content of the 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, 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 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 a header of an invalid block (or used it to initiate a cross-shard transaction), but never distributed the block, the honest validators have no way to craft a challenge. We will cover two approaches to address this problem that complement each other. Proof of Custody The most immediately 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 the validators. 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 some evidence or to stake some amount of tokens attesting that the block was downloaded. One such solution is discussed here. Erasure Codes When a particular light node receives a hash of a block, 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, since 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: Both Polkadot and Ethereum Serenity have designs around this idea that provide a way for light nodes to be reasonably confident the blocks are available. The Ethereum Serenity approach has a detailed description in this paper. Both approaches rely on challenges, and thus are potentially vulnerable to griefing attacks. Long term availability, and Conclusion 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 later become unavailable for a variety of reasons: nodes going offline, nodes intentionally erasing historical data, and others. A whitepaper worth mentioning that addresses this issue is Polyshard, which uses erasure codes to make blocks available across shards even if several shards completely lose their data. Unfortunately their specific approach requires all the shards to download blocks from all other shards, which is prohibitively expensive. Luckily, the long term availability is not as pressing of 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 the sharded protocol needs to be designed in such a way that the system is secure even if some old blocks in some shards become completely unavailable. Data validity and data availability remain two problems in designing secure protocols that do not yet have a satisfactory solution. We are actively researching these problems. Stay tuned for updates. Outro Near Protocol builds a sharded general purpose blockchain with a huge emphasis on usability. If you like our write-ups, follow us on twitter to learn when we post new content: http://twitter.com/nearprotocol If you want to be more involved, join our Discord channel where we discuss all technical and non-technical aspects of Near Protocol, such as consensus, economics and governance: https://discord.gg/nqAXT7h Near Protocol is being actively developed, and the code is open source, follow our progress on GitHub: https://github.com/nearprotocol/nearcore https://upscri.be/633436/ Thanks to Justin Drake from Ethereum Foundation, Alistair Stewart from Polkadot, Zaki Manian from Cosmos Protocol, Monica Quaintance from Kadena Protocol and Dan Robinson from Interstellar for reviewing an early draft of this post and providing feedback.
The Graph Expands Subgraph Support to NEAR and 40+ Blockchains COMMUNITY March 14, 2024 The Graph Foundation recently announced the inclusion of NEAR into its expansive subgraph support, now encompassing over 40 leading L1 and L2 blockchains including Arbitrum, Base, Fantom, Celo, Optimism, Polygon Labs, and Scroll. By integrating with The Graph, NEAR developers gain access to a decentralized network for streamlined data querying, significantly reducing costs and improving synchronization speeds. The partnership highlights the NEAR Foundation’s ongoing commitment to enhancing developer resources and interoperability within open web ecosystems as part of advancing the Chain Abstraction vision. In 2021, NEAR became The Graph’s first non-EVM chain integration for its hosted service, kickstarting the evolution towards a multichain open web ecosystem. Subgraph support will take things a step further, facilitating better multichain data accessibility for NEAR builders and increasing the reach and breadth of tools and technologies to support Chain Abstraction. This moment also marks NEAR as the first non-EVM chain to become available on The Graph Network. How Subgraph Support Empowers NEAR Developers Subgraphs on The Graph are transformative open APIs that efficiently organize and serve blockchain data, accelerating the development of decentralized applications (dApps) on the NEAR Protocol. This integration offers developers further support in efficient data querying, swift access to indexed blockchain data, and seamless interoperability across multiple chains. By streamlining data retrieval, The Graph’s subgraph support eliminates the need for exhaustive blockchain scans, allowing for quick navigation, filtering, and location of specific data points. This advancement equips NEAR developers with tools similar to Web 2.0 search engine capabilities, tailored for the precision and complexity of blockchain data. The Graph’s Multichain Support and Expansion Goals The Graph’s integration with NEAR and over 40 additional blockchains is a step towards more rich multichain development. By extending beyond Ethereum, The Graph is facilitating a unified, accessible ecosystem for designing advanced, user-focused decentralized applications (dApps) across a diverse range of blockchains. Enhancing interoperability among different blockchain networks also grants developers access to a broader spectrum of data, supporting the creation of dApps that are both feature-dense and user-friendly. These improvements also promote more unrestricted data exchange across chains for the purposes of dApp development. NEAR Protocol and Future of The Graph Network Looking forward, The Graph Network is aiming to break the barriers of decentralized access to blockchain data, as it plans to introduce new data services to meet the growing needs of Web3. The Graph’s core devs are planning ahead on executing the “Sunrise of decentralized data” initiative, designed to improve tooling and developer experience. Soon, NEAR devs building on The Graph Network will be able to take advantage of a free query plan, an intuitive subgraph upgrade wizard, and more. The Graph-NEAR Foundation collaboration will further emphasize the shared mission of both teams for a more interconnected and inclusive Web3 ecosystem via Chain Abstraction, enhancing the value of indexing and querying blockchain data.
Stake Wars is Over, but We’re Just Getting Started COMMUNITY October 9, 2020 Almost one year from its first announcement, we are closing one of the most important chapters in the history of NEAR Protocol: The Stake Wars. Born as a competition on top of our incentivized testnet, it quickly became everything but war, it was the birth of our Validator community. Over the course of the year, professional validators and skilled node operators helped each other to complete challenges and learn more about what it takes to be a great Validator for the NEAR community. Stake Wars participants spent hours on community chats and Github repositories to build the robust and secure infrastructure that today is running NEAR MainNet. As a reward, a relatively small number of them, out of more than 200 active members, were selected to be the first Validators to produce blocks for MainNet Phase I. It was hard to pick the best, as every participant deserved this privilege for their commitment, passion, and participation. Their names are (in order of staking transactions from here): Staked, DSRV Labs, Dokia Capital, Cryptium Labs, Buildlinks, Sparkpool, Hashquark, Jazza, Erm, Bison Trails, ZKValidator, Certus One, Zavodil, Inotel, Masternode24, Lunanova, Fresh, Figment, Bazilik, 01node, Stakefish, Moonlet, Open Shards, Stakin, OkEx Pool, Chorus One, Nodeasy, Astro Stakers. With the end of Stake Wars, all grants related to the program are ending: no more tokens will be provided to contributors, and the NEAR Foundation will not be staking to Validators for completing the challenges. Furthermore, BetaNet (the network we used for the Stake Wars) will be repurposed for deeply testing weekly releases, so we expect to hard fork within a few days, reset the accounts, and onboard only a small number of selected Validators from the community for testing. When One Chapter Ends, a New One Begins While the Stake Wars competition is over, we’re excited to announce three new opportunities to join NEAR as Validators, offering even more opportunities for rewards and community building than the Stake Wars alone: NEAR Foundation Delegation BetaNet Analysis Group Open Shards Alliance 1) NEAR Foundation Delegation The NEAR Foundation, which isn’t running validating nodes of its own, will offer delegation to new validators who apply and meet a set of ongoing criteria in supporting the network. This initiative has three objectives: Supporting High-quality Validators. Organizations that are geographically diverse, invest in building their own infrastructure, and are responsive to outages, but rarely have them because their uptime is close to 100%. Fostering Ecosystem Growth. Identifying Validators committed to NEAR Community growth. Hosting local events, creating educational NEAR content, and developing tools and user interfaces for the community. Guiding Fair Operations. Funds will be rotated between Validators as needed to balance the ecosystem and will take into consideration fees associated with every delegation. It’s important for Validators to be transparent about their operations and communicate openly with the community. If interested in learning more or providing feedback about this initiative, please reach out via this form. 2) BetaNet Analysis Group If during the Stake Wars you loved the thrill of catching bugs, chatting with NEAR developers in the middle of the night, sending detailed bug reports, and submitting pull-requests, this is for you. We are assembling a group of 5 skilled node operators to run a BetaNet node in a production-grade environment to test future releases of NEAR. This program will offer a monthly grant of $1000 (paid in NEAR) to partially cover the costs of servers, technical calls and submitting bug reports. Also, new Validators joining this program will be mentioned in the community updates, a valuable perk to attract stake from the community of delegators. Apply from this link (the same as the above), specifying in the notes that you want to join the BetaNet Analysis Group. The NEAR Core team will evaluate your application based on geography, type of infrastructure, previous validator experience, Stake Wars participation and community participation. If selected, you can be in the group for up to six months at a time before applying again if you wish to continue in the program. Every six months we will rotate members of the group to encourage participation from the wider community. 3) The Open Shards Alliance During the Stake Wars, a group of Validators decided to deploy and launch their own NEAR network, with different parameters and rules – including sharding, which is not yet enabled on NEAR MainNet. This community-driven initiative started from our Guild Program, and is not related to the NEAR Core team. The Open Shards Alliance is an excellent opportunity to become proficient in running NEAR nodes and learn the internals of the protocol. Thanks to a grant from NEAR Foundation, the Open Shards Alliance is now offering tokens to all contributors who help run their network, ‘GuildNet’, visible on the explorer, at this address. You can learn more and join the Open Shards Alliance today, on Discord. Wrapping up The Stake Wars, NEAR’s incentivized testnet program, is now over, but there are even more new and exciting ways to stay engaged and receive support to become a Validator on NEAR: The NEAR Foundation Delegation initiative is an application-based process to onboard more high quality validators from the community The BetaNet Analysis Group is for technical teams who want to help NEAR build future releases of nearcore. The Open Shards Alliance is a community initiative under the Guild Program that will provide small NEAR token contributions, and will offer a great opportunity to learn NEAR Protocol internals Questions? Join the conversation on Discord, and connect to our community calendar to never miss any NEAR event.
--- id: introduction title: About Rust SDK --- Rust is a programming language designed for performance and safety. It is syntactically similar to C++, but can guarantee memory safety without resorting to garbage collection. Rust has proven to be a mature and secure language, which makes it ideal to write smart contracts. Because of this, **Rust is the preferred programming language for writing smart contracts on NEAR**. While there might be a learning curve for those coming from web development, learning Rust enables to write safer and faster contracts. Furthermore, core contracts such as Fungible Tokens and DAOs are currently only available in Rust. :::info If you're getting started with Rust, we recommend you look through [this overview in the `nearcore` repository](https://github.com/near/nearcore/blob/master/docs/practices/rust.md). It's a great way to get your first steps in for the language and its ecosystem. ::: --- ## Create Your First Rust Contract Create your first **Rust contract** in minutes: 1. Download and install [Rust](https://doc.rust-lang.org/book/ch01-01-installation.html). 2. Create a new **rust** project using our [quickstart guide](../../2.build/2.smart-contracts/quickstart.md). 3. Read our docs on **[how to write smart contracts](../../2.build/2.smart-contracts/anatomy/anatomy.md)**.
NEAR & Social Good: The Future of Social Good and Crypto COMMUNITY July 28, 2022 Since their inception, blockchains and cryptocurrencies have been about much more than novel technologies and financial applications. Principles like building a more open, accessible, and equitable world have always featured prominently in the Web3 community. But crypto has even more potential in fostering social good, empowering communities, and solving some of the world’s biggest challenges. It’s difficult to predict how crypto and social good will look moving forward. However, by examining the green shoots emerging from NEAR projects and communities, clues begin to emerge from the cryptographic code. Here’s what the future of social good and crypto on NEAR might look like based on current ecosystem trends, projects, and initiatives. Creating novel ways for nonprofits to succeed With traditional Non-Government Organizations (NGOs) workflows, gaps have existed in terms of coordination and fundraising. One project on the NEAR blockchain, BeeTogether, is working to fill these gaps. The project is connecting NGOs with NFT and blockchain artists to gain visibility, raise awareness, and enhance fundraising efforts. “The BeeTogether approach is to give each artist the opportunity to present themselves individually,” explains Claudia Peter, founder of BeeTogether. “Then we give nonprofits a way to present themselves differently in marketing and social media. Together, we present the projects and how artists and their art are contributing to a greater cause.” BeeTogether also provides NFT stores for artists on the NEAR blockchain via MintBase. And with each artist or piece of art tied to a specific cause, people can directly support both nonprofits and NFT artists. Artists may choose to support, with the help of BeeTogether, a sustainability-focused nonprofit like Seas 4 Life. (Built on MintBase, Seas 4 Life promotes oceanic sustainability through funds and educational ocean safaris with experts.) This approach points to a future where creators and nonprofits are more closely integrated via the blockchain. “All the artists in BeeTogether stores can choose which projects and causes they want to work with and donate to,” Peter continues. “It’s defined in the store as a smart contract. As far as revenue split, the highest percentage goes to the artist and after that the nonprofit.” Peter predicts that cooperative models involving creators, NGOs, and even DAOs on the blockchain will enhance fundraising efforts and create even greater benefits for all parties involved. “We try to build a triangle of three parties: artists, nonprofits, and BeeTogether. And if everyone does their share of work, everyone also gets their share of profits,” says Peter. “It goes along with the decentralized ethos. It’s not one-directional, where people just give money to an NGO and hope they do something good with it. Donors are interacting on a deeper level and with greater transparency.” Supporting BeeTogether’s efforts is NEAR Ocean, an NFT information aggregator platform for the NEAR ecosystem. NEAR Ocean will donate a percentage of its proceeds to various charitable endeavors in partnership with BeeTogether. Founder Efte also thinks that nonprofits could potentially use unique NFTs to boost fundraising efforts and visibility. “Wouldn’t it be cool if when you donate to a cause you automatically receive a one-of-one NFT?” Efte says. “Not as an investment, but as a unique collectible that people could showcase. Or if a donor goes on safari to a nature reserve, they get pictures minted as NFT keepsakes? There’s a lot of potential for NGOs and nonprofits once we build out more infrastructure.” New paths for empowering underserved communities Cryptocurrency and blockchain technologies continue to yield social good by creating financial, social, and educational opportunities for disadvantaged and underserved communities. Web3 Familia is a perfect example. An organization and DAO, Web3 Familia’s goal is onboarding over one million Latinos worldwide onto Web3. “In the beginning, we identified a lack of Web3 resources for Spanish speakers globally,” says Christian Narvaez, Founder of Web3 Familia. “And we’ve evolved from just engaging with people who are crypto-curious. Now we educate institutional investors and venture capitalists who want to learn about blockchain to refocus how they deploy capital.” In Web3, this sort of intersection between disadvantaged communities and investors is not uncommon and has great potential. “We have a cycle where people are learning and building, and now non-Web3 investors are using Web3 Familia to learn more about blockchain capabilities,” Narvaez continues. “So we’re going full circle from just teaching retail how to use Web3 for their benefit to connecting people directly with institutions.” Narvaez also notes that DAOs and projects designed specifically for one community can and will have a wider reach and applications. Web3 Familia, for instance, is now educating English speakers and even people in remote locations in their own indigenous languages. “We’ve branched out to working with a female collective in Peru, for instance, that teaches crypto to locals in their indigenous language of Quechua,” says Narvaez “It just goes to show that people are using our model to cater to different regions and indigenous languages across Latin America.” Web3 Familia’s ever-evolving work is a beacon of what’s to come in crypto. Narvaez notes that many DAOs, projects, and other blockchain initiatives are rapidly evolving. They’re moving from the educational and onboarding stages to creating real-world, visible results that make a difference in people’s lives. “Blockchain for good is graduating to the point where real-world initiatives are coming to life,” he says. “Whether it’s something like ChoiceDAO raising funds for reproductive rights or UnChained Fund getting assistance to Ukrainians at a fast pace, crypto is now helping society in tangible ways.” Advancing educational and career opportunities Parallel to Narvaez’s achievements with Web3 Familia is the work of the Blockchain Acceleration Foundation (BAF). Its mission: offer practical education, skills, and training that lead to jobs and contribution roles in the Web3 space. BAF has a unique structure and positioning as connective tissue between academia, students, and the blockchain industry. It provides meaningful insight into how individuals can go from simply learning about crypto to building substantial careers and income. “BAF’s vision is to create an incentive-aligned, automated, and tax-exempt nonprofit that scales blockchain education, development, and adoption around the world,” says Nour Assili, head of growth at BAF. “Our acceleration program works closely with blockchain clubs at different universities to support them in a variety of ways, from connecting them to funding and providing mentorship.” Student blockchain clubs and organizations face a variety of challenges. They range from legally accepting donations to accessing practical and relevant blockchain curriculum that leads to job opportunities. BAF is not just addressing many of those issues. They’re breaking new ground by coordinating with universities, students, and Web3 industry organizations. “We’re completely blockchain agnostic and funded by a variety of protocols and labs, including the NEAR Foundation,” Assili continues. “So we’re really a source of truth for a lot of professors, students, and universities when it comes to developing and accelerating blockchain curriculums.” But one of BAF’s most unique aspects is how the organization helps students and clubs get funding and even earn income in a regulatory-compliant manner. “Our Fiscal Sponsorship program is looking towards the future in that when crypto goes more mainstream, we’ll all need to pay a lot more attention to regulatory compliance,” notes Aaron Casillas, senior advisor for BAF. “Compliance is one of the biggest threats to students and blockchain clubs,” he continues. “Whether it’s receiving donations, minting NFTs, or creating a social token, we need to think about how that’s all done in a compliant way and play by the rules.” With the Fiscal Sponsorship program, BAF helps match university clubs with donors and provide the legal means and framework for money to exchange hands. BAF is also teaching students how to become validators on networks like NEAR. The project offers both the technical expertise for working Web3 and the legal passive crypto income for funding purposes. “We engage blockchain clubs and support them to run validators,” Casillas explains. “We equip them with the right hardware, educational playbooks, mentorship, and office hours to give them hands-on experience in Web3 and generate a revenue stream for their club by running nodes. NEAR has been instrumental in this process, including the upcoming Stake Wars program.” “In the future, we’ll probably see even more workers throughout the world displaced by technology,” he adds. “So I can also see the blockchain becoming needed to be some kind of rails to facilitate a type of universal basic income.” Building a better future with NEAR One thing is clear about the future of crypto for social good. A diverse array of organizations, projects, and individuals will create real-world impact. Organizations like BeeTogether are showing the innovative and powerful ways of connecting NFT creators and nonprofits for environmental awareness and fundraising. Projects working with underserved communities, like Web3 Familia, will branch out to help any and all groups. This will include educating investors, business leaders, and financial institutions about blockchain and crypto. It will also involve consulting on how to invest in the creators, communities, and builders who most need it. And organizations like BAF show that blockchain education will migrate from theoretical to providing meaningful Web3 opportunities for everyone. From NFT storefronts supporting the environment to campus blockchain clubs getting students jobs, the future is being built right now. Whatever your Web3 passion might be, there’s no better time to start building on NEAR than today.
--- id: bounty title: Bug Bounty Program --- NEAR has a [revamped bug bounty program](https://hackenproof.com/near/near-protocol)! Hackers - help audit, test, and toughen NEAR up, starting with bounties in the protocol category, and soon expanding to wallet, web, console, and smart contracts
# Accounts ## Account ID NEAR Protocol has an account names system. Account ID is similar to a username. Account IDs have to follow the rules. ### Account ID Rules - minimum length is 2 - maximum length is 64 - **Account ID** consists of **Account ID parts** separated by `.` - **Account ID part** consists of lowercase alphanumeric symbols separated by either `_` or `-`. - **Account ID** that is 64 characters long and consists of lowercase hex characters is a specific **implicit account ID**. Account names are similar to a domain names. Top level account (TLA) like `near`, `com`, `eth` can only be created by `registrar` account (see next section for more details). Only `near` can create `alice.near`. And only `alice.near` can create `app.alice.near` and so on. Note, `near` can NOT create `app.alice.near` directly. Additionally, there is an implicit account creation path. Account ids, that are 64 character long, can only be created with `AccessKey` that matches account id via `hex` derivation. Allowing to create new key pair - and the sender of funds to this account to actually create an account. Regex for a full account ID, without checking for length: ```regex ^(([a-z\d]+[\-_])*[a-z\d]+\.)*([a-z\d]+[\-_])*[a-z\d]+$ ``` ### Top Level Accounts | Name | Value | | - | - | | REGISTRAR_ACCOUNT_ID | `registrar` | | MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH | 32 | Top level account names (TLAs) are very valuable as they provide root of trust and discoverability for companies, applications and users. To allow for fair access to them, the top level account names that are shorter than `MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH` characters going to be auctioned off. Specifically, only `REGISTRAR_ACCOUNT_ID` account can create new top level accounts that are shorter than `MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH` characters. `REGISTRAR_ACCOUNT_ID` implements standard Account Naming (link TODO) interface to allow create new accounts. ```python def action_create_account(predecessor_id, account_id): """Called on CreateAccount action in receipt.""" if len(account_id) < MIN_ALLOWED_TOP_LEVEL_ACCOUNT_LENGTH and predecessor_id != REGISTRAR_ACCOUNT_ID: raise CreateAccountOnlyByRegistrar(account_id, REGISTRAR_ACCOUNT_ID, predecessor_id) # Otherwise, create account with given `account_id`. ``` *Note: we are not going to deploy `registrar` auction at launch, instead allow to deploy it by Foundation after initial launch. The link to details of the auction will be added here in the next spec release post MainNet.* ### Examples Valid accounts: ```c ok bowen ek-2 ek.near com google.com bowen.google.com near illia.cheap-accounts.near max_99.near 100 near2019 over.9000 a.bro // Valid, but can't be created, because "a" is too short bro.a ``` Invalid accounts: ```c not ok // Whitespace characters are not allowed a // Too short 100- // Suffix separator bo__wen // Two separators in a row _illia // Prefix separator .near // Prefix dot separator near. // Suffix dot separator a..near // Two dot separators in a row $$$ // Non alphanumeric characters are not allowed WAT // Non lowercase characters are not allowed me@google.com // @ is not allowed (it was allowed in the past) system // cannot use the system account, see the section on System account below // TOO LONG: abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz.abcdefghijklmnopqrstuvwxyz ``` ## System account `system` is a special account that is only used to identify refund receipts. For refund receipts, we set the predecessor_id to be `system` to indicate that it is a refund receipt. Users cannot create or access the `system` account. In fact, this account does not exist as part of the state. ## Implicit account IDs Implicit accounts work similarly to Bitcoin/Ethereum accounts. It allows you to reserve an account ID before it's created by generating a ED25519 key-pair locally. This key-pair has a public key that maps to the account ID. The account ID is a lowercase hex representation of the public key. ED25519 Public key is 32 bytes that maps to 64 characters account ID. Example: public key in base58 `BGCCDDHfysuuVnaNVtEhhqeT4k9Muyem3Kpgq2U1m9HX` will map to an account ID `98793cd91a3f870fb126f66285808c7e094afcfc4eda8a970f6648cdf0dbd6de`. The corresponding secret key allows you to sign transactions on behalf of this account once it's created on chain. ### Implicit account creation An account with implicit account ID can only be created by sending a transaction/receipt with a single `Transfer` action to the implicit account ID receiver: - The account will be created with the account ID. - The account will have a new full access key with the ED25519-curve public key of `decode_hex(account_id)` and nonce `0`. - The account balance will have a transfer balance deposited to it. This account can not be created using `CreateAccount` action to avoid being able to hijack the account without having the corresponding private key. Once an implicit account is created it acts as a regular account until it's deleted. ## Account Data for an single account is collocated in one shard. The account data consists of the following: - Balance - Locked balance (for staking) - Code of the contract - Key-value storage of the contract. Stored in a ordered trie - [Access Keys](AccessKey.md) - [Postponed ActionReceipts](../RuntimeSpec/Receipts.md#postponed-actionreceipt) - [Received DataReceipts](../RuntimeSpec/Receipts.md#received-datareceipt) #### Balances Total account balance consists of unlocked balance and locked balance. Unlocked balance is tokens that the account can use for transaction fees, transfers staking and other operations. Locked balance is the tokens that are currently in use for staking to be a validator or to become a validator. Locked balance may become unlocked at the beginning of an epoch. See [Staking](../BlockchainLayer/EpochManager/Staking.md) for details. #### Contracts A contract (AKA smart contract) is a program in WebAssembly that belongs to a specific account. When account is created, it doesn't have a contract. A contract has to be explicitly deployed, either by the account owner, or during the account creation. A contract can be executed by anyone who calls a method on your account. A contract has access to the storage on your account. #### Storage Every account has its own storage. It's a persistent key-value trie. Keys are ordered in lexicographical order. The storage can only be modified by the contract on the account. Current implementation on Runtime only allows your account's contract to read from the storage, but this might change in the future and other accounts's contracts will be able to read from your storage. NOTE: To pay for blockchain storage, the protocol locks a token amount per account proportional to its state size. This includes storage of the account itself, contract code, contract storage and all access keys. See [Storage Staking](https://docs.near.org/concepts/storage/storage-staking) in the docs. #### Access Keys An access key grants an access to a account. Each access key on the account is identified by a unique public key. This public key is used to validate signature of transactions. Each access key contains a unique nonce to differentiate or order transactions signed with this access key. An access key has a permission associated with it. The permission can be one of two types: - `FullAccess` permission. It grants full access to the account. - `FunctionCall` permission. It grants access to only issued function call transactions. See [Access Keys](AccessKey.md) for more details.
--- id: overview sidebar_position: 1 sidebar_label: "Crossword Game Overview" title: "Basics overview laying out what will be accomplished in this first section." --- import basicCrossword from '/docs/assets/crosswords/basics-crossword.jpg'; import rustScary from '/docs/assets/crosswords/rust-scary--ksart.near.png'; import rustGood from '/docs/assets/crosswords/rust-good--ksart.near.png'; # Basics overview This first chapter of the crossword puzzle tutorial will introduce fundamental concepts to smart contract development in a beginner-friendly way. By the end of this chapter you'll have a proof-of-concept contract that can be interacted with via [NEAR CLI](https://docs.near.org/tools/near-cli) and a simple frontend that uses the [`near-api-js` library](https://www.npmjs.com/package/near-api-js). ## It's not as bad as you think Rust is a serious systems programming language. There are pointers, lifetimes, macros, and other things that may look foreign. Don't worry if this is how you feel: <figure> <img src={rustScary} alt="Programmer looking at Rust code and looking worried. Art created by ksart.near" width="600"/> <figcaption>Art by <a href="https://twitter.com/ksartworks" target="_blank">ksart.near</a></figcaption> </figure> <br/> The good news is the Rust SDK takes care of a lot of the heavy lifting. We'll also have the compiler on our side, often telling us exactly what went wrong and offering suggestions. As we go through this tutorial, you'll begin to see patterns that we'll use over and over again. So don't worry, writing smart contracts in Rust on NEAR doesn't require a heavy engineering background. <img src={rustGood} alt="Programmer looking quite relieved at the Rust code from the NEAR SDK. Art created by ksart.near" width="600"/> ## Assumptions for this first chapter - There will be only one crossword puzzle with one solution. - The user solving the crossword puzzle will not be able to know the solution. - Only the author of the crossword puzzle smart contract can set the solution. ## Completed project Here's the final code for this chapter: https://github.com/near-examples/crossword-tutorial-chapter-1 ## How it works <img src={basicCrossword} alt="Basic crossword puzzle" width="600" /> We'll have a rule about how to get the words in the proper order. We collect words in ascending order by number, and if there's and across and a down for a number, the across goes first. So in the image above, the solution will be **near nomicon ref finance**. Let's begin!
--- id: ft title: Fungible Tokens (FT) hide_table_of_contents: false --- import {FeatureList, Column, Feature} from "@site/src/components/featurelist" import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import BOSGetMetadata from "./ft/bos/get-metadata.md" import BOSCheckBalance from "./ft/bos/check-balance.md" import BOSSendToken from "./ft/bos/send.md" import BOSRegister from "./ft/bos/register.md" import BOSAttachTokenToCall from "./ft/bos/attach-to-call.md" import BOSCreateToken from "./ft/bos/create.md" import WebAppGetMetadata from "./ft/web-app/get-metadata.md" import WebAppCheckBalance from "./ft/web-app/check-balance.md" import WebAppSendToken from "./ft/web-app/send.md" import WebAppRegister from "./ft/web-app/register.md" import WebAppAttachTokenToCall from "./ft/web-app/attach-to-call.md" import WebAppCreateToken from "./ft/web-app/create.md" import CLIGetMetadata from "./ft/near-cli/get-metadata.md" import CLICheckBalance from "./ft/near-cli/check-balance.md" import CLISendToken from "./ft/near-cli/send.md" import CLIRegister from "./ft/near-cli/register.md" import CLIAttachTokenToCall from "./ft/near-cli/attach-to-call.md" import CLICreateToken from "./ft/near-cli/create.md" import SmartContractSendToken from "./ft/smart-contract/send.md" import SmartContractAttachTokenToCall from "./ft/smart-contract/attach-to-call.md" Besides the native NEAR token, NEAR accounts have access to a [multitude of tokens](https://guide.ref.finance/developers-1/cli-trading#query-whitelisted-tokens) to use thoughtout the ecosystem. Moreover, it is even possible for users to create their own fungible tokens. In contrast with the NEAR native token, fungible token (FT) are **not stored** in the user's account. In fact, each FT lives in **their own contract** which is in charge of doing **bookkeeping**. This is, the contract keeps track of how many tokens each user has, and handles transfers internally. ![FT](/docs/primitives/ft.png) In order for a contract to be considered a FT-contract it has to follow the [**NEP-141 and NEP-148 standards**](https://nomicon.io/Standards/FungibleToken/). The **NEP-141** & **NEP-148** standards explain the **minimum interface** required to be implemented, as well as the expected functionality. --- ## Token Factory You can create an FT using the community tool [Token Farm](https://tkn.farm/). Token farm is a token factory, you can interact with it through its graphical interface, or by making calls to its contract. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSCreateToken /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppCreateToken /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLICreateToken /> </TabItem> </Tabs> The FT you create will live in the account `<your_token_symbol>.tkn.near` (e.g. `test.tkn.near`). --- ## Deploying Your Own Contract You can also create a fungible token by deploying and initializing a [canonical FT contract](https://github.com/near-examples/FT). On initialization you will define the token's metadata such as its name (e.g. Ethereum), symbol (e.g. ETH) and total supply (e.g. 10M). You will also define an `owner`, which will own the tokens **total supply**. To initialize a FT contract you will need to deploy it and then call the `new` method defining the token's metadata. ```bash near deploy <account-id> --wasmFile fungible_token.wasm near call <account-id> new '{"owner_id": "<owner-account>", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId <account-id> ``` :::tip Check the [Contract Wizard](https://near.org/contractwizard.near/widget/ContractWizardUI) to create a personalized FT contract!. ::: --- ## Querying Metadata You can query the FT's metadata by calling the `ft_metadata`. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSGetMetadata /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppGetMetadata /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIGetMetadata /> </TabItem> </Tabs> --- ## Checking Balance To know how many coins a user has you will need to query the method `ft_balance_of`. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSCheckBalance /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppCheckBalance /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLICheckBalance /> </TabItem> </Tabs> --- ## Registering a User In order for an user to own and transfer tokens they need to first **register** in the contract. This is done by calling `storage_deposit` and attaching 0.00125Ⓝ. By calling this `storage_deposit` the user can register themselves or **register other users**. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSRegister /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppRegister /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIRegister /> </TabItem> </Tabs> :::info You can make sure a user is registered by calling `storage_balance_of`. ::: :::tip After a user calls the `storage_deposit` the FT will appear in their Wallets. ::: --- ## Transferring Tokens To send FT to another account you will use the `ft_transfer` method, indicating the receiver and the amount of FT you want to send. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSSendToken /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppSendToken /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLISendToken /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract" default> <SmartContractSendToken /> </TabItem> </Tabs> --- ## Attaching FTs to a Call Natively, only NEAR tokens (Ⓝ) can be attached to a function calls. However, the FT standard enables to attach fungible tokens in a call by using the FT-contract as intermediary. This means that, instead of you attaching tokens directly to the call, you ask the FT-contract to do both a transfer and a function call in your name. Let's assume that you need to deposit FTs on Ref Finance. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSAttachTokenToCall /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppAttachTokenToCall /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIAttachTokenToCall /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract" default> <SmartContractAttachTokenToCall /> </TabItem> </Tabs> How it works: 1. You call ft_transfer_call in the FT contract passing: the receiver, a message, and the amount. 2. The FT contract transfers the amount to the receiver. 3. The FT contract calls receiver.ft_on_transfer(sender, msg, amount) 4. The FT contract handles errors in the ft_resolve_transfer callback. 5. The FT contract returns you how much of the attached amount was actually used. --- ## Handling Deposits (Contract Only) If you want your contract to handle deposit in FTs you have to implement the `ft_on_transfer` method. When executed, such method will know: - Which FT was transferred, since it is the predecessor account. - Who is sending the FT, since it is a parameter - How many FT were transferred, since it is a parameter - If there are any parameters encoded as a message The `ft_on_transfer` must return how many FT tokens have to **be refunded**, so the FT contract gives them back to the sender. ```rust // Implement the contract structure #[near_bindgen] impl Contract {} #[near_bindgen] impl FungibleTokenReceiver for Contract { // Callback on receiving tokens by this contract. // `msg` format is either "" for deposit or `TokenReceiverMessage`. fn ft_on_transfer( &mut self, sender_id: AccountId, amount: U128, msg: String, ) -> PromiseOrValue<U128> { let token_in = env::predecessor_account_id(); assert!(token_in == self.ft_contract, "{}", "The token is not supported"); assert!(amount >= self.price, "{}", "The attached amount is not enough"); env::log_str(format!("Sender id: {:?}", sender_id).as_str()); if msg.is_empty() { // Your internal logic here PromiseOrValue::Value(U128(0)) } else { let message = serde_json::from_str::<TokenReceiverMessage>(&msg).expect("WRONG_MSG_FORMAT"); match message { TokenReceiverMessage::Action { buyer_id, } => { let buyer_id = buyer_id.map(|x| x.to_string()); env::log_str(format!("Target buyer id: {:?}", buyer_id).as_str()); // Your internal business logic PromiseOrValue::Value(U128(0)) } } } } } ``` --- ## Additional Resources 1. [NEP-141 and NEP-148 standards](https://nomicon.io/Standards/Tokens/FungibleToken/) 2. [FT Event Standards](https://nomicon.io/Standards/Tokens/FungibleToken/Event) 3. [FT reference implementation](https://github.com/near-examples/FT) 4. [Fungible Tokens 101](../../3.tutorials/fts/0-intro.md) - a set of tutorials that cover how to create a FT contract using Rust.
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs groupId="nft-contract-tabs" className="file-tabs"> <TabItem value="Paras" label="Paras" default> ```js const tokenData = Near.call( "x.paras.near", "nft_buy", { token_series_id: "299102", receiver_id: "bob.near", }, undefined, 205740000000000000000000 // NFT price + storage cost ); ``` **Example response:** ```json "299102:1" ``` </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```js const tokenData = Near.call( "simple.market.mintbase1.near", "buy", { nft_contract_id: "rubennnnnnnn.mintbase1.near", token_id: "38", referrer_id: null, }, undefined, 1000000000000000000000 // NFT price + storage cost (optional, depends on a contract) ); ``` **Example response:** ```json { "payout": { "rub3n.near": "889200000000000000000", "rubenm4rcus.near": "85800000000000000000" } } ``` </TabItem> </Tabs>
--- id: minting title: Minting sidebar_label: Minting --- import {Github} from "@site/src/components/codetabs" This is the first of many tutorials in a series where you'll be creating a complete NFT smart contract from scratch that conforms with all the NEAR [NFT standards](https://nomicon.io/Standards/NonFungibleToken/). Today you'll learn how to create the logic needed to mint NFTs and have them show up in your NEAR wallet. You will be filling a bare-bones [skeleton smart contract](/tutorials/nfts/skeleton) to add minting functionalities. :::info Contracts You can find the skeleton contract in our [Skeleton folder](https://github.com/near-examples/nft-tutorial/tree/main/nft-contract-skeleton) A completed version of this tutorial can be found in the [Basic NFT folder](https://github.com/near-examples/nft-tutorial/tree/main/nft-contract-basic) ::: --- ## Introduction To get started, go to the `nft-contract-skeleton` folder in our repo. If you haven't cloned the repository, refer to the [Contract Architecture](/tutorials/nfts/skeleton) to get started. ``` cd nft-contract-skeleton/ ``` If you wish to see the finished code of this step-by-step basic NFT contract tutorial, that can be found on the `nft-contract-basic` folder. --- ## Modifications to the skeleton contract {#what-does-minting-mean} In order to implement the logic needed for minting, we should break it up into smaller tasks and handle those one-by-one. Let's step back and think about the best way to do this by asking ourselves a simple question: what does it mean to mint an NFT? To mint a non-fungible token, in the most simple way possible, a contract needs to be able to associate a token with an owner on the blockchain. This means you'll need: - A way to keep track of tokens and other information on the contract. - A way to store information for each token such as `metadata` (more on that later). - A way to link a token with an owner. That's it! We've now broken down the larger problem into some smaller, less daunting, subtasks. Let's start by tackling the first and work our way through the rest. <hr class="subsection" /> ### Storing information on the contract {#storing-information} Start by navigating to `nft-contract-skeleton/src/lib.rs` and filling in some of the code blocks. You need to be able to store important information on the contract such as the list of tokens that an account has. #### Contract Struct The first thing to do is modifying the contract `struct` as follows: <Github language="rust" start="35" end="52" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/lib.rs" /> This allows you to get the information stored in these data structures from anywhere in the contract. The code above has created 3 token specific storages: - **tokens_per_owner**: allows you to keep track of the tokens owned by any account - **tokens_by_id**: returns all the information about a specific token - **token_metadata_by_id**: returns just the metadata for a specific token In addition, you'll keep track of the owner of the contract as well as the metadata for the contract. You might be confused as to some of the types that are being used. In order to make the code more readable, we've introduced custom data types which we'll briefly outline below: - **AccountId**: a string that ensures there are no special or unsupported characters. - **TokenId**: simply a string. As for the `Token`, `TokenMetadata`, and `NFTContractMetadata` data types, those are structs that we'll define later in this tutorial. #### Initialization Functions Next, create what's called an initialization function; we will name it `new`, but you can choose any name you prefer. This function needs to be invoked when you first deploy the contract. It will initialize all the contract's fields that you've defined above with default values. Don't forget to add the `owner_id` and `metadata` fields as parameters to the function, so only those can be customized. This function will default all the collections to be empty and set the `owner` and `metadata` equal to what you pass in. <Github language="rust" start="96" end="114" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/lib.rs" /> More often than not when doing development, you'll need to deploy contracts several times. You can imagine that it might get tedious to have to pass in metadata every single time you want to initialize the contract. For this reason, let's create a function that can initialize the contract with a set of default `metadata`. You can call it `new_default_meta` and it'll only take the `owner_id` as a parameter. <Github language="rust" start="74" end="89" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/lib.rs" /> This function is simply calling the previous `new` function and passing in the owner that you specify and also passes in some default metadata. <hr class="subsection" /> ### Metadata and token information {#metadata-and-token-info} Now that you've defined what information to store on the contract itself and you've defined some ways to initialize the contract, you need to define what information should go in the `Token`, `TokenMetadata`, and `NFTContractMetadata` data types. Let's switch over to the `nft-contract-skeleton/src/metadata.rs` file as this is where that information will go. If you look at the [standards for metadata](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata), you'll find all the necessary information that you need to store for both `TokenMetadata` and `NFTContractMetadata`. Simply fill in the following code. <Github language="rust" start="10" end="39" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/metadata.rs" /> This now leaves you with the `Token` struct and something called a `JsonToken`. The `Token` struct will hold all the information directly related to the token excluding the metadata. The metadata, if you remember, is stored in a map on the contract in a data structure called `token_metadata_by_id`. This allows you to quickly get the metadata for any token by simply passing in the token's ID. For the `Token` struct, you'll just keep track of the owner for now. <Github language="rust" start="41" end="46" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/metadata.rs" /> Since NEAR smart contracts receive and return data in JSON format, the purpose of the `JsonToken` is to act as output when the user asks information for an NFT. This means you'll want to store the owner, token ID, and metadata. <Github language="rust" start="49" end="58" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/metadata.rs" /> :::tip Some of you might be thinking _"how come we don't just store all the information in the `Token` struct?"_. The reason behind this is that it's actually more efficient to construct the JSON token on the fly only when you need it rather than storing all the information in the token struct. In addition, some operations might only need the metadata for a token and so having the metadata in a separate data structure is more optimal. ::: #### Function for querying contract metadata Now that you've defined some of the types that were used in the previous section, let's move on and create the first view function `nft_metadata`. This will allow users to query for the contract's metadata as per the [metadata standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata). <Github language="rust" start="60" end="70" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/metadata.rs" /> This function will get the `metadata` object from the contract which is of type `NFTContractMetadata` and will return it. Just like that, you've completed the first two tasks and are ready to move onto last part of the tutorial. <hr class="subsection" /> ### Minting Logic {#minting-logic} Now that all the information and types are defined, let's start brainstorming how the minting logic will play out. In the end, you need to link a `Token` and `TokenId` to a specific owner. Let's look back at the `lib.rs` file to see how you can accomplish this. There are a couple data structures that might be useful: ```rust //keeps track of all the token IDs for a given account pub tokens_per_owner: LookupMap<AccountId, UnorderedSet<TokenId>>, //keeps track of the token struct for a given token ID pub tokens_by_id: LookupMap<TokenId, Token>, //keeps track of the token metadata for a given token ID pub token_metadata_by_id: UnorderedMap<TokenId, TokenMetadata>, ``` Looking at these data structures, you could do the following: - Add the token ID into the set of tokens that the receiver owns. This will be done on the `tokens_per_owner` field. - Create a token object and map the token ID to that token object in the `tokens_by_id` field. - Map the token ID to it's metadata using the `token_metadata_by_id`. #### Storage Implications {#storage-implications} With those steps outlined, it's important to take into consideration the storage costs of minting NFTs. Since you're adding bytes to the contract by creating entries in the data structures, the contract needs to cover the storage costs. If you just made it so any user could go and mint an NFT for free, that system could easily be abused and users could essentially "drain" the contract of all it's funds by minting thousands of NFTs. For this reason, you'll make it so that users need to attach a deposit to the call to cover the cost of storage. You'll measure the initial storage usage before anything was added and you'll measure the final storage usage after all the logic is finished. Then you'll make sure that the user has attached enough $NEAR to cover that cost and refund them if they've attached too much. This is how we do it in code: <Github language="rust" start="3" end="45" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/mint.rs" /> You'll notice that we're using some internal methods such as `refund_deposit` and `internal_add_token_to_owner`. We've described the function of `refund_deposit` and as for `internal_add_token_to_owner`, this will add a token to the set of tokens an account owns for the contract's `tokens_per_owner` data structure. You can create these functions in a file called `internal.rs`. Go ahead and create the file. Your new contract architecture should look as follows: ``` nft-contract ├── Cargo.lock ├── Cargo.toml ├── README.md ├── build.sh └── src ├── approval.rs ├── enumeration.rs ├── internal.rs ├── lib.rs ├── metadata.rs ├── mint.rs ├── nft_core.rs ├── events.rs └── royalty.rs ``` Add the following to your newly created `internal.rs` file. <Github language="rust" start="1" end="133" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/internal.rs" /> :::note You may notice more functions in the `internal.rs` file than we need for now. You may ignore them, we'll come back to them later. ::: Let's now quickly move to the `lib.rs` file and make the functions we just created invokable in other files. We'll add the internal crates and mod the file as shown below: <Github language="rust" start="10" end="23" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/lib.rs" /> At this point, the core logic is all in place so that you can mint NFTs. You can use the function `nft_mint` which takes the following parameters: - **token_id**: the ID of the token you're minting (as a string). - **metadata**: the metadata for the token that you're minting (of type `TokenMetadata` which is found in the `metadata.rs` file). - **receiver_id**: specifies who the owner of the token will be. Behind the scenes, the function will: 1. Calculate the initial storage before adding anything to the contract 2. Create a `Token` object with the owner ID 3. Link the token ID to the newly created token object by inserting them into the `tokens_by_id` field. 4. Link the token ID to the passed in metadata by inserting them into the `token_metadata_by_id` field. 5. Add the token ID to the list of tokens that the owner owns by calling the `internal_add_token_to_owner` function. 6. Calculate the final and net storage to make sure that the user has attached enough NEAR to the call in order to cover those costs. <hr class="subsection" /> ### Querying for token information If you were to go ahead and deploy this contract, initialize it, and mint an NFT, you would have no way of knowing or querying for the information about the token you just minted. Let's quickly add a way to query for the information of a specific NFT. You'll move to the `nft-contract-skeleton/src/nft_core.rs` file and edit the `nft_token` function. It will take a token ID as a parameter and return the information for that token. The `JsonToken` contains the token ID, the owner ID, and the token's metadata. <Github language="rust" start="129" end="143" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/nft_core.rs" /> With that finished, it's finally time to build and deploy the contract so you can mint your first NFT. --- ## Interacting with the contract on-chain Now that the logic for minting is complete and you've added a way to query for information about specific tokens, it's time to build and deploy your contract to the blockchain. ### Deploying the contract {#deploy-the-contract} For deployment, you will need a NEAR account with the keys stored on your local machine. Navigate to the [NEAR wallet](https://testnet.mynearwallet.com//) site and create an account. :::info Please ensure that you deploy the contract to an account with no pre-existing contracts. It's easiest to simply create a new account or create a sub-account for this tutorial. ::: Log in to your newly created account with `near-cli` by running the following command in your terminal. ```bash near login ``` To make this tutorial easier to copy/paste, we're going to set an environment variable for your account ID. In the command below, replace `YOUR_ACCOUNT_NAME` with the account name you just logged in with including the `.testnet` portion: ```bash export NFT_CONTRACT_ID="YOUR_ACCOUNT_NAME" ``` Test that the environment variable is set correctly by running: ```bash echo $NFT_CONTRACT_ID ``` Verify that the correct account ID is printed in the terminal. If everything looks correct you can now deploy your contract. In the root of your NFT project run the following command to deploy your smart contract and answer questions: ```bash cargo near deploy $NFT_CONTRACT_ID > Select the need for initialization: with-init-call - Add an initialize > What is the name of the function? new_default_meta > How would you like to pass the function arguments? json-args > Enter the arguments to this function: {"owner_id": "<YOUR_NFT_CONTRACT_ID>"} > Enter gas for function call: 100 TeraGas > Enter deposit for a function call (example: 10NEAR or 0.5near or 10000yoctonear): 0 NEAR > What is the name of the network? testnet > Select a tool for signing the transaction: sign-with-keychain > How would you like to proceed? send ``` You don't need to answer these questions every time. If you look at the results you will find the message `Here is the console command if you ever need to re-run it again`. The next line is the command which you may use instead of answering to interactive questions: ```bash cargo near deploy $NFT_CONTRACT_ID with-init-call new_default_meta json-args '{"owner_id": "'$NFT_CONTRACT_ID'"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send ``` You've just deployed and initialized the contract with some default metadata and set your account ID as the owner. At this point, you're ready to call your first view function. <hr class="subsection" /> ### Viewing the contract's metadata Now that the contract has been initialized, you can call some of the functions you wrote earlier. More specifically, let's test out the function that returns the contract's metadata: ```bash near view $NFT_CONTRACT_ID nft_metadata ``` This should return an output similar to the following: ```bash { spec: 'nft-1.0.0', name: 'NFT Tutorial Contract', symbol: 'GOTEAM', icon: null, base_uri: null, reference: null, reference_hash: null } ``` At this point, you're ready to move on and mint your first NFT. <hr class="subsection" /> ### Minting our first NFT {#minting-our-first-nft} Let's now call the minting function that you've created. This requires a `token_id` and `metadata`. If you look back at the `TokenMetadata` struct you created earlier, there are many fields that could potentially be stored on-chain: <Github language="rust" start="23" end="39" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-basic/src/metadata.rs" /> Let's mint an NFT with a title, description, and media to start. The media field can be any URL pointing to a media file. We've got an excellent GIF to mint but if you'd like to mint a custom NFT, simply replace our media link with one of your choosing. If you run the following command, it will mint an NFT with the following parameters: - **token_id**: "token-1" - **metadata**: - _title_: "My Non Fungible Team Token" - _description_: "The Team Most Certainly Goes :)" - _media_: `https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif` - **receiver_id**: "'$NFT_CONTRACT_ID'" ```bash near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-1", "metadata": {"title": "My Non Fungible Team Token", "description": "The Team Most Certainly Goes :)", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID --amount 0.1 ``` :::info The `amount` flag is specifying how much NEAR to attach to the call. Since you need to pay for storage, 0.1 NEAR is attached and you'll get refunded any excess that is unused at the end. ::: <hr class="subsection" /> ### Viewing information about the NFT Now that the NFT has been minted, you can check and see if everything went correctly by calling the `nft_token` function. This should return a `JsonToken` which should contain the `token_id`, `owner_id`, and `metadata`. ```bash near view $NFT_CONTRACT_ID nft_token '{"token_id": "token-1"}' ``` <details> <summary>Example response: </summary> <p> ```bash { token_id: 'token-1', owner_id: 'goteam.examples.testnet', metadata: { title: 'My Non Fungible Team Token', description: 'The Team Most Certainly Goes :)', media: 'https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif', media_hash: null, copies: null, issued_at: null, expires_at: null, starts_at: null, updated_at: null, extra: null, reference: null, reference_hash: null } } ``` </p> </details> **Go team!** You've now verified that everything works correctly and it's time to view your freshly minted NFT in the NEAR wallet's collectibles tab! --- ## Viewing your NFTs in the wallet If you navigate to the [collectibles tab](https://testnet.mynearwallet.com//?tab=collectibles) in the NEAR wallet, this should list all the NFTs that you own. It should look something like the what's below. ![empty-nft-in-wallet](/docs/assets/nfts/empty-nft-in-wallet.png) We've got a problem. The wallet correctly picked up that you minted an NFT, however, the contract doesn't implement the specific view function that is being called. Behind the scenes, the wallet is trying to call `nft_tokens_for_owner` to get a list of all the NFTs owned by your account on the contract. The only function you've created, however, is the `nft_token` function. It wouldn't be very efficient for the wallet to call `nft_token` for every single NFT that a user has to get information and so they try to call the `nft_tokens_for_owner` function. In the next tutorial, you'll learn about how to deploy a patch fix to a pre-existing contract so that you can view the NFT in the wallet. --- ## Conclusion In this tutorial, you went through the basics of setting up and understand the logic behind minting NFTs on the blockchain using a skeleton contract. You first looked at [what it means](#what-does-minting-mean) to mint NFTs and how to break down the problem into more feasible chunks. You then started modifying the skeleton contract chunk by chunk starting with solving the problem of [storing information / state](#storing-information) on the contract. You then looked at what to put in the [metadata and token information](#metadata-and-token-info). Finally, you looked at the logic necessary for [minting NFTs](#minting-logic). After the contract was written, it was time to deploy to the blockchain. You [deployed the contract](#deploy-the-contract) and [initialized it](#initialize-contract). Finally, you [minted your very first NFT](#minting-our-first-nft) and saw that some changes are needed before you can view it in the wallet. --- ## Next Steps In the [next tutorial](/tutorials/nfts/upgrade-contract), you'll find out how to deploy a patch fix and what that means so that you can view your NFTs in the wallet. :::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` - Metadata standard: [NEP177](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata), version `2.1.0` :::
--- title: 2.6 Crypto Ecosystems and Emerging Technologies description: Crypto, the 21st Century General Purpose Technology --- # 2.6 Crypto Ecosystems and Emerging Technologies The focus of this lecture is on crypto and emerging technologies. But from another angle, this could equally be stated as _Crypto, the 21st Century General Purpose Technology_ Economic history loves to reference general purpose technologies like the steam engine or the microprocessor, but when we zoom in and look fundamentally at how general purpose technologies operate we can gain a much clearer picture of the _timeframes they operate on_, inherent blockers and presuppositions for their success, and most importantly, the value proposition of intermingling with other emerging technologies of the time. ## Emerging Technologies of Our Time Looking towards past technological revolutions can help inform our understanding of what to make of the current technological revolution known as _the fourth industrial revolution._ Three important points deserve attention: * **The Time For Impact:** While a ‘revolution’ is often constitutive of a broad and sudden change, recent studies of macro-economic growth indicate that few changes actually took place in the British economy until the 1830s, with the majority of population unaffected until the 1850s and 1860s. [^1] * **The Industries Are Not Always The Ones We Expect:** At the same time, the industries that experienced the most growth through 1830, grew due to specific innovations that were minimally if at all related to ‘industrialization’ [^2]. This view is further complemented by Clark, who holds that improvements from new technologies are most visible in the production of textiles (increased by 43%), transportation technologies (increase of 20%), and agriculture (increase by 20%) with a much smaller portion credited to improvements surrounding coal, iron, and steel. [^3] * **The Social Savings Lag By Decades:** It was not until the 1830s that the first railroads began to be implemented, while “social savings” due to steam engine improvements remained stagnant at 0.3% per year between 1830 and 1850.[^4] * **General Purpose Technologies Facilitate Technology Diffusion:** While the steam engine was not the most impactful technology at first, it quickly became the foundation from which entire industries emerged. Blockchain, in a similar vein, inhabits the same ‘General Purpose Technology’ place, as a foundational piece of digital infrastructure for the future of smart-contract based execution of assets and data. **Keeping this in Mind, Here Are Some of the Most Promising Emerging Technologies That Intersect Directly With Crypto:** **_Virtual Reality:_** Virtual Reality refers to 3D digital experiences, either entirely based from within a digital environment, or layered onto a physical environment using some form of technology. People most often associate it with the metaverse in a fully digital environment (ready player 1), or something akin to a more ‘hands on’ _Pokemon Go_ or _Google Glass_ for layering in the physical world. Overlap between crypto and virtual reality is multiple but most interesting in the following areas: * _Decentralized Metaverse - Land, Ownership, Property and Items:_ Using a Layer 1 blockchain to handle all of the value inside of a metaverse in a decentralized and permissionless manner, is the basis of creating a ‘community’ operated metaverse as opposed to one operated exclusively by a big tech company. Crypto facilitates the object, account, asset, and property ownership of the items inside of the metaverse. * _NFTs:_ Any type of future non-fungible value interfacing with the physical world, can be harmonized with virtual reality to create interactive incentives between the backers of the project and the users. The real-world implications are simple: Use a VR headset, to be able to see or collect the NFT. In the metaverse, the NFT can be embedded across the digital-verse and collected by any active user. * _Gaming:_ The close connection between VR and Play to Earn (P2E) gaming is well known → An enhanced gaming experience can center around connecting physical objects and movements with in-game actions. Virtual reality effectively bridges the gap between the personal and the digital for an integrated gaming experience. Set within a P2E game, the user would own and participate in an open and permissionless game economy such that the assets and collectables they own in the game, are exclusively theirs. * _Network States_ : Digital countries known as network states are discussed in detail in Module 5. However the idea expands to any social or political group: In short, only a user with a specific NFT or access to a gated community, conjoined with a virtual reality set, would be able to see a layering of their digital country inside of the physical world. This would refer to viewing entrances to specific community areas, banners showing representation of that country, or resources and other benefits in being associated with the country. **_IoT / 3D Printing:_** The Internet of Things (and the prospect of printing intelligent objects using 3D Printers) refers to the ever expanding world of intelligent objects capable of receiving, connecting, and transmitting information between one another, and a central node. The overlap with crypto is multiple: * _Automated supply chain networks:_ In 2017, a number of projects launched promising to re-invent supply chain management. The basis for this is the prospect of autonomous verification and traceability networks, outsourced to blockchains for decentralized and permissionless management. This would center around any single asset or event, that a sensor would be attached to, such that there would be an immutable proof hashed or recorded on-chain to be used up and downstream by suppliers and purchasers. * _Decentralized Insurance:_ Closely connected to autonomous supply chain networks, is the prospect of forms of decentralized insurance built around independent sensor data from the Internet of Things. These markets could vary from a smart fridge, and smart home, to a suite of sensors collecting agricultural, air quality, water quality, and biomass health. Entities such as IBM have actively experimented with such use-cases in terms of water resource management and settlement. The value proposition here is the following: Contract based settlement, payout, and financial transfer of liability, based upon a smart device(s) data reading recorded on a chain and interacting with a smart contract. * _Data Markets of the Future:_ In the world of the Internet of Things implicit value centers on the concept of ‘information’. A sensor can collect data, from which data can be collected, aggregated and utilized for enhanced _insight, decision making_, and _financial planning. _Classic examples refer to the quality of cargo moving between countries, first-mover advantage on fresh data coming from street sensors used to determine traffic and consumption levels, and even data surrounding climate measurements for insurance and real-estate prices. Data markets - moving on-chain - suggest that the general public will have automated and permissionless access to increasing amounts of information. * _Blueprints and logs of printed items:_ For 3D printing purposes, the future marketplaces of blue-prints, designs, and rights to 3D Printed objects is oriented to moving on-chain. The concept is quite straightforward: With the accelerated development of 3D printed systems and objects (closely connected to advances in material science) a market for the sharing and building of different objects becomes more affordable across geographies and jurisdictions to the extent that a retail user could self-print a household item. Blockchain offers the opportunity for these systems to be publicly accessible, open-source, and decentralized (most likely using NFTs) in a similar way to how art creation and monetization is becoming decentralized. The difference with 3D printing, is that the blueprint is connected to generating the item physically. **_Artificial Intelligence / Machine Learning / Neural Networks:_** Perhaps no other field has drawn such scrutiny, hype, and fear as the concept of artificial intelligence. For the sake of convenience we link together AI, with Machine Learning (rapid algorithmic processing of information), as well as Digital Neural Networks, to refer to the increasingly responsive, interactive, and automated world of software. From ChatGPT to Boston Dynamics, the future intersection of AI and blockchain is closely connected: * _Trading Bots:_ The simplest and most actively utilized form of AI / ML is at the intersection of trading, MEV, and automated interaction with smart contracts. Many market dynamics are correlated with automated contract execution strategies that are becoming increasingly sophisticated. These bots, and AI’s have the potential of analyzing large amounts of data and triggering trade positions, * _AI-Generated Art and Value:_ A large portion of the production value to be utilized in future metaverses, gaming engines, and in terms of art, music, and content, is moving into the realm of becoming AI-generated. This has the prospect of both saturating and expediting the development of crypto-networks, at global scale. Imagine for example, a logo generating AI, that any user can use after purchasing a specific NFT or paying in a specific token? **_Synthetic Biology and Genomics:_** CRISPR and CRISPR Prime, are biotechnologies that allow individual strands of DNA To be edited and altered. Companies like The Odin, are increasingly demonstrating the capacity to participate in the revolution in synthetic biology in a DIY manner. These breakthroughs have increased the ability to downsize access to revolutionary biological tools, while also increasing the importance of biological data - specifically genomics. Crypto as a foundational technology for facilitating the transfer of data and information with value attached, is poised to play a massive role in the synthetic biology revolution: * **Retail Value of Genetic Data:** Today the value of genomic data is locked in private siloes, usually concentrated across a select few countries in Europe, China and the USA. Many data sets are missing from individuals in Africa, South East Asia and South America. Crypto has the opportunity to create systems-level incentives for individuals to upload and share their genomic data, with privacy guaranteed, and access limited to those who are willing to pay directly to the individual for the fair value of it. * **Clinical Trial Data/ Decentralized Genetic data repositories and computational programs.** One step above simply licensing access to an individual genome, is the ability to share and monetize large scale studies from between jurisdictions. In essence, being able to decentralize access and insight - and eventually aggregate learnings - from different clinical trial studies dealing with genomics, metabolic processes, medicine reactions, and more. All of this is done in a manner such that regulatory bodies could access the information for approval for certain drugs, or commercial companies could re-sell IP and content developed based upon the on-chain information or hashes. * **DeSci for biohacking labs and Research.** The final frontier of the genomics revolution centers on financing and sharing the discoveries done by increasingly decentralized labs around the world. Decentralized Science seeks to revolutionize how science is done such that a protocol or self-executing code can better distribute and coordinate the flow of value based upon decentralized communities preferences. This would mean funding for new and radical experiments, as well as on-chain sharing of results with value built into the process. **_Space Exploration:_** While Space Exploration in itself is not a technology stack like AI or CRISPR, it is an industry that is pushing the limits of science and technology, from which crypto is most likely going to play a massive role. Today there are a number of initiatives working at the intersection of crypto and Space research. And while more use-cases remain to be developed there are some that are already clearly visible: * **DAOs for Resource Coordination and Financing:** Utilizing on-chain infrastructure for coordinating the financing, ownership, and management of Space resources. From launching payloads into space, to operating space stations, to colonizing planets, to fractionalizing profits from asteroid mining initiatives. * **Non-State Space Initiatives:** What SpaceX has demonstrated is that there is room for a private space industry. Blue Origin and many others are actively pushing this frontier. Crypto, connected with non-state space initiatives suggests that network states, launch pads, and space enterprises can all develop into the space domain with smart contract guarantees, value facilitation, and data generation being handled and settle primarily on-chain and not through an existing centralized entity. ## Why is Crypto Different? A Question of Design There is one fundamental and clear cut reason as to why crypto rather than any other of these emerging industries operates as the general foundation for the others: It’s open and permissionless nature. Shoshana Zuboff documents quite well how the privatization of AI and ML expertise has created a division of learning within society, at great cost to the general public: _“The division of learning in society has been hijacked by surveillance capitalism. In the absence of a robust double movement in which democratic institutions and civil society tether raw information capitalism to the people’s interests - however imperfectly - we are thrown back on the market form of the surveillance capitalist companies in the most decisive of contests over the division of learning in society. Experts in the disciplines associated with Machine Intelligence know this, but they have little grasp of its wider implications.” (The Age of Surveillance Capitalism, page 190)._ In simple terms, the innovation inside of AI and ML has been closed off in its own tiny ivory tower hidden deeply inside of existing technology companies. And while some programming languages have been opened up such as MOVE or GO, the App store itself and the algorithms developed have not been made public for open-source innovation and iteration. In crypto - everything is done out in the open. Any open-source protocol cedes its ability to be forked by launching itself on a public blockchain. The system becomes complete, by allowing a community of users to participate, inhabit, and eventually govern the system. This is why a twelve year old in Thailand, and a 40 year old in Canada can work on the same protocol, or participate in the same DeSci project. Crypto’s design is fundamentally _open, accessible, forkable, permissionless, communal, decentralized,_ and _composable_- such that on the level of value, it is the optimal communication and synthesis technology for moving on from an era of fragmentation, siloes, and ivory towers. ## Being Realistic About Blockchain Powering the Fourth Industrial Revolution Characteristically, general purpose technologies accelerate the efficiency and proliferation of other technologies. But the development of general purpose technologies themselves - and their capacity to integrate across society - is a long and strenuous process that takes significant amounts of time. In the case of the steam engine it was over three decades from Watt’s original invention. And while crypto has leapfrogged its bottlenecks at the speed of software as opposed to hardware, it remains to be seen how long it will take to penetrate institutions and other industries in a manner that actually ‘catches’. ## Important Takeaways * **Caution With Enterprise Blockchain:** The idea of enterprise blockchain is much clearer than the ability for existing companies to readily incorporate such technologies into their business models. If early experimentation with Hyperledger and private blockchains for supply-chain management, fashion traceability, and shipping have demonstrated, it is that product market fit can take decades from the time the initial use-case has been conceived. To date (2023) Enterprise blockchain remains an extremely tricky and difficult niche of crypto that few if any entrepreneurs have successfully cracked open. * **Even if the Tech is ‘Ready’, The World Might Not Be:** If there is any example of being too early it is the sad story of the Leblanc and Solvay process. One ended up bankrupt and killed himself, the other profited immensely. The same chemical process was commercialized by both. However one was early, and the other was just on time. What this tells us is that oftentimes in cycles of innovation - the macro, external events - are catalysts for the adoption and implementation of existing technology ‘on hand’. * **First Movers Are Likely Winners:** As we have seen with Uniswap, Aave, MakerDAO, GMX, Ethereum, and OpenSea - first mover advantage accrues significant market share and user-engagement, relative to copy-cat’s or iterations later on. This suggests that first-movers of innovation (particularly in the emerging technology stack discussed above), capable of building original blue chip products, have the most to gain from opening up a new market cluster. * **Will it all eventually go on-chain?** The idea that software is eating the world has been touted from the likes of a16z and Google for more than 15 years. The question for Web3 is _to what extent is the world going to move on-chain? _As it stands today, most industries and software systems can benefit from moving onto some form of distributed ledger (private, public, permissioned, permissionless). Some have gone so far to speculate that SAAS as a whole stands to be disrupted and unified in the coming twenty years by smart contracts networks (most likely between L1s). So while it is likely that most of our systems and industries will eventually move on-chain to some degree (Similar to how many things on-boarded to the internet since 2000), it is unclear the velocity of this change as well as the hotspots for innovation from it. --- ## Notes [^1]: Mokyr, "Accounting for the Industrial Revolution," 1-2. [^2]: Mokyr, "Accounting for the Industrial Revolution," 2. [^3]: Gregory Clark, “The Industrial Revolution: In Theory and History,” 6. [^4]: Joel Mokyr, "The Enlightened Economy: An Economic History of Britain 1700 - 1850" , The New Economic History of Britain, New Haven: Yale University Press, 2009, 125 - 126. and Clark, “The Industrial Revolution: In Theory and History,” 8.
Community Update: June 5th, 2020 COMMUNITY June 5, 2020 This week in America, millions have taken to the streets to protest the murder of George Floyd and a system that pushes down minorities and perpetuates injustice. We have been humbled and inspired to watch this movement spread across the globe. We applaud your support. This is too important for silence. There is always more we can do in the pursuit of growth, acceptance, and allyship. We understand that many don’t have the bandwidth for newsletters. If community programs and learning new ways to earn and learn serve you, read on. If not, we love you and are here for you regardless. If there are other ways we can support you and this community, please let us know. The Launch of our Guild Program We are thrilled to announce the launch of our second community program. At the beginning of the year, we started our Contributor Program to directly work with community members on NEAR initiatives. Since we began, people around the world have been looking for ways to get more involved. The existing Contributor Program is focused on individual contributors to NEAR’s engineering efforts and it will continue. The Guild Program is focused on community contributions. Whether you already run a community, project, or company, or you want to start one, the Guild Program allows you to receive rewards based on the engagement of your Guild. Head over to the launch announcement. Difference between Contributors and Guilds RL1 Hackathon Winners NEAR hosted a two-week hackathon with Gitcoin right after Ready Layer One, a virtual conference. In case you missed it, the recordings are uploaded on the RL1 YouTube Channel. We want to thank all participants, who got involved and competed for the $9.500 prize pool. Over 25 teams submitted their project, of which 12 received a prize. Check-out the full list on our blog. Links to all the winners for anyone else clicking through 1/https://t.co/bYk3EahPC6https://t.co/CKDX4iHiOyhttps://t.co/io3cJtvpvChttps://t.co/YKT2ljwWyDhttps://t.co/mmlwJiTIgqhttps://t.co/heJUIvFXEjhttps://t.co/3NxWFI2bb5https://t.co/f5DOkDqThNhttps://t.co/7u9ZY9toWL — Maria ⚡️ (@MariaShen) June 3, 2020 Tweet by Maria Shen — List of hackathon winners Events Our friends at Fabric Ventures are hosting their third edition of Web 3.0 Stage at CogX on June 8-10th. Illia and Erik will be speaking. Message us for the chance to receive a free ticket — first-come-first-serve basis. Do you want to see what our community is up to? Join us at our Community Talk next Wednesday at 5 PM CEST. Jan will cover how cities can be introduced to smart solutions on blockchain. For more info and how to sign-up head over to our Community Calendar. Peter joined a panel on Ecosystem development at Mainnet.events with Jacob Arluck from TQTezos and Colin Evran from Protocol Labs Engineering Update We completed the security audit of our core contracts. The issues that were found can be addressed by the improving documentation or adjusting the fees; Finishing the implementation of the core functionality of the NEAR to Ethereum bridge. Last Friday, we successfully transferred an ERC20 token from Ethereum to NEAR; We have formed a team to work on the “contract runtime”, which in the future will be a general-purpose out of the box solution for any blockchain wanting to run Wasm contracts; We published a spec and the implementation of light client proofs; Lots of work on testing and stabilizing the chain; Validator Updates Stake Wars is now open for contributions: every validator challenge gives the opportunity to earn NEAR tokens by creating tutorials, blog posts and videos. More info in the Github repo. Blaze, one of our contributors and validators, is building a Validator Dashboard on NEAR. Congrats to our friends from Polkadot and Celo for launching their MainNet 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.
--- id: feed-indexer title: Social Feed Indexer sidebar_label: Social Feed Indexer --- :::info NEAR QueryAPI is currently under development. Users who want to test-drive this solution need to be added to the allowlist before creating or forking QueryAPI indexers. You can request access through [this link](http://bit.ly/near-queryapi-beta). ::: ## Running `feed-indexer` The indexer `indexingLogic.js` is comprised of functions that help handle, transform and record data. The main logic for handling transaction data as it occurs from the blockchain can be found underneath the comment marked: ```js // Add your code here ``` A schema is also specified for the tables in which data from relevant transactions is to be persisted, this can be found in the `schema.sql` tab. :::tip This indexer can be found by [following this link](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=dataplatform.near/social_feed). ::: ## Schema Definition :::note Note that database tables are named as `roshaan_near_feed_indexer_posts` which follows the format `<account_name>_near_<indexer_name>_<table_name>`. ::: ### Schema-Defined Table Names ```sql CREATE TABLE "posts" ( "id" SERIAL NOT NULL, "account_id" VARCHAR NOT NULL, "block_height" DECIMAL(58, 0) NOT NULL, "receipt_id" VARCHAR NOT NULL, "content" TEXT NOT NULL, "block_timestamp" DECIMAL(20, 0) NOT NULL, "accounts_liked" JSONB NOT NULL DEFAULT '[]', "last_comment_timestamp" DECIMAL(20, 0), CONSTRAINT "posts_pkey" PRIMARY KEY ("id") ); CREATE TABLE "comments" ( "id" SERIAL NOT NULL, "post_id" SERIAL NOT NULL, "account_id" VARCHAR NOT NULL, "block_height" DECIMAL(58, 0) NOT NULL, "content" TEXT NOT NULL, "block_timestamp" DECIMAL(20, 0) NOT NULL, "receipt_id" VARCHAR NOT NULL, CONSTRAINT "comments_pkey" PRIMARY KEY ("id") ); CREATE TABLE "post_likes" ( "post_id" SERIAL NOT NULL, "account_id" VARCHAR NOT NULL, "block_height" DECIMAL(58, 0), "block_timestamp" DECIMAL(20, 0) NOT NULL, "receipt_id" VARCHAR NOT NULL, CONSTRAINT "post_likes_pkey" PRIMARY KEY ("post_id", "account_id") ); CREATE UNIQUE INDEX "posts_account_id_block_height_key" ON "posts" ("account_id" ASC, "block_height" ASC); CREATE UNIQUE INDEX "comments_post_id_account_id_block_height_key" ON "comments" ( "post_id" ASC, "account_id" ASC, "block_height" ASC ); CREATE INDEX "posts_last_comment_timestamp_idx" ON "posts" ("last_comment_timestamp" DESC); ALTER TABLE "comments" ADD CONSTRAINT "comments_post_id_fkey" FOREIGN KEY ("post_id") REFERENCES "posts" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION; ALTER TABLE "post_likes" ADD CONSTRAINT "post_likes_post_id_fkey" FOREIGN KEY ("post_id") REFERENCES "posts" ("id") ON DELETE CASCADE ON UPDATE NO ACTION; ``` The tables declared in the schema definition are created when the indexer is deployed. In this schema definition, three tables are created: `posts`, `comments` and `post_likes`. Indexes are then defined for each and then foreign key dependencies. ## Main Function The main function can be explained in two parts. The first filters relevant transactional data for processing by the helper functions defined earlier in the file scope, the second part uses the helper functions to ultimately save the relevant data to for querying by applications. ### Filtering for Relevant Data ```js const SOCIAL_DB = "social.near"; const nearSocialPosts = block .actions() .filter((action) => action.receiverId === SOCIAL_DB) .flatMap((action) => action.operations .map((operation) => operation["FunctionCall"]) .filter((operation) => operation?.methodName === "set") .map((functionCallOperation) => { try { const decodedArgs = base64decode(functionCallOperation.args); return { ...functionCallOperation, args: decodedArgs, receiptId: action.receiptId, }; } catch (error) { console.log( "Failed to decode function call args", functionCallOperation, error ); } }) .filter((functionCall) => { try { const accountId = Object.keys(functionCall.args.data)[0]; return ( Object.keys(functionCall.args.data[accountId]).includes("post") || Object.keys(functionCall.args.data[accountId]).includes("index") ); } catch (error) { console.log( "Failed to parse decoded function call", functionCall, error ); } }) ); ``` We first designate the near account ID that is on the receiving end of the transactions picked up by the indexer, as `SOCIAL_DB = "social.near"` and later with the equality operator for this check. This way we only filter for transactions that are relevant to the `social.near` account ID for saving data on-chain. The filtering logic then begins by calling `block.actions()` where `block` is defined within the `@near-lake/primtives` package. The output from this filtering is saved in a `nearSocialPosts` variable for later use by the helper functions. The `.filter()` line helps specify for transactions exclusively that have interacted with the SocialDB. `.flatMap()` specifies the types of transaction and looks for attributes in the transaction data on which to base the filter. Specifically, `.flatMap()` filters for `FunctionCall` call types, calling the `set` method of the SocialDB contract. In addition, we look for transactions that include a `receiptId` and include either `post` or `index` in the function call argument data. ### Processing Filtered Data ```js if (nearSocialPosts.length > 0) { console.log("Found Near Social Posts in Block..."); const blockHeight = block.blockHeight; const blockTimestamp = block.header().timestampNanosec; await Promise.all( nearSocialPosts.map(async (postAction) => { const accountId = Object.keys(postAction.args.data)[0]; console.log(`ACCOUNT_ID: ${accountId}`); // if creates a post if ( postAction.args.data[accountId].post && Object.keys(postAction.args.data[accountId].post).includes("main") ) { console.log("Creating a post..."); await handlePostCreation( ... // arguments required for handlePostCreation ); } else if ( postAction.args.data[accountId].post && Object.keys(postAction.args.data[accountId].post).includes("comment") ) { // if creates a comment await handleCommentCreation( ... // arguments required for handleCommentCreation ); } else if ( Object.keys(postAction.args.data[accountId]).includes("index") ) { // Probably like or unlike action is happening if ( Object.keys(postAction.args.data[accountId].index).includes("like") ) { console.log("handling like"); await handleLike( ... // arguments required for handleLike ); } } }) ); } ``` This logic is only entered if there are any `nearSocialPosts`, in which case it first declares the `blockHeight` and `blockTimestamp` variables that will be relevant when handling (transforming and persisting) the data. Then the processing for every transaction (or function call) is chained as a promise for asynchronous execution. Within every promise, the `accountId` performing the call is extracted from the transaction data first. Then, depending on the attributes in the transaction data, there is logic for handling post creation, comment creation, or a like/unlike. ## Helper Functions ### `base64decode` ```js function base64decode(encodedValue) { let buff = Buffer.from(encodedValue, "base64"); return JSON.parse(buff.toString("utf-8")); } ``` This function decodes a string that has been encoded in Base64 format. It takes a single argument, **`encodedValue`**, which is the Base64-encoded string to be decoded. The function returns the decoded string as a JavaScript object. Specifically: 1. The **`Buffer.from()`** method is called with two arguments: **`encodedValue`** and **`"base64"`**. This creates a new **`Buffer`** object from the **`encodedValue`** string and specifies that the encoding format is Base64. 2. The **`JSON.parse()`** method is called with the **`Buffer`** object returned by the **`Buffer.from()`** method as its argument. This parses the **`Buffer`** object as a JSON string and returns a JavaScript object. 3. The **`toString()`** method is called on the **`Buffer`** object with **`"utf-8"`** as its argument. This converts the **`Buffer`** object to a string in UTF-8 format. 4. The resulting string is returned as a JavaScript object. ### `handlePostCreation` ```js async function handlePostCreation( accountId, blockHeight, blockTimestamp, receiptId, content ) { try { const postData = { account_id: accountId, block_height: blockHeight, block_timestamp: blockTimestamp, content: content, receipt_id: receiptId, }; // Call GraphQL mutation to insert a new post await context.db.Posts.insert(postData); console.log(`Post by ${accountId} has been added to the database`); } catch (e) { console.log( `Failed to store post by ${accountId} to the database (perhaps it is already stored)` ); } } ``` An object containing the relevant data to populate the `posts` table defined in the schema is created first to then be passed into the graphQL `createPost()` query that creates a new row in the table. ### `handleCommentCreation` ```js async function handleCommentCreation( accountId, blockHeight, blockTimestamp, receiptId, commentString ) { try { const comment = JSON.parse(commentString); const postAuthor = comment.item.path.split("/")[0]; const postBlockHeight = comment.item.blockHeight; // find post to retrieve Id or print a warning that we don't have it try { // Call GraphQL query to fetch posts that match specified criteria const posts = await context.db.Posts.select( { account_id: postAuthor, block_height: postBlockHeight }, 1 ); console.log(`posts: ${JSON.stringify(posts)}`); if (posts.length === 0) { return; } const post = posts[0]; try { delete comment["item"]; const commentData = { account_id: accountId, receipt_id: receiptId, block_height: blockHeight, block_timestamp: blockTimestamp, content: JSON.stringify(comment), post_id: post.id, }; // Call GraphQL mutation to insert a new comment await context.db.Comments.insert(commentData); // Update last comment timestamp in Post table const currentTimestamp = Date.now(); await context.db.Posts.update( { id: post.id }, { last_comment_timestamp: currentTimestamp } ); console.log(`Comment by ${accountId} has been added to the database`); } catch (e) { console.log( `Failed to store comment to the post ${postAuthor}/${postBlockHeight} by ${accountId} perhaps it has already been stored. Error ${e}` ); } } catch (e) { console.log( `Failed to store comment to the post ${postAuthor}/${postBlockHeight} as we don't have the post stored.` ); } } catch (error) { console.log("Failed to parse comment content. Skipping...", error); } } ``` To save or create a comment the relevant post is fetched first. If no posts are found the comment will not be created. If there is a post created in the graphQL DB, the `mutationData` object is constructed for the `createComment()` graphQL query that adds a row to the `comments` table. Once this row has been added, the relevant row in the `posts` table is updated to this comment’s timestamp. ### `handleLike` ```js async function handleLike( accountId, blockHeight, blockTimestamp, receiptId, likeContent ) { try { const like = JSON.parse(likeContent); const likeAction = like.value.type; // like or unlike const [itemAuthor, _, itemType] = like.key.path.split("/", 3); const itemBlockHeight = like.key.blockHeight; console.log("handling like", receiptId, accountId); switch (itemType) { case "main": try { const posts = await context.db.Posts.select( { account_id: itemAuthor, block_height: itemBlockHeight }, 1 ); if (posts.length == 0) { return; } const post = posts[0]; switch (likeAction) { case "like": await _handlePostLike( post.id, accountId, blockHeight, blockTimestamp, receiptId ); break; case "unlike": await _handlePostUnlike(post.id, accountId); break; } } catch (e) { console.log( `Failed to store like to post ${itemAuthor}/${itemBlockHeight} as we don't have it stored in the first place.` ); } break; case "comment": // Comment console.log(`Likes to comments are not supported yet. Skipping`); break; default: // something else console.log(`Got unsupported like type "${itemType}". Skipping...`); break; } } catch (error) { console.log("Failed to parse like content. Skipping...", error); } } ``` As with `handleCommentCreation` , first the relevant post is sought from the DB store. If the relevant post is found, the logic proceeds to handling the like being either a like or a dislike. ### `_handlePostLike` ```js async function _handlePostLike( postId, likeAuthorAccountId, likeBlockHeight, blockTimestamp, receiptId ) { try { const posts = await context.db.Posts.select({ id: postId }); if (posts.length == 0) { return; } const post = posts[0]; let accountsLiked = post.accounts_liked.length === 0 ? post.accounts_liked : JSON.parse(post.accounts_liked); if (accountsLiked.indexOf(likeAuthorAccountId) === -1) { accountsLiked.push(likeAuthorAccountId); } // Call GraphQL mutation to update a post's liked accounts list await context.db.Posts.update( { id: postId }, { accounts_liked: JSON.stringify(accountsLiked) } ); const postLikeData = { post_id: postId, account_id: likeAuthorAccountId, block_height: likeBlockHeight, block_timestamp: blockTimestamp, receipt_id: receiptId, }; // Call GraphQL mutation to insert a new like for a post await context.db.PostLikes.insert(postLikeData); } catch (e) { console.log(`Failed to store like to in the database: ${e}`); } } ``` As with `handleLike`, the relevant `post` is first sought from the graphQL DB table defined in `schema.sql`. If a post is found, the `accountsLiked` array is defined from the post’s previous array plus the additional account that has performed the like account in `accountsLiked.push(likeAuthorAccountId)`. The graphQL query then updates the `posts` table to include this information. Lastly, the `postLikeMutation` object is created with the required data for adding a new row to the `post_likes` table. ### `_handlePostUnlike` ```js async function _handlePostUnlike(postId, likeAuthorAccountId) { try { const posts = await context.db.Posts.select({ id: postId }); if (posts.length == 0) { return; } const post = posts[0]; let accountsLiked = post.accounts_liked.length === 0 ? post.accounts_liked : JSON.parse(post.accounts_liked); console.log(accountsLiked); let indexOfLikeAuthorAccountIdInPost = accountsLiked.indexOf(likeAuthorAccountId); if (indexOfLikeAuthorAccountIdInPost > -1) { accountsLiked.splice(indexOfLikeAuthorAccountIdInPost, 1); // Call GraphQL mutation to update a post's liked accounts list await context.db.Posts.update( { id: postId }, { accounts_liked: JSON.stringify(accountsLiked) } ); } // Call GraphQL mutation to delete a like for a post await context.db.PostLikes.delete({ account_id: likeAuthorAccountId, post_id: postId, }); } catch (e) { console.log(`Failed to delete like from the database: ${e}`); } } ``` Here we also search for an existing relevant post in the `posts` table and if one has been found, the `accountsLiked` is defined as to update it removing the account ID of the account that has performed the like action. Then a graphQL `delete` query is called to remove the like from the `post_likes` table. ## Querying data from the indexer The final step is querying the indexer using the public GraphQL API. This can be done by writing a GraphQL query using the GraphiQL tab in the code editor. For example, here's a query that fetches `likes` from the _Feed Indexer_, ordered by `block_height`: ```graphql query MyQuery { <user-name>_near_feed_indexer_post_likes(order_by: {block_height: desc}) { account_id block_height post_id } } ``` Once you have defined your query, you can use the GraphiQL Code Exporter to auto-generate a JavaScript or NEAR Widget code snippet. The exporter will create a helper method `fetchGraphQL` which will allow you to fetch data from the indexer's GraphQL API. It takes three parameters: - `operationsDoc`: A string containing the queries you would like to execute. - `operationName`: The specific query you want to run. - `variables`: Any variables to pass in that your query supports, such as `offset` and `limit` for pagination. Next, you can call the `fetchGraphQL` function with the appropriate parameters and process the results. Here's the complete code snippet for a NEAR component using the _Feed Indexer_: ```js const QUERYAPI_ENDPOINT = `https://near-queryapi.api.pagoda.co/v1/graphql/`; State.init({ data: [] }); const query = `query MyFeedQuery { <user-name>_near_feed_indexer_post_likes(order_by: {block_height: desc}) { account_id block_height post_id } }` function fetchGraphQL(operationsDoc, operationName, variables) { return asyncFetch( QUERYAPI_ENDPOINT, { method: "POST", headers: { "x-hasura-role": `<user-name>_near` }, body: JSON.stringify({ query: operationsDoc, variables: variables, operationName: operationName, }), } ); } fetchGraphQL(query, "MyFeedQuery", {}).then((result) => { if (result.status === 200) { if (result.body.data) { const data = result.body.data.<user-name>_near_feed_indexer_post_likes; State.update({ data }) console.log(data); } } }); const renderData = (a) => { return ( <div key={JSON.stringify(a)}> {JSON.stringify(a)} </div> ); }; const renderedData = state.data.map(renderData); return ( {renderedData} ); ``` :::tip To view a more complex example, see this widget which fetches posts with proper pagination: [Posts Widget powered By QueryAPI](https://near.org/edit/roshaan.near/widget/query-api-feed-infinite). :::
NEAR Launches 1,000 Teacher Education Program COMMUNITY December 9, 2021 As part of NEAR Foundation, the NEAR Education team is building a vast and vibrant ecosystem with the mission of making the open web accessible to everyone, regardless of experience, age, background, or native tongue. From lightweight, minute-long tutorials to the fully-fledged certification programs offered by NEAR University, a diverse range of expanding, community-led educational content illuminates the wonders of decentralization in a way that has never been more accessible. To help make mass adoption of Web3 a reality, the NEAR Education team is launching a unique and exciting initiative to onboard 1,000 teachers from all backgrounds and disciplines. Through both self-paced and instructor-led online courses, workshops, and fellowships, this army of educators will learn the ins and outs of blockchain technology and will, in turn, pass that knowledge on to others. If we can train 1,000 teachers—not just teachers, but those who simply enjoy learning and sharing—on all things NEAR, we can reach our moonshot goal of onboarding 1 million developers and, ultimately, 1 billion users. It’s that simple: 1,000 teachers → 1 million developers → 1 billion users. Ambitious? Yes. Doable? Let’s roll up our sleeves and find out. Interested in learning and teaching with us? Be sure to head over to NEAR University for more information. Why Create an Ecosystem of Teachers? It’s great that Web3 developers and other crypto-natives can grasp blockchain’s technology and potential—that’s what brought crypto to the edge of this major paradigm-shifting moment. To cross that threshold and truly shift the paradigm, this technology needs to be simple enough for anyone to understand. This initiative explains concepts in new and engaging ways: like how blockchain works as a digital clock that cannot be stopped, and how smart contracts are autonomous programs that always tell the truth. To realize blockchain’s revolutionary potential, the technology has to disappear behind a layer of simplicity and clarity. Truth, trust, and time are major factors in our daily lives. If we can trust our friends and family with a copy of our house keys, or trust a bank with our life savings, then perhaps we will soon learn to trust (and easily use) smart contracts that can’t lie about our identity, money, and other valuable possessions. These are the keys to understanding blockchain technology: it’s a digital clock, controlled by no one, that ticks in blocks and dutifully records our shared history. It never tells a lie. To read from it, we simply ask it, since all of its data is public. To write to it, we must use bank-level secure cryptography to identify ourselves before sending our instructions. “A blockchain ticks like a clock,” says NEAR Education’s Sherif Abushadi, “and it is in this ticking we trust, because in the end, the network is keeping an indelible record of everything that happens using cryptography. There’s not enough money or computing resources on the planet to lie about the history of this thing. It is an economically incentivized truth.” “So, now we can trust these things (computers) with stuff that we actually care about, like identity, money, and of course the combination of the two: something we all call ‘ownership’— that’s why this tech is so important,” says Abushadi. “This is a huge idea that developers alone are not qualified to handle. We need to pull in the artists, historians, philosophers, professors, economics experts, social studies, and home economics teachers so that together we might paint a clearer picture of the vast new future this tech will bring.” All Backgrounds and Disciplines Welcome! Are you a philosopher, an economist, or a social studies teacher? A historian? A brick-and-mortar business owner? An adventurer? Perfect! We want to hear from you. Come learn, see, and teach the future with us. We want the NEAR ecosystem to be a place where all feel welcome and able to learn, from developers and designers to makers, social entrepreneurs, and more. If Web3 is to fulfill its promise, we will need folks from all walks of life to help shape its future. Learn Blockchain, Inspire Future Web3 Developers In NEAR Education’s new initiative, you will go beyond the headlines of token speculation and NFT minting to explore the technology and innovation that lies at the heart of the blockchain. Even better, you will be able to share what you learn with others. “It’s not enough for developers to talk about Web3 software,” Abushadi says. “We need 1,000 teachers talking about this from every imaginable angle, especially in the humanities and the liberal arts. Those are the teachers that are above and beyond the software realm—the people who will give us perspective.” Once participating teachers learn the ins and outs, you will be able to inspire the next generation of Web3 users, explorers, entrepreneurs and developers. How to Get Started on Your NEAR Teaching Journey If you’re wondering how to get started, we’ve got you covered. NEAR University offers several paths to becoming a blockchain teacher. These paths are available to each and every participant, as both part-time and full-time roles. Here’s a brief breakdown of NEAR Education opportunities, available to teachers today. For more details on the 4 teacher pathways, you can head over to NEAR University ’s Time for Teachers page for this information and more! Education Grants Your idea, your time. Fellowship Roles (Teacher-in-Residence) Your courses, your content, your audience. NEAR Certified Instructor (NCI) Our courses, our content, our audience. Core Education Team Roles Core contributor on the NEAR Education Team. From this group of 1,000 teachers, the NEAR Education team plans to invite two or three core team members that will help craft the community’s educational content and deliver world class learning experiences to the world.
NEAR Foundation CEO Transition: A Note from Erik Trautman NEAR FOUNDATION December 16, 2021 I’m proud to say that, earlier today, the NEAR Foundation announced its selection of Marieke Flament as its new CEO starting January 1st, 2022. It’s an exciting time of transition and we’re thrilled to bring Marieke aboard because she brings world class leadership to the NEAR community. Her hiring highlights how this ecosystem is pulling in more and more of the best talent in the world to drive it to the next level. As we head into the new year with new leadership, I just wanted to send a personal note out to everyone at NEAR with some context for the transition and thoughts for the future. NEAR’s Progress In the last 3 years, the NEAR project has undertaken an extraordinary evolution. What started as a whiteboard idea to fix the scaling problems of existing chains by using a novel sharding approach quickly grew into a juggernaut that brought in some of the best technical talent in the world. Along the way, we realized that scalability was only half the solution, so we built a flexible contract-based account model to help apps achieve the kind of usability that enables mass adoption. And today, just a little over a year after launching, NEAR has hundreds of apps, thousands of community members, and over 1.7 million accounts. It’s been an incredible journey to see this ecosystem grow, and especially to join the community in NEARCon Lisbon to announce over $800M in funding to power the ecosystem to the next level. Growing from 1 to 100 My role from the beginning has always been “do whatever it takes to make this project successful.” In its earliest days, that meant building out the original development company so the technology could surface. For the last 2 years it has meant standing up the NEAR Foundation so the protocol could launch from its genesis block to a fully decentralized community hand-off in 2020. Now, both the NF and the ecosystem around it have changed substantially. In 2019, the NF was a piece of paper on a long table in a Swiss lawyer’s office. Now it is powered by the efforts of more than 50 people spread around the world who help to advocate for a community that has grown exponentially. As with any startuppy organization, the NF has reinvented itself several times during the intervening years but, at last, I can say that it has officially made it from 0 to 1. Now, the NF is ready for the even bigger journey from 1 to 100 and it’s ready for the right hands to guide it there. For the better part of a year, the NFC and I have conducted a careful search to build out the right leadership team. This is a strange-shaped organization in a strange-shaped ecosystem so it takes an unusual leader to carry it forward. With a mandate to support and advocate for the community, this requires someone who has the mentality of a founder, experience scaling global organizations, an intimate understanding of crypto, an unusual community orientation and, of course, world class servant leadership. This led to an extremely narrow list. Marieke Marieke is the perfect fit. Her experience growing Circle’s European operations and, later, their entire marketing organization, made her deeply familiar with both the power and the unusual nature of this community. She took those skills into the leading edge of the banking world as Mettle’s CEO, but the future of finance is decentralized and we’ve managed to guide her back home to an ecosystem that’s truly breaking out at NEAR. Marieke has earned the faith and trust of the leadership team and the NFC so I hope you’ll welcome her too 🙂 The Transition Marieke will take the lead of the NF on January 1, 2021, where she’ll continue to support the explosive progress of the NEAR community and ecosystem. As for me… my job description in the next stage will be the same—do whatever it takes to make NEAR successful. So, I’ll be supporting the transition, advising the NF, and engaging areas of the ecosystem where we can do even better, including by creating bridges through product, growth, and community to help NEAR-based applications achieve mass adoption. This project has been a hell of a ride and it’s still the opportunity of a lifetime for anyone who’s ready to get involved. I’m excited to read its next chapter from a different perspective and to have Marieke at the helm of the NF to help write it.
--- id: xcc title: Cross Contract Call --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" This example performs the simplest cross-contract call possible: it calls our [Hello NEAR](https://github.com/near-examples/hello-near-examples) example to set and retrieve a greeting. It is one of the simplest examples on making a cross-contract call, and the perfect gateway to the world of interoperative contracts. :::info Advanced Cross-Contract Calls Check the tutorial on how to perform cross-contract calls [in batches and in parallel](./advanced-xcc) ::: --- ## Obtaining the Cross Contract Call Example You have two options to start the project: 1. You can use the app through `Github Codespaces`, which will open a web-based interactive environment. 2. Clone the repository locally and use it from your computer. | Codespaces | Clone locally | | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | | [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/near-examples/cross-contract-calls?quickstart=1) | 🌐 `https://github.com/near-examples/cross-contract-calls` | --- ## Structure of the Example The smart contract is available in two flavors: Rust and JavaScript <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash ┌── sandbox-ts # sandbox testing │ ├── hello-near │ │ └── hello-near.wasm │ └── main.ava.ts ├── src # contract's code │ └── contract.ts ├── package.json ├── README.md └── tsconfig.json ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash ┌── tests # sandbox testing │ ├── hello-near │ │ └── hello-near.wasm │ └── tests.rs ├── src # contract's code │ ├── external.rs │ └── lib.rs ├── Cargo.toml # package manager ├── README.md └── rust-toolchain.toml ``` </TabItem> </Tabs> --- ## Smart Contract ### Contract The contract exposes methods to query the greeting and change it. These methods do nothing but calling `get_greeting` and `set_greeting` in the `hello-near` example. <CodeTabs> <Language value="js" language="ts"> <Github fname="contract.ts" url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/src/contract.ts" start="17" end="39" /> </Language> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/lib.rs" start="22" end="51" /> <Github fname="external.rs" url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/external.rs" start="2" end="12" /> </Language> </CodeTabs> ### Testing the Contract The contract readily includes a set of unit and sandbox testing to validate its functionality. To execute the tests, run the following commands: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash cd contract-simple-ts yarn yarn test ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash cd contract-simple-rs cargo test ``` </TabItem> </Tabs> :::tip The `integration tests` use a sandbox to create NEAR users and simulate interactions with the contract. ::: In this project in particular, the integration tests first deploy the `hello-near` contract. Then, they test that the cross-contract call correctly sets and retrieves the message. You will find the integration tests in `sandbox-ts/` for the JavaScript version and in `tests/` for the Rust version. <CodeTabs> <Language value="js" language="js"> <Github fname="main.ava.ts" url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/sandbox-ts/main.ava.ts" start="8" end="52" /> </Language> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/tests/tests.rs" start="4" end="77" /> </Language> </CodeTabs> <hr class="subsection" /> ### Deploying the Contract to the NEAR network In order to deploy the contract you will need to create a NEAR account. <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash # Optional - create an account near create-account <accountId> --useFaucet # Deploy the contract cd contract-simple-ts yarn build near deploy <accountId> ./build/cross_contract.wasm init --initFunction init --initArgs '{"hello_account":"hello.near-example.testnet"}' ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash # Optional - create an account near create-account <accountId> --useFaucet # Deploy the contract cd contract-simple-rs cargo near build # During deploying pass {"hello_account":"hello.near-example.testnet"} as init arguments cargo near deploy <accountId> ``` </TabItem> </Tabs> <hr class="subsection" /> ### CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands: ```bash # Get message from the hello-near contract # Replace <accountId> with your account ID near call <accountId> query_greeting --accountId <accountId> # Set a new message for the hello-near contract # Replace <accountId> with your account ID near call <accountId> change_greeting '{"new_greeting":"XCC Hi"}' --accountId <accountId> ``` --- ## Moving Forward A nice way to learn is by trying to expand a contract. Modify the cross contract example to use the [guest-book](guest-book.md) contract!. In this way, you can try to make a cross-contract call that attaches money. Remember to correctly [handle the callback](../../2.build/2.smart-contracts/anatomy/crosscontract.md#callback-method), and to return the money to the user in case of error. ### Advanced Cross Contract Calls Your contract can perform multiple cross-contract calls in simultaneous, creating promises that execute in parallel, or as a batch transaction. Check the [advanced cross contract calls tutorial](./advanced-xcc) to learn more. :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `4.0.13` - node: `18.19.1` - rustc: `1.77.0` :::
Blockchain Scaling Approaches: NEAR Sharding vs. Layer 2s NEAR FOUNDATION June 14, 2023 Layer-twos (L2s) have become increasingly popular as a scaling solution for layer one (L1) blockchains in the past several years, especially after Ethereum decided to scale via a rollup-centric roadmap. A layer-two is a protocol built on top of an existing blockchain to improve its scalability, throughput, or privacy and reduce the congestion and cost of operating on the L1 blockchain. NEAR, on the other hand, chose to scale through a different approach: sharding. In this post, I’ll explain the rationale behind NEAR’s approach and why NEAR does not plan to scale through layer 2. To understand the differences in scaling approaches, let’s first take a look at how layer 2s work. Generally speaking, layer 2s work by performing state transitions outside of (or off-chain from) the layer 1 they build on and committing state roots and transaction data to the underlying layer 1. Depending on how exactly the state transitions are verified, these may be optimistic rollups, which rely on fraud proofs, or ZK rollups, which use zero-knowledge proofs to show the validity of the layer 2 state transition. The premise of scaling through rollups is that a rollup has higher throughput than the underlying L1 due to decreased consensus overhead; there could be many rollups running as their own chain and processing different transitions. The underlying L1 provides security for rollups as a settlement layer, and rollups offer scalability in return. This offloads the significant challenge of scalability onto a protocol that exists outside of the L1 and therefore simplifies the L1 protocol design. Ethereum, for example, is well known for its plan to scale through rollups such as Arbitrum, Optimism, ZkSync and Polygon zkEVM. How well does this promising design approach work in practice? While it may still be too early to say, given that Ethereum is the only major blockchain adopting this approach and that L2s themselves are relatively nascent, there are lessons to be learned already. First, composability between layer 2s is a problem. While each rollup itself has higher throughput than Ethereum, rollups lack the native interoperability that allows contracts from different rollups to interact with each other. Each one can only interact with the Ethereum L1. Composability is especially important for financial applications and is arguably what makes the Ethereum L1 so successful. Second, while in theory rollups should work together to scale Ethereum, in practice the overall scaling achieved by rollups collectively is not much more than what one rollup offers. That is mostly due to the fact that popular Ethereum dapps run on almost all rollups and as a result, similar transactions are “duplicated” across different rollups. The transactions to use DeFi applications such as Uniswap on different rollups actually compete for call data space on Ethereum for data availability. In contrast, NEAR scales through sharding, or parallelizing the network into partitions that are built into the protocol itself, with the same security guarantees of the L1 blockchain. NEAR’s architecture is, in some sense, similar to Ethereum with rollups, where each shard is similar to an optimistic rollup. The difference is that because sharding is built into the protocol, applications on one shard can natively interact with applications on another shard. The homogeneous sharding model also means that two apps interact in the same way regardless of whether or not they are deployed on the same shard. As a result, not only do developers not need to care about which shard to deploy their applications on, they also have the peace of mind that their application can freely interact with any other application deployed on NEAR without having to resort to third-party bridges. While composability is a nontrivial advantage of NEAR’s sharding approach, it is not all NEAR has to offer. Fast finality on NEAR means that users can be confident that their transactions are finalized in two to three seconds. In the rollup world, however, transaction finality is much worse. Optimistic rollups are known for their long exit time (usually 7 days) and ZK rollups are bottlenecked on proof generation, which takes up to 10 minutes today. Furthermore, in NEAR’s sharding model, since both processing and state are completely sharded, the throughput almost scales linearly with the number of shards. Thanks to the native composability mentioned above, developers and users truly benefit from the scalability as one application is only deployed once on one shard, unlike the current state of rollups where many popular applications have to be deployed on many rollups, which reduces the amount of true parallelism in transaction processing. This is not to say, however, that NEAR’s approach is superior. Sharding makes the protocol very complex, hard to understand, and difficult to implement. In comparison, the rollup-centric approach taken by Ethereum has a relatively simple design, even though it still requires data availability sharding (Danksharding) for layer 2s to work efficiently. Ultimately, the different choices on scaling approaches reflect different design philosophies of the underlying protocol. Ethereum wants the protocol itself to be maximally robust and resilient and therefore it is important to minimize the complexity of the L1 protocol design. NEAR, on the other hand, prioritizes simplicity for developers and users and is willing to make the protocol more complex under the hood for the sake of a better experience for its users. It is worth noting that NEAR is not just a blockchain protocol, but an operating system that offers a common layer for browsing and discovering open web experiences and is compatible with any blockchain. Despite the differences in protocol design, NEAR as the blockchain operating system allows developers and users from different blockchains, including Ethereum layer 2s, to build and use applications across many different blockchain ecosystems.
```js const tokenContract = "token.v2.ref-finance.near"; const result = Near.call( tokenContract, "ft_transfer_call", { receiver_id: "v2.ref-finance.near", amount: "100000000000000000", msg: "", }, 300000000000000, 1 ); ``` <details> <summary>Example response</summary> <p> ```json '100000000000000000' ``` </p> </details>
NEAR Wallet Rockets to Over 20 Million Users With SWEAT Partnership COMMUNITY November 3, 2022 It’s almost hard to believe that the NEAR Wallet had only 2 million users at the start of this year. At over 20 million users, NEAR is thrilled to mark its wallet’s tenfold growth in less than a year. NEAR is really creating without limits! This meteoric rise can be attributed to a number of factors, including growing support among builders for NEAR’s user-friendly, highly scalable, climate neutral blockchain. But also instrumental in this growth is NEAR’s epic partnership with companies such as SWEAT Economy, the world’s most popular fitness app. Largest ever on-ramping of Web2 users into Web3 At the moment, over 800 projects are building on NEAR, which uses Proof-of-Stake consensus to secure and validate transactions on the blockchain. NEAR has also lowered barriers for creators with developments such as the launch of Javascript SDK. This gives over 20 million developers the chance to build Web3 apps using JavaScript, the most popular coding language in the world. In September, Sweat Economy—the “economy of movement”—successfully launched on NEAR with the largest ever airdrop to active, opted-in, wallets. The Move-to-Earn platform, active in Web2 since 2016 with over 130 million global users of its Sweatcoin app, distributed their new Web3 SWEAT token to 13.5M token holders. The Sweat Wallet app quickly became the #1 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. Sweat Economy distributed over 4.7 Billion of its newly launched SWEAT tokens to the 13.5M Sweatcoin users who opted to enter Web3. For many of these users, it is their first experience with blockchain technology, making this the largest ever on-ramping of self-custody users from Web2 to Web3. “It’s been an extraordinary year for NEAR as we ramp up efforts to attract the world’s best and socially-minded developers on our protocol,” says Marieke Flament, CEO of NEAR Foundation. “We have put our emphasis on championing talent diversity, regional hub development, and sustainable practices. Equally important to our success is the strategic partnerships we have forged with prominent companies that have done a brilliant job at transitioning from a Web2 business model to Web3.” Onboarding 1 billion users to Web3 This transition is particularly important as NEAR works hard to onboard one billion users to Web3. “Sweat Economy is one of these companies that have made it easy for people to access Web3 applications with the help of NEAR, which has led to millions of users for its product and for our protocol,” Flament adds. “ These partnerships are key to helping us to realize our ambition to achieve mass adoption for crypto and to show the world that Web3 is capable of solving real world problems and making society a better place for all.” If you still have yet to join the “economy of movement,” head to your mobile app store and download Sweatcoin today and see how millions of people are earning crypto just by being physically active. Join NEAR and Sweat Economy to build a healthier collective future.
```bash near call primitives.sputnik-dao.near act_proposal '{"id": 0, "action": "VoteApprove"}' --gas 300000000000000 --accountId bob.near ``` :::note Available vote options: `VoteApprove`, `VoteReject`, `VoteRemove`. :::
NDC V1 Governance Elections FAQ COMMUNITY July 20, 2023 The NEAR Digital Collective (NDC), the largest decentralization effort on any layer 1 blockchain, has spent much of 2023 designing a number of frameworks that will allow any member of the NEAR Protocol network to have a say in how NEAR is run. NDC’s goal is to combine transparency, collective decision making, evolving governance models, and self-determination in a completely new way. After laying this decentralization groundwork, the NDC is gearing up for its first elections. As of July 19th at 15:00 pm UTC: I-AM-HUMAN OG SBT Soul Bound Tokens holders can now nominate themselves for office. This is your opportunity to upvote and to comment on candidates you believe in and who could add the most value to the future of NEAR! What are the key dates to remember for the NDC election? July 19, 15:00:00 UTC — Start date for candidacy submissions on BOS and get I-AM-HUMAN SBT September 1, 23:59:59 UTC — Deadline for Voter Registration via I-AM-HUMAN September 1, 23:59:59 UTC — Deadline for applying for an OG Badge for candidacy eligibility September 7, 23:59:59 UTC — Deadline for candidacy submissions September 8, 00:00:00 UTC — Voting begins at Near APAC in Vietnam September 22, 23:59:59 UTC — Voting ends Below you will find a list of frequently asked questions about the elections, from how participation and voting works to candidate selection, election integrity, and more. NDC V1 Governance Structure NDC V1 Governance includes three elected houses, a voting body, and a community treasury. The qualification to run for V1 governance requires an OG SBT. Elected Community members (OG’s) of each house are responsible for planning, overseeing, and allocating funding aligned with the ecosystems Northstar to grow and decentralize NEAR. What will the NDC government look like? The NDC government will be composed of three houses, structured as following: Name of the House House of Merit (HoM) Council of Advisors (CoA) Transparency Commission (TC) Seats 15 seats 7 seats 7 seats Responsibilities In charge of allocating the treasury and deploying capital for the growth of the ecosystem. In charge of vetoing proposals from the HoM and guiding the deployment of the treasury. In charge of keeping behavior of elected officials clean, and making sure cartels do not form in the ecosystem. Commitment 5-20 hours weekly with a minimum participation threshold. 5-20 hours weekly with a minimum participation threshold. 5-20 hours weekly with a minimum participation threshold. Expertise Required Budgetary expertise for ecosystem-wide budget planning, treasury management, and review. Strategic minds to advise the House of Merit and hold budget veto power. Unbiased guardians of the treasury that investigate and remove bad actors. Nominate Yourself for Candidacy Who can run for office? In order to run for office, you must hold an OG SBT. These aren’t given out to just anyone; these are for people that have been actively contributing to the NEAR ecosystem for extended periods of time. If you already have an OG SBT, you can self-nominate yourself right now. To find out the full criteria and to see if you qualify, please refer to Safeguards and OG. If you still require help, head over to the official NDC Telegram and ask a member of the team for help. Why should you run for office? If you’re an OG, we need your expertise and authentic commitment to the continued growth, success, and most importantly… Decentralization of NEAR. This is an opportunity for you to actualize an incredible future for NEAR. What information will be available in the candidate profiles? The candidate profiles are on BOS Nomination and will contain their name, background, affiliation, and policy positions. The profiles should give you a clear overview of what to expect should you select them as your preferred candidate. You can choose to upvote the candidate and comment on the candidate profiles as long as you are registered through I-AM-HUMAN. Election Overview Nomination starts the NDC v1 governance process and runs for 50 days and allow the community to rally their candidates. The nomination ends on September 7, and the election starts on September 8 and runs for two weeks. The elected representatives are onboarded for one week, and begin to organize the first government for the NEAR ecosystem. Nomination Period: July 19th to September 7th, 2023 Election Period: September 8th – September 22nd, 2023 Start of 1st Congress: October 1st – April 1st, 2024 How can my vote shape the future of the NEAR ecosystem? By engaging in the election process, you get to help determine the direction of the NDC and the future of decentralization on NEAR. This is not like a presidential election where your vote is a thimble of water added to a sea. Every vote in the NDC election actually makes a difference, and some of the elected positions will likely come down to just a few votes. When the candidates have very different policy positions, each vote has a potentially outsize impact. How else does my vote matter? By participating in the elections process and on-chain voting, you are also contributing to your own on-chain reputation. Participation How can I participate in the NDC election? The main ways to participate in the NDC election are of course voting for candidates or running as a candidate, but there’s a lot more to it than just that. Through our Nominations platform, voters and candidates will be able to engage with one another discussing policy positions and contribute to candidacy social proof through commenting or upvoting. What is the eligibility criteria to vote? Any person with a Face Verified Soul Bound Token (SBT) is eligible to vote, and anyone can get one with a NEAR wallet through I-AM-HUMAN. What is the eligibility to run in the NDC election? In order to be eligible to run in the NDC election, candidates will need to be one or more of the following: A Champion of the NDC that is still actively contributing to the ecosystem. Champions are ecosystem leaders that run nodes or projects and contribute to a workgroup or initiative they feel passionate about to help bring NDC V1 Gov online. They contribute by lending time or resources and also help by referring or recruiting contributors to help deliver objectives. An NDC Contributor that forfeited or received a bounty through June ’23 that is still actively contributing to the ecosystem. A member of NEAR Inc or NEAR Foundation before the Pagoda rebrand in Feb ’22 that is still actively contributing to the ecosystem. A member of VCs, nodes, projects, or spinout founders in the ecosystem before the Pagoda rebrand in Feb ’22 that is still actively contributing to the ecosystem (including, but not limited to, Aurora, NEAR UA, Proximity Labs, Lyrik(MOVE) Capital, NEAR Balkans, MetaWeb, MetaPool, Orderly, NEAR Vietnam, Satori, Open Shard Alliance, Open Forest Protocol, Human Guild, HAPI Labs, Calimero, OnMachina, Ref, PemBrock, etc.). A known OG and Community member for at least one year that is still actively contributing to the ecosystem. Remember: bids for candidacy can be turned in as soon as July 19 and no later than September 7th. Give yourself ample time to fill out a form detailing your background, experience, and what you plan to bring to NDC governance. This material you provide helps the NEAR community make an informed decision about your candidacy. Election Integrity What procedures will be in place to ensure election integrity? We would love to see every single person in the NEAR ecosystem vote in NDC elections, but in order to maintain election integrity, there is one important requirement in order to cast a valid ballot. You will need to have a Face-Verified Soul Bound Token (SBT) linked with a NEAR wallet. You may use your main wallet or create a new one explicitly for the purpose of voting. Does Face Verification mean you have a picture of my face connected to my wallet? No. I-AM-HUMAN does not store your biometrics. You are also free to request the deletion of any and all data collected in this process should you decide to forfeit your FV SBT. Will there be any election oversight? It goes without saying that we want as fair and transparent an election as possible. Given that we are remote, and that the internet can be a strange place, there have been certain safeguards implemented into all NDC elections, that deter poor behavior, and also guarantee that bad actors are punished if they are able to manipulate an election. Election integrity can ultimately be broken down into six clear safeguards: Safeguard 1. Fair Voting Policy (voters agreement to not sell votes). On behalf of all voters, holding an I-Am-Human verified account, you agree when you vote, that you will not sell your vote. If it turns out that you do sell your vote, you are eligible to post-election enforcement from the TC (see safeguard 6). Safeguard 2. Candidate Agreement to Transparency and Accountability to not buy votes. On the candidates’ side, they all also agree to not buy votes for their election, and are equally eligible for post-election enforcement if they are found guilty. Safeguard 3. Implementing a Vote Bonding: Vote bonding is a mechanism designed to deter malicious voting behaviors. Participants must stake a certain amount of NEAR tokens, as a bond to vote. This bond ensures good faith participation and can be reclaimed post-voting if all rules are adhered to. However, if participants engage in vote manipulation, such as buying or selling votes, the bond is forfeited. This mechanism introduces a strong financial disincentive to engage in fraudulent activities, safeguarding the integrity of the voting process. Recently, in a NDC produced EasyPoll, the community had a majority vote to have a bond for the vote. Safeguard 4. Pikes Peak review Election results ongoing/after. NEAR is fortunate enough to have the data visualization and tracking capabilities of Pikespeak, active and involved in the ecosystem. As a core supporter of NDC, Pikes Peak is also going to be monitoring election results both during and after the election to identify any anomalies and ensure it is done as fairly as possible. Safeguard 5. Whistleblower program and bounty. In addition to the technical safeguards and Pikespeak oversight, the NDC is also instituting a whistleblower incentive program whereby anyone who has knowledge of potential election fraud can receive a bounty assuming their claims as to people and impact are justified and accurate. Safeguard 6. Enforcement by Transparency Commission. In the event of any serious election fraud the investigation, and decision to remove, or forever ban either a voter or a candidate, will lie with the Transparency Commission. This means that there is ultimately no escape for a wrongdoer once they have been discovered or accused. The official Transparency Commission process is to field a complaint, investigate the complaint, and then publicly move to either remove, or ban the member in question from further participation. With these six safeguards, we are hopeful that all elections for the V1 framework will be fair and transparent. Is NEAR Foundation or any other organization external to NDC involved? No. The NDC community is the sole administrator of this election, though NDC funding originated at NEAR Foundation. Voting Voting powered by I-Am-Human proof of personhood soul-bound tokens (SBTs). 1 Human, 1 Vote kickstarts voting. future versions factor in activity throughout the NEAR Ecosystem, giving merit based on contribution and reputation. What date does voting start for the NDC General Election? The NDC Election starts on September 8, 00:00:00 UTC, which coincides with NEAR APAC in Vietnam. How can I vote in the NDC election? Voting in the NDC election is designed to be as simple as possible and will take place on NEAR’s Blockchain Operating System. A link to voting will be found on the NDC’s Medium, Telegram, and Discord. You’ll simply log in, review candidate profiles and their platforms, and submit your choices. Be sure to vote within the designated time frame to be sure your voice is counted. What should I consider before voting for a candidate? Just like in any civic election, you should familiarize yourself with the policy positions of the candidates as well as their backgrounds. All candidates will have been vetted and have an “OG SBT,” but will likely have widely divergent views on the direction of the NDC. Asking questions and commenting on their platforms can also be a valuable way to get clarity on any positions that seem unclear to you. Can I change my vote once I’ve submitted it? Since all votes are recorded on the blockchain, they are immutable and cannot be changed after submission. Therefore it is in your best interest to triple check your selections before hitting that “submit” button. Information & Support Where can I find the most accurate and up-to-date information about the NDC election? You can find the most accurate and up-to-date information on the NDC’s Medium, Telegram, and Discord. Where can I get support if I have any issues or questions during the election process? You are welcome to reach out for support on Telegram or Discord. Post-Election How will the election results be announced? Election results will be announced on the NDC’s Medium, Telegram, and Discord and will also be viewable in the Election UI. Winning candidates will be highlighted in green. What happens after the election results are announced? After the election results are announced, the elected representatives will convene for the first time in the first NDC governance town hall, where we will hear from elected members from the three branches of NDC governance.
--- id: web-methods title: Web Browser Methods --- import {WidgetEditor} from "@site/src/components/widget-editor" NEAR Components have access to classic web methods that enable them to: - [Fetch](#fetch) data from external sources. - [Cache](#cache) values to avoid redundant computations. - Use [LocalStorage](#localstorage) to store data in the web browser. - Access to the [Clipboard](#clipboard). --- ## Fetch `fetch` allows to fetch data from the URL. It acts like a hook. It's a wrapper around the `fetch` function from the browser behind the caching layer. The possible returned values are: - If the data is not cached, it returns `null` and fetches the data in the background. - If the data is cached, it returns the cached value and then revalidates it. <WidgetEditor height="80"> ```js const res = fetch("https://rpc.mainnet.near.org/status"); return res.body; ``` </WidgetEditor> <hr className="subsection" /> #### Async Version `asyncFetch` is the `async` version of [`fetch`](#fetch), meaning that it returns a promise instead of a value. <WidgetEditor height="80"> ```js const [uptime, setUptime] = useState(null); function reportUptime() { const promise = asyncFetch("https://rpc.mainnet.near.org/status") promise.then( res => { setUptime(res.body.uptime_sec) } ); } return <> <p> {uptime? `Uptime: ${uptime}s` : `Fetch a value` } </p> <button onClick={reportUptime}>Fetch uptime</button> </> ``` </WidgetEditor> :::tip In contrast with `fetch`, `asyncFetch` does **not** cache the resulting value, so it should only be used within a function to avoid frequent requests on every render. ::: --- ## Cache The `useCache` hook takes a promise through a generator function, fetches the data and caches it. It can be used to easily use and cache data from async data sources. The cache is global for the VM, but each cached element is identified by a unique `dataKey` within each component. The possible values returned are: - `null` if the cache is cold and data is fetching - the `cached value` while the data is being fetched - A new `value` if new data is fetched. <WidgetEditor> ```js const status = useCache( () => asyncFetch("https://rpc.mainnet.near.org/status").then((res) => res.body), "mainnetRpcStatus", { subscribe: true } ); return status; ``` </WidgetEditor> <details markdown="1"> <summary> Parameters </summary> | param | required | type | description | |--------------------|--------------|--------|----------------------------------------------------------------------| | `promiseGenerator` | **required** | object | a function that returns a promise, which generates data. | | `dataKey` | **required** | object | the unique name (within the current component) to identify the data. | | `options` | _optional_ | object | optional argument. | :::info options object - `subscribe` _(optional)_: if `true`, the data refreshes periodically by invalidating cache. ::: :::note - `promiseGenerator`: you don't return the promise directly, because it should only be fired once. ::: </details> :::tip The [fetch](#fetch) method is built on top of the `useCache` hook. ::: :::note The data is being cached and compared as JSON serialized objects. ::: --- ## LocalStorage NEAR Components have access to a simulated `localStorage` through the `Storage` object: - [`Storage.get`](#storageget) - [`Storage.set`](#storageset) - [`Storage.privateGet`](#storageprivateget) - [`Storage.privateSet`](#storageprivateset) <WidgetEditor> ```jsx const [time, setTime] = useState(stored || Date.now()) const storeValue = () => { const date = Date.now(); Storage.set('time_now', date) } return <> <p> Time Now: {Date.now()} </p> <p> Time Stored: {Storage.get('time_now')} </p> <button onClick={storeValue}>Store Date.now()</button> </> ``` </WidgetEditor> <details markdown="1"> <summary> Parameters </summary> #### Storage.get `Storage.get(key, widgetSrc?)` - returns the public value for a given key under the given widgetSrc or the current component if `widgetSrc` is omitted. Can only read public values. | param | required | type | description | |-------------|--------------|--------|--------------------------| | `key` | **required** | object | a user-defined key | | `widgetSrc` | _optional_ | object | a user-defined component | --- #### Storage.set `Storage.set(key, value)` - sets the public value for a given key under the current widget. The value will be public, so other widgets can read it. | param | required | type | description | |---------|--------------|--------|----------------------| | `key` | **required** | object | a user-defined key | | `value` | **required** | object | a user-defined value | --- #### Storage.privateGet `Storage.privateGet(key)` - returns the private value for a given key under the current component. | param | required | type | description | |-------|--------------|--------|------------------------------------------------| | `key` | **required** | object | a user-defined key under the current component | --- #### Storage.privateSet `Storage.privateSet(key, value)` - sets the private value for a given key under the current component. The value is private, only the current component can read it. :::note Private and public values can share the same key and don't conflict. ::: | param | required | type | description | |---------|--------------|--------|------------------------------------------------| | `key` | **required** | object | a user-defined key under the current component | | `value` | **required** | object | a user-defined value | </details> --- ## Clipboard NEAR Components can **write** data to the system's clipboard through the `clipboard.writeText` method. Writing to the clipboard is **only** allowed in **trusted actions**, for example, when the user clicks a button. <WidgetEditor> ```js const copyToClipboard = (test) => { clipboard.writeText("Hello World!") } return <> <button onClick={copyToClipboard}> Copy </button> <textarea className="form-control mt-2" placeholder="Test pasting here" /> </> ``` </WidgetEditor>
import DocCardList from '@theme/DocCardList'; import {useCurrentSidebarCategory} from '@docusaurus/theme-common'; # Multi Token Standard <DocCardList items={useCurrentSidebarCategory().items}/>
NEAR’s April Town Hall Highlights COMMUNITY May 5, 2022 NEAR’s explosive and diverse ecosystem growth continued into the spring. As always, the NEAR Town Hall is a virtual venue for the growing global NEAR community to put their finger on the ecosystem pulse. It’s also a great opportunity to meet community members, as well as teach, learn, and collectively advance NEAR adoption and the multi-chain Open Web future. The April NEAR Town Hall explored music on the blockchain, new partnerships like Sweatcoin, events such as Paris Blockchain Week Summit, and more. Here are the highlights. A Flurry of NEAR Initiatives and Conferences NEAR Foundation CEO Marieke Flament opened the April Town Hall with details on NEAR’s latest initiatives. This included a recent partnership with Sweatcoin, announced at Paris Blockchain Week Summit, which will power the “movement economy”. In little under a month, Sweatcoin has added 1 million wallets to the NEAR ecosystem. Flament highlighted NEAR’s presence at New York Blockchain Week, PBWS, and Devconnect Amsterdam blockchain conferences. But the conferences haven’t been the only places where you can find in-person activities from NEAR’s global community. “We had several meetups organized in several parts of the world,” said Flament. “In particular, one in Portugal for the new EU integration of our Ukraine In Exile hub. And last but not least, we’re also working on our first hacker house in Miami.” “Again, lots of amazing things are happening, [especially] on the side of fundraising,” she added. “Congrats to the many projects who have raised significant amounts of external capital. In particular, Mintbase, Bastion, Trisolaris, Sender Wallet, Rocketo, and Burrow.” Flament also got into the NEAR Foundation’s efforts to keep the NEAR Protocol climate neutral. “The new blockchain is climate neutral… but also our entire ecosystem,” she said at the town hall. “We’ve partnered with South Pole to continuously assess and look at auditing the footprint not only of the NEAR Protocol but also our entire ecosystem.” Tune into Marieke’s talk here. NEAR partnerships in the news After Flament’s introduction, Chris Ghent, Head of Marketing and Brand Partnerships at NEAR Foundation, updated the community on strategic partnerships. Many of these collaborations have made the news, not only elevating NEAR’s profile but also laying the groundwork for mass adoption. “The Sweat economy from the Sweatcoin team has really been an amazing thing to see,” said Ghent. “In the last 11 days or so we’ve seen over a million accounts created on the NEAR. Pretty phenomenal when you think about the future of movement and a new economy based on movement.” “So, jumping into crypto is as easy as just walking,” he added. “And, really, the health benefits, the economic benefits of that are going to be amazing to see unfold.” Ghent also talked about upcoming milestones for the NEAR partnership with SailGP. In case you missed it, this partnership will feature a variety of activations and products, including the creation and launch of a SailGP by a DAO run on the NEAR ecosystem. Tune into Chris’ talk here. NEAR Education launches NEAR Certified Analyst program Next, Sherif Abushadi, Head of Education at NEAR Foundation, updated the community on its education efforts. He noted that NEAR Education has tens of thousands of students, millions in ecosystem grants, and dozens of programs shipping with more on the way. “We are interested in engaging people with our NEAR Certified programs,” Abushadi said. “NEAR Certified Analyst, Developer, and Entrepreneur.” Abushadi noted that half of the NEAR Certified program applications are submitting to join a certification program without any software development experience. So, NEAR Education wants to meet applicants where they are with the NEAR Certified Analyst program. “And that is, basically to spend some time talking about what are these [blockchain] systems?” Abushadi said during the town hall. “How do you think about them? And how can you make a contribution without necessarily, you know, fingers on a keyboard typing code, as would a NEAR Certified Developer?” “So, we’re excited to announce the upcoming launch here of NEAR Certified Analysts,” he added. “We have a couple of different proposals in play. Hopefully, this quarter we’ll see that course in full swing.” This is just a small fraction of NEAR Education’s learning opportunities. Stay tuned to the NEAR Education homepage, which is expanding and evolving monthly to learn more. Tune into Sherif’s full talk here. NEAR funding and ecosystem updates Josh Daniels, Head of Funding at NEAR Foundation, noted that there has been a great deal of growth in funding in the first quarter of 2022. He noted that there has been a lot of positive ecosystem activity with regard to funding, both from external sources and NEAR Foundation grants. “On the grant side of things, we’ve had a stellar quarter in terms of grant growth and support,” Daniels said. “But I think the important thing to note as we look at our grants program is not necessarily how much we’re deploying or committing to deploy, but the quality of those projects. And we’ve really seen an uptick in the quality of products that are coming into the ecosystem.” New NEAR products include those looking for a multi-chain strategy, transitioning from Web2, and Tier 1 teams coming in to build from the ground up. “So, we’ve committed to deploying almost $26 million in capital to date for almost 360 projects,” Daniels said. “And the important thing to notice here is that the diversity of those projects is quite expansive.” One such project is eFuse, an esports and gaming platform that received a NEAR Foundation grant to build on NEAR. This grant allows eFuse to bring their project into a Web3 environment. “There’s two ways we’re going to be partnering with them,” said Daniels. “One is the creation of an NFT platform to help mint gaming moments for, in particular, folks that are using the eFuse environment. The next is setting up a league via DAOs to help basically run gaming eSports leagues on top of eFuse leveraging the NEAR and Astro DAO technology.” Be sure to check out Daniels’ spot for a bumper reel of all of Web3 games building on NEAR. Tune into Josh’s full talk here. NEAR’s Regional Hubs strategy Grace Torrellas, NEAR Foundation’s Head of Regional Hubs, followed Daniels with an update on hubs. NEAR Regional Hubs fulfill many functions, but chief among them are helping NEAR decentralize and spur mass adoption. “What are the hubs? Well, they’re independent entities,” said Torrellas. “They are completely aligned with the foundation’s missions and objectives, but they are completely autonomous and independent entities. They have been set up by a Web3 experienced leader and they are looking at creating traction in the Open Web world.” Hubs do this in two different ways. Firstly, a hub aims to foster Web3 talent. The hub’s other function is to help create Web3 projects on NEAR. “Just to make sure that it’s clear hubs are not NEAR offices in those locations, they are not an extension of the NEAR foundation,” Torrellas said at the town hall. “So, the current state shows that we have 5 hubs. We are allocating $100 million in funding to create the network of regional hubs. And all these are very much focusing on developing the ecosystem. That means very close ties with NEAR University, with product labs, with Web3 incubators for both talent and projects coming for ecosystem funds.” Torrellas spoke in detail on the Kenya Regional Hub. Emerging out of the NEAR Guild Sankore’s meetups, the Kenya hub will be critical in fostering the Open Web in continental Africa. Beyond the five currently active NEAR Regional Hubs, 14 prospective hubs are currently under consideration across the globe. The next hub set to go live is LATAM, which will include the Latin American countries Mexico, Colombia, Venezuela, and Argentina. Tune into Grade’s full talk here. Panel on music in the Open Web era The Town Hall wrapped with an exploration of music on the blockchain. Moderated by Vijay Gurbaxni, Founding Director of the Center for Digital Transformation, the discussion was lively, fascinating, and informative. Check out some choice quotes below and watch the blockchain music panel here. Amber Stoneman, Minting Music “What we’re working on with Minting Music is [creating] that bridge between Web2 and Web3, making the NFT marketplace feel very 2.0… Blockchain doesn’t look pretty behind the scenes. The cool thing about building with NEAR is that we’ve been able to really focus on a clean, very simple, and easy to use interface.” Tim Exile, Endlesss “What’s really magical about Endlesss is it allows you to collaborate in real time with musicians around the world. So, you can spin up what is kind of music’s answer to a live musical chat. You can throw down musical ideas, share them with a bunch of people in real time, and anybody can chime in, add layers to that, remix it, and send it back.” Iota Chan, Tenk DAO “NEAR is a new chain. You have to attract artists with an alternative way to launch their NFT project. What is [also] successful in attracting them is to build this creator’s culture.” Nathan Pillai, SailGP “Every time there’s been a major technological advancement it’s just about evolution… What we should all be working toward is how we all come together, whether that’s through A&R, whether that’s filmmaking, and try to get your project funded. There are just so many areas where I see those communities who may have been disenfranchised and not had access now have opportunity. Opportunity is really what Web3 comes down to. It’s broadening reach and that, for me, is the most exciting aspect of this.” Tune into the blockchain music panel here.
--- sidebar_position: 2 --- # Collections When deciding on data structures to use for the data of the application, it is important to minimize the amount of data read and written to storage but also the amount of data serialized and deserialized to minimize the cost of transactions. It is important to understand the tradeoffs of data structures in your smart contract because it can become a bottleneck as the application scales and migrating the state to the new data structures will come at a cost. The collections within `near-sdk` are designed to split the data into chunks and defer reading and writing to the store until needed. These data structures will handle the low-level storage interactions and aim to have a similar API to the [`std::collections`](https://doc.rust-lang.org/std/collections/index.html). :::info Note The `near_sdk::collections` will be moving to `near_sdk::store` and have updated APIs. If you would like to access these updated structures as they are being implemented, enable the `unstable` feature on `near-sdk`. ::: It is important to keep in mind that when using `std::collections`, that each time state is loaded, all entries in the data structure will be read eagerly from storage and deserialized. This will come at a large cost for any non-trivial amount of data, so to minimize the amount of gas used the SDK collections should be used in most cases. The most up to date collections and their documentation can be found [in the rust docs](https://docs.rs/near-sdk/latest/near_sdk/collections/index.html). <!-- TODO include/update link for store module to replace collections mod when docs updated --> The following data structures that exist in the SDK are as follows: | SDK collection | `std`&nbsp;equivalent | Description | | ------------------------------------- | ------------------------------- | ------------| | `LazyOption<T>` | `Option<T>` | Optional value in storage. This value will only be read from storage when interacted with. This value will be `Some<T>` when the value is saved in storage, and `None` if the value at the prefix does not exist. | | `Vector<T>` | `Vec<T>` | A growable array type. The values are sharded in memory and can be used for iterable and indexable values that are dynamically sized. | | <code>LookupMap`<K,&nbsp;V>`</code> | <code>HashMap`<K,&nbsp;V>`</code> | This structure behaves as a thin wrapper around the key-value storage available to contracts. This structure does not contain any metadata about the elements in the map, so it is not iterable. | | <code>UnorderedMap`<K,&nbsp;V>`</code> | <code>HashMap`<K,&nbsp;V>`</code> | Similar to `LookupMap`, except that it stores additional data to be able to iterate through elements in the data structure. | | <code>TreeMap`<K,&nbsp;V>`</code> | <code>BTreeMap`<K,&nbsp;V>`</code> | An ordered equivalent of `UnorderedMap`. The underlying implementation is based on an [AVL tree](https://en.wikipedia.org/wiki/AVL_tree). This structure should be used when a consistent order is needed or accessing the min/max keys is needed. | | `LookupSet<T>` | `HashSet<T>` | A set, which is similar to `LookupMap` but without storing values, can be used for checking the unique existence of values. This structure is not iterable and can only be used for lookups. | | `UnorderedSet<T>` | `HashSet<T>` | An iterable equivalent of `LookupSet` which stores additional metadata for the elements contained in the set. | ## In-memory `HashMap` vs persistent `UnorderedMap` - `HashMap` keeps all data in memory. To access it, the contract needs to deserialize the whole map. - `UnorderedMap` keeps data in persistent storage. To access an element, you only need to deserialize this element. Use `HashMap` in case: - Need to iterate over all elements in the collection **in one function call**. - The number of elements is small or fixed, e.g. less than 10. Use `UnorderedMap` in case: - Need to access a limited subset of the collection, e.g. one or two elements per call. - Can't fit the collection into memory. The reason is `HashMap` deserializes (and serializes) the entire collection in one storage operation. Accessing the entire collection is cheaper in gas than accessing all elements through `N` storage operations. Example of `HashMap`: ```rust /// Using Default initialization. #[near(contract_state)] #[derive(Default)] pub struct Contract { pub status_updates: HashMap<AccountId, String>, } #[near] impl Contract { pub fn set_status(&mut self, status: String) { self.status_updates.insert(env::predecessor_account_id(), status); assert!(self.status_updates.len() <= 10, "Too many messages"); } pub fn clear(&mut self) { // Effectively iterating through all removing them. self.status_updates.clear(); } pub fn get_all_updates(self) -> HashMap<AccountId, String> { self.status_updates } } ``` Example of `UnorderedMap`: ```rust #[near(contract_state)] #[derive(PanicOnDefault)] pub struct Contract { pub status_updates: UnorderedMap<AccountId, String>, } #[near] impl Contract { #[init] pub fn new() -> Self { // Initializing `status_updates` with unique key prefix. Self { status_updates: UnorderedMap::new(b"s".to_vec()), } } pub fn set_status(&mut self, status: String) { self.status_updates.insert(&env::predecessor_account_id(), &status); // Note, don't need to check size, since `UnorderedMap` doesn't store all data in memory. } pub fn delete_status(&mut self) { self.status_updates.remove(&env::predecessor_account_id()); } pub fn get_status(&self, account_id: AccountId) -> Option<String> { self.status_updates.get(&account_id) } } ``` ## Error prone patterns Because the values are not kept in memory and are lazily loaded from storage, it's important to make sure if a collection is replaced or removed, that the storage is cleared. In addition, it is important that if the collection is modified, the collection itself is updated in state because most collections will store some metadata. Some error-prone patterns to avoid that cannot be restricted at the type level are: ```rust use near_sdk::store::UnorderedMap; let mut m = UnorderedMap::<u8, String>::new(b"m"); m.insert(1, "test".to_string()); assert_eq!(m.len(), 1); assert_eq!(m.get(&1), Some(&"test".to_string())); // Bug 1: Should not replace any collections without clearing state, this will reset any // metadata, such as the number of elements, leading to bugs. If you replace the collection // with something with a different prefix, it will be functional, but you will lose any // previous data and the old values will not be removed from storage. m = UnorderedMap::new(b"m"); assert!(m.is_empty()); assert_eq!(m.get(&1), Some(&"test".to_string())); // Bug 2: Should not use the same prefix as another collection // or there will be unexpected side effects. let m2 = UnorderedMap::<u8, String>::new(b"m"); assert!(m2.is_empty()); assert_eq!(m2.get(&1), Some(&"test".to_string())); // Bug 3: forgetting to save the collection in storage. When the collection is attached to // the contract state (`self` in `#[near_bindgen]`) this will be done automatically, but if // interacting with storage manually or working with nested collections, this is relevant. use near_sdk::store::Vector; // Simulate roughly what happens during a function call that initializes state. { let v = Vector::<u8>::new(b"v"); near_sdk::env::state_write(&v); } // Simulate what happens during a function call that just modifies the collection // but does not store the collection itself. { let mut v: Vector<u8> = near_sdk::env::state_read().unwrap(); v.push(1); // The bug is here that the collection itself if not written back } let v: Vector<u8> = near_sdk::env::state_read().unwrap(); // This will report as if the collection is empty, even though the element exists assert!(v.get(0).is_none()); assert!( near_sdk::env::storage_read(&[b"v".as_slice(), &0u32.to_le_bytes()].concat()).is_some() ); // Bug 4 (only relevant for `near_sdk::store`): These collections will cache writes as well // as reads, and the writes are performed on [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) // so if the collection is kept in static memory or something like `std::mem::forget` is used, // the changes will not be persisted. use near_sdk::store::LookupSet; let mut m: LookupSet<u8> = LookupSet::new(b"l"); m.insert(1); assert!(m.contains(&1)); // This would be the fix, manually flushing the intermediate changes to storage. // m.flush(); std::mem::forget(m); m = LookupSet::new(b"l"); assert!(!m.contains(&1)); ``` ## Pagination with persistent collections Persistent collections such as `UnorderedMap`, `UnorderedSet` and `Vector` may contain more elements than the amount of gas available to read them all. In order to expose them all through view calls, we can use pagination. This can be done using iterators with [`Skip`](https://doc.rust-lang.org/std/iter/struct.Skip.html) and [`Take`](https://doc.rust-lang.org/std/iter/struct.Take.html). This will only load elements from storage within the range. Example of pagination for `UnorderedMap`: ```rust #[near(contract_state)] #[derive(PanicOnDefault)] pub struct Contract { pub status_updates: UnorderedMap<AccountId, String>, } #[near] impl Contract { /// Retrieves multiple elements from the `UnorderedMap`. /// - `from_index` is the index to start from. /// - `limit` is the maximum number of elements to return. pub fn get_updates(&self, from_index: usize, limit: usize) -> Vec<(AccountId, String)> { self.status_updates .iter() .skip(from_index) .take(limit) .collect() } } ``` ## `LookupMap` vs `UnorderedMap` ### Functionality - `UnorderedMap` supports iteration over keys and values, and also supports pagination. Internally, it has the following structures: - a map from a key to an index - a vector of keys - a vector of values - `LookupMap` only has a map from a key to a value. Without a vector of keys, it doesn't have the ability to iterate over keys. ### Performance `LookupMap` has a better performance and stores less data compared to `UnorderedMap`. - `UnorderedMap` requires `2` storage reads to get the value and `3` storage writes to insert a new entry. - `LookupMap` requires only one storage read to get the value and only one storage write to store it. ### Storage space `UnorderedMap` requires more storage for an entry compared to a `LookupMap`. - `UnorderedMap` stores the key twice (once in the first map and once in the vector of keys) and value once. It also has a higher constant for storing the length of vectors and prefixes. - `LookupMap` stores key and value once. ## `LazyOption` It's a type of persistent collection that only stores a single value. The goal is to prevent a contract from deserializing the given value until it's needed. An example can be a large blob of metadata that is only needed when it's requested in a view call, but not needed for the majority of contract operations. It acts like an `Option` that can either hold a value or not and also requires a unique prefix (a key in this case) like other persistent collections. Compared to other collections, `LazyOption` only allows you to initialize the value during initialization. ```rust #[near(contract_state)] #[derive(PanicOnDefault)] pub struct Contract { pub metadata: LazyOption<Metadata>, } #[near(serializers=[borsh, json])] pub struct Metadata { data: String, image: Base64Vec, blobs: Vec<String>, } #[near] impl Contract { #[init] pub fn new(metadata: Metadata) -> Self { Self { metadata: LazyOption::new(b"m", Some(metadata)), } } pub fn get_metadata(&self) -> Metadata { // `.get()` reads and deserializes the value from the storage. self.metadata.get().unwrap() } } ```
Internet at Crossroads — Where do we go from here? COMMUNITY August 27, 2018 At the time of this writing, Amazon, Apple, Facebook, Google, and Netflix are worth $696 billion on average. That’s higher than the GDP of large countries like Argentina or Switzerland. How did the world converge to such a hegemony of just several organizations? Additionally, I noticed that I now have a dedicated app folder for Google and Amazon apps on my iPhone. My Google mobile app folder and Amazon app folder have 9 apps and 6 apps, respectively. I also have 4 Facebook-owned apps on my phone. It seems to me that Internet giants monopolized my attention over time and has slowly become the go-to choice for pretty much everything: reading, searching for information, socializing, shopping, and entertainment. Why is my attention of value to Internet giants? As aggregator platforms (more on what defines aggregator is here), Facebook and Google charge advertisers for my attention by getting me interested in some particular content (i.e. search results in Google, or articles posted on Facebook). It’s a nice business model for them since they don’t even produce any content in the first place. Instead, they merely distribute someone else’s content. To add to this, Facebook and Google initially gained wide adoption by offering their users a variety of options, but later focused on commoditizing content providers that helped them grow in the first place. Over time, the best entrepreneurs, developers, and investors have become wary of building on top of centralized platforms. The reason is that centralized platforms follow a predictable life cycle over time. Search for “S-Curve” in this article if you want to learn more about this evolution. Back in my childhood, when the internet was at its infancy, we had an “intranet” built around our neighborhood back in Belarus. All of “intranet” users would collaborate, get to know each other, and share the content around. It felt like a collaborative system and a potential blueprint for how the Internet itself should evolve. Why did the internet I remember as a collaborative ecosystem with numerous options evolved into such a centralized “walled garden” dominated by half a dozen companies? Back at Internet infancy, Tim Berners-Lee and other early Internet creators envisioned it to be a decentralized system (more on this here). But as the web has grown from an obscure community of researchers, gamers, and other early adopters into a platform for commerce, communication, and entertainment, the decentralized nature of it seem to be fading away. As a result, there is a growing sentiment in the developer community that the pendulum has swung too far towards centralization. Gladly, we now have a choice of how the Internet will evolve going forward. During the peak of the 2008 financial crisis as Lehman Brothers declared bankruptcy, someone named Satoshi Nakamoto published a 9 page paper about a peer-to-peer version of electronic cash, which could be sent from one party to the other without going through a traditional financial institution. It was a radically new version of the financial system and it took some time for this idea to really percolate through the community. His ideas combined game theory, cryptography, and distributed computing to offer an alternative system in which participants could come to a consensus in a trustless environment. To follow up on Satoshi’s ideas and research, Vitalik Buterin in late 2013 suggested that arguably the most important part of the bitcoin experiment is the underlying blockchain technology as a tool for distributed consensus, and that it could be used to build applications involving having digital assets being directly controlled by a piece of code implementing arbitrary rules. Also known as “smart contracts”, this generalized approach to decentralized application development caught the attention of much larger community. By now, the ideas of Bitcoin and Ethereum have materialized into thousands of servers running the blockchain software, and it seems like we are on the verge of a fork in terms of where the Internet as a whole could go. The internet could continue going towards more centralization and reliance on behemoths like Google, Amazon, and Facebook, or it could go back to where it was originally architected — peer-to-peer systems without a centralized authority or corporation taking advantage of the rest of the ecosystem. The decision is in our hands. Decentralized applications could provide better security, privacy, and governance, but would require moving away from the convenience of using familiar services (i.e. Google, Facebook and others). Additionally, any systems costs money to run. In the world of blockchain, the miners are the ones who are compensated for providing computing resources to keep the overall system up to date. If there is no Facebook to take the cost on themselves (they can easily afford this cost since they make money off our data), the cost will be on users. So there is a tradeoff between convenience and “free” familiar service on one hand (subsidized by our data), and the service that’s free of middleman and more privacy friendly, but not quite free, on other hand. It’s yet unclear what the end users would prefer. While Internet users need time to really understand the benefits of decentralized systems, the sentiment of the developer community is clear: the world will most definitely move towards more decentralized systems. It will be quite difficult for an average developer to pick up “smart contracts” development skills (background in networking, distributed systems, data structures and cryptography is needed), but there are teams actively working on making developer experience better and lowering the barrier of blockchain development. I think there will be use cases that will naturally evolve towards decentralized versions first. A decentralized exchange could replace NASDAQ. Decentralized writing platform could replace Medium. Decentralized indie gaming platform could replace Steam. From the infrastructure perspective, underlying blockchain protocols don’t scale well to be able to run decentralized NASDAQ, Steam or Medium just yet. Projects like Ethereum, Zilliqa, and a dozen others are trying to solve scalability, but fall short for a variety of reasons. As we know, one game put the a lot of strain on Ethereum infrastructure. Clearly, a better, more scalable solution is needed. I am excited to be a part of this movement by joining Near Protocol — the team that has built sharding for the commercial distributed database, MemSQL, and is now focused on solving the scalability for blockchain, which will in turn enable the wide variety of future decentralized applications built on top of a scalable blockchain architecture. Taking the experience of building distributed databases, we now focus on building a sharding solution for blockchain infrastructure (we will cover our approach in detail in future blog series). We believe that our approach will enable access to blockchain for mobile devices around the world, which will in turn provide an even higher degree of decentralization. It’s really up to us, regular Internet users, to ultimately decide whether the Internet will be centralized, decentralized or somewhere in between. I encourage you to reach out to your friends who already work in blockchain space, learn, and contribute, and more importantly, understand the tradeoffs I briefly outlined above. Blockchain does surely seem to be a space that will create an Internet-scale tsunami of change over the next decade or two. I am well aware that majority of blockchain projects today are scams, but that’s how large-scale innovations start anyway. It will probably take several years to fix the scalability issues, and then we will have a clear shot at swinging the pendulum of the Internet back to the decentralized state. The future is NEAR. To follow our progress you can use: Twitter — https://twitter.com/nearprotocol, Discord — https://near.chat https://upscri.be/633436/ Thank you to Mikhail Kever & Bowen Wang for providing feedback in writing this blog post.
# StateRecord _type: Enum_ Enum that describes one of the records in the state storage. ## Account _type: Unnamed struct_ Record that contains account information for a given account ID. ### account_id _type: `AccountId`_ The account ID of the account. ### account _type: [Account](../DataStructures/Account.md)_ The account structure. Serialized to JSON. U128 types are serialized to strings. ## Data _type: Unnamed struct_ Record that contains key-value data record for a contract at the given account ID. ### account_id _type: `AccountId`_ The account ID of the contract that contains this data record. ### data_key _type: `Vec<u8>`_ Data Key serialized in Base64 format. _NOTE: Key doesn't contain the data separator._ ### value _type: `Vec<u8>`_ Value serialized in Base64 format. ## Contract _type: Unnamed struct_ Record that contains a contract code for a given account ID. ### account_id _type: `AccountId`_ The account ID of that has the contract. ### code _type: `Vec<u8>`_ WASM Binary contract code serialized in Base64 format. ## AccessKey _type: Unnamed struct_ Record that contains an access key for a given account ID. ### account_id _type: `AccountId`_ The account ID of the access key owner. ### public_key _type: [PublicKey]_ The public key for the access key in JSON-friendly string format. E.g. `ed25519:5JFfXMziKaotyFM1t4hfzuwh8GZMYCiKHfqw1gTEWMYT` ### access_key _type: [AccessKey](../DataStructures/AccessKey.md)_ The access key serialized in JSON format. ## PostponedReceipt _type: `Box<`[Receipt](../RuntimeSpec/Receipts.md)`>`_ Record that contains a receipt that was postponed on a shard (e.g. it's waiting for incoming data). The receipt is in JSON-friendly format. The receipt can only be an `ActionReceipt`. NOTE: Box is used to decrease fixed size of the entire enum. ## ReceivedData _type: Unnamed struct_ Record that contains information about received data for some action receipt, that is not yet received or processed for a given account ID. The data is received using `DataReceipt` before. See [Receipts](../RuntimeSpec/Receipts.md) for details. ### account_id _type: `AccountId`_ The account ID of the receiver of the data. ### data_id _type: [CryptoHash]_ Data ID of the data in base58 format. ### data _type: `Option<Vec<u8>>`_ Optional data encoded as base64 format or null in JSON. ## DelayedReceipt _type: `Box<`[Receipt](../RuntimeSpec/Receipts.md)`>`_ Record that contains a receipt that was delayed on a shard. It means the shard was overwhelmed with receipts and it processes receipts from backlog. The receipt is in JSON-friendly format. See [Delayed Receipts](../RuntimeSpec/Components/RuntimeCrate.md#delayed-receipts) for details. NOTE: Box is used to decrease fixed size of the entire enum.
Built on NEAR: Celebrating Partners and Innovators at NEARCON ’23 NEAR FOUNDATION October 13, 2023 Partnerships are one of the biggest pillars to expanding NEAR’s footprint. They help drive the ecosystem toward fostering new and innovative use cases that will bring the next billion users to the open web. And that’s exactly what’s happening on NEAR, with partnerships ranging from sports to social taking center stage. At NEARCON — the ultimate Web3 education — a number of NEAR partners will be on-hand to talk about Web3 partnerships and innovation. Throughout the past few years, NEAR has engaged, collaborated, and built with partners who share the vision of a decentralized, user-centric open web. Each partnership is contributing their unique, innovative flair to the ecosystem, with a scalable, user-friendly blockchain helping to propel their efforts. As NEARCON ‘23 approaches, let’s celebrate and explore how NEAR’s collaborations and partnerships are shaping the future of the open web. By registering for and attending NEARCON ‘23, you’ll be able to meet some of the following founders, entrepreneurs, and innovators below. And these names are just the tip of the iceberg, so don’t forget to register for NEARCON ‘23 and let’s take part in learning, networking, and building an open web together. Register $99 Creating consumer fun and engagement in the open web An area where NEAR partnerships are thriving is making the blockchain more fun and engaging for the masses. NEAR’s partnership with NFT launchpad Mintbase is a perfect illustration. Mintbase recently celebrated the traditional Indian festival, Raksha Bandhan, by seamlessly transforming photos into NFTs on the NEAR blockchain. During Raksha Bandan, sisters tie a good-luck talisman around the wrists of their brothers, a special moment often photographed and cherished by families. With Mintbase’s open web wallet built on NEAR, users could easily create an account without seed phrases and seamlessly upload their photos, transforming them into NFTs in an instant. Let’s also toast to GLASS, a one-of-a-kind Web3 platform that empowers alcohol brands to engage directly with consumers. Built on the NEAR blockchain, spirit brands can issue token rewards and other blockchain perks to social drinkers who try new cocktail recipes, socialize with friends, and vote on brand decisions. Gaming is also a key entry point into the open web, and NEAR’s partnership with PlayEmber is kicking the door wide open. PlayEmber’s creative gaming studio is fusing AAA quality mobile games on the blockchain, with NEAR providing the backend foundation. Decentralized mobile gaming experiences are now becoming more accessible to a wider audience. Then there’s Cosmose AI’s KaiKai, a fusion of shopping, retail, and gamification dubbed”Shoppertainment.” Built on NEAR’s Blockchain Operating System (B.O.S), KaiKai offers a captivating brand discovery avenue, with features like Augmented Reality (AR) product interactions, exclusive product drops, and celebrity live streams. More than just a shopping app, KaiKai also uses a native cryptocurrency, Kai-Ching. Shoppers earn rewards with the help of Cosmose’s AI-powered personalization, all while transacting on the NEAR blockchain. It’s all about enhancing personalization, user empowerment, and engagements in the retail space with a unique, powerful blockchain twist. And in a fusion of health and blockchain, Sweatcoin’s partnership with NEAR helps people earn SWEAT tokens with literally every step towards better fitness. With a user base of over 63 million who’ve clocked in more than 19 trillion steps, Sweatcoin and NEAR are incentivizing healthier lifestyles. Oleg Fomenko, co-founder of Sweatcoin, believes in the potential of merging health and blockchain, enabling users to “walk into the world of crypto.” This partnership, built on the NEAR blockchain, personifies the next level of open web adoption, encouraging physical wellness via crypto-based rewards. Financial empowerment and innovation on NEAR One of the biggest challenges that the open web is addressing is financial empowerment and inclusion. NEAR Foundation’s partnerships in this area are helping bring that vision to life. The Foundation’s collaboration with Proximity Labs is helping talented builders create innovative Web3 financial solutions, with substantial grants and support. Calimero Network is another example of NEAR’s commitment to financial innovation. Calimero provides what’s called ‘private sharding’ infrastructure, a feature that ensures data privacy in Web3 finance without sacrificing the power of open-source platforms. With both financial and technical support from NEAR, more business can be safely conducted on the blockchain. Building the technical foundation for tomorrow’s open web The ongoing partnership between NEAR Protocol and Octopus Network signifies the ecosystem’s infrastructure strides. Early on, Octopus Network selected NEAR as its “mother-chain” protocol citing speed ability to accommodate a large user base. Octopus Network and NEAR are paving the way for developers aiming to launch tailored applications using their own dedicated blockchains — also known as “Appchains” — making deployment a breeze. Partnering with a tech infrastructure behemoth like Google Cloud is another way of giving Web3 startups pathways to world-class startup expertise. It’s all part of NEAR’s commitment to making blockchain solutions more accessible, robust, and primed for mainstream adoption. In collaboration with Urbit, NEAR is also continuing to make the open web more user friendly. Urbit’s vision — shared and supported by the NEAR Foundation — is to improve the frontend experience of open web apps. Urbit allows developers to easily create sleek designs so that tomorrow’s decentralized applications are as seamless as the most popular ones in the App Store. On another front, NEAR’s collaboration with SailGP is bringing Decentralized Autonomous Organizations (DAOs) to professional sports, creating a bridge between leagues and fans. The introduction of a DAO-owned racing team on the NEAR Protocol gives fans a novel way to engage, interact with, and participate in active decision making along with teams and athletes. Partnership innovation rolls on at NEARCON Past, current, and future partnership will take center stage at NEARCON 2023 — now less than a month away. It’ll be four full days of full immersion into the NEAR ecosystem — a place for you to truly step into the open web. Build on the B.O.S and network with thousands of other blockchain enthusiasts. Get the inside scoop on onboarding Web2 companies into Web3 with Google Cloud’s James Tromans, and get the low down on SWEAT with Oleg Fomenko. From raising a glass to blockchain brand loyalty with GLASS and setting sail towards new DAO horizons with SailGP, each and every NEAR partner is playing its own pivotal role in crafting how tomorrow’s open web experiences will look, feel, and even taste. Better decentralized infrastructure, financial empowerment, and exciting consumer experiences are just the start. Ready to dive into sessions, hackathons, and more in Lisbon at NEARCON 2023? Go ahead and register now to secure your spot.
--- id: introduction title: NFT Zero to Hero sidebar_label: Introduction --- In this _Zero to Hero_ series, you'll find a set of tutorials that will cover every aspect of a non-fungible token (NFT) smart contract. You'll start by minting an NFT using a pre-deployed contract and by the end you'll end up building a fully-fledged NFT smart contract that supports every extension. --- ## Prerequisites To complete these tutorials successfully, you'll need: - [Rust](https://www.rust-lang.org/tools/install) - [A Testnet wallet](https://testnet.mynearwallet.com/create) - [NEAR-CLI](/tools/near-cli#setup) - [cargo-near](https://github.com/near/cargo-near) :::info New to Rust? If you are new to Rust and want to dive into smart contract development, our [Quick-start guide](../../2.build/2.smart-contracts/quickstart.md) is a great place to start ::: --- ## Overview These are the steps that will bring you from **_Zero_** to **_Hero_** in no time! 💪 | Step | Name | Description | |------|---------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------| | 1 | [Pre-deployed contract](/tutorials/nfts/predeployed-contract) | Mint an NFT without the need to code, create, or deploy a smart contract. | | 2 | [Contract architecture](/tutorials/nfts/skeleton) | Learn the basic architecture of the NFT smart contract and compile code. | | 3 | [Minting](/tutorials/nfts/minting) | Flesh out the skeleton so the smart contract can mint a non-fungible token. | | 4 | [Upgrade a contract](/tutorials/nfts/upgrade-contract) | Discover the process to upgrade an existing smart contract. | | 5 | [Enumeration](/tutorials/nfts/enumeration) | Explore enumeration methods that can be used to return the smart contract's states. | | 6 | [Core](/tutorials/nfts/core) | Extend the NFT contract using the core standard which allows token transfer. | | 7 | [Approvals](/tutorials/nfts/approvals) | Expand the contract allowing other accounts to transfer NFTs on your behalf. | | 8 | [Royalty](/tutorials/nfts/royalty) | Add NFT royalties allowing for a set percentage to be paid out to the token creator. | | 9 | [Marketplace](/tutorials/nfts/marketplace) | Learn about how common marketplaces operate on NEAR and dive into some of the code that allows buying and selling NFTs. | <!-- 1. [Events](/tutorials/nfts/events): in this tutorial you'll explore the events extension, allowing the contract to react on certain events. 2. [Marketplace](/tutorials/nfts/marketplace): in the last tutorial you'll be exploring some key aspects of the marketplace contract. --> --- ## Next steps Ready to start? Jump to the [Pre-deployed Contract](/tutorials/nfts/predeployed-contract) tutorial and begin your learning journey! If you already know about non-fungible tokens and smart contracts, feel free to skip and jump directly to the tutorial of your interest. The tutorials have been designed so you can start at any given point!
--- id: integration-test title: Integration Tests #sidebar_label: 🥼 Integration Test --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs" import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Integration tests enable to deploy your contract in the NEAR `testnet` or a local `sandbox`, and create test-users to interact with it. In this way, you can thoroughly test your contract in a realistic environment. Moreover, when using the local `sandbox` you gain complete control of the network: 1. Create test `Accounts` and manipulate their `State` and `Balance`. 2. Simulate errors on callbacks. 3. Control the time-flow and fast-forward into the future (Rust ready, TS coming soon). :::tip NEAR Workspaces In NEAR, integration tests are implemented using a framework called **Workspaces**. Workspaces comes in two flavors: [🦀 Rust](https://github.com/near/workspaces-rs) and [🌐 Typescript](https://github.com/near/workspaces-js). All of our [examples](https://github.com/near-examples/docs-examples) come with integration testing. ::: --- ## Snippet I: Testing Hello NEAR Lets take a look at the test of our [Quickstart Project](../quickstart.md) [👋 Hello NEAR](https://github.com/near-examples/hello-near-examples), where we deploy the contract on an account and test it correctly retrieves and sets the greeting. <CodeTabs> <Language value="js" language="js"> <Github fname="main.ava.ts" url="https://github.com/near-examples/hello-near-examples/blob/main/contract-ts/sandbox-ts/main.ava.ts" start="8" end="43"/> </Language> </CodeTabs> --- ## Snippet II: Testing Donations In most cases we will want to test complex methods involving multiple users and money transfers. A perfect example for this is our [Donation Example](https://github.com/near-examples/donation-examples), which enables users to `donate` money to a beneficiary. Lets see its integration tests <CodeTabs> <Language value="js" language="js"> <Github fname="main.ava.ts" url="https://github.com/near-examples/donation-examples/blob/main/contract-ts/sandbox-ts/src/main.ava.ts" start="50" end="73" /> </Language> </CodeTabs> --- ## Sandbox Testing NEAR Workspaces allows you to write tests once, and run them either on `testnet` or a local `Sandbox`. By **default**, Workspaces will start a **sandbox** and run your tests **locally**. Lets dive into the features of our framework and see how they can help you. ### Spooning Contracts [Spooning a blockchain](https://coinmarketcap.com/alexandria/glossary/spoon-blockchain) is copying the data from one network into a different network. NEAR Workspaces makes it easy to copy data from Mainnet or Testnet contracts into your local Sandbox environment: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" default> ```ts const refFinance = await root.importContract({ mainnetContract: 'v2.ref-finance.near', blockId: 50_000_000, withData: true, }); ``` This would copy the Wasm bytes and contract state from [v2.ref-finance.near](https://nearblocks.io/address/v2.ref-finance.near) to your local blockchain as it existed at block `50_000_000`. This makes use of Sandbox's special [patch state](#patch-state-on-the-fly) feature to keep the contract name the same, even though the top level account might not exist locally (note that this means it only works in Sandbox testing mode). You can then interact with the contract in a deterministic way the same way you interact with all other accounts created with near-workspaces. :::note `withData` will only work out-of-the-box if the contract's data is 50kB or less. This is due to the default configuration of RPC servers; see [the "Heads Up" note here](../../../5.api/rpc/contracts.md#view-contract-state-view-contract-state). ::: See a [TypeScript example of spooning](https://github.com/near/workspaces-js/blob/main/__tests__/05.spoon-contract-to-sandbox.ava.ts) contracts. </TabItem> <TabItem value="rust" label="🦀 Rust"> Specify the contract name from `testnet` you want to be pulling, and a specific block ID referencing back to a specific time. (Just in case the contract you're referencing has been changed or updated) ```rust const CONTRACT_ACCOUNT: &str = "contract_account_name_on_testnet.testnet"; const BLOCK_HEIGHT: BlockHeight = 12345; ``` Create a function called `pull_contract` which will pull the contract's `.wasm` file from the chain and deploy it onto your local sandbox. You'll have to re-initialize it with all the data to run tests. ```rust async fn pull_contract(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Result<Contract> { let testnet = workspaces::testnet_archival(); let contract_id: AccountId = CONTRACT_ACCOUNT.parse()?; ``` This next line will actually pull down the relevant contract from testnet and set an initial balance on it with 1000 NEAR. ```rust let contract = worker .import_contract(&contract_id, &testnet) .initial_balance(parse_near!("1000 N")) .block_height(BLOCK_HEIGHT) .transact() .await?; ``` Following that you'll have to init the contract again with your metadata. This is because the contract's data is too big for the RPC service to pull down. (limits are set to 50Mb) ```rust owner .call(&worker, contract.id(), "init_method_name") .args_json(serde_json::json!({ "arg1": value1, "arg2": value2, }))? .transact() .await?; Ok(contract) } ``` </TabItem> </Tabs> ### Patch State on the Fly In Sandbox-mode, you can add or modify any contract state, contract code, account or access key with `patchState`. :::tip You can alter contract code, accounts, and access keys using normal transactions via the `DeployContract`, `CreateAccount`, and `AddKey` [actions](https://nomicon.io/RuntimeSpec/Actions#addkeyaction). But this limits you to altering your own account or sub-account. `patchState` allows you to perform these operations on any account. ::: Keep in mind that you cannot perform arbitrary mutation on contract state with transactions since transactions can only include contract calls that mutate state in a contract-programmed way. For example, with an NFT contract, you can perform some operation with NFTs you have ownership of, but you cannot manipulate NFTs that are owned by other accounts since the smart contract is coded with checks to reject that. This is the expected behavior of the NFT contract. However, you may want to change another person's NFT for a test setup. This is called "arbitrary mutation on contract state" and can be done with `patchState`: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" > ```js const {contract, ali} = t.context.accounts; // Contract must have some state for viewState & patchState to work await ali.call(contract, 'set_status', {message: 'hello'}); // Get state const state = await contract.viewState(); // Get raw value const statusMessage = state.get('STATE', {schema, type: StatusMessage}); // Update contract state statusMessage.records.push( new BorshRecord({k: 'alice.near', v: 'hello world'}), ); // Serialize and patch state back to runtime await contract.patchState( 'STATE', borsh.serialize(schema, statusMessage), ); // Check again that the update worked const result = await contract.view('get_status', { account_id: 'alice.near', }); t.is(result, 'hello world'); ``` To see a complete example of how to do this, see the [patch-state test](https://github.com/near/workspaces-js/blob/main/__tests__/02.patch-state.ava.ts). </TabItem> <TabItem value="rust" label="🦀 Rust" > ```rust // Grab STATE from the testnet status_message contract. This contract contains the following data: // get_status(dev-20211013002148-59466083160385) => "hello from testnet" let (testnet_contract_id, status_msg) = { let worker = workspaces::testnet().await?; let contract_id: AccountId = TESTNET_PREDEPLOYED_CONTRACT_ID .parse() .map_err(anyhow::Error::msg)?; let mut state_items = worker.view_state(&contract_id, None).await?; let state = state_items.remove(b"STATE".as_slice()).unwrap(); let status_msg = StatusMessage::try_from_slice(&state)?; (contract_id, status_msg) }; info!(target: "spooning", "Testnet: {:?}", status_msg); // Create our sandboxed environment and grab a worker to do stuff in it: let worker = workspaces::sandbox().await?; // Deploy with the following status_message state: sandbox_contract_id => "hello from sandbox" let sandbox_contract = deploy_status_contract(&worker, "hello from sandbox").await?; // Patch our testnet STATE into our local sandbox: worker .patch_state( sandbox_contract.id(), "STATE".as_bytes(), &status_msg.try_to_vec()?, ) .await?; // Now grab the state to see that it has indeed been patched: let status: String = sandbox_contract .view( &worker, "get_status", serde_json::json!({ "account_id": testnet_contract_id, }) .to_string() .into_bytes(), ) .await? .json()?; info!(target: "spooning", "New status patched: {:?}", status); assert_eq!(&status, "hello from testnet"); ``` </TabItem> </Tabs> As an alternative to `patchState`, you can stop the node, dump state at genesis, edit the genesis, and restart the node. This approach is more complex to do and also cannot be performed without restarting the node. ### Time Traveling `workspaces` offers support for forwarding the state of the blockchain to the future. This means contracts which require time sensitive data do not need to sit and wait the same amount of time for blocks on the sandbox to be produced. We can simply just call `worker.fast_forward` to get us further in time: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" default> <Github fname="fast-forward.ava.ts" language="js" url="https://github.com/near/near-workspaces-js/blob/main/__tests__/08.fast-forward.ava.ts" start="34" end="53" /> </TabItem> <TabItem value="rust" label="🦀 Rust"> ```rust #[tokio::test] async fn test_contract() -> anyhow::Result<()> { let worker = workspaces::sandbox().await?; let contract = worker.dev_deploy(WASM_BYTES); let blocks_to_advance = 10000; worker.fast_forward(blocks_to_advance); // Now, "do_something_with_time" will be in the future and can act on future time-related state. contract.call(&worker, "do_something_with_time") .transact() .await?; } ``` _[See the full example on Github](https://github.com/near/workspaces-rs/blob/main/examples/src/fast_forward.rs)._ </TabItem> </Tabs> --- ## Using Testnet NEAR Workspaces is set up so that you can write tests once and run them against a local Sandbox node (the default behavior) or against [NEAR TestNet](../../../1.concepts/basics/networks.md). Some reasons this might be helpful: * Gives higher confidence that your contracts work as expected * You can test against deployed testnet contracts * If something seems off in Sandbox mode, you can compare it to testnet :::tip In order to use Workspaces in testnet mode you will need to have a `testnet` account. You can create one [here](https://testnet.mynearwallet.com/). ::: You can switch to testnet mode in three ways. 1. When creating Worker set network to `testnet` and pass your master account: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" default> ```ts const worker = await Worker.init({ network: 'testnet', testnetMasterAccountId: '<yourAccountName>', }) ``` </TabItem> <TabItem value="rust" label="🦀 Rust" > ```rust #[tokio::main] // or whatever runtime we want async fn main() -> anyhow::Result<()> { // Create a sandboxed environment. // NOTE: Each call will create a new sandboxed environment let worker = workspaces::sandbox().await?; // or for testnet: let worker = workspaces::testnet().await?; } ``` </TabItem> </Tabs> 2. Set the `NEAR_WORKSPACES_NETWORK` and `TESTNET_MASTER_ACCOUNT_ID` environment variables when running your tests: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" default> ```bash NEAR_WORKSPACES_NETWORK=testnet TESTNET_MASTER_ACCOUNT_ID=<your master account Id> node test.js ``` If you set this environment variables and pass `{network: 'testnet', testnetMasterAccountId: <masterAccountId>}` to `Worker.init`, the config object takes precedence. </TabItem> </Tabs> 3. If using `near-workspaces` with AVA, you can use a custom config file. Other test runners allow similar config files; adjust the following instructions for your situation. <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript" default> Create a file in the same directory as your `package.json` called `ava.testnet.config.cjs` with the following contents: ```js module.exports = { ...require('near-workspaces/ava.testnet.config.cjs'), ...require('./ava.config.cjs'), }; module.exports.environmentVariables = { TESTNET_MASTER_ACCOUNT_ID: '<masterAccountId>', }; ``` The [near-workspaces/ava.testnet.config.cjs](https://github.com/near/workspaces-js/blob/main/ava.testnet.config.cjs) import sets the `NEAR_WORKSPACES_NETWORK` environment variable for you. A benefit of this approach is that you can then easily ignore files that should only run in Sandbox mode. Now you'll also want to add a `test:testnet` script to your `package.json`'s `scripts` section: ```diff "scripts": { "test": "ava", + "test:testnet": "ava --config ./ava.testnet.config.cjs" } ``` </TabItem> </Tabs> --- ## Additional Media #### Test Driven Design Using Workspaces and AVA {#test-driven-design} The video below walks through how to apply TDD with Workspaces and AVA for a simple contract: <iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/LCu03IYwu1I" title="TDD Using Workspaces" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe>
Announcing Ready Layer One: An Open Blockchain Week COMMUNITY April 6, 2020 Ready Layer One Today we’re excited to announce an unprecedented collaboration between base layer blockchain projects to put on a free virtual summit for all of the builders out there. This multi-day event, called Ready Layer One, will take place from May 4-6, 2020. Why? People in the blockchain space are more distributed than a typical community, which means we *really* like to get together in person when we can. The explosive rise of COVID and associated stay-at-home orders suddenly left everyone without their favorite excuses to geek out on protocol theory and hack together over lousy wifi connections. The spirit of collaboration has driven this technology forward from the start–the best projects are open source, their teams are always learning from each other, and it often feels like a small community. Since this macro shock is more significant than anyone’s project, rather than competing for space in an already crowded digital world, we decided to use this opportunity as a rallying cry to gather everyone together. Open Blockchain Week The past couple of years have seen several base layer protocols make outstanding progress in addressing the core issues of usability and scalability that have held back more widespread adoption. Some of these protocols are recently launched, and others, like NEAR, are on the home stretch. Application developers are ready for it. Enterprise adopters are ready for it. Gamers are ready for it. Fintech entrepreneurs are ready for it. Even hodlers are ready for it. …and the base layer protocols, also known as “layer one,” are finally ready to support all of these people and the apps that serve them. Hence, Ready Layer One. A New Digital Experience Ready Layer One is specifically designed to be more than just a conference experience — it’s a place where developers can learn but also participate and connect in a way that’s atypical for the digital realm. To do this, we took the best parts of in-person hackerspaces and mixed them with some of the principles that create genuine and meaningful experiences in real life. Ready Layer One is built around each of the following principles: Collaborative Co-creation: We believe in the principles of free software and open-source, where groups of people who come together to share technology, skills, and ideas produce the most impactful results. Here, this means making workshops interactive and collaborative between participants wherever possible. Participation, Presence, and Immediacy: We aim to create interactions that facilitate collaborative knowledge and enable you to construct new ideas with people from around the world. Dive in, be present, and build! We ask participants to shut down email and social apps so they can focus on being present. To keep things immediate, we’ll offer a number of experiences that will not be recorded for later. Decommercialization: To encourage new technologies and ideas to be considered and take root, we kindly ask that everyone focus on the tech and its societal applications rather than sponsorships, branding, or pitching. This isn’t about one of us; it’s about all of us. The content will include well-known speakers from across the ecosystem plus several tracks of engineering content targeted at helping developers get their hands dirty with all sorts of different use cases. We’ll have Easter eggs and surprise speakers crafting custom, small-scale experiences throughout to keep you on your toes. After it ends, we’ll all get together to apply what we’ve learned in a digital hackathon. Getting Involved Are you ready to join us in making Ready Layer One a success? We’d like to keep the quality of content and attendees high, so tickets are limited. To learn more about the event, grab a free ticket or submit a workshop, register at https://readylayer.one/ We hope to see you there!
--- id: interaction title: Smart Contract Interaction --- Your frontend can interact with different blockchains using the built-in BOS API. Let's see how to create an application that reads and stores a greeting from a NEAR smart contract. ![widgets](/docs/hello-near-logedin.png) *View of our Hello Near app when the user is logged-in* :::info Check the finished example at [near.social code page](https://near.social/#/mob.near/widget/WidgetSource?src=gagdiez.near/widget/HelloNear). ::: --- ## The Contract We have deployed a `Hello World` smart contract in the NEAR network at `hello.near-examples.near`. The contract exposes two methods: - `set_greeting(greeting: string): void`, which accepts a greeting and stores it in the contract state. - `get_greeting(): string` which returns the stored greeting. --- ## Retrieving the Greeting Since we want to interact with the NEAR network, we will use the `Near` object from the BOS API. ```ts const contract = "hello.near-examples.near"; const greeting = Near.view(contract, "get_greeting", {}); return <div>{greeting} World</div>; ``` Assuming the contract is storing `"Hello"`, this will render a simple: ```json Hello World ``` --- ## Changing the Greeting To modify the greeting, we simply need to use `Near.call` to call the `set_greeting` method. This however, requires us to have a frontend in which the user can input the new greeting. Lets create it in two steps: 1. Build the HTML that will be rendered 2. Add the logic to handle the function call <hr className="subsection" /> ### 1. HTML Components Use the following code to create a simple frontend, composed by a title, an input form to change the greeting, and a button to submit the change. ```js const contract = "hello.near-examples.near"; const greeting = Near.view(contract, "get_greeting", {}); // Define components const greetingForm = ( <> <div className="border border-black p-3"> <label>Update greeting</label> <input placeholder="Howdy" onChange={onInputChange} /> <button className="btn btn-primary mt-2" onClick={onBtnClick}> Save </button> </div> </> ); const notLoggedInWarning = <p> Login to change the greeting </p>; // Render return ( <> <div className="container border border-info p-3"> <h3 className="text-center"> The contract says: <span className="text-decoration-underline"> {greeting} </span> </h3> <p className="text-center py-2"> Look at that! A greeting stored on the NEAR blockchain. </p> {context.accountId ? greetingForm : notLoggedInWarning} </div> </> ); ``` :::info Relevant HTML There are two important things to notice in the code above: 1. **onChange & onClick**: We have prepared our `<input>` and `<button>` to act when something happens. Particularly, we will build two methods: one when the input changes, and one when the button is pressed. 2. **context.accountId**: We check if `context.accountId` is set, which tells us if the user has logged in using their NEAR account, and thus can interact with NEAR contracts. ::: <hr className="subsection" /> ### 2. Handling User's Input Having our component's view ready, we now need to define the logic for when the user inputs a new greeting and presses the `Submit` button. This is, we need to define the `onInputChange` and `onBtnClick` methods. #### onInputChange When the user inputs a new greeting, we want to store it somewhere until the `Submit` button is pressed, for this, we can use the [application's State](../../2.build/3.near-components/anatomy/state.md). In BOS, the state is initialized through `State.init`, updated with `State.update`, and accessed through the `state` variable (notice the lowercase). Lets store the new greeting in the App's state: ```js State.init({ new_greeting: "" }); const onInputChange = ({ target }) => { State.update({ new_greeting: target.value }); }; ``` #### onBtnClick The only thing left to do, is to handle when the user clicks the `Submit` button. What we want is to check if the user changed the greeting, and submit it to the contract. ```js const onBtnClick = () => { if (!state.new_greeting) { return; } Near.call(contract, "set_greeting", { greeting: state.new_greeting, }); }; ``` --- ## Complete Example We have deployed a complete version of this example on the NEAR blockchain, so you can see its code and play with it. :::tip - **Code**: Check the code of this example at the [near.social code page](https://near.social/#/mob.near/widget/WidgetSource?src=gagdiez.near/widget/HelloNear). - **Try It**: Interact with the application at the [near.social page](https://near.social/#/gagdiez.near/widget/HelloNear). :::
Armored Kingdom, Brave, JavaScript: Highlights from NEAR @ Consensus COMMUNITY June 12, 2022 The NEAR community was busy connecting at the Consensus conference this weekend in Austin, Texas. The NEAR Foundation made its presence felt in a variety of ways, from hosting educational developer workshops to panel discussions and speeches from key members of the ecosystem and Foundation. From NEAR’s roadmap to raising crypto funds for Ukraine, here are the main takeaways from Consensus, Austin. Major Dev Experience Announcements NEAR Foundation’s presence at Consensus 2022 kicked off with opening remarks by CEO Marieke Flemant on the Foundations Stage. Flemant highlighted the NEAR Foundation’s continued commitment to sustainability and ecosystem growth before turning things over to NEAR co-founder Illia Polosukhin, who presented a roadmap for the NEAR Protocol over the next 12 months along with some exciting news for developers. After re-iterating the Foundation’s goal of onboarding the first one billion users onto Web3, Polosukhin announced that NEAR will soon be rolling out a JavaScript software development kit (SDK) within the next few months. Developers will then be able to build in JavaScript and ship code directly to NEAR. Polosukhin was particularly excited about this announcement because he feels that JavaScript is the language for mass developer adoption. To piggyback on Polosukhin’s announcement, Josh Ford and Ben Kurrek from the developer relations team led a Test Drive Javascript for NEAR session on the Crypto Cities stage. Ford and Kurrek noted that with over seven million developers currently coding with JavaScript, the upcoming SDK release will prove extremely fruitful in user onboarding. Not to mention that Brendan Eiche, the inventor of JavaScript, attended both sessions and expressed his excitement about NEAR’s JavaScript SDK on Twitter. The Web3 World According to NEAR On the second day of Consensus, Flament gave a speech on the Feature Stage speech entitled “The Web3 World According to NEAR.” Building upon her opening remarks on day one, she painted a clearer picture of how Web3 and NEAR will evolve in the upcoming years and why she still believes that crypto can fulfill the promise of re-defining money and creating a more inclusive world. Flament also addressed current market conditions and pointed out the importance of an even deeper commitment to building during a bear market. “We have much more talent, funding, and infrastructure than the last bear market,” Flamant observed. “While it seems that the world is filled with bad news, this is not the time for pessimism but for action. It’s urgent that we make even more progress at a faster pace than ever.” Flament restated NEAR’s commitment to creating an open, inclusive Web3 based on the three pillars of Ownership, Community, and Incentives. Once self-sovereign individuals gain ownership and control over their data, Flament said that only then can we collectively fight exploitative behavior by Web2 giants. After the notion of ownership has been decentralized and turned on its head, Flament predicted that we can then re-think modes of incentivizing participation and building community. And while Flament observed that some at Consensus were bearish on the “X to Earn” phenomena, in her opinion, the trend has barely scratched the surface. Sweatcoin continues to onboard users to NEAR and Web3 with their app. Not to mention SailGP and Armored Kingdom, projects and partners that are re-defining sports team ownership and entertainment with DAOs and NFTs. She concluded by saying that NEAR is committed to providing tools to create a simple, sustainable, and scalable Web3 world. NEAR Helping Ukrainians in Need Co-founder Illia Polosukhin re-emerged on the second day of Consusus to participate in a panel discussion around how crypto and the blockchain is being used to aid Ukraine during the ongoing war. The discussion was moderated by Emily Parker from CoinDesk, and included Valeriya Ionan Ukraine’s Deputy Minister of Digital Transformation as well as Mike Chobanian from the Blockchain Association of Ukraine. Polosukhin recounted that when he heard the news about Ukraine, his first instinct was to find ways to personally donate to those affected by the conflict. He then started thinking bigger, and shortly thereafter the Unchain Fund was started on NEAR to raise funds via a DAO model. Unchain Fund raised over $10 million within the first few weeks and expanded to work with over 5,000 volunteers on the ground. Crypto has been a huge part of effective relief, said Polosukhin, as NGOs can sometimes be slow to respond immediately. He then reminded the audience that there will be a time – hopefully soon – that the conflict comes to an end. And at that point, blockchain, crypto, and Web3 can play a crucial role in rebuilding Ukraine and even preserving cultural artifacts on the blockchain. Chobanian from the Blockchain Association of Ukraine added that they are currently in the proposal stage with NEAR to place NFT versions of important Ukrainian art and other artifacts on the blockchain in case the IRL versions are ever destroyed. Armored Kingdom and Brave Announcements Two of the biggest NEAR announcements that came out of Consensus were on the gaming and browser integration fronts. Firstly, Brave and NEAR will collaborate to integrate Aurora, an Ethereum Virtual Machine (EVM) on the NEAR Protocol, into Brave Wallet. This means greater multi-chain functionality in Brave Wallet and expanded utility for the Basic Attention Token (BAT). “This is a very significant partnership for the future advancement of Web3 and mass adoption, offering a multi-chain integration bridging the Ethereum and NEAR communities via Aurora – and one of the first big integrations via Brave,” said Marieke Flament, CEO of NEAR Foundation. “With the new Brave Wallet there will be a host of Web3 functionality supported such as NFT and Swap – all of which will provide the protection of a privacy-preserving, in-browser wallet that’s secure and mass-market ready.” In addition, Deadline Hollywood broke the news that superstar actress Mila Kunis has partnered with superhero creator Sharad Devarajan of Graphic India to launch Armored Kingdom Media Inc, which will be a new entertainment franchise spanning a Web3 trading card game, digital comics, animation, and film built on NEAR. “We are excited to support the launch of Armored Kingdom and the storytelling opportunities it will bring to fans,” said Flament. “NEAR is a perfect blockchain for an entertainment franchise as it can support various platforms, which is crucial for multiverse experiences across different mediums. Our focus on ease of use also allows developers to deliver intuitive experiences for a large fan base.” Between the upcoming JavaScript SDK, Armored Kingdom launching on NEAR, and partnering with Brave, Consensus was extraordinarily eventful, demonstrating the strength and commitment of the entire ecosystem. The NEAR Foundation thanks all community members, builders, and partners that engaged at Consensus Austin, and looks forward to seeing many of the same faces at NEARCON this September in Lisbon!
# Access Keys Access key provides an access for a particular account. Each access key belongs to some account and is identified by a unique (within the account) public key. Access keys are stored as `account_id,public_key` in a trie state. Account can have from [zero](#account-without-access-keys) to multiple access keys. ```rust pub struct AccessKey { /// The nonce for this access key. /// NOTE: In some cases the access key needs to be recreated. If the new access key reuses the /// same public key, the nonce of the new access key should be equal to the nonce of the old /// access key. It's required to avoid replaying old transactions again. pub nonce: Nonce, /// Defines permissions for this access key. pub permission: AccessKeyPermission, } ``` There are 2 types of `AccessKeyPermission` in NEAR currently: `FullAccess` and `FunctionCall`. `FullAccess` grants permissions to issue any action on the account. This includes [DeployContract](../RuntimeSpec/Actions.md#DeployContractAction), [Transfer](../RuntimeSpec/Actions.md#TransferAction) tokens, call functions [FunctionCall](../RuntimeSpec/Actions.md#FunctionCallAction), [Stake](../RuntimeSpec/Actions.md#StakeAction) and even permission to delete the account [DeleteAccountAction](../RuntimeSpec/Actions.md#DeleteAccountAction). `FunctionCall` on the other hand, **only** grants permission to call any or a specific set of methods on one given contract. It has an allowance of $NEAR that can be spent on **GAS and transaction fees only**. Function call access keys **cannot** be used to transfer $NEAR. ```rust pub enum AccessKeyPermission { FunctionCall(FunctionCallPermission), FullAccess, } ``` ## AccessKeyPermission::FunctionCall Grants limited permission to make [FunctionCall](../RuntimeSpec/Actions.md#FunctionCall) to a specified `receiver_id` and methods of a particular contract with a limit of allowed balance to spend. ```rust pub struct FunctionCallPermission { /// Allowance is a balance limit to use by this access key to pay for function call gas and /// transaction fees. When this access key is used, both account balance and the allowance is /// decreased by the same value. /// `None` means unlimited allowance. /// NOTE: To change or increase the allowance, the old access key needs to be deleted and a new /// access key should be created. pub allowance: Option<Balance>, /// The access key only allows transactions with the given receiver's account id. pub receiver_id: AccountId, /// A list of method names that can be used. The access key only allows transactions with the /// function call of one of the given method names. /// Empty list means any method name can be used. pub method_names: Vec<String>, } ``` ## Account without access keys If account has no access keys attached it means that it has no owner who can run transactions from its behalf. However, if such accounts has code it can be invoked by other accounts and contracts.
NEARCON IRL Hackathon 2023: Build the Open Web NEAR FOUNDATION September 28, 2023 If you attended NEARCON last year, you know the 48-hour IRL hackathon — “Building Beyond the Hype” was a great event, with all sorts of exciting prototypes that helped propel NEAR through the last year. For NEARCON 2023, which will be held November 7-10th, we’re leveling up the hackathon. This year’s hackathon explores NEARCON 2023’s theme — “Step into the Open Web”. And that hacking together apps and experiences that explore how the NEAR Protocol and Blockchain Operating System are paving the way for a truly open web. Let’s explore what’s new for the NEARCON 2023 Hackathon. Hacker HQ: a space just for the hackers Not only do hackers get into NEARCON 2023 for free, but they also get their own space. NEARCON’s Hacker HQ will be a place for hackers to hang out, network, and build — whether that’s for the Hackathon or if you’re just interested in continuing to build your project on NEAR. Hacker HQ will be located at: Armazem 16 R. Pereira Henriques nº1, 1950-242 Lisboa, Portugal Hack the days and nights away for a chance to build on the BOS and win $140k+. Important NEARCON Hackathon dates and information The Hackathon is held November 7-10th. November 7th — Hackathon orientation, team matching, and a welcome party hosted by NEARWEEK. November 8th — Day 1 of hacking. Mentoring available. November 9th — Day 2 of hacking. Mentoring available. Submission Deadline. November 10th — Pitch competition. Request a visa letter to support hackers’ visa applications. All requests must be submitted via the form by October 7, 2023. Travel stipends are available depending on your location. Please read the Hacker Stipend Guidelines. Stay tuned in the coming weeks for details on NEARCON IRL Hackathon bounties.