jcarbonnell/preTrainingNEAR huggingface dataset:
How to Convert Web 2 Games to Web 3
DEVELOPERS
July 1, 2022
Gaming has become one of the fastest growing sectors of the Web3 world. On NEAR alone, there are nearly 100 projects building gaming titles in the ecosystem. But harnessing the unique properties of blockchain can be a challenge. Which is why an ecosystem project, in collaboration with the NEAR Foundation has created a handy tutorial for anyone considering converting their games to Web3.

If you’ve ever tried to find a simple answer to the question of “How do I start converting my mobile game to NEAR blockchain?”, then this Web2 to Web3 tutorial is for you.

The tutorial was created by Sigma Software Group, a consultancy group with Swedish and Ukrainian roots, as a result of its own work converting a free to play large-scale mobile AR game called Black Snow, which makes players the heroes of an epic sci-fi movie at their physical or virtual locations.

Through this conversion, Black Snow is utilising NFTs to radically reimagine the gaming experience for players. So the team have decided to share its knowledge with other gaming companies looking to explore similar conversions.
Essentially, there is no way of just “converting” your game to use a blockchain, although NEAR strives to make the transition and onboarding to web3 ecosystem as natural and hassle free as possible. Thus, even the very first step to add NFTs into a mobile game presents a multi-faceted challenge that includes game mechanics, architecture, engineering, and live ops. 

A step-by-step guide
The tutorial begins with explanations of the very core concepts, which you’ll need to understand before starting the move to web3. It highlights both the benefits and constraints of moving to blockchain.

Then, you’ll find a sequence of practical steps along with code examples to guide you through converting a regular mobile game to a game with NFTs in the NEAR ecosystem.

These steps cover the technical aspects of how to choose libraries, frameworks and which third-party solutions can be used to implement the blockchain architecture. 

The tutorial describes how NFTs are used to represent ownership of an asset in web3 world, how to implement them technically, and on which moment you need to stay focused during this process. Further, it covers aspects on NFT usage and minting as well as NFT marketplace integration. 

The tutorial also provides a number of tips and tricks, which are not that obvious for any newcomer to blockchain, concerning security, scalability, availability, and costs of a web3 application.
---
sidebar_position: 3
---

# Creating Accounts

