jcarbonnell/preTrainingNEAR huggingface dataset:
---
id: usecases
title: Interacting with a Contract
sidebar_label: 💡 Interacting with a Contract
---

Here we enumerate case scenarios, and point to where the documentation is present.

---

## Integrating Contracts into a Web App
If you are developing a website (or a web-app), then you will be using `near-api-js` to communicate with the blockchain. Go to the [website](/tools/near-api-js/quick-reference) for more information about it.

---

## Command Line Interface
You can use [NEAR CLI](./cli.md) to automatize tasks from the command line such as:
- Creating sub-accounts
- Deploying contracts to them
- Calling initialization methods

---

## Querying Post Hoc Information
The [NEAR Indexer](./indexer4explorer.md) enables you to query information from a deployed contract such as:

1. Which users called a specific method?
2. How much money they attached?
3. How much GAS was used?

It is very useful for analyzing scenarios that happened in the past.

---

## Getting Real Time Information
If you want to track real time information from your contract, then you need the [Events framework](/tools/realtime).
---
id: mpc
title: Multi-Party Computation (MPC)
---

MPC, or multi-party computation, is about how multiple parties can do shared computations on private inputs without revealing the private data.

As an example, suppose two investors want to compare who holds more crypto tokens without revealing their account balances. MPC can solve this situation, by computing the function `f(x > y)`, where `x` and `y` are private inputs. Each person would submit a private value, and would get the function `x > y` result.

In general, MPC can be used to build all kinds of useful protocols, like threshold cryptography, dark pools, and private auctions. For example, MPC can be used to jointly encrypt a message, with the key split up among many different parties.

<details>
<summary> MPC versus key splitting</summary>
In secret sharing, the key has to get reassembled. At some point, some trusted party is going to have the entire key available to them. With MPC, the whole operation is done in MPC, meaning there's no point where the combined key could be extracted.
</details>

:::info
Want to learn more about multi-party computation? Check [this article](https://www.zellic.io/blog/mpc-from-scratch/).
:::

---

## MPC signature generation

- MPC nodes are doing a multistep process called signature generation.
- They are doing it by using user key shares derived from their root key shares.
- A root key is never reconstructed, but protocol allows to create signatures using it’s shares.

:::info
Using MPC, the root key is never reconstructed and it’s never available. User key is never reconstructed as well.
:::

## How MPC creates a new key

- Once MPC account verification is complete, a root key becomes available to sign a new signature that creates a new key
- This new key is created using [Additive Key Deriviation](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#specification-key-derivation) (a mechanism for deriving many _sub-keys_ from a single _master key_)
- This new sub-key can now be used to sign a payload for a given account associated with a given blockchain
```js
Near.call(
  "primitives.sputnik-dao.near",
  "add_proposal",
  {
    proposal: {
      description: "My first proposal",
      kind: {
        Transfer: {
          token_id: "",
          receiver_id: "bob.near",
          amount: "10000000000000000000000000",
        },
      },
    },
  },
  300000000000000,
  100000000000000000000000
);
```
# Staking and slashing

## Stake invariant
`Account` has two fields representing its tokens: `amount` and `locked`. `amount + locked` is the total number of
tokens an account has: locking/unlocking actions involve transferring balance between the two fields, and slashing
is done by subtracting from the `locked` value.

On a stake action the balance gets locked immediately (but the locked balance can only increase), and the stake proposal is 
passed to the epoch manager. Proposals get accumulated during an epoch and get processed all at once when an epoch is finalized.
Unlocking only happens at the start of an epoch.

Account's stake is defined per epoch and is stored in `EpochInfo`'s `validators` and `fishermen` sets. `locked` is always
equal to the maximum of the last three stakes and the highest proposal in the current epoch.


### Returning stake
`locked` is the number of tokens locked for staking, it's computed the following way:
- initially it's the value in genesis or `0` for new accounts
- on a staking proposal with a value higher than `locked`, it increases to that value
- at the start of each epoch it's recomputed:
    1. consider the most recent 3 epochs
    2. for non-slashed accounts, take the maximum of their stakes in those epochs
    3. if an account made a proposal in the block that starts the epoch, also take the maximum with the proposal value
    4. change `locked` to the resulting value (and update `amount` so that `amount + locked` stays the same)

### Slashing
TODO.
---
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:

```js
NearPromise.new("subaccount.example.near").createAccount().addFullAccessKey(near.signerAccountPk()).transfer(BigInt(250_000_000_000_000_000_000_000)); // 2.5e23yN, 0.25N
```

In the context of a full contract:

```js
import { NearPromise, near } from "near-sdk-js";

@NearBindgen({})
export class Contract {
  @call({ privateFunction: true })
  createSubaccount({ prefix }) {
    const subaccountId = `${prefix}.${near.currentAccountId()}`;
    return NearPromise.new(subaccount_id).createAccount().addFullAccessKey(near.signerAccountPk()).transfer(BigInt(250_000_000_000_000_000_000_000)); // 2.5e23yN, 0.25N
  }
}
```

Things to note:

- `addFullAccessKey` – This example passes in the public key of the human or app that signed the original transaction that resulted in this function call ([`signerAccountPk`](https://github.com/near/near-sdk-js/blob/d1ca261feac5c38768ab30e0b24cf7263d80aaf2/packages/near-sdk-js/src/api.ts#L187-L194)). You could also use [`addAccessKey`](https://github.com/near/near-sdk-js/blob/d1ca261feac5c38768ab30e0b24cf7263d80aaf2/packages/near-sdk-js/src/promise.ts#L526-L548) to add a Function Call access key that only permits the account to make calls to a predefined set of contract functions.
- `{ privateFunction: true }` – 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 [`{ privateFunction: true }`](../contract-interface/private-methods.md) decorator parameter.
Aurora Partners With ConsenSys, Bringing MetaMask, Infura and More Ethereum Tools to NEAR
COMMUNITY
December 2, 2021
Aurora, the Ethereum scaling solution that allows projects built on Ethereum to utilize the cutting-edge technology of the NEAR Protocol, is partnering with ConsenSys, the enterprise blockchain company to provide access to its suite of developer tools. 

The partnership aims to empower both the NEAR and Ethereum ecosystems by improving developer facilities – through the availability of the product suite – with the goal of increasing cross-chain interoperability. 

The product suite features projects including MetaMask, Infura, ConsenSys Quorum, Truffle, Codefi, and Diligence. MetaMask is the primary way a global user base of over 21 million monthly active users interact with applications on Web3. Over 350,000 developers use Infura to access Ethereum, IPFS and Layer 2 networks. In addition, 4.7 million developers create and deploy smart contracts using Truffle and ConsenSys Diligence has secured more than $25 billion in smart contracts with its hands-on dapp audits and testing tools. 

“We are thrilled to join forces with ConsenSys on our shared mission of empowering the Ethereum ecosystem and extending its economy,” said Alex Shevchenko, the CEO of Aurora Labs.

The partnership means ConsenSys will now have official participation in the ongoing development of the AuroraDAO. 

“We are excited to be partnering with the talented Aurora and NEAR protocol teams. Developer interest in EVM-compatible scaling solutions continues to grow at the same pace as the rapid expansion of the Web3 ecosystem, says E.G. Galano, Co-Founder and Head of Engineering at Infura.

“We believe developers will benefit from the addition of Aurora to the Infura product suite by enabling them to utilize the NEAR network with the EVM tooling they are already familiar with.”

Infura is directly involved in the AuroraDAO, which hands over key decision making to its community as a part of its vision to create a scaling solution that is as decentralized as possible.

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.
# Account Receipt Storage

There is a definition of all the keys and values we store in the Account Storage

## Received data

*key = `receiver_id: String`,`data_id: CryptoHash`*
*value = `Option<Vec<u8>>`*

Runtime saves incoming data from [DataReceipt](Receipts.md#data) until every [input_data_ids](Receipts.md#input_data_ids) in [postponed receipt](#Postponed-receipts) [ActionReceipt](Receipts.md#ActionReceipt) for `receiver_id` account is satisfied.

## Postponed receipts

For each awaited `DataReceipt` we store

*key = `receiver_id`,`data_id`*
*value = `receipt_id`*

Runtime saves incoming [ActionReceipt](Receipts.md#ActionReceipt) until all ``
Update on the Grassroots Support Initiative
NEAR FOUNDATION
August 28, 2023
One of the things the NEAR Foundation has always been most proud of is the passion and enthusiasm of our builders and grassroots projects — something we have seen demonstrated again since the recent post about the NDC. Over the past week alone, over 30 projects have reached out to the Ecosystem Team and a number of conversations are already underway. This has allowed NEAR Foundation to begin mapping out current needs, and understand the best way to provide support that will ensure the NEAR ecosystem remains a vibrant, open, and accessible place to build. 

For us at the Foundation, hearing directly from builders provides invaluable insight into the state of the ecosystem and how we can best continue to support the people and projects that make it what it is. What we have heard so far is that while financial support is important as the NDC fully ramps up, every project has a unique set of needs that requires a holistic approach to provide the right support, and that simply re-starting a grants program is not the right solution. To make sure that we get as many perspectives from across the ecosystem, we will be leaving the form open for one more week (until September 4th) to give anyone who needs support a chance to have their voice heard.

Once the form is closed and we have had a chance to review all of the inputs, we will then begin setting out a broader plan — in alignment with the NDC — to ensure projects get the support they need as we continue moving forward on the path to decentralization. The moment we have the full insights from these conversations, which should be within the next few weeks, we will share them in a follow-up blog post along with a clear plan on how we will be moving forward. 

We are excited to have so much interest from builders, and look forward to creating a plan that can help keep grassroots projects engaged and building.

You can sign up for a time to speak with the Ecosystem Relations Team here.
# Proposals

This section contains the NEAR Enhancement Proposals (NEPs) that cover a fleshed out concept for NEAR. Before an idea is turned into a proposal, it will be fleshed out and discussed on the [NEAR Governance Forum](https://gov.near.org).

These subcategories are great places to start such a discussion:

- [Standards](https://gov.near.org/c/dev/standards/29) — examples might include new protocol standards, token standards, etc.
- [Proposals](https://gov.near.org/c/dev/proposals/68) — ecosystem proposals that may touch tooling, node experience, wallet usage, and so on.

Once and idea has been thoroughly discussed and vetted, a pull request should be made according to the instructions at the [NEP repository](https://github.com/near/NEPs).

The proposals shown in this section have been merged and exist to offer as much information as possible including historical motivations, drawbacks, approaches, future concerns, etc.

Once a proposal has been fully implemented it can be added as a specification, but will remain a proposal until that time.
NEARCON: The Ultimate Web3 Education for Only $99!
NEAR FOUNDATION
September 22, 2023
As NEAR’s flagship conference, NEARCON is the place to learn all of the latest on Web3 technologies and the open web. NEARCON 2023 will be the ultimate Web3 education — and for only $99. 

Let’s explore what you can expect from the NEARCON crash course — from recent Web3 developments in venture capital, decentralization, and AI to NEAR technologies like the Blockchain Operating System (B.O.S), and much more. 

What you’ll learn at NEARCON 2023
The Web3 ecosystem consists of several key roles and sectors, and we’re lucky to have some of the biggest names attending NEARCON. Over 4 days, you will hear from venture capital figures like Samantha Bohbot (RockawayX) and Nathalie Oestmann (Outlier Ventures) as well as accelerator leaders like Nicolai Reinbold (CV Labs). There will also be a number of entrepreneurs and founders, including Michael Casey (CoinDesk), Alexander Skidanov (NEAR Protocol), Rebecca Allen (Contented), Dave Balter (Flipside Crypto), Aurelie Boiteux (Nansen), Mitchell Amador (Immunefi), Marc Goldich (Proximity Labs), and many others. 

Featured talks, panels, and discussions will include learnings on:

Open Web — Learn how open source technologies and ideals are colliding with blockchain technologies like NEAR to create an open web where everyone can be fairly rewarded for their data, ideas, and effort. 
AI & Blockchain — Learn from the OG of AI himself, NEAR co-founder Illia Polosukhin, on how Blockchain and Artificial Intelligence are intersecting in 2023, and how they will develop in the near future. 
Decentralization — See how the NDC (NEAR Digital Collective) is helping to decentralize governance to the NEAR community. 
Regulation & Policy — Get updated on the latest Web3 regulatory developments. 
Your Web3 education doesn’t stop at NEARCON — take the next step
If you love what you learn at NEARCON, you can keep going with your NEAR and open web education. The NEAR ecosystem offers a number of resources to help you find success in Web3. 

Thanks to the NEAR Horizon team — who will be on hand at NEARCON — you can get help in your journey of building, getting funding, and networking as a Web3 builder, founder, and entrepreneur. 

See you in Lisbon!
```rust
// Validator interface, for cross-contract calls
#[ext_contract(ext_amm_contract)]
trait ExternalAmmContract {
  fn get_deposits(&self, account_id: AccountId) -> Promise;
}

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

    // Return the pools data
    let deposits_data = call_result.unwrap();
    return Some(deposits_data);
  }

  pub fn get_contract_deposits(&self) -> Promise {
    let promise = ext_amm_contract::ext(self.amm_contract.clone())
      .get_deposits(env::current_account_id());

    return promise.then( // Create a promise to callback query_greeting_callback
      Self::ext(env::current_account_id())
      .external_get_deposits_callback()
    )
  }
}
```
NEAR Foundation to fund USN Protection Programme
COMMUNITY
October 24, 2022
The NEAR Foundation has set aside $40m USD for a USN Protection Programme grant, designed to protect users from a recent issue relating to USN by ensuring eligible USN holders can redeem their USN on a 1:1 basis with USDT.e. The Programme is now live, run by a subsidiary of Aurora Labs, and can be found here.

Decentral Bank (DCB) recently contacted the NEAR Foundation to advise that USN – a NEAR-native stablecoin created and launched by DCB independently of NEAR Foundation – had become undercollateralised. DCB confirmed that this was due to an initial algorithmic version of USN (v1), which is no longer algorithmic since its upgrade to v2 in June, that was susceptible to undercollateralisation during extreme market conditions. 

This collateral gap of $40m USD is fully covered by the USN Protection Programme. This gap is fixed and not linked to the $NEAR token price in any way (and $NEAR has never had a hardcoded burn/mint relationship to USN).

Given the issues described above, the NEAR Foundation is recommending that DCB wind-down USN in an orderly manner. To assist with this process, the NEAR Foundation has provided a $40m USD grant to a subsidiary of Aurora Labs – one of the NEAR ecosystem’s most prominent contributors – to set up the USN Protection Programme which is now live. Redemptions will begin once DCB has taken certain steps to ensure an orderly wind down. This Programme will be available for 1 year (until 24th October 2023). Eligible USN holders can choose to redeem their USN through the USN Protection Programme or can exchange their USN via any other available route. We’re confident this action best safeguards users and the wider NEAR ecosystem by funding the known collateral gap.

The NEAR Foundation is confident that as the ecosystem grows and matures, this type of intervention should not be required in the future. Moving forward, the NEAR Foundation expects to be working with the NEAR Digital Collective (NDC) and wider community to set up a funded initiative with the remit of developing robust community standards and guardrails, in particular in relation to stablecoins, to help ensure that users are protected in situations of rapid innovation, and evolving markets and regulations.

Note: this article is a summary of and based on the assumptions in a longer article describing events relating to USN and information on the USN Protection Programme (including eligibility requirements and excluded jurisdictions incl. the US) in more detail – this can be found here
```js
const ammContract = "v2.ref-finance.near";
const result = Near.view(
  ammContract,
  "get_pools",
  {
    from_index: 0,
    limit: 1000
  }
);
```

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

```js
[
  {
    pool_kind: 'SIMPLE_POOL',
    token_account_ids: [ 'token.skyward.near', 'wrap.near' ],
    amounts: [ '51865812079751349630100', '6254162663147994789053210138' ],
    total_fee: 30,
    shares_total_supply: '1305338644973934698612124055',
    amp: 0
  },
  {
    pool_kind: 'SIMPLE_POOL',
    token_account_ids: [
      'c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2.factory.bridge.near',
      'wrap.near'
    ],
    amounts: [ '783621938569399817', '1100232280852443291118200599' ],
    total_fee: 30,
    shares_total_supply: '33923015415693335344747628',
    amp: 0
  }
]
```

</p>

</details>
---
sidebar_position: 4
---

# Deploying Contracts

You might want your smart contract to deploy subsequent smart contract code for a few reasons:

- The contract acts as a Factory, a pattern where a parent contract creates many child contracts ([Mintbase](https://www.mintbase.xyz/) does this to create a new NFT store for [anyone who wants one](https://docs.mintbase.xyz/creating/store/deploy-fee); [Rainbow Bridge](https://near.org/bridge/) does this to deploy separate Fungible Token contracts for [each bridged token](https://github.com/aurora-is-near/rainbow-token-connector/blob/ce7640da144f000e0a93b6d9373bbc2514e37f3b/bridge-token-factory/src/lib.rs#L311-L341))
- The contract [updates its own code](../../../2.build/2.smart-contracts/release/upgrade.md#programmatic-update) (calls `deploy` on itself).
- You could implement a "contract per user" system that creates app-specific subaccounts for users (`your-app.user1.near`, `your-app.user2.near`, etc) and deploys the same contract to each. This is currently prohibitively expensive due to NEAR's [storage fees](https://docs.near.org/concepts/storage/storage-staking), but that may be optimized in the future. If it is, this sort of "sharded app design" may become the more scalable, user-centric approach to contract standards and app mechanics. An early experiment with this paradigm was called [Meta NEAR](https://github.com/metanear).

If your goal is to deploy to a subaccount of your main contract like Mintbase or the Rainbow Bridge, you will also need to create the account. So, combining concepts from the last few pages, here's what you need:

```js
import { includeBytes, NearPromise, near } from "near-sdk-js";

const CODE = includeBytes("./res/contract.wasm");

NearPromise.new("subaccount.example.near")
  .createAccount()
  .addFullAccessKey(near.signerAccountPk())
  .transfer(BigInt(3_000_000_000_000_000_000_000_000)) // 3e24yN, 3N
  .deployContract(CODE);
```

Here's what a full contract might look like, showing a naïve way to pass `code` as an argument rather than hard-coding it with `includeBytes`:

```js
import { NearPromise, near, validateAccountId } from "near-sdk-js";

const INITIAL_BALANCE = BigInt(3_000_000_000_000_000_000_000_000); // 3e24yN, 3N

@NearBindgen({})
export class Contract {
  @call({ privateFunction: true })
  createAccount({ prefix, code }) {
    const subAccountId = `${prefix}.${near.currentAccountId()}`;
    validateAccountId(subAccountId);
    NearPromise.new(subAccountId)
        .createAccount()
        .addFullAccessKey(near.signerAccountPk())
        .transfer(INITIAL_BALANCE)
        .deployContract(code);
  }
}
```

Why is this a naïve approach? It could run into issues because of the 4MB transaction size limit – the function above would deserialize and heap-allocate a whole contract. For many situations, the `includeBytes` approach is preferable. If you really need to attach compiled Wasm as an argument, you might be able to copy the approach [used by Sputnik DAO v2](https://github.com/near-daos/sputnik-dao-contract/blob/a8fc9a8c1cbde37610e56e1efda8e5971e79b845/sputnikdao2/src/types.rs#L74-L142).