jcarbonnell/preTrainingNEAR huggingface dataset:
---
sidebar_position: 1
sidebar_label: "Overview"
title: "Highlights of some beginner topics covered."
---

import chapter2Correct from '/docs/assets/crosswords/chapter-2-solve.gif';
import multipleCrosswords from '/docs/assets/crosswords/puzzle-piggy-bank--r3v.near--rev_rodrigueza.png';

# Diving deeper

In the last chapter we installed Rust and got up and running with a simple smart contract. The contract has a few issues, however, and isn't as powerful as we'd like it to be. For instance, we can only store one crossword puzzle in the smart contract, the frontend is  hardcoded, and we don't offer any incentives to the person who wins.

Let's give the smart contract the ability to store multiple crosswords and offer the winner a prize, paid in NEAR.

<figure>
    <img src={multipleCrosswords} alt="Man holding a book full of crossword puzzles, in his other hand he's holding a piggy bank. Art created by r3v.near"/>
    <figcaption className="full-width">Art by <a href="https://twitter.com/rev_rodrigueza" target="_blank">r3v.near</a></figcaption>
</figure>
<br/>

In this chapter we'll:

- Allow the contract to store multiple crossword puzzles
- Store the positions of the clues in the contract
- Allow users to log in with a NEAR account
- Give a prize (in NEAR tokens) to the first person to solve the puzzle
- Explore using Rust structs and enums
- more…

<figure>
    <img src={chapter2Correct} width="600" alt="A user fills in the last clue in a crossword puzzle and an overlay appears saying that a transaction is pending" />
    <figcaption>A user solves the crossword puzzle, interacts with the blockchain, and gets a prize</figcaption>
</figure>

As we implement the list above, we'll learn key concepts about NEAR:

- [Actions](https://nomicon.io/RuntimeSpec/Actions.html)
- Full and function-call [access keys](https://docs.near.org/concepts/basics/account#access-keys)
- NEAR's specialized [Collections](https://docs.near.org/concepts/storage/data-storage#rust-collection-types) that are generally preferable to, say, Rust's standard HashMap 
- The flow of logging in to a decentralized app (dApp)
- more…

Let's jump right in!

## Completed project

Here's the final code for this chapter:

https://github.com/near-examples/crossword-tutorial-chapter-2
# Economics API

Accounts own certain balance; and each transaction and each receipt have certain amount of balance and prepaid gas
attached to them.
During the contract execution, the contract has access to the following `u128` values:

- `account_balance` -- the balance attached to the given account. This includes the `attached_deposit` that was attached
  to the transaction;
- `attached_deposit` -- the balance that was attached to the call that will be immediately deposited before
  the contract execution starts;
- `prepaid_gas` -- the tokens attached to the call that can be used to pay for the gas;
- `used_gas` -- the gas that was already burnt during the contract execution and attached to promises (cannot exceed `prepaid_gas`);

If contract execution fails `prepaid_gas - used_gas` is refunded back to `signer_account_id` and `attached_deposit`
is refunded back to `predecessor_account_id`.

The following spec is the same for all functions:

```rust
account_balance(balance_ptr: u64)
attached_deposit(balance_ptr: u64)

```

-- writes the value into the `u128` variable pointed by `balance_ptr`.

###### Panics

- If `balance_ptr + 16` points outside the memory of the guest with `MemoryAccessViolation`;
- If called in a view function panics with `ProhibitedInView`.

###### Current bugs

- Use a different name;

---

```rust
prepaid_gas() -> u64
used_gas() -> u64
```

###### Panics

- If called in a view function panics with `ProhibitedInView`.
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
import { Wallet } from './near-wallet';

const CONTRACT_ADDRESS = "x.paras.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'nft_buy',
  args: {
    token_series_id: "299102",
    receiver_id: "bob.near",
  },
  contractId: CONTRACT_ADDRESS,
  deposit: 205740000000000000000000 // attached deposit in yoctoNEAR, covers NFT price + storage cost
});
```

_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>

```json
"299102:1"
```

</details>

</TabItem>

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

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

const CONTRACT_ADDRESS = "simple.market.mintbase1.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
 
await wallet.callMethod({
  method: 'buy',
  args: {
    nft_contract_id: "rubennnnnnnn.mintbase1.near",
    token_id: "38"
  },
  contractId: CONTRACT_ADDRESS,
  deposit: 1000000000000000000000 // attached deposit in yoctoNEAR, covers NFT price + storage cost (optional)
});
```

_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>

```json
{
  "payout": {
    "rub3n.near": "889200000000000000000",
    "rubenm4rcus.near": "85800000000000000000"
  }
}
```

</details>

:::tip

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

:::

</TabItem>

</Tabs>
---
title: Legal Resources
description: Legal resources to support a decentralized world
---

# Legal Resources

The legal space in web3 is a frontier but luckily it's one we're tackling together and in public. This section is meant to help gather resources for someone who is looking to get involved in supporting projects or for projects to draw on legal best practices.  

The key disclaimer is obvious -- while this is a collection of resources, it is no substitute for actual, official legal representation or advice.



## Getting Started With Web 3 Legal

If you're just getting started with web 3 and want to dip your toes, there are a lot of ways to do this.
The key difference here is that we do most things in public and learning is collaborative, so everyone can participate in some way and everyone can learn.
Join office hours, read blogs, follow twitter and start contributing wherever you can :)

* [Open Law](https://www.openlaw.io) is working to build open source tookits and best practices for Ethereum.  Follow some of their lawyers like [Larry Florio](https://twitter.com/larryflorio?lang=en) from Syndicate DAO.
* This is [a mega list](https://daotalk.org/t/resource-list-dao-legal/533) of DAO legal background resources (2019)
near-api-js 0.44.0 Released
DEVELOPERS
December 10, 2021
We have just released a new minor version of our JavaScript client library (NEAR-API-JS). v0.44.0 brings some significant changes, so let’s take a moment to go over the changelog and review what’s new.

RPC API Keys
TL;DR: Added support for RPC Server API Keys (PR #729)
The JavaScript library now allows you to define an API key to authenticate with the target RPC server. This feature comes in preparation for the upcoming change that will require keys to access our public RPC servers. Supporting API keys will also allow you to connect to third-party and non-public RPC servers in the future. If you’re wondering about the integration, you can find some practical code examples in our Cookbook.

For the moment there’s no need to take action on your side: currently, this is a non-breaking change, and your JavaScript code will continue to work correctly if you don’t provide an API key.

New verify method
TL;DR: Added a verify method on PublicKey type to verify signature correctness (PR #710)
Before this change, you could only verify a message or signature with KeyPair, which also required having a secret key. This requirement was completely irrelevant in the context of the signature verification process.

Thanks to the new verify method, it’s now possible to verify signatures using just a public key. You can find a code example on how to verify with a public key in our GitHub repository.

Key file permissions
TL;DR: Key file permissions changed to 0o600 (#706)
Account credentials are stored on your hard drive whenever you use the CLI with NEAR login. Regular file permissions allowed anyone on the system to access and read those credentials. As we care about security, we changed how the stored credentials’ file permissions are set, so only the owner can access the content.

Please note that this change won’t affect the permissions on existing keys. If you are handling sensitive keys, we recommend changing the file permissions manually.

Before:

[near@x1 ~] stat –format ‘%a’ ~/.near-credentials/testnet/near-test.testnet.json

644

After:

[near@x1 ~] stat –format ‘%a’ ~/.near-credentials/testnet/near-test.testnet.json

600
---
id: bos-loader
title: BOS Loader
---

# BOS Loader

In this article you'll learn how to develop, test, and deploy BOS components using CLI tools. You can use this workflow to tap into the colaboration, pull-request, and other GitHub benefits while still deploying components to the BOS. 

[BOS Component Loader](https://github.com/near/bos-loader) serves a local directory of component files as a JSON payload properly formatted to be plugged into a BOS `redirectMap`. When paired with a viewer configured to call out to this loader, it enables local component development.

## Development flow

1. _(Optional)_ Download and install [`bos` CLI](https://bos.cli.rs).

   :::info
   You need `bos` CLI if you have component code on the BOS already that you want to use or if you want to manage component deploys locally instead of the GitHub actions CI/CD.
   :::

2. To get component code saved on the BOS, use `bos` to download the source code. Otherwise, create a `src` folder.

3. Create a component within that src folder like `src/<component name>.jsx`.

   :::tip
   It's common practice to use `.` delimited component names for namespacing. You can handle this with folders for better files organization.
   
   For example, `AppName.Component` → `AppName/Component.jsx`.
   :::

5. Download and install [BOS Component Loader](https://github.com/near/bos-loader/releases) (`bos-loader`).

6. Run `bos-loader <youraccount.near> --path src` (or run from `src` folder)

7. Open https://near.org/flags, and set the loader URL to `http://127.0.0.1:3030`.

8. Open `https://near.org/<youraccount.near>/widget/<component name>` (case sensitive)

   :::info
   If you're testing on `testnet`, use your testnet account and open https://test.near.org instead.
   
   Run `bos-loader <youraccount.testnet> --path src` locally, set loader URL in https://test.near.org/flags and open `https://test.near.org/<youraccount.testnet>/widget/<component name>` to view your component locally.
   :::

   :::tip
   You can work on multiple components at once by embedding them in a wrapper component.
   :::

9. Make changes to the component's code.

   :::info
   You must refresh the browser's web page to see the changes.
   :::

10. When you're done, use the <kbd>X</kbd> on the banner to stop loading locally.

## Component deployment

At this point, your new component is ready to be deployed. To deploy, you can use either of the following two paths: 

 - Use `bos` CLI to deploy from command line:

   ```
   bos deploy
   ```

 - Set up a [GitHub actions](https://github.com/FroVolod/bos-cli-rs/blob/master/README.md#reusable-workflow) deployment workflow. Check [this document](https://github.com/FroVolod/bos-cli-rs/blob/master/README.md#github-actions) for instructions.

You should now be able to see your component in discovery. Happy Hacking!
---
sidebar_position: 1
sidebar_label: Introduction
title: Pagoda RPC API
---

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

:::warning

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

:::

## Overview

The Pagoda RPC provides you with instant access to maintenance free, scalable NEAR infrastructure, powering you on the fastest path from ideas to launch.

Developers can interact with on-chain data and send different types of transactions to the network by utilizing the RPC endpoints.

In addition to the powerful node infrastructure, we also created the Pagoda RPC Stats page so that you can have visibility into your RPC usage and performances and take control of your project from the infrastructure level. What’s more? You can subscribe to the alerts from our Status page so that you can follow the health of Pagoda RPC real time. All accesible via [Pagoda Console](https://console.pagoda.co/).

## Setup

### API Keys

- [Getting API keys](get-keys.md)
- [Testing your API keys](setup.md#test-your-api-keys)

### Tools

- [Postman](setup.md#postman-setup) setup
- [Command-line (CLI)](setup.md#command-line-setup) setup
- [JavaScript](setup.md#javascript-setup) setup
- [Rust](setup.md#rust-setup) setup

---

## RPC Endpoints - Quick Links

| API                                        | Description                                                                  |
| ------------------------------------------ | ---------------------------------------------------------------------------- |
| [Access Keys](/api/rpc/access-keys)        | Retrieve information about an account's access keys.                         |
| [Accounts / Contracts](/api/rpc/contracts) | View details about accounts and contracts as well as perform contract calls. |
| [Block / Chunk](/api/rpc/block-chunk)      | Query the network and get details about specific blocks or chunks.           |
| [Gas](/api/rpc/gas)                        | Get gas price for a specific block or hash.                                  |
| [Protocol](/api/rpc/protocol)              | Retrieve current genesis and protocol configuration.                         |
| [Network](/api/rpc/network)                | Return status information for nodes and validators.                          |
| [Transactions](/api/rpc/transactions)      | Send transactions and query their status.                                    |

:::tip

You can access the JSON RPC 2.0 endpoints using [Postman](setup.md#postman-setup),
[JavaScript](setup.md#javascript-setup), [Rust](setup.md#rust-setup), and [CLI](setup.md#command-line-setup).

:::
---
description: Links to Research Papers and Posts
sidebar_position: 7
title: Research
---

---

:::info on this page
* Research articles on NEAR's sharding, consensus, and economics.
* General research on blockchain platforms and their architecture
* Consensus Mechanisms: Proof of Work vs Proof of Stake
:::

## Research Papers

* [The NEAR network in review](https://www.finoa.io/resources/near-report/) - A report on the NEAR network by Finoa.
* [Sharding Design: Nightshade](https://near.org/papers/nightshade) - Sharding approach that is focused on sharding blocks instead of chains.
* [Doomslug vs PBFT, Tendermint, and Hotstuff](https://near.org/blog/doomslug-comparison) - Novel consensus algorithm that allows to have super fast blocks with BFT finality.
* [Fast Finality: Proof of Space-Time](https://near.org/papers/proof-of-space-time/) - A design for a fork choice rule, Sybil resistance mechanism and finality gadget that collectively provide fast finality, resistance to long range attacks, and discourage pooling.
* [Economics in Sharded Blockchain](https://near.org/papers/economics-in-sharded-blockchain/) - Paper reviews economic incentive design for sharded blockchains.

## Research Posts

* [Detailed overview of Ethereum 2.0 shard chains: Committees, Proposers and Attesters](https://near.org/blog/detailed-overview-of-ethereum-2-0-shard-chains-committees-proposers-and-attesters/)
* [The authoritative guide to Blockchain Sharding, part 1](https://near.org/blog/the-authoritative-guide-to-blockchain-sharding-part-1/)
* [Unsolved Problems in Blockchain Sharding](https://near.org/blog/unsolved-problems-in-blockchain-sharding/)
* [How Unrealistic is Bribing Frequently Rotated Validators?](https://near.org/blog/how-unrealistic-is-bribing-frequently-rotated-validators/)
* [Avalanche vs The new IOTA consensus algorithm, with a touch of Spacemesh](https://near.org/blog/avalanche-vs-the-new-iota-consensus-algorithm-with-a-touch-of-spacemesh/)
* [Overview of Layer 2 approaches: Plasma, State Channels, Side Chains, Roll Ups](https://near.org/blog/layer-2/)
* [Randomness in Blockchain Protocols](https://near.org/blog/randomness-in-blockchain-protocols/)
* [Long Range Attacks and New Fork Choice Rule](https://near.org/blog/long-range-attacks-and-a-new-fork-choice-rule/)
* [Introduction of NEAR Economics](https://near.org/blog/near-protocol-economics/)
* [Deep Dive Into Private Transactions On NEAR](https://near.org/blog/private-transactions-on-near/)
* [Rainbow bridge: Ethereum-NEAR](https://near.org/blog/eth-near-rainbow-bridge/)
* [So what exactly is Vlad’s Sharding PoC doing?](https://near.org/blog/so-what-exactly-is-vlads-sharding-poc-doing/)
* [Exploring liveness of Avalanche](https://medium.com/@zaver.max/exploring-liveness-of-avalanche-d22f13b2db00)
* [Thresholded Proof Of Stake](https://near.org/blog/thresholded-proof-of-stake/)
* [Limitations of Zilliqa’s Sharding approach](https://near.org/blog/limitations-of-zilliqas-sharding-approach/)
```js
const args = {
  config: {
    name: "Primitives",
    purpose: "Building primitives on NEAR",
    metadata: ""
  },
  policy: ["bob.near"]
};
Near.call(
  "sputnik-dao.near",
  "create",
  {
    name: "primitives",
    args: Buffer.from(JSON.stringify(args)).toString("base64"),
  },
  300000000000000,
  6000000000000000000000000
);
```


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

While developing a decentralized app you might want track specific events in real time. For example, you could want
to be informed each time a specific NFT marketplace makes a sell. For this to be possible you need:

1. A way for the contract to inform that an event took place.
2. A way to track such events in real time.

To tackle these challenges is that the [standard events format (NEP-297)](https://nomicon.io/Standards/EventsFormat) was created.
[NEP-297](https://nomicon.io/Standards/EventsFormat) defines a standard way for contracts to inform about an event. Since these
events are public, a service can then be built to track them in real time through the use of websocket.

---

## NEP-297 - Events
In NEAR, `Events` use the standard logs capability of contracts, since every log is forever stored in the blockchain. In this way,
Events are normal log entries that start with the `EVENT_JSON:` prefix, followed by a single valid JSON string. The JSON string
must codify an object with the following interface:

```ts
interface EventLogData {
    standard: string, // name of standard, e.g. nep171
    version: string, // e.g. 1.0.0
    event: string, // type of the event, e.g. nft_mint
    data?: unknown, // event data defined in the nep171
}
```

See the [NEP-297 page](https://nomicon.io/Standards/EventsFormat) for examples.

:::warning
There is a known limitation of 16kb strings when capturing logs
:::

---

## Listening to Events (Mainnet)

To listen to events in the `mainnet` simply connect to the secure websocket `wss://events.near.stream/ws`. There is no websocket **for `testnet`**.

As first message you will need to pass an object stating the type of events you want to filter for, and a limit if necessary. For example, here we filter for the `nft_mint` event in the `nft.nearapps.near` account.

```json
{
  secret: "ohyeahnftsss",
  filter: [{
    "account_id": "nft.nearapps.near",
    "status": "SUCCESS",
    "event": {
      "standard": "nep171",
      "event": "nft_mint",
    }
  }],
  fetch_past_events: 20,
}
```

:::caution
There is no websocket implemented for `testnet`, but you can run your own using this [modified indexer](https://github.com/evgenykuzyakov/indexer-tutorials/tree/master/example-indexer) to
populate a database with events, and then serve them using the [event-api project](https://github.com/evgenykuzyakov/event-api). 
:::

:::tip Reference implementation
If you need a reference implementation, [here is a project from Evgeny Kuzyakov](https://github.com/evgenykuzyakov/nft-mints)
that listens for **all** `nft_mint` and `nft_transfer` events in the NEAR network.
:::

---
---
sidebar_position: 7
sidebar_label: Receipt
---

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

# `Receipt` Structure

## Definition

Receipt is an internal transaction in NEAR Protocol.

## `ReceiptView`

<Tabs>
  <TabItem value="rust" label="Rust">

```rust links=1
pub struct ReceiptView {
    pub predecessor_id: AccountId,
    pub receiver_id: AccountId,
    pub receipt_id: CryptoHash,

    pub receipt: ReceiptEnumView,
}
```

  </TabItem>
  <TabItem value="typescript" label="TypeScript">

```ts links=1
export type Receipt = {
  predecessorId: string;
  receipt: ReceiptEnum;
  receiptId: string;
  receiverId: string;
}
```

  </TabItem>
</Tabs>

## `ReceiptEnumView`

<Tabs>
  <TabItem value="rust" label="Rust">

```rust links=1
pub enum ReceiptEnumView {
    Action {
        signer_id: AccountId,
        signer_public_key: PublicKey,
        #[serde(with = "u128_dec_format")]
        gas_price: Balance,
        output_data_receivers: Vec<DataReceiverView>,
        input_data_ids: Vec<CryptoHash>,
        actions: Vec<ActionView>,
    },
    Data {
        data_id: CryptoHash,
        #[serde(with = "option_base64_format")]
        data: Option<Vec<u8>>,
    },
}
```

  </TabItem>
  <TabItem value="typescript" label="TypeScript">

```ts links=1
export type ReceiptEnum =
  | {
      Action: {
        actions: Action[];
        gasPrice: string;
        inputDataIds: string[];
        outputDataReceivers: string[];
        signerId: string;
        signerPublicKey: string;
      };
    }
    | {
      Data: {
        data: string;
        dataId: string;
      };
    };
```

  </TabItem>
</Tabs>

## ActionReceipt

ActionReceipts hold info about what actions to perform. In the cross-contract calls some actions might happen only when specific data is available, such data is in the [DataReceipts](#datareceipt).

## DataReceipt

DataReceipts hold the data that is produced by `Promise` during the cross-contract calls.
```js
const dropSupplyForOwner = await wallet.viewMethod({
  contractId: KEYPOM_CONTRACT_ADDRESS
  method: 'get_drop_supply_for_owner',
  args: { account_id: accountId },
});

const dropsForOwner = await wallet.viewMethod({
  contractId: KEYPOM_CONTRACT_ADDRESS
  method: 'get_drops_for_owner',
  args: { account_id: accountId, from_index: (dropSupplyForOwner - 1).toString() }
});

const dropId = dropsForOwner[dropsForOwner.length - 1].drop_id;
```

_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
NEAR Foundation Launches New AMA Series
NEAR FOUNDATION
October 28, 2022
The NEAR Foundation realizes there has been an issue with communication to the NEAR ecosystem. We hear you. 

To that end, NEAR Foundation will host its first AMA on Twitter Spaces next Tuesday, November 1, which will be moderated by Community Team member Marcus Ribeiro. Bring your questions and concerns to Foundation CEO Marieke Flament, NEAR Co-founder Illia Polosukhin, and the rest of the Foundation leadership team. 

NEAR Foundation’s commitment to improving communication will also include a weekly blog and more regular AMAs designed to update the community on the Foundation’s activities. Bring your ideas to next week’s AMA as well as other future ones! 

Stay tuned for AMA details this coming Monday.