jcarbonnell/preTrainingNEAR huggingface dataset:
---
id: dev-environment
title: Choose your Dev Environment
---

The environments in which you can develop `Components` are divided into two categories:

- [Web Tools](#web-tools): Online tools that allow you to quickly start building and sharing components.
- [Local Tools](#local-tools): Tools that allow you to develop and test components locally.

:::tip Handling collaborations
If you plan to collaborate with multiple people, we recommend you to check [this repository template](https://github.com/near-examples/bos-components) which automatically deploys components each time a PR is merged. 
:::

---

## Web Tools
The quickest way to start building NEAR Components is by using one of the online tools. They are great for taking your first steps, while they let you find other developers and components in the NEAR ecosystem.

#### [NEAR Sandbox](https://near.org/sandbox)
The [near website](https://near.org/) contains its own [sandbox editor](https://near.org/sandbox). The sandbox allows you to code, preview and deploy your components directly from your browser.

#### [Jutsu.ai](https://jutsu.ai)
[Jutsu.ai](https://jutsu.ai) is a web IDE made for NEAR developers. It contains examples and tutorials to help onboarding you.

---

## Local Tools

If you want to collaborate with a team or work on a larger project, you will likely want more **version control**, automated testing and deployment, and other workflows. For this, the NEAR ecosystem offers a set of tools to easily develop and test your components entirely locally.

#### [NEAR VSCode Extension](https://marketplace.visualstudio.com/items?itemName=near-protocol.near-discovery-ide)
The [NEAR VSCode Extension](https://marketplace.visualstudio.com/items?itemName=near-protocol.near-discovery-ide) integrates with the VSCode IDE to help you develop, preview and deploy components all within VSCode.

#### [BOS Loader](../../3.tutorials/near-components/bos-loader.md)
A CLI tool to preview local components in NEAR BOS. A perfect companion to the [BOS CLI](https://github.com/FroVolod/bos-cli-rs).

#### [BOS CLI](https://github.com/FroVolod/bos-cli-rs)
A command line utility that simplifies local component development for NEAR BOS.

#### [BOS Workspace](https://github.com/nearbuilders/bos-workspace)
A comprehensive toolset for simplifying the local development of NEAR components and applications, featuring hot reload, TypeScript support, multi-app management, and a local gateway.

#### [Além](https://github.com/wpdas/alem)
A web3 JavaScript/TypeScript library to create web3 applications for Near BOS. It's developer-friendly and uses React patterns, making it easy to organize files and write code. Access the [Além Docs](https://alem.dev/) to get to know more.
```js
import { Wallet } from './near-wallet';

const DAO_CONTRACT_ADDRESS = "primitives.sputnik-dao.near";
const wallet = new Wallet({ createAccessKeyFor: DAO_CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'add_proposal',
  args: {
    proposal: {
      description: "My first proposal",
      kind: {
        Transfer: {
          token_id: "",
          receiver_id: "bob.near",
          amount: "10000000000000000000000000",
        },
      },
    },
  },
  contractId: DAO_CONTRACT_ADDRESS,
  gas: 300000000000000,
  deposit: 100000000000000000000000
});
```

_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
---
id: epoch
title: Epoch
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';


An **epoch** is a unit of time when validators of the network remain constant. It is measured in blocks:

- Both `testnet` and `mainnet` have an epoch duration of 43,200 blocks. Ideally epochs last about 12 hours, since blocks are created every second (in reality, they take slightly longer to be created).
- You can view this setting by querying the **[`protocol_config`](/api/rpc/setup#protocol-config)** RPC endpoint and searching for `epoch_length`.

**Note:** Nodes garbage collect blocks after 5 epochs (~2.5 days) unless they are [archival nodes](https://near-nodes.io/intro/node-types#archival-node).

**Example:**

<Tabs>
<TabItem value="json" label="JSON" default>

```json
{
  "jsonrpc": "2.0",
  "id": "dontcare",
  "method": "EXPERIMENTAL_protocol_config",
  "params": {
    "finality": "final"
  }
}
```

</TabItem>
<TabItem value="http" label="HTTPie">

```bash
http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_protocol_config \
  params:='{
    "finality": "final"
  }'
```

</TabItem>
</Tabs>

**Example Response:**

```json
{
    "jsonrpc": "2.0",
    "result": {
        "protocol_version": 44,
        "genesis_time": "2020-07-21T16:55:51.591948Z",
        "chain_id": "mainnet",
        "genesis_height": 9820210,
        "num_block_producer_seats": 100,
        "num_block_producer_seats_per_shard": [
            100
        ],
        "avg_hidden_validator_seats_per_shard": [
            0
        ],
        "dynamic_resharding": false,
        "protocol_upgrade_stake_threshold": [
            4,
            5
        ],
        "epoch_length": 43200,
        "gas_limit": 1000000000000000,
        "min_gas_price": "1000000000",
        "max_gas_price": "10000000000000000000000",
        "block_producer_kickout_threshold": 90,
        "chunk_producer_kickout_threshold": 90,

// ---- snip ----
}
```

You can learn more about how epochs are used to manage network validation in the [Validator FAQ](https://github.com/near/wiki/blob/master/Archive/validators/faq.md#what-is-an-epoch).

:::tip Got a question?
<a href="https://stackoverflow.com/questions/tagged/nearprotocol"> Ask it on StackOverflow! </a>
:::
An Update from the NEAR Foundation
NEAR FOUNDATION
January 11, 2024
Dear NEAR Community,
The NEAR Foundation’s vision has always been to help the world create a truly Open Web, giving all people full control of their data, privacy, and power of governance. In 2023, the NEAR ecosystem saw remarkable progress towards this vision, with the NEAR Protocol now home to three of the top ten apps in Web3, a record number of daily users, and closer collaboration than ever with the Ethereum community.
With the NEAR Foundation Council (NFC), we’ve conducted a thorough review of the Foundation’s activities. During this process, we heard feedback that the Foundation has not always been as effective as it could be, sometimes moving too slowly and trying to do too many things at once. Following this review, we have decided to significantly consolidate the core Foundation team to focus on a narrower and higher-impact set of activities. Over time, Foundation’s footprint will continue to contract as the ecosystem further decentralizes and various nodes drive more activity in the network and across the ecosystem.
As part of this realignment, NEAR Foundation will reduce its team by approximately 40%, impacting 35 colleagues, primarily across the marketing, business development, and community teams. The NEAR Protocol Engineering Team at Pagoda will continue to operate as it has. The NEAR Foundation will provide support to affected colleagues during this time to help them find new opportunities in the NEAR ecosystem, the Web3 industry, and beyond. We thank each of our departing colleagues for your efforts and contributions towards our shared vision of the Open Web.

The NEAR Foundation treasury remains strong and well-managed, with over $285m fiat, 305m NEAR (worth over $1B), and $70m of investments and loans. The Foundation is well-placed to continue to support the ongoing growth, development, and further decentralization of the NEAR Protocol and ecosystem.
Thank you to everyone in the NEAR community for your ongoing efforts and support. We are excited to move forward with more focus, more efficiency, and more speed. We’ll share more updates soon about what comes next as we work to advance chain abstraction, user-owned AI, and mainstream adoption of the Open Web.
Keep building,
Embracing Decentralization: What’s Next for the NEAR Wallet
DEVELOPERS
July 12, 2023
When NEAR Mainnet launched in late 2020, it included a wallet built and hosted by Pagoda’s (then known as Near Inc.) core team on https://wallet.near.org to support NEAR’s unique account model. Nearly three years later, the NEAR wallet ecosystem is home to a myriad of high quality, open source wallets supported by NEAR’s community of active contributors. This significant milestone reflects NEAR’s ongoing commitment to empower users and foster decentralization. The evolution of NEAR wallets also showcases the substantial growth of the ecosystem, as NEAR now supports a diverse list of cross-chain wallets, as well as native wallets with innovative onboarding approaches such as FastAuth.

To celebrate these excellent contributions from across the NEAR community, and to reflect the priority of decentralization, over the next few months Pagoda will start migrating the domain https://wallet.near.org from being a browser wallet to being a wallet hub. In this way, https://wallet.near.org will become the reference place for all NEAR wallets, allowing users to discover and implement the right wallets for their specific needs.

If you currently use https://wallet.near.org as your main wallet, you have nothing to worry about. The Pagoda team has been working hard to build a Wallet Transfer Wizard to help you transfer your accounts to a new wallet easily and smoothly, while keeping your funds and assets safe. The Transfer Wizard will allow you to choose between Browser and Extension-based wallets, so you will still have the same friendly wallet experience you are accustomed to after the Wizard is finished.

For more details, visit the Migrating from NEAR Wallet page. 

Timeline for transitioning the main wallet domain 
The NEAR Wallet will remain a browser wallet until January 1st, 2024, during which time the wallet will encourage and help you to transfer your accounts to a new wallet. You can do this manually with your recovery phrase or use the Transfer Wizard to securely migrate your accounts to the wallet of your choice. 

Do not worry if you have not transferred your accounts by January 1st, 2024 —the Transfer Wizard will still be available after the wallet functionality sunsets. Rest assured that your assets will remain secure until you import them to a new wallet.

The Transfer Wizard will remain available on the new wallet landing page at wallet.near.org indefinitely. This repurposed page will act as an introduction to the various options for wallets in the NEAR ecosystem.

A new era for NEAR Wallets
This new step moves NEAR closer to achieving a truly decentralized ecosystem driven by its own community. Thanks to the wallet hub and the wallet selector (which enables the use of any compatible NEAR wallet in web applications), users will now be able to use any wallet they like. This will not only improve their experience on NEAR, but also the full spectrum of available Web3 experiences thanks to the BOS.
Etherscan will Launch on Aurora
COMMUNITY
September 1, 2021
Aurora, an Ethereum scaling solution that allows projects built on Ethereum to utilise the cutting-edge technology of NEAR has teamed up with Etherscan, the leading block explorer for Ethereum to allow developers to use the same familiar tool. 

While Aurora utilises NEAR as its foundation, it has always envisioned a future in which projects can move seamlessly between blockchains to suit their needs. The partnership with Etherscan is a significant step in that direction. 

“Etherscan provides the familiar interface of the explorer,” says Alex Shevchenko, the CEO of Aurora Labs. “Users and devs won’t need to educate themselves on how to use the Aurora block explorer, instead they would get the familiar tool.”

While Etherscan is most commonly known as a block explorer for Ethereum, it’s capable of so much more: from statistics, and token transfers and listing; to smart contract source code verification and ability to issue read and write calls directly from the UI. Making those tools available to a greater number of devs is key to Aurora’s mission. 

“Aurora is always focused on making the experience of devs and users as seamless as possible,” says Shevchenko. 

The explosive growth of DeFi and NFTs frequently causes surges in Ethereum gas prices––a problem that economically limits the participation of many users, and prevents dApp developers from scaling their businesses to their full potential. Helping developers to grow their business is a mission Etherscan shares with Aurora.

“We are happy to utilize our experience in building block explorer solutions into supporting Aurora, and extend our own vision of providing equitable access to blockchain data”, says Matthew Tan, Founder & CEO of Etherscan.

While today marks the start of the integration process, the product will be available later in the year. Stay tuned for updates on the release and other upcoming ones from the Aurora team.

About NEAR

NEAR Protocol is a high-performance blockchain platform for developing Open Web applications. Easy to build on and easy to use, NEAR will bridge the users of today’s internet to the blockchain-based web of the future.

NEAR Protocol is built by a world-class team of engineers and entrepreneurs, including world champions of ACM-ICPC, Google Code Jam, and TopCoder Open. NEAR is backed by top VCs such as A16Z, Pantera Capital, Electric Capital, Dragonfly Capital, Coinbase Ventures, Blockchain.com, and Baidu Ventures.

Join NEAR’s community:

Telegram: https://t.me/cryptonear
Discord: https://discord.com/invite/UY9Xf2k
Twitter: @NEAR_Blockchain & @NEARProtocol

About Aurora

Aurora is an EVM built on the NEAR Protocol, delivering a turn-key solution for developers to operate their apps on an Ethereum-compatible, high-throughput, scalable and future-safe platform, with low transaction costs for their users.
```js
import { Wallet } from './near-wallet';

const DAO_FACTORY_CONTRACT_ADDRESS = "sputnik-dao.near";
const wallet = new Wallet({ createAccessKeyFor: DAO_FACTORY_CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'create',
  args: {
    name: "primitives",
    args: btoa({
      config: {
        name: "Primitives",
        purpose: "Building primitives on NEAR",
        metadata: ""
      },
      policy: ["bob.near"]
    }),
  },
  contractId: DAO_FACTORY_CONTRACT_ADDRESS,
  gas: 300000000000000,
  deposit: 6000000000000000000000000
});
```

:::note
The full list of roles and permissions you can find [here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions).
:::

_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
```js
await wallet.callMethod({
  method: 'storage_deposit',
  args: {
    account_id: 'alice.near',
  },
  contractId: TOKEN_CONTRACT_ADDRESS,
  deposit: 1250000000000000000000
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
---
id: near-lake-state-changes-indexer
title: NEAR Lake Indexer Tutorial
---

:::note Source code for the tutorial

[`near-examples/near-lake-accounts-watcher`](https://github.com/near-examples/near-lake-accounts-watcher/tree/0.2.0): source code for a video tutorial on how to use the NEAR Lake Framework

:::

:::info Version 0.2.0

The video is based on the [`near-lake-framework`](/concepts/advanced/near-lake-framework) version 0.2.0

At the same time we're keeping the source code up to date with the latest version of the published crate.

:::

We've created a video tutorial to empower the release announcement of [NEAR Lake Framework](/concepts/advanced/near-lake-framework).

In this tutorial you will build an indexer application to watch for any `StateChange`s affecting the account or a list of account provided.

<iframe
 width="560"
 height="315"
 src="https://www.youtube.com/embed/GsF7I93K-EQ"
 title="YouTube video player"
 frameborder="0"
 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
 allowfullscreen>
</iframe>
Case Study: Satori’s Jeff Bissinger Talks NEAR Tasks for the Gig Economy
CASE STUDIES
July 31, 2023
NEAR is a home to a number of amazing apps and projects. These developers, founders, and entrepreneurs are using NEAR to effortlessly create and distribute innovative decentralized apps, while helping build a more open web — free from centralized platforms. In these Case Study videos, NEAR Foundation showcases some of these projects. 

In the latest NEAR Foundation Case Study video, we hear from Jeff Bissinger, Product Manager at Satori. As a product team building innovative Web3 solutions, Satori is creating AI integrations that enable people to work with purpose. NEAR Tasks, which launched at Consensus 2023 in Austin, is one of Satori’s latest products. 

In this case study video, Jeff Bissinger takes viewers on a trip into NEAR Tasks — Satori’s effort to blend the gig economy with blockchain technology. With NEAR Tasks, users can earn $NEAR while completing simple, yet meaningful, AI related tasks
---
id: welcome
title: Examples & Tutorials
sidebar_label: Home
hide_table_of_contents: true
---

import {FeatureList, Column, Feature} from "@site/src/components/featurelist"

Explore our collection of Examples and Tutorials

<FeatureList>
  <Column title="Popular Examples">
    <Feature url="/tutorials/examples/guest-book" title="Guest Book" subtitle="Create a simple guest book" image="guest-book.png" />
    <Feature url="/tutorials/examples/donation" title="Donation" subtitle="Receive and send tokens" image="donation.png" />
    <Feature url="/tutorials/examples/xcc" title="Basic Cross-Contract Call" subtitle="Learn how to call other contracts" image="cross-call.png" />
    <Feature url="/tutorials/examples/coin-flip" title="Coin Flip Game" subtitle="Learn to create basic random numbers" image="random.png" />
    <Feature url="/tutorials/examples/factory" title="Factory Contract" subtitle="Build a contract that deploys contracts" image="factory.png" />
    <Feature url="/tutorials/examples/update-contract-migrate-state" title="Update & Migrate" subtitle="Programmatically update contracts" image="update.png" />
    <Feature url="/tutorials/examples/frontend-multiple-contracts" title="Multi-Contract Frontend" subtitle="Interact with multiple contracts" image="multiple.png" />

  </Column>
  <Column title="Popular Tutorials">
    <Feature url="/tutorials/near-components/interaction" title="Components & Contracts" subtitle="Use a contract from your component" image="bos-contract.png" />
    <Feature url="/tutorials/near-components/lido" title="ETH Component" subtitle="Build an Ethereum Component" image="bos-lido.png" />
    <Feature url="/tutorials/nfts/minting-nfts" title="NFT Mint" subtitle="Mint an NFT without using code" image="frontend-bos.png" />
    <Feature url="/tutorials/near-components/indexer-tutorials/nft-indexer" title="Events (NEAR Lake)"
             subtitle="Use our Data Lake to listen for events" image="monitor.png" />
  </Column>
  <Column title="From Zero to Hero">
    <Feature url="/tutorials/nfts/js/introduction" title="Master NFTs on NEAR (JS)" subtitle="Learn everything about NFT in JS" image="nft-marketplace-js.png" />
    <Feature url="/tutorials/nfts/introduction" title="Master NFTs on NEAR (RS)" subtitle="Learn everything about NFT in Rust" image="nft-marketplace-rs.png" />
    <Feature url="/tutorials/fts/introduction" title="Fungible Tokens 101"
             subtitle="Learn everything about fungible tokens" image="ft.png" />
    <Feature url="/tutorials/crosswords/basics/overview" title="Crossword Game" 
             subtitle="Build a Crossword Game from zero" image="crossword.png" />
  </Column>
</FeatureList>
Case Study: Sweat Economy’s Oleg Fomenko on Reshaping Fitness with Move-to-Earn
NEAR FOUNDATION
June 12, 2023
NEAR is a home to a number of amazing apps and projects. These developers, founders, and entrepreneurs are using NEAR to effortlessly create and distribute innovative decentralized apps, while helping build a more open web — free from centralized platforms. In recent installments, NEAR Foundation explored the BOS with Pagoda’s Chief Product Officer Alex Chiocchi, and heard from OnMachina co-founder Jonathan Bryce on building decentralized storage. 

In the latest case study, Sweat Economy founder Oleg Fomenko talks about revolutionizing fitness with blockchain technology. Aside from talking about Sweat Economy’s integration with NEAR, Fomenko also talks about integrating the Sweat Wallet app with the BOS. With over 6 million active users, the Sweat Wallet is the most active dApp on NEAR. 

Watch the Sweat Economy Case Study video below.

Sweat Economy’s Learn & Earn program brings in over 200,000 users
As part of its partnership with NEAR Foundation, Sweat Economy launched its Learn & Earn feature in the Sweat Wallet to educate users about Stablecoins and promote USDT on NEAR in the Sweat Wallet. 

In Sweat Economy’s Learn & Earn Program, which ran from May 23-31, Sweat Wallet users were rewarded with 1 USDT by completing the “What are Stablecoins?”  lesson and an interactive quiz. In total, 100,000 USDT was given out as rewards in this initiative. In just 9 Days: 

245,048+ users started the lesson
218,789 users completed the lesson: 218,789
130,068 users completed the lesson & quiz: 
100,000+ users were rewarded with 1 USDT (by completing the lesson and passing the quiz within 6 attempts)
```rust
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct SwapAction {
    /// Pool which should be used for swapping.
    pub pool_id: u64,
    /// Token to swap from.
    pub token_in: AccountId,
    /// Amount to exchange.
    /// If amount_in is None, it will take amount_out from previous step.
    /// Will fail if amount_in is None on the first step.
    pub amount_in: Option<U128>,
    /// Token to swap into.
    pub token_out: AccountId,
    /// Required minimum amount of token_out.
    pub min_amount_out: U128,
}

// Validator interface, for cross-contract calls
#[ext_contract(ext_amm_contract)]
trait ExternalAmmContract {
  fn swap(&self, actions: Vec<SwapAction>) -> Promise;
}

// Implement the contract structure
#[near_bindgen]
impl Contract {
  #[private] // Public - but only callable by env::current_account_id()
  pub fn external_call_callback(&self, #[callback_result] call_result: Result<String, PromiseError>) {
    // Check if the promise succeeded
    if call_result.is_err() {
      log!("There was an error contacting external contract");
    }
  }

  #[payable]
  pub fn swap_tokens(&mut self, pool_id: u64, token_in: AccountId, token_out: AccountId, amount_in: U128, min_amount_out: U128) -> Promise {
    assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");

    let swap_action = SwapAction {
      pool_id,
      token_in,
      token_out,
      amount_in: Some(amount_in),
      min_amount_out
    };

    let mut actions = Vec::new();
    actions.push(swap_action);

    let promise = ext_amm_contract::ext(self.amm_contract.clone())
      .with_static_gas(Gas(150*TGAS))
      .with_attached_deposit(YOCTO_NEAR)
      .swap(actions);

    return promise.then( // Create a promise to callback query_greeting_callback
      Self::ext(env::current_account_id())
      .with_static_gas(Gas(100*TGAS))
      .external_call_callback()
    )
  }
}
```