You might want to create an account from a contract for many reasons. One example:
You want to [progressively onboard](https://www.youtube.com/watch?v=7mO4yN1zjbs&t=2s) users, hiding the whole concept of NEAR from them at the beginning, and automatically create accounts for them (these could be sub-accounts of your main contract, such as `user123.some-cool-game.near`).

Since an account with no balance is almost unusable, you probably want to combine this with the token transfer from [the last page](./token-tx.md). You will also need to give the account an access key. Here's a way do it:

```rust
Promise::new("subaccount.example.near".parse().unwrap())
    .create_account()
    .add_full_access_key(env::signer_account_pk())
    .transfer(250_000_000_000_000_000_000_000); // 2.5e23yN, 0.25N
```

In the context of a full contract:

```rust
use near_sdk::{env, near_bindgen, AccountId, Balance, Promise};

const INITIAL_BALANCE: Balance = 250_000_000_000_000_000_000_000; // 2.5e23yN, 0.25N

#[near_bindgen]
pub struct Contract {}

#[near_bindgen]
impl Contract {
    #[private]
    pub fn create_subaccount(prefix: AccountId) -> Promise {
        let subaccount_id = AccountId::new_unchecked(
          format!("{}.{}", prefix, env::current_account_id())
        );
        Promise::new(subaccount_id)
            .create_account()
            .add_full_access_key(env::signer_account_pk())
            .transfer(INITIAL_BALANCE)
    }
}
```

Things to note:

* `add_full_access_key` – This example passes in the public key of the human or app that signed the original transaction that resulted in this function call ([`signer_account_pk`](https://docs.rs/near-sdk/3.1.0/near_sdk/env/fn.signer_account_id.html)). You could also use [`add_access_key`](https://docs.rs/near-sdk/latest/near_sdk/struct.Promise.html#method.add_access_key) to add a Function Call access key that only permits the account to make calls to a predefined set of contract functions.
* `#[private]` – if you have a function that spends your contract's funds, you probably want to protect it in some way. This example does so with a perhaps-too-simple [`#[private]`](../contract-interface/private-methods.md) macro.
* `INITIAL_BALANCE` uses the [`Balance`](https://docs.rs/near-sdk/3.1.0/near_sdk/type.Balance.html) type from near-sdk-rs. Today this is a simple alias for `u128`, but in the future may be expanded to have additional functionality, similar to recent [changes to the `Gas` type](https://github.com/near/near-sdk-rs/pull/471).
Case Study: Bernoulli-Locke-Locke’s David Palmer on the DAO-Owned SailGP Team
NEAR FOUNDATION
June 14, 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, heard from OnMachina co-founder Jonathan Bryce on building decentralized storage, and dove into Move-to-Earn with Sweat Economy’s Oleg Fomenko.

In the latest case study video, Bernouilli-Locke founder David Palmer details how his group is implementing a DAO for team ownership and governance for SailGP boat racing, by leveraging the power of NEAR.
---
id: utils
title: Utilities
sidebar_label: Utilities
---

### NEAR => yoctoNEAR {#near--yoctonear}

```js
// converts NEAR amount into yoctoNEAR (10^-24)

const { utils } = nearAPI;
const amountInYocto = utils.format.parseNearAmount("1");
```

[<span className="typedoc-icon typedoc-icon-function"></span> Function `parseNearAmount`](https://near.github.io/near-api-js/functions/_near_js_utils.format.parseNearAmount.html)

### YoctoNEAR => NEAR {#yoctonear--near}

```js
// converts yoctoNEAR (10^-24) amount into NEAR

const { utils } = nearAPI;
const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");
```

[<span className="typedoc-icon typedoc-icon-function"></span> Function `formatNearAmount`](https://near.github.io/near-api-js/functions/_near_js_utils.format.formatNearAmount.html)
# Data Types

## type CryptoHash = [u8; 32]

A sha256 or keccak256 hash.

## AccountId = String

Account identifier. Provides access to user's state.

## type MerkleHash = CryptoHash

Hash used by a struct implementing the Merkle tree.

## type ValidatorId = usize

Validator identifier in current group.

## type ValidatorMask = [bool]

Mask which validators participated in multi sign.

## type StorageUsage = u64

StorageUsage is used to count the amount of storage used by a contract.

## type StorageUsageChange = i64

StorageUsageChange is used to count the storage usage within a single contract call.

## type Nonce = u64

Nonce for transactions.

## type BlockIndex = u64

Index of the block.

## type ShardId = u64

Shard index, from 0 to NUM_SHARDS - 1.

## type Balance = u128

Balance is type for storing amounts of tokens.

## Gas = u64

Gas is a type for storing amount of gas.
NEAR Community Update: January 17th, 2020
COMMUNITY
January 17, 2020
Welcome to our first Community Update of 2020. This is a weekly summary of our progress and community. As you might realise, we decided to change the structure of our community update. If you have any thoughts, please let us know what you think. Want something mentioned? Tweet us at @NEARProtocol or send us a message.

Content 
Tune in to Ep. 32 of NEAR Protocol’s Whiteboard Series with @celoHQ to hear from Time Moreton
Evgeny’s tweet thread explaining transactions in NEAR
Have a read of Flux’ use case series. The best part? — They publish new ones every Friday
Our must watch

Alex’ sharding jam with Dean Eigenmann and Ryan Zurrer

Call for Participation
We want to hear from you! Will you take 15 seconds to fill out this survey so we can make more of the kind of content you love? 
Stardust: One of our beta program projects just released their integration guide. If you have experience with nodejs and would like to help out by providing some feedback, please reach out to Canaan: [email protected].
Community
Illia, Amos and several NEAR core developers just came back from an event series and hackathon in China. Have a look at the pictures on our Discord.
We did a complete overhaul of our community channels. Please join us in our new Telegram channels for development and validators.
Engineering
108 PRs across 31 repos by 28 authors. Featured repos: nearcore, near-bindgen-as, near-explorer, near-bridge, nearlib, near-runtime-ts, near-wallet, create-near-app, near-fiddle-api and near-shell

Responding to view requests from a different actor than the actor that produces blocks to ensure requests do not interfere with chain maintenance in nearcore
Limiting the number of blocks / chunks per height to prevent spamming in nearcore
New infrastructure to execute smart contracts from python tests in nearcore
Release 0.4.12 of nearcore
Added near dev-deploy which allows developer to deploy contract easily on throwaway account (similar to studio) during development in near-shell
We made our tooling compatible with GitPod (for now onlyhttps://github.com/nearprotocol/near-chess converted)
Added account list in near-explorer
Added EthRelay in near-bridge
Use near-bindgen-as in near-runtime-ts
Expose batch action promise API in near-runtime-ts
Stake Wars is on hold until the implementation of Doomslug is fully finalized and our internal testing becomes all green.
Upcoming Events 
We are going to be at ETHDenver between the 14th and 16th of February
And at the same time, you can meet us at SF Developer Week Expo and Hackathon
Are you a developer, student, or entrepreneur interested in joining us at DevWeek2020? Fill out this brief survey for a chance to win two free tickets!

@One of our events in Shanghai earlier this month; kudos to our co-hosts HashQuark and IOSG
https://upscri.be/633436/
```js
import { Wallet } from './near-wallet';

const DAO_CONTRACT_ADDRESS = "nearweek-news-contribution.sputnik-dao.near";
const wallet = new Wallet({ createAccessKeyFor: DAO_CONTRACT_ADDRESS });
 
await wallet.viewMethod({
  method: 'get_proposals',
  args: { from_index: 9262, limit: 2 },
  contractId: DAO_CONTRACT_ADDRESS
});
```

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

Config of wasm operations.

## ext_costs:

_type: [ExtCostsConfig](ExtCostsConfig.md)_

Costs for runtime externals

## grow_mem_cost

_type: u32_

Gas cost of a growing memory by single page.

## regular_op_cost

_type: u32_

Gas cost of a regular operation.

## max_gas_burnt
_type: Gas_

Max amount of gas that can be used, excluding gas attached to promises.

## max_stack_height
_type: u32_

How tall the stack is allowed to grow?

## initial_memory_pages
_type: u32_

## max_memory_pages
_type: u32_

The initial number of memory pages.
What is the maximal memory pages amount is allowed to have for
a contract.

## registers_memory_limit
_type: u64_

Limit of memory used by registers.

## max_register_size
_type: u64_

Maximum number of bytes that can be stored in a single register.

## max_number_registers
_type: u64_

Maximum number of registers that can be used simultaneously.

## max_number_logs
_type: u64_

Maximum number of log entries.

## max_log_len
_type: u64_

Maximum length of a single log, in bytes.
Register for NEAR’s May Town Hall: NFTs and NEAR
COMMUNITY
May 16, 2022
Hey there, NEAR World! This month we’re exploring the world of NFTs. Join the community for NEAR’s May Town Hall on May 26, 2022, at 5:00pm GMT (1:00PM EDT/10:00am PDT) for a deep dive into NEAR’s ecosystem of NFT projects and platforms. 

NEAR Foundation CEO Marieke Flament will open the Town Hall with updates on the NEAR community and ecosystem, as well as the Foundation’s ongoing effort to onboard millions into Web3. 

The Town Hall will also include other exciting news, including details of a major NEAR Protocol upgrade. There will also be updates on strategic partnerships, ecosystem funding and education progress, upcoming crypto events, and a panel dedicated to the ever-evolving world of NFTs.

NEAR Protocol Validator Upgrade
One of the NEAR Foundation’s major missions is to help decentralize NEAR Protocol’s block validation. This is accomplished through regular protocol upgrades. 

In the May Town Hall, Pagoda will detail NEAR’s new staking pool contract, which will give validators additional features and functionality. Over the next few months, ecosystem players will work with validators and delegators to help migrate currently staked $NEAR from the old staking pool (poolv1.near) to the new staking pool (pool.near). 

Pagoda will share more details, including the pool migration timeline for validators and delegators. 

A Panel on NFTs in the NEAR ecosystem
NEAR Foundation CEO Marieke Flament will return to talk briefly about NEAR’s vibrant NFT marketplaces, projects, and creatives. There will also be a panel on NFTs, with surprise guests from across the NFT and NEAR ecosystems. 

Register for the May Town Hall
To join the conversation with the global NEAR community, register for the May Town Hall.
Case Study: Pagoda Chief Product Officer Alex Chiocchi on the BOS
NEAR FOUNDATION
May 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.

To showcase some of the innovative products launching on NEAR, the Case Studies content vertical is making a return. With its new multimedia makeover, Case Studies will demonstrate how these projects are leveraging the power of NEAR’s layer 1 protocol and the Blockchain Operating System (BOS) to distribute their apps and onboard the masses into the open web. 

The new NEAR Case Studies series kicks off with a video featuring Pagoda’s Chief Product Officer Alex Chiocchi. For much of the last year Alex has been deeply embedded in the development and launch of the BOS — an OS for an Open Web. 

In the BOS Case Study video, Alex explains how the BOS takes advantage of the NEAR Protocol’s scaling architecture, while allowing builders to code in languages they already know, like Javascript. As you’ll learn from Alex, the BOS 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. 

Stay tuned for more Case Study videos on NEAR, the Blockchain Operating System for an open web.
```js
const keypomContract = "v2.keypom.near";
const dropAmount = "10000000000000000000000";

Near.call([
  {
    contractName: keypomContract,
    methodName: "create_drop",
    args: {
      public_keys: state.publicKeys,
      deposit_per_use: dropAmount,
    },
    deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000,
    gas: "100000000000000",
  },
]);
```
NEAR Ecosystem Kicks Up a Sandstorm at TOKEN2049 Dubai
COMMUNITY
April 4, 2024
After making waves at last year’s Singapore edition, we’re turning up the heat for TOKEN2049 in Dubai, the city that’s rapidly becoming a hotbed for Fintech and AI innovation. This year, the NEAR ecosystem is buzzing with excitement to introduce discussions on chain abstraction and spotlight some of our most dynamic projects, including Calimero, Sweat Economy, and Aurora, to the forefront of the global tech scene.

Tech, Coffee, & Bubbles!
By day, make your way to our booth to engage with the NEAR collective and the visionaries from Calimero, Sweat Economy, and Aurora. Unpack the ways we’re transforming the Web3 space with breakthroughs in chain abstraction, data availability, frameworks for building decentralized application protocols, and Blockchain as a Service (BaaS). Indulge in the flavors of traditional Arabic coffee and pick up the hottest swag.
Yet, the experience doesn’t stop at coffee.
As the enthusiastic sponsor of TOKEN2049 Dubai’s closing party, NEAR is preparing an unforgettable evening. Anticipate a gala filled with select champagne and spirits, celebrating the milestones and fellowship of the Web3 community.

Can’t-Miss Speaking Engagements

At TOKEN2049 Dubai, NEAR Protocol is diving into the conversations that are shaping the future of Web3. We’re kicking things off with a panel on “AI x Web3: Pioneering Decentralized Intelligence,” featuring NEAR’s own Illia Polosukhin alongside experts like Ahmad Shadid from io.net, Niraj Pant of Ritual, Sean Ren of Sahara, and moderated by Tarun Chitra of Gauntlet. They’ll unpack the exciting crossroads of AI and Web3 in fostering decentralized intelligence. Then, don’t miss our fireside chat, “Sweat Economy’s Billion-User Blueprint for Scaling Consumer Crypto Apps,” where Chris Donovan, COO of NEAR Foundation and Oleg Fomenko, Co-founder & CEO of  Sweat Economy open up about their ground-breaking collaboration.

Swing by our booth for a firsthand look at how NEAR is redefining norms with chain abstraction, data availability, and more—all powered by a healthy dose of caffeine.

TOKEN2049 is gearing up to be a dynamic assembly featuring the forefront of Web3 innovation, an event you won’t want to miss. For updates on our activities, side events, and speakers, please visit our Lu.ma page and the TOKEN2049 landing page!
```js
const args = {
  args: {
    owner_id: "bob.near",
    total_supply: "1000000000",
    metadata: {
      spec: "ft-1.0.0",
      name: "Test Token",
      symbol: "test",
      icon: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
      decimals: 18,
    },
  },
  account_id: "bob.near",
};

Near.call("tkn.near", "create_token", args, 300000000000000, "2234830000000000000000000");
```
---
id: storage
title: Million Small Deposits
---

On NEAR, your contract pays for the storage it uses. This means that the more data you store, the more balance you need to cover for storage. If you don't handle these costs correctly (e.g. asking the user to cover their storage usage), then a million little deposits can drain your contract of its funds.

Let's walk through an example:

1. You launch [a guest book app](https://examples.near.org/guest-book-js), deploying your app's smart contract to the account `example.near`
2. Visitors to your app can add messages to the guest book. This means your users will pay a small gas fee to **store** their message to your contract.
3. When a new message comes in, NEAR will check if `example.near` has enough balance to cover the new storage needs. If it does not, the transaction will fail.

Note that this can create an attack surface. If sending data to your guest book is inexpensive to the user while costing the contract owner significantly more, a malicious user can exploit the imbalance to make maintaining the contract prohibitively expensive.

One possible way to tackle this problem is asking the user to attach money to the call to cover the storage used by their message.

:::tip
Remember that you can release the *balance locked for storage* by simply deleting data from the contract.
:::
```bash
near call v2.ref-finance.near swap "{\"actions\": [{\"pool_id\": 79, \"token_in\": \"token.v2.ref-finance.near\", \"amount_in\": \"100000000000000000\", \"token_out\": \"wrap.near\", \"min_amount_out\": \"1\"}]}" --gas 300000000000000 --depositYocto 1
 --accountId bob.near
```

<details>
<summary>Example response</summary>
<p>

```bash
'5019606679394603179450'
```

</p>

</details>
NEAR and Circle Announce USDC Support for Multi-Chain Ecosystem 
COMMUNITY
September 28, 2022
Big news coming out of the Converge22 conference in San Francisco this week. Circle Internet Financial, a global digital fintech firm and the issuer of USD Coin (USDC), announced a partnership with NEAR that will make USDC widely available on the NEAR ecosystem by the end of 2022. 

Having USDC on NEAR is definitely a reason to celebrate. Circle will also make USDC available on other platforms to support a multi-chain ecosystem.

Powering NEAR developers 
Bringing USDC to NEAR will help empower developers to integrate stablecoin payments flows into their Javascript and Rust-based decentralized applications. This will unlock a new wave of accessibility for Web2 builders moving into Web3. It will also serve a vital role in NEAR’s mission of Web3 mass adoption, while helping developers build without limits.

“The multi-chain expansion increases USDC’s native availability from eight ecosystems to thirteen, and enables blockchain developers building on USDC and their users to experience greater liquidity and interoperability within the crypto economy,” said Joao Reginatto, VP of Product at Circle. “Extending multi-chain support for USDC opens the door for institutions, exchanges, developers and more to build their innovations and have easier access to a trusted and stable asset.” 

Bringing USDC to NEAR is a big win for developers, who will now be able to integrate stablecoin payment flows into Javascript or Rust-based dApps. This will help usher in a new wave of accessibility for Web 2 builders making the shift to Web3.

What to know about stablecoins
A stablecoin is simply a cryptocurrency that is “pegged” to a more traditional currency like USD or EURO. Through various treasury and/or collateral models, they are designed to keep a 1:1 value, or parity, with their pegged counterparts. Stablecoins can also be pegged to credit and/or debt or have no collateral at all, as seen in algorithmic stablecoins. 

Their presence in the Web3 ecosystem brings a sense of familiarity for natives and newcomers alike. A stablecoin is also a sort of on-ramp to understanding token economics—the gas that powers Web3 and beyond. 

While designed to reduce cryptocurrency volatility, stablecoins present their own set of risks. When centralized, stablecoins can be victims of hacks, theft, or even over-printing which can lead to hyperinflation. If an algorithmic stablecoin experiences algorithmic failure, as happened with Terra and its sister currency, Luna, the stablecoin can fail. If a stablecoin is fractionally reserved instead of fully backed, there can be a bank run that triggers a dramatic stablecoin price drop.
# action_creation_config

Describes the cost of creating a specific action, `Action`. Includes all variants.

## create_account_cost

_type: Fee_

Base cost of creating an account.

## deploy_contract_cost

_type: Fee_

Base cost of deploying a contract.

## deploy_contract_cost_per_byte

_type: Fee_

Cost per byte of deploying a contract.

## function_call_cost

_type: Fee_

Base cost of calling a function.

## function_call_cost_per_byte

_type: Fee_

Cost per byte of method name and arguments of calling a function.

## transfer_cost

_type: Fee_

Base cost of making a transfer.

NOTE: If the account ID is an implicit account ID (64-length hex account ID), then the cost of the transfer fee
will be `transfer_cost + create_account_cost + add_key_cost.full_access_cost`.
This is needed to account for the implicit account creation costs.

## stake_cost

_type: Fee_

Base cost of staking.

## add_key_cost:
_type: [AccessKeyCreationConfig](AccessKeyCreationConfig.md)_
Base cost of adding a key.

## delete_key_cost

_type: Fee_

Base cost of deleting a key.

## delete_account_cost

_type: Fee_

Base cost of deleting an account.