jcarbonnell/preTrainingNEAR huggingface dataset:
---
id: token-loss
title: Avoiding Token Loss
sidebar_label: Avoiding Token Loss
---

:::warning
Careful! Losing tokens means losing money!
:::


Token loss is possible under multiple scenarios. These scenarios can be grouped into a few related classes:

1. Improper key management
2. Refunding deleted accounts
3. Failed function calls in batches

---

## Improper key management

Improper key management may lead to token loss. Mitigating such scenarios may be done by issuing backup keys
allowing for recovery of accounts whose keys have been lost or deleted.

### Loss of `FullAccess` key

A user may lose their private key of a `FullAccess` key pair for an account with no other keys.
No one will be able to recover the funds. Funds will remain locked in the account forever.

### Loss of `FunctionCall` access key

An account may have its one and only `FunctionCall` access key deleted.
No one will be able to recover the funds. Funds will remain locked in the account forever.

---
## Refunding deleted accounts

When a refund receipt is issued for an account, if that account no longer exists, the funds will be dispersed among
validators proportional to their stake in the current epoch.

### Deleting account with non-existent beneficiary

When you delete an account, you must assign a beneficiary.
Once deleted, a transfer receipt is generated and sent to the beneficiary account.
If the beneficiary account does not exist, a refund receipt will be generated and sent back to the original account.
Since the original account has already been deleted, the funds will be dispersed among validators.

### Account with zero balance is garbage-collected, just before it receives refund

If an account `A` transfers all of its funds to another account `B` and account `B` does not exist,
a refund receipt will be generated for account `A`. During the period of this round trip,
account `A` is vulnerable to deletion by garbage collection activities on the network.
If account `A` is deleted before the refund receipt arrives, the funds will be dispersed among validators.

---
## Failed function calls in batches

:::warning
When designing a smart contract, you should always consider the asynchronous nature of NEAR Protocol.
:::

If a contract function `f1` calls two (or more) other functions `f2` and `f3`, and at least one of these functions, `f2` and `f3` fails, then tokens will be refunded from the function that failed, but tokens will be appropriately credited to the function(s) which succeed.

The successful call's tokens may be considered lost depending on your use case if a single failure in the batch means the whole batch failed.
Grassroots Support Initiative Update – September 11, 2023
NEAR FOUNDATION
September 11, 2023
As a follow up to the NEAR Foundation’s previous grassroots support post, we wanted to take a moment to share an update on our progress. On September 4th, we closed the form through which projects could request support until the NDC funding mechanism is live. Over the past two weeks, we have spoken to builders across the ecosystem to understand their needs and begin mapping out the different paths forward to ensure they receive the support they need. 

We have encountered a range of different requests and have been taking a holistic approach to understand the unique needs faced by each project and the resources available to help them achieve their goals moving forward. While financial support is only one part of this, there have been a number of questions about the range of options available, so we wanted to give everyone visibility into the next steps.

Projects looking for funding will first explore internal resources including the BD/Ecosystem success team and ad hoc advisory support via a 1-1 call with the Horizon team, as well as by working closely with the MarketingDAO, CreativesDAO, and DevHub. Projects that do not qualify through any of these routes will have the ability to go to an internal review process. 

To make sure the community voices are heard and involved in the process, members of the Governance Working Group (GWG) have collaborated with NEAR Foundation to define the criteria needed to receive financial support. The criteria the committee will use to make the selections are the following:

Is the project built on NEAR and live on mainnet?
Is there a current grant already in place? 
Are there a minimum 100 monthly active users?
Does the request cover a maximum of 3 months of runway?
This process should be completed within the coming two weeks, at which point the NEAR Foundation will provide a further update. In the meantime, if you have any questions you can always reach us at [email protected].
Decentralized Storage for dApp Developers
DEVELOPERS
December 8, 2021
While security, speed, and reliable data records are key elements in developing a decentralized app (dApp) in the Web3 ecosystem, the complexity of decentralization is a critical factor that can drive the cost and effort required in deployment.

Standard dApp development consists of a Web 2 tech stack for the front-end and state management handled by smart contracts deployed on the blockchain for the back-end. With this hybrid approach, it can be tricky to determine what to store on and off-chain. For example, keeping all of the files for a front-end’s UI on-chain is less efficient and cost-effective when compared to existing SQL or no-SQL solutions. However, there are times when larger data files will need to be stored in a permanent decentralized manner (such as NFTs that contain large images or songs), so the content is always accessible to its owner.

As a new developer in the crypto space, your first approach to storing various media files might be to use the same blockchain where the smart contract is being deployed. However, the storage cost for large amounts of binary data on the blockchain can be prohibitive and ultimately not practical.

To solve this problem, teams of developers have been working on creating decentralized storage solutions focused on storing large amounts of data at a competitive price. These solutions allow dApp developers to maintain a decentralized infrastructure that secures the availability of your data when needed. Arweave, IPFS, and Sia’s Skynet are three great examples of such projects, and we are excited to share ways you can integrate their platforms into your project.

The DevRel team has published a new article on Decentralized Storage Solutions, that gives you a brief introduction to each solution and an integration example so you can quickly try them out and find the optimal solution for your project.

At NEAR we are committed to helping create a healthy Web3 ecosystem where everyone can build projects that integrate different technologies, solutions, and networks that fit their needs. We want developers and users to choose which tool is the best for the job and ensure interoperability is maintained.

Have any questions, comments, or feedback? 
Join us on Discord and let us know in the #development channels. 
We also host daily Office Hours live Monday – Friday 11AM – 12PM PT (6PM – 7PM UTC), where the DevRel team will answer any questions you may have!
```js
const accountId = context.accountId ?? props.accountId;
const keypomContract = "v2.keypom.near";

const dropSupplyForOwner = Near.view(
  keypomContract,
  "get_drop_supply_for_owner",
  { account_id: accountId }
);

const dropsForOwner = Near.view(keypomContract, "get_drops_for_owner", {
  account_id: accountId,
  from_index: (dropSupplyForOwner - 1).toString(),
});

const dropId = dropsForOwner[dropsForOwner.length - 1].drop_id;
```
NEAR at Collision: Expand into the Open Web with the Blockchain Operating System
NEAR FOUNDATION
May 24, 2023
NEAR Foundation is excited to announce that NEAR is heading to the 2023 edition of Collision from June 26-29 in Toronto, Ontario. 

NEAR experts will be at Collision to demonstrate how brands and companies can expand into the open web using the Blockchain Operating System (BOS). The BOS is  an industry-first category: a common layer for browsing and discovering open web experiences with any blockchain — all in one browser. 

Here is what to expect from NEAR at Collision 2023. 

The BOS and NEAR Horizon at Collision 
If you saw NEAR’s big announcement out of ETHDenver and Collision, NEAR isn’t just a Layer 1 blockchain. It’s a Blockchain Operating System that makes it easy to use the tools you already know to build apps that engage users, while fostering an open web free from centralized platforms.

Also appearing at Collision will be NEAR Horizon — NEAR Foundation’s new Web3 startup support platform. Meet with the Horizon team and get started on the Web3 funding and building journey.  

NEAR speakers at Collision
At Collision, catch a number of exciting NEAR speakers and sessions. 

Illia Polosukhin – Co-founder, NEAR Protocol; CEO, Pagoda

Elad Gil – Investor

Kendall Cole – Founder, Proximity

Laura Cunningham – General Manager, NEAR Horizon

Joyce Yang – Founder, Global Coin Research

Steven Chien –  Founder, Press Start Capital

Paul Hsu – CEO & Founder, Decasonic

Stay updated on the complete slate of confirmed speakers at near.org/Collision. 

NEAR @ Collision
NEAR Horizon pitch and networking event
NEAR Horizon will be hosting another Pitch and networking event with VC partners the evening of June 27th. Applications to pitch are being accepted now through June 7th.
---
id: state
title: Basics
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {WidgetEditor} from "@site/src/components/widget-editor"

Borrowing from React, Near Components use hooks such as [**`useState`**](#state) and [**`useEffect`**](#useeffect-hook) to handle the state's logic, and [**props**](#props) to receive parameters.

Near Components are stored in the blockchain, for which you will use the `NEAR VM` to [retrieve and execute them in the browser](../../4.web3-apps/integrate-components.md).

Using a VM enforces components to be sandboxed, making them very secure since they cannot access your `LocalStorage` or other elements in the page they are incorporated to. However, because of this, components cannot import external libraries. However, they can [**import functions**](#import) from other components.

---

## State
To handle the component's state you can use `useState` hook. The `useState` hook returns a tuple of two values: the current state and a function that updates it.

<WidgetEditor>

```jsx
const [count, setCount] = useState(0);

return (
  <div>
    <p>You clicked {count} times</p>
    <button onClick={() => setCount(count + 1)}>Click me</button>
  </div>
);

```

</WidgetEditor>

Each time a state variable is updated, the component will be **re-rendered**. This means that the **whole code will run again**.

---

## Props
Each component has access to a local variable named `props` which holds the properties received as input when the component is composed.

<WidgetEditor id='2'>

```jsx
return <>
  <p> This component props: {JSON.stringify(props)} </p>
  <Widget src="influencer.testnet/widget/Greeter" 
          props={{name: "Maria", amount: 2}} />
</>
```

</WidgetEditor>

---

## useEffect Hook

The [`useEffect` hook](https://react.dev/learn/synchronizing-with-effects) is used to handle side effects. It will execute each time one of the dependencies changes.

<WidgetEditor id='3'>

```jsx
const [count, setCount] = useState(0);
const [visible, setVisible] = useState(false);

useEffect(() => {
  if(count > 5) setVisible(true);
}, [count]);

return (
  <div>
    <p>You clicked {count} times</p>
    <p className="alert alert-danger" hidden={!visible}>
      You clicked more than 5 times
    </p>
    <button onClick={() => setCount(count + 1)}>Click me</button>
  </div>
);  
```
</WidgetEditor>

---

## Import

Components can import functions from other components. This is useful to reuse code and to create libraries of components.

<WidgetEditor id='4'>

```jsx
const {add, multiply} = VM.require('influencer.testnet/widget/Math');

return <>
  <p> 2 + 3 = {add(2, 3)} </p>
  <p> 2 * 3 = {multiply(2, 3)} </p>
</>
```

</WidgetEditor>

Where the code of the `Math` component is:

```js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

return { add, multiply };
```
---
sidebar_position: 3
sidebar_label: Statistics Dashboard 
title: RPC Statistics
---

:::warning

Please be advised that these tools and services will be discontinued soon.

:::

Inspect your RPC Usage in the [Statistics Tab](https://console.pagoda.co/apis?tab=statistics):

![](/docs/pagoda/stats1.png)

:::info
Data defaults to the last 30 days.
Currently the statistics page show the usage data across all projects and API keys within an organization set on Pagoda Console.
:::

Aggregated key metrics available at the top of the dashboard are

-    Total Request Volume
-    Request Success Rate
-    Total failed request
-    Average Latency

## Set a Time Period

Data is sent with UTC time to the browser and the browser adjusts to the user’s timezon.

-    Last 15 Minutes is the last complete 15 minutes. This updates every few seconds.
-    Last 1 Hour is the last fully completed hour; from 00 to 59 minutes and 59 seconds.
-    Last 24 Hours is the last fully completed 24 consecutive hours.
-    Last 7 Days is the previous 7 days from the current time. Each data point groups one hour’s worth of data. The most recent hour is partial data for the current hour and updates every few seconds.
-    Last 30 Days is the previous 30 days from the current time. Each data point groups one hour’s worth of data. The most recent hour is partial data for the current hour and updates every few seconds.

## Requests breakdowns

Multiple breakdowns are available in the statistics page

![](/docs/pagoda/stats2.png)

Requests can be broken down by

-    Requests Methods
-    Requests Status
-    Aggregated status display breakdown by requests methods

We are working to include more detailed breakdown by each requests and more interactive dashboard that enable clickthrough from the charts

## Network Status

Check the [Pagoda Status page](https://status.pagoda.co/) for the latest service information across all networks and subscribe to updates based on your service choice and needs.

![](/docs/pagoda/stats3.png)
---
id: basics
title: "Basic Instructions"
---

# Basic instructions
To compile release version of the smart contract you can run a build script (specified in `package.json` for your project as `{ build: near-sdk-js build, ... }`):

```bash
npm run build
```

:::info
The above `build` command seeks a `index.js` file in `/src` and outputs a `contract.wasm` file in a newly created `/build` folder at the same level as `/src`. For more information, see the [source code for the CLI commands here](https://github.com/near/near-sdk-js/blob/2a51b6c6233c935c7957b91818cfe6f9c3073d71/packages/near-sdk-js/src/cli/cli.ts?_pjax=%23js-repo-pjax-container%2C%20div%5Bitemtype%3D%22http%3A%2F%2Fschema.org%2FSoftwareSourceCode%22%5D%20main%2C%20%5Bdata-pjax-container%5D#L28-L36).
:::

<!-- TODO: custom build commands using CLI -->
# Epoch

All blocks are split into epochs. Within one epoch, the set of validators is fixed, and validator rotation
happens at epoch boundaries.

Genesis block is in its own epoch. After that, a block is either in its parent's epoch or
starts a new epoch if it meets certain conditions.

Within one epoch, validator assignment is based on block height: each height has a block producer assigned to it, and
each height and shard have a chunk producer.

### End of an epoch
A block is defined to be the last block in its epoch if it's the genesis block or if the following conditions are met:
- Let `estimated_next_epoch_start = first_block_in_epoch.height + epoch_length`
- `block.height + 1 >= estimated_next_epoch_start`
- `block.last_finalized_height + 3 >= estimated_next_epoch_start`

`epoch_length` is defined in `genesis_config` and has a value of `43200` height delta on mainnet (12 hours at 1 block per second).

### EpochHeight
Epochs on one chain can be identified by height, which is defined the following way:
- Special epoch that contains genesis block only: undefined
- Epoch starting from the block that's after genesis: `0` (NOTE: in current implementation it's `1` due to a bug, so there are two epochs with height `1`)
- Following epochs: height of the parent epoch plus one

### Epoch id
Every block stores the id of its epoch - `epoch_id`.

Epoch id is defined as
- For special genesis block epoch it's `0`
- For epoch with height `0` it's `0` (NOTE: the first two epochs use the same epoch id)
- For epoch with height `1` it's the hash of genesis block 
- For epoch with height `T+2` it's the hash of the last block in epoch `T`

### End of an epoch
- After processing the last block of epoch `T`, `EpochManager` aggregates information from block of the epoch, and computes
validator set for epoch `T+2`. This process is described in [EpochManager](EpochManager.md).
- After that, the validator set rotates to epoch `T+1`, and the next block is produced by the validator from the new set
- Applying the first block of epoch `T+1`, in addition to a normal transition, also applies the per-epoch state transitions:
  validator rewards, stake unlocks and slashing.
```rust
#[payable]
pub fn call_with_attached_tokens(&mut self, receiver_id: AccountId, amount: U128) -> Promise {
  assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");

  let promise = ext(self.ft_contract.clone())
    .with_static_gas(Gas(150*TGAS))
    .with_attached_deposit(YOCTO_NEAR)
    .ft_transfer_call(receiver_id, amount, None, "".to_string());

  return promise.then( // Create a promise to callback query_greeting_callback
    Self::ext(env::current_account_id())
    .with_static_gas(Gas(100*TGAS))
    .external_call_callback()
  )
}
```
---
id: hardware-archival
title: Hardware Requirements for Archival Node
sidebar_label: Hardware Requirements
sidebar_position: 1
description: NEAR Archival Node Hardware Requirements
---

This page covers the minimum and recommended hardware requirements for engaging with the NEAR platform as an Archival node.


## Recommended Hardware Specifications {#recommended-hardware-specifications}

| Hardware       |  Recommended Specifications                                               |
| -------------- | -----------------------------------------------------------------------   |
| CPU            | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support           |
| CPU Features   | CMPXCHG16B, POPCNT, SSE4.1, SSE4.2, AVX                                   |
| RAM            | 24GB DDR4                                                                 |
| Storage        | 9 Terabyte SSD                                                            |

_Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh  avx```. If the output is empty, your CPU is not supported._


## Minimal Hardware Specifications {#minimal-hardware-specifications}

| Hardware       |  Minimal Specifications                                                    |
| -------------- | -------------------------------------------------------------------------- |
| CPU            | 8-Core (16-Thread) Intel i7/Xeon or equivalent with AVX support            |
| RAM            | 16GB DDR4                                                                   |
| Storage        | 9 Terabyte SSD                                                             |

_Verify AVX support on Linux by issuing the command ```$ lscpu | grep -oh  avx```. If the output is empty, your CPU is not supported._

## Cost Estimation {#cost-estimation}

Estimated monthly costs depending on operating system:

| Cloud Provider | Machine Size    | Linux                     |
| -------------- | --------------- | ------------------------  |
| AWS            | m5.2xlarge      | $330 CPU + $800 storage † |
| GCP            | n2-standard-8   | $280 CPU + $800 storage † |
| Azure          | Standard_F8s_v2 | $180 CPU + $800 storage † |

_( † ) The storage cost will grow overtime as an archival node stores more data from the growing NEAR blockchain._


<blockquote class="info">
<strong>Resources for Cost Estimation</strong><br /><br />

All prices reflect *reserved instances* which offer deep discounts on all platforms with a 1 year commitment

- AWS
  - cpu: https://aws.amazon.com/ec2/pricing/reserved-instances/pricing
  - storage: https://aws.amazon.com/ebs/pricing
- GCP
  - cpu: https://cloud.google.com/compute/vm-instance-pricing
  - storage: https://cloud.google.com/compute/disks-image-pricing
- Azure — https://azure.microsoft.com/en-us/pricing/calculator

</blockquote>

> Got a question?
> <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> > <h8>Ask it on StackOverflow!</h8></a>
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs groupId="nft-contract-tabs" className="file-tabs">
<TabItem value="NFT Primitive" label="Reference" default>

```js
import { Wallet } from './near-wallet';

const CONTRACT_ADDRESS = "nft.primitives.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'nft_mint',
  args: {
    token_id: "1",
    receiver_id: "bob.near", 
    token_metadata: {
      title: "NFT Primitive Token",
      description: "Awesome NFT Primitive Token",
      media: "string", // URL to associated media, preferably to decentralized, content-addressed storage
    }
  },
  contractId: CONTRACT_ADDRESS,
  deposit: 10000000000000000000000
});
```

</TabItem>

<TabItem value="Paras" label="Paras">

```js
import { Wallet } from './near-wallet';

const CONTRACT_ADDRESS = "x.paras.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'nft_mint',
  args: {
    token_series_id: "490641",
    receiver_id: "bob.near",
  },
  contractId: CONTRACT_ADDRESS,
  deposit: 10000000000000000000000 // Depends on your NFT metadata
});
```

:::note
In order to use `nft_mint` method of the `x.paras.near` contract you have to be a creator of a particular token series.
:::

</TabItem>

<TabItem value="Mintbase" label="Mintbase">

```js
import { Wallet } from './near-wallet';

const CONTRACT_ADDRESS = "thomasettorreiv.mintbase1.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'nft_batch_mint',
  args: {
    num_to_mint: 1,
    owner_id: "bob.near",
    metadata: {},
  },
  contractId: CONTRACT_ADDRESS,
  deposit: 10000000000000000000000 // Depends on your NFT metadata
});
```

:::note
In order to use `nft_batch_mint` method of Mintbase store contract your account have to be a in the contract minters list.
:::

:::tip
Check how to do this using [`Mintbase JS`](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/sdk/mint)
:::

</TabItem>

</Tabs>

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