text
stringlengths 46
74.6k
|
---|
March of the Ambassadors | September 6th, 2019
COMMUNITY
September 6, 2019
In the last two weeks we set a new record for pull requests on GitHub with 126 PRs! We’re really picking up steam towards shipping MainNet. Also, we’ve kicked off our ambassador program with the first call. It went really well and now we’ve got ambassadors across 17 countries. These guys are awesome, and they’re kicking off events all over the world. Stay tuned for an event in your area, and if you don’t have an ambassador or a meetup for NEAR near you (hehe), then you should become an ambassador! Finally, we’ve expanded the team across Russia, Ukraine, Germany. If you think it’s time you joined us, check out our open positions. As usual, links below in their respective sections.
COMMUNITY AND EVENTS
We’re going to be heading to China and Korea this month, and we’ll be at DevCon as well. If you’re in one of those areas, make sure to come say hi! Those events are not yet set in stone, but here are a few coming up soon! Events in Korea and Japan will be announced in the next update
[Shanghai] 9/16; Staking in Shanghai 2 to 6pm at 外滩茂悦大酒店 Hyatt The Bund
[Shanghai] 9/16; Math Wallet Meetup 5:30pm at The Bund
[Shanghai] 9/17; Wanxiang Panel: Developer Friendly & User Friendly Blockchain 3:50pm to 4:30pm at the Bund
[Shanghai] 9/17; IOSG event 5:30pm to 9pm at LAVIN Rose in The Bund
[Shanghai] Tech workshop TBD! (stay tuned)
Also, our co-founder Illia led our very first AMA for the Chinese community. Chinese speakers: Check out the short video below!
Video Player
00:00
01:22
WRITING AND CONTENT
Three new whiteboard series released! And, we’re officially a token type with Satoshi Labs. Check out this last tweet from Berlin below.
NEAR is now officially registered coin type https://github.com/satoshilabs/slips/pull/718
Our Beta Program participant Flux got a major engagement during ETH Berlin (good blog explaining Chainlink limitations and how Augur helped them)
Whiteboard ep 27 with Xiaoshan Zhu from Meter https://youtu.be/7-4UNSyoK9M
Whiteboard ep 28 with Jaynti Kanani from Matic https://youtu.be/P0hDzOzwzYw
Whiteboard ep 29 with Taylor Wei from TOP Network: https://youtu.be/PXLjORNlqlE
ENGINEERING HIGHLIGHTS
The recent major release has fully reworked our transaction bindings. You can now atomically batch transactions. For example, you can create an account and call a function in one atomic operation. This is impossible on most other blockchains! For instance, if you create an account on Ethereum, it requires multiple transactions. If one of those fails, you might have a gremlin account or you might be stuck in limbo. Not today, failed transactions. Not today.
Additionally, we’ve moved serialization to our in house serializer, Borsh. Make sure to check out the website. This is the first binary serializer for security critical projects. And it’s fast!
A record 126 PRs across 20 repos by 18 authors. Featured repos: nearcore, nearlib, near-shell, near-wallet, near-bindgen, and borsh.
We’ve shipped 0.3.0 of core!
The work on Nightshade (Near Sharding Design) is merged into staging from its own branch. Thus, version 0.4.0 of the testnet will be the first sharded version.
Reworking the block production to make it simpler and better handle some corner cases.
A large pull request with the first implementation of the routing is merged in.
Nodes can now explicitly specify which shards they are tracking.
Proper propagation of errors in the storage layer.
Proper checks for the first block after state syncing.
Added proper verification that the block producers send correct receipts between shards.
The stability of the branch in which we are working on the implementation of Nightshade (NEAR sharding design) is improving rapidly. With the most recent changes it passes core protocol CI.
Updated near-bindgen to be safer and use new bindings.
Our binary serializer now has its own website! http://borsh.io
HOW YOU CAN GET INVOLVED
Join us: there are new jobs we’re hiring across the board!
If you want to work with one of the most talented teams in the world right now to solve incredibly hard problems, check out our careers page for openings. And tell your friends!
Learn more about NEAR in The Beginner’s Guide to NEAR Protocol. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox.
https://upscri.be/633436/ |
Women of Web3 Changemakers: Cathy Hackl
NEAR FOUNDATION
October 31, 2023
“I have always said that I’m not the typical face you see representing technology, and that’s why it’s essential for everyone to know that the future is for all,” says Cathy Hackl, a leading authority in emerging tech and co-founder of Journey, a consultancy that advises companies, brands, cities and governments about gaming, AR, AI, spatial computing, metaverse, web3, and virtual world strategies.
Hackl is one of the 10 finalists of the 2023 Women in Web3 Changemakers List, an annual competition designed to champion women pushing boundaries in the space. Hackl, along with nine other outstanding candidates, are showing the industry the change women are bringing about during the advent of the Open Web.
Hackl was selected not only for her work advising companies like Nike, Walmart, Louis Vuitton, and Clinique on navigating emerging digital spaces and technologies, but her tireless work as an educator.
She has taught at IE Business School and SDA Bocconi School of Management, two of the world’s leading business schools, and spoke at Ivy League universities across America. Hackl is one of the world’s leading female tech trailblazers that is constantly evolving and helping build a more inclusive future.
But Hackl’s journey to becoming one of the world’s foremost leaders on emerging technologies nearly didn’t happen.
A chance encounter
Hackl started her career working in live video and live streaming in silicon valley. But it wasn’t until a chance encounter with VR that led her career in a completely new direction.
“I was invited to an event where there were some VR demos. I had the opportunity to try on a VR headset for the first time and experienced what it would be like to be in a solitary confinement cell in virtual reality. Within a few minutes, I felt claustrophobic and I took the device off, but something had changed. It felt like I was able to fully turn on my humanity dial again. I also knew I had seen something important, maybe it was part of the future of storytelling or maybe it was the future of business, but I was sure of one thing: this is what I wanted to do for the rest of my life.”
Soon after that moment, Hackl left the video production space and went all in on AR and VR. Stints at companies like HTC and its VIVE VR project led Hackl to landing her dream job at Magic Leap, the American technology company specialising in augmented reality.
It was here that technologist Neal Stephenson and Chief Futurist at Magic Leap first coined the term “Metaverse”. But for Hackl, it wasn’t to be. When the pandemic struck she was among many that were laid off as the company contracted.
“I had to ask myself: what do I do now? This led me to Amazon Web Services, where I worked on several projects including large scale simulations and learned a lot about cloud computing.”
During the Covid years, Hackl had been writing a lot about the Metaverse after she was first exposed to it at Magic Leap, helping her to connect to companies looking to explore the space.
“I eventually got the courage to leave AWS and launch off on my own. In 2021 I founded my own consulting firm. In just 10 months my company was acquired by Journey, where I am currently the co-founder and I lead the company’s virtual, gaming, and Metaverse studio.”
Since then, Hackl has become one of the main proponents of metaverse technology, especially for women.
The future is female
According to research by McKinsey, women are spending more time in the proto-metaverse than men are and are more likely to spearhead and implement metaverse initiatives.
However, just as in the tech sector as a whole, women represent a minority in the metaverse economy. Both the entrepreneurial capital and the CEO roles in the metaverse space remain disproportionately reserved for men.
“The research shows that women are more likely than men to engage in hybrid use cases in the metaverse, traversing both physical and digital worlds to participate in gaming, fitness, education, live events, and shopping via AR/VR technologies,” says Hackl.
“By contrast, men use the metaverse to participate in purely digital experiences such as gaming, trading nonfungible tokens (NFTs), and attending social events.”
For Hackl, bringing women into technology results in more creative solutions and has more significant potential for innovations that meet women’s needs and promote gender equality. But their lack of inclusion comes with massive costs.
“Suppose women cannot access the Internet and do not feel safe online. In that case, they cannot develop the necessary digital skills to engage in digital spaces, which diminishes their opportunities to pursue careers in science, technology, engineering, and mathematics (STEM) related fields. By 2050, 75% of jobs will be connected to STEM areas. Yet today, women hold just 22% of positions in artificial intelligence”
But Hackl feels the Web3 world is ready for change. “My message is always to be bold, speak your mind, and settle for more. The world needs your essence, work, art, creativity, femininity, intuition, and heart to make the Web3 industry. There will always be obstacles, but there is a vast community to mentor, support and stand by you to continue exploring, building, and creating in the Web3 industry.” |
---
id: ethers-js
title: NEAR for Ethereum developers
---
import {WidgetEditor} from "@site/src/components/widget-editor"
NEAR components are chain-agnostic, enabling you to create decentralized frontends tailored for any Ethereum dApps. Throughout this article, we'll navigate prevalent use-cases with code snippets. You’ll also find links to exemplary NEAR components for reference.
---
## Interact with Ethereum using Ethers.js
The NEAR VM has imported the [Ethers.js](https://docs.ethers.org/) library, allowing for seamless interaction with Ethereum nodes using JavaScript in a NEAR component.
The `Ethers` object exposes the provider connection:
- `Ethers.provider()` is a read-only connection to the blockchain, which allows querying the blockchain state (e.g., account, block or transaction details), querying event logs or evaluating read-only code using call.
- `Ethers.provider().getSigner()` abstracts the class that interacts with an account
- `Ethers.provider().getSigner().getBalance()` returns a Promise that resolves to the account address.
- `Ethers.provider().getBlockNumber()` looks up the current block number (i.e. height)
- `Ethers.provider().getFeeData()` gets the best guess at the recommended FeeData
You can see various ways of using `Ethers` objects on the [Ethers documentation portal](https://docs.ethers.org/)).
---
Furthermore, numerous [basic tools](https://docs.ethers.org/v6/api/utils/) can be found in the ethers.utils object (be aware of the lowercase 'e').
- `ethers.utils.parseUnits(value, unit)` converts the decimal string value to a BigInt, assuming unit decimal places. The unit may the number of decimal places or the name of a unit (e.g. "gwei" for 9 decimal places).
- `ethers.utils.formatEther(wei)` converts value into a decimal string using 18 decimal places.
#### Example showing the difference between `Ethers.provider()` and `ethers.utils`:
```ts
Ethers.provider()
.getSigner()
.getBalance()
.then((balance) => {
console.log("Your ETH balance: ", ethers.utils.formatEther(balance))
});
```
## FAQ
### How to get a user account?
```ts
const receiver = Ethers.provider().send("eth_requestAccounts", [])[0];
```
### How to get the current chain ID?
```ts
Ethers.provider().getNetwork().then((chainIdData) => {
console.log(chainIdData.chainId);
});
```
### How to show a Web3Login button?
```ts
<Web3ConnectButton
className="my-class"
connectLabel="Connect Web3 Wallet"
disconnectLabel="Disconnect Web3 Wallet"
connectingLabel="Connecting..."
/>
```
### How to load a contract ABI?
```ts
const abi = fetch(`https://eth.blockscout.com/api?module=contract&action=getabi&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2`);
if (!abi.ok) {
return "Loading";
}
console.log(abi.body.result);
```
### How to load data from EVM nodes?
```ts
// create a contract interface
const iface = new ethers.utils.Interface(abi.body.result);
// encode the balanceOf get request
const encodedBalanceData = iface.encodeFunctionData("balanceOf", [receiver]);
// perform a call
Ethers.provider().call({
to: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
data: encodedBalanceData,
})
.then((rawBalance) => {
// decode the result
const receiverBalanceHex = iface.decodeFunctionResult(
"balanceOf",
rawBalance
);
console.log(Big(receiverBalanceHex).toFixed());
});
```
### How to send a transaction to Ethereum nodes?
```ts
// create a contract instance
const wEthContract = new ethers.Contract(
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
abi.body.result,
Ethers.provider().getSigner()
);
// perform a given method (withdraw in this case)
wEthContract
.withdraw(balance, {
value: 0
})
.then((transactionHash) => {
console.log(transactionHash);
});
```
### How to convert HEX values to human readable numbers?
```ts
// use Big().toFixed method
Big(balanceHex).toFixed()
```
### How to locate the ABI of a Smart Contract?
Utilize platforms like etherscan.com and blockscout.com, or delve into the project's GitHub repositories and documentation.
### Is there an example of applications with a description of how they were created?
Yes, there is an article that describes [best practices for creating applications for Ethereum developers on NEAR](bos-ethersjs-best-practices.md), with a breakdown of individual steps.
## Examples
Below is a curated list of NEAR components, developed by the community, that epitomize the best practices for creating NEAR components:
- [Unwrap ETH](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/unwrap-weth&tab=source)
- [ERC-20 Token sender](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/erc20-sender&tab=source)
- [Lido Component](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/Lido&tab=source)
- [Swap component](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/swap&tab=source) (a set of swap dApps for Ethereum Mainnet, Polygon Mainnet, Polygon zkevm, Aurora, NEAR, etc)
- [1inch](https://near.org#/near/widget/ComponentDetailsPage?src=chanon.near/widget/1inch)
- [Liquity](https://near.org/near/widget/ComponentDetailsPage?src=garlicfaucet.near/widget/liquityWidget)
|
```rust
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct SwapAction {
/// Pool which should be used for swapping.
pub pool_id: u64,
/// Token to swap from.
pub token_in: AccountId,
/// Amount to exchange.
/// If amount_in is None, it will take amount_out from previous step.
/// Will fail if amount_in is None on the first step.
pub amount_in: Option<U128>,
/// Token to swap into.
pub token_out: AccountId,
/// Required minimum amount of token_out.
pub min_amount_out: U128,
}
// Validator interface, for cross-contract calls
#[ext_contract(ext_amm_contract)]
trait ExternalAmmContract {
fn swap(&self, actions: Vec<SwapAction>) -> Promise;
}
// Implement the contract structure
#[near_bindgen]
impl Contract {
#[private] // Public - but only callable by env::current_account_id()
pub fn external_call_callback(&self, #[callback_result] call_result: Result<String, PromiseError>) {
// Check if the promise succeeded
if call_result.is_err() {
log!("There was an error contacting external contract");
}
}
#[payable]
pub fn swap_tokens(&mut self, pool_id: u64, token_in: AccountId, token_out: AccountId, amount_in: U128, min_amount_out: U128) -> Promise {
assert_eq!(env::attached_deposit(), 1, "Requires attached deposit of exactly 1 yoctoNEAR");
let swap_action = SwapAction {
pool_id,
token_in,
token_out,
amount_in: Some(amount_in),
min_amount_out
};
let mut actions = Vec::new();
actions.push(swap_action);
let promise = ext_amm_contract::ext(self.amm_contract.clone())
.with_static_gas(Gas(150*TGAS))
.with_attached_deposit(YOCTO_NEAR)
.swap(actions);
return promise.then( // Create a promise to callback query_greeting_callback
Self::ext(env::current_account_id())
.with_static_gas(Gas(100*TGAS))
.external_call_callback()
)
}
}
``` |
NEAR Foundation and Eigen Labs Partner to Enable Faster, Cheaper Web3 Transactions for Ethereum Rollups via EigenLayer
NEAR FOUNDATION
November 10, 2023
EigenLabs, one of the leaders in building scaling solutions on Ethereum, is partnering with the NEAR Foundation to create an industry first partnership designed to foster faster, cheaper transactions for Layer 2 projects building on Ethereum.
Ethereum rollups, projects that perform transaction execution outside of the main Ethereum blockchain, have been one of the fastest growing sectors on the world’s largest blockchain. However, they have consistently faced challenges around finality and cost, making them an expensive option for developers looking to build on Ethereum. With the partnership with the NEAR Blockchain and NEAR Foundation, those roadblocks disappear.
The world’s first ‘fast finality layer’ for Ethereum layer 2s
The partnership, which will have the two teams build the world’s first “fast finality layer” for Ethereum layer 2s, will see transaction times shrink from minutes and hours to 3-4 seconds. The cost of transacting on this new finality layer will become 4,000 times cheaper than it is currently, creating the perfect conditions for teams looking to scale on Ethereum.
This advancement will reduce liquidity fragmentation between Layer-2s through increased efficiency while also allowing them to make individual decisions around the sequencers they use to process those transactions, either on-chain or off-chain. The fast finality layer retains all Ethereum security guarantees while adding both NEAR and EigenLayer guarantees, making it an attractive option for any team building on Ethereum L2s.
“We are thrilled to partner with the highly innovative team behind the NEAR protocol,” says Sreeram Kannan, founder of EigenLabs. “This is a mutually beneficial partnership that will leverage both NEAR and EigenLayer’s technologies to make it easier, faster, and cheaper for developers to build on Ethereum.”
Making the Open Web more usable
The collaboration, spearheaded by Pagoda, the NEAR ecosystem development team, will help transition the NEAR-Ethereum Rainbow Bridge to an actively validated service (AVS).
“Pagoda is proud to work with Eigen Labs, a world-class team, to cobuild the fast finality layer. This solution improves the composability with Ethereum L2s and reduces liquidity fragmentation within the rollup ecosystem,” says Bowen Wang, Director of Protocol at Pagoda.
The partnership will not only help projects building on Ethereum, but NEAR too, create a better bridging experience between NEAR and Ethereum, allowing transactions to reach finality faster, with stronger security guarantees and decentralization.
“NEAR Foundation is proud to partner with such an excellent team as Eigen Labs to offer a fast finality layer for ETH rollups,” says Illia Polosukhin, co-founder of NEAR Protocol.
“The fast finality layer showcases the strengths of NEAR’s technology while making the Open Web more usable, which has always been the core goal for NEAR. It will also help defragment liquidity for Ethereum rollups and make all of Web3 more interoperable as a result.”
The NEAR Foundation’s mission is to help usher in the dawn of the open web, a radically new form of Web3 where infrastructure, application protocols, and access is open to anyone, anywhere. Facilitating the development of Ethereum by creating a pathway to fast, low-cost, and scalable infrastructure is one the many ways NEAR is helping bring about this radical shift in how the internet works.
A testnet is expected to launch in Q1 2024, and more details will be shared around that time. |
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at social@near.org. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
|
# Epochs and staking
- [Epoch](Epoch.md)
- [EpochManager](EpochManager.md)
- [Staking](Staking.md)
|
NEAR Day at ETHDenver: Ethereum Without Limits
COMMUNITY
January 20, 2023
ETHDenver is once again upon us. NEAR will be there with a full schedule of talks, panels, bounties, after parties, and more, exploring why NEAR is the place where mainstream adoption of the Open Web will happen.
NEAR makes building and innovating on Web3 simple, secure, and scalable — all well before “The Merge”. Soon, anyone in the world—devs, founders, creators, and app users — will be able to create without limits. Join us on March 2nd for NEAR Day at ETHDenver — a 1-day mini summit on all things NEAR. From March 3rd to March 5th, join NEAR at ETHDenver for the Main Event and Hackathon.
Registering for NEAR Day is free. Sign up for a spot via the link below to meet people from the NEAR community and join the hackathon! To join NEAR Day at ETHDenver, you will also need an ETHDenver pass.
Why NEAR @ ETH Denver?
With the Aurora EVM and Rainbow Bridge, the NEAR ecosystem is basically “Ethereum without limits”. While NEAR will be in attendance to help foster a decentralized multi-chain future, NEAR is showcasing why it’s the platform of choice for Web3 builders and onboarding the masses into the Open Web.
Register for NEAR Day at ETHDenver
Builders, creators, and entrepreneurs will find us at NEAR Day, a 1-day mini summit on ETHDenver’s Main Stage of the National Western Complex on March 2nd. From March 3rd – March 5th, find the NEAR ecosystem booth during ETHDenver and mingle with NEAR Devs, Community members, and others from the ecosystem.
To participate at NEAR Day, all you need to do is register via the link below and have an ETHDenver pass. ETHDenver is a free event. Register now to secure your spot and find out why NEAR is the easiest, most accessible, and scalable blockchain in Web3. Stay tuned for more details!
Register for NEAR Day
For the full schedule and information about NEAR Day at ETHDenver as well as #BUIDLWEEK and Main Event, please visit our event page. Check out ETHDenver’s full schedule to learn more about featured NEAR sessions and more.
Join the Hackathon
Join ETHDenver’s Hackathon and build on NEAR. Members of NEAR Foundation, Aurora, and other projects will be on-site to help onboard devs, creators, and entrepreneurs into NEAR and advise on building dApps.
Building on NEAR is easy and fun, and you’ll instantly be part of a vibrant and supportive community. Let’s get you started!
Register for Hackathon
Notable Speakers at NEAR Day and ETHDenver
Catch a number of exciting NEAR speakers and sessions at NEAR Day and ETHDenver. The final list of participants and sessions is still being solidified. However, we do have some speakers to highlight.
Illia Polusukhin – NEAR Co-founder, CEO of NEAR
Marieke Flament – CEO of NEAR Foundation
Alex Shevchenko – CEO of Aurora Labs
Alex Skidanov – NEAR Co-founder
Polina Aladina – OnMachina Co-Founder
Learn about our other speakers at the NEAR Day event page. |
---
id: gas
title: Gas (Execution Fees)
---
import {NearWidget} from "@site/src/components/near-widget"
On every transaction the NEAR network charges a tiny fee known as **gas**. This fee is a simple mechanism that allows us to:
1. **Prevent** bad actors from **spamming** the network with useless transactions
2. **Burn** a minuscule fraction of the **token supply** on each transaction
3. **Incentivize developers** by giving contracts 30% of the gas they burn while executing
4. Implement a **wall time** by capping transactions to `300Tgas` (~`300ms` of compute time)
Gas in NEAR is computed on [**gas units**](#gas-units--gas-price) and charged using $NEAR tokens based on the network's [**gas price**](#gas-units--gas-price).
:::tip Did you know?
In NEAR, attaching extra gas to a transaction does **not** make it faster. Actions cost a fixed amount of gas, and any extra gas attached is simply sent back to the user
:::
---
## Understanding Gas Fees
For every transaction, users get charged a small $NEAR fee which has to be paid **upfront**. This fee is calculated using deterministic **gas units**, and transformed into a cost in $NEAR using the network's **gas price**.
<hr class="subsection" />
### Gas Units
Every action in NEAR costs a fixed amount of **gas units**, meaning that the same operation will always cost the **same amount of gas units**.
Gas units were engineered in such a way that they can be translated into compute resources, where `1Tgas` gets you approx. `1ms` of compute time.
Transactions can use a maximum of `300Tgas`, meaning they should be processed in less than `300ms`, allowing the network to produce a new block approximately **every second**.
:::tip
Gas units encapsulate not only compute/CPU time but also bandwidth/network time and storage/IO time
:::
<hr class="subsection" />
### Gas Price
To determine the actual $NEAR fee, the cost of all actions in the transaction are multiplied by a **gas price**.
The gas price is **recalculated each block** based on the network's demand and floors at `1Tgas = 0.0001Ⓝ`.
If the previous block is **more than half full** the price goes up by 1%, otherwise it goes down by 1% (until it reaches the floor).
<details>
<summary> What is the gas price now? </summary>
You can query how much a gas unit costs in `yoctoNEAR` (1Ⓝ = `1e24` yocto) through the [`RPC`](/api/rpc/gas#gas-price). To convert in `Tgas` per `NEAR` simply divide by `1e12`.
<NearWidget height="40px">
```js
const query = fetch('https://rpc.near.org', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 'dontcare',
method: 'gas_price',
params: [null]
})
})
const yocto = query.body.result.gas_price
return `Right now, 1 Tgas costs ${Number(yocto) / 1e12}Ⓝ`
```
</NearWidget>
</details>
<hr class="subsection" />
### Cost for Common Actions
Knowing that actions have a fixed cost in gas units, we can calculate the cost of common operations at the minimum gas price of `1Tgas = 0.0001Ⓝ`.
| Action | TGas | Fee (Ⓝ) |
|------------------------------|----------------|----------|
| Create Account | 0.42 | 0.000042 |
| Transfer NEAR | 0.45 | 0.000045 |
| Add Full Access Key | 0.42 | 0.000042 |
| Delete Key | 0.41 | 0.000041 |
| Function Call* | ≤ 300 | ≤ 0.03 |
| Deploying a `16`kb contract | 2.65 | 0.000265 |
| Deploying a `X`kb contract** | 0.58 + 0.13`X` | |
_Note that the fee is in $NEAR, to obtain the cost in dollars multiply by the current price of $NEAR_
:::tip Function Calls*
The cost of calling a function will depend on how complex the function is, but will be consistent across function calls. Learn more bellow.
:::
:::tip Deploying a Contract**
Note that this covers the cost of uploading and writing bytes to storage, but does **not** cover the cost of [holding these bytes in storage](./smart-contract.md#contracts-storage)
:::
<details className="info">
<summary>Where do these numbers come from?</summary>
NEAR is [configured](https://github.com/near/nearcore/blob/master/core/primitives/res/runtime_configs/parameters.yaml) with base costs. An example:
```json
transfer_cost: {
send_sir: 115123062500,
send_not_sir: 115123062500,
execution: 115123062500
},
deploy_contract_cost: 184765750000,
deploy_contract_cost_per_byte: 64572944
```
The "sir" here stands for "sender is receiver". Yes, these are all identical, but that could change in the future.
When you make a request to transfer funds, NEAR immediately deducts the appropriate `send` amount from your account. Then it creates a [_receipt_, an internal book-keeping mechanism](./transaction-execution.md). Creating a receipt has its own associated costs:
```json
action_receipt_creation_config: {
send_sir: 108059500000,
send_not_sir: 108059500000,
execution: 108059500000
}
```
You can query this value by using the [`protocol_config`](/api/rpc/setup#protocol-config) RPC endpoint and search for `action_receipt_creation_config`.
The appropriate amount for creating this receipt is also immediately deducted from your account.
The "transfer" action won't be finalized until the next block. At this point, the `execution` amount for each of these actions will be deducted from your account (something subtle: the gas units on this next block could be multiplied by a gas price that's up to 1% different, since gas price is recalculated on each block). Adding it all up to find the total transaction fee:
```
(transfer_cost.send_not_sir + action_receipt_creation_config.send_not_sir ) * gas_price_at_block_1 +
(transfer_cost.execution + action_receipt_creation_config.execution) * gas_price_at_block_2
```
</details>
---
## How Do I Buy Gas?
You don't buy gas, instead, the gas fee is automatically removed from your account's balance when the transaction [is first proccesed](./transaction-execution.md#block-1-the-transaction-arrives) based on the action's gas cost and the network's gas price.
The only exception to this rule is when you make a function call to a contract. In this case, you need to define how many gas units to use, up to a maximum value of `300Tgas`. This amount will be converted to $NEAR using the network's gas price and deducted from your account's balance.
Since many transactions will take more [than 1 block to execute](./transaction-execution.md), and the gas price is recalculated on each block and could go up, you will be charged a pessimistic estimate of $NEAR (see details bellow).
If the transaction ends up using less gas than the amount deducted, the difference will simply be **refunded to your account**.
<details>
<summary> Pessimistic Estimate </summary>
While actions have a fixed cost in gas units, the gas price might change block to block. Since transactions can take more than 1 block to execute, the gas price might go up during the transaction's execution.
To avoid the need to recalculate the gas price for each block, the network will charge you upfront a pessimistic estimate of the gas fee.
Lets take as an example [this transaction calling a contract method](https://testnet.nearblocks.io/txns/JD8Bg4u8kaYeaSsGBqkvhSDCEPgXhtwJRBBPKicCEPMs). The transaction was submitted with 10Tgas attached.
- 10Tgas would cost 0.001Ⓝ at the price when the transaction was submitted
- The transaction used:
- 2.4Tgas to convert the [transaction into a receipt](./transaction-execution.md#block-1-the-transaction-arrives): 0.00024Ⓝ
- 3.2Tgas to execute the function in the contract: 0.00032Ⓝ
- Total: 5.6Tgas or 0.00056Ⓝ
- In the end, the user was returned 0.00104Ⓝ
Since the system returned `0.00104Ⓝ`, and the transaction expended `0.00056Ⓝ`, the user was charged upfront `0.0016Ⓝ`, this is 60% more than what the user expected to pay (0.001Ⓝ).
This 60% up comes from assuming that the price of gas will go up by 1% on each block, and the transaction will take 50 blocks to execute (`1.01**50 ~ 1.64`).
</details>
:::tip
In other chains, paying a higher gas price gets your transaction processed faster. In NEAR, **gas costs are deterministic**, and you **can't pay extra**. Any extra gas attached to a transaction is simply sent back to the user.
:::
---
## Gas as a Developer Incentive
In NEAR, 30% of the gas fees burn while executing a contract go to the contract's accounts. This is a powerful incentive for developers to create and maintain useful contracts.
For example, in [this transaction](https://testnet.nearblocks.io/txns/JD8Bg4u8kaYeaSsGBqkvhSDCEPgXhtwJRBBPKicCEPMs) the user calls a function in the `guestbook.near-examples.testnet` contract.
Executing the function call burned a total of ~0.00032Ⓝ, from which 30% goes to the contract's account. This means that the contract's account received 0.000096Ⓝ.
Notice that the fee comes from the gas burned during the function execution, and not from the total gas used.
---
## Estimating Costs for a Call
:::warning
This section will soon be moved from here to the [build documentation](../../2.build/2.smart-contracts/anatomy/environment.md).
:::
If you developing a smart contract, you might want to estimate how much gas a function call will consume. This is useful to estimate limits for your function and avoid running into out-of-gas errors.
One of the most accurate ways to estimate gas costs is by running your function in `testnet`. To know exactly how much gas a specific part of your function uses, you can use the `used_gas` method from our SDK.
Another option is to use `Sandbox Testing` (available in [Rust](https://github.com/near/workspaces-rs/tree/main/examples/src) and [JavaScript](https://github.com/near/workspaces-js)), which simulates the NEAR network. There you can access the gas burnt after each function call.
Finally, you can obtain gas cost estimates for a given function call using `api.gasbuddy.tech`. This API is experimental and may be removed in the future. One can obtain a gas cost estimate for a given function call by sending a POST request to `https://api.gasbuddy.tech/profile` with the following JSON body:
```json
{
"contract_id": "<your-contract-account-id>",
"method": "<your-contract-method-name>",
"args": {
"arg1": "value1",
"arg2": "value2"
}
}
```
|
NEAR’s January Town Hall Recap
COMMUNITY
January 28, 2022
The last 12 months was an incredible year for the NEAR community. The ecosystem grew at a phenomenal clip, bringing in new developers, projects and users. The NEAR Protocol was also successfully upgraded to Phase 0 of Simple Nightshade, making the blockchain faster and more robust, while keeping it carbon neutral.
On January 20, NEAR Foundation kicked off the new year with its first Town Hall of 2022. Users and developers from all over the world tuned in. From Korea and Africa to Belarus, Thailand, and Turkey, the NEAR community mirrored the ecosystem’s rapidly growing global reach and influence.
In case you missed the NEAR’s January Town Hall, here’s a roundup.
An ode to the ecosystem
“At NEAR, we believe in a world where people can control their assets, their data, and their power of governance,” said Marieke Flament, NEAR Foundation’s CEO. “We believe that is key to creating an Open Web world. A world where everyone can engage and participate; a world where new business models can be created, and where creators, developers, and users can be better rewarded.”
That vision is not only shared by everyone at NEAR, but the wider community, too. That’s why this month’s town hall was all about championing the voices and ideas from the wider ecosystem.
Team members from the Open Forest Protocol and Sankore took center stage to discuss their progress and why they chose to build on NEAR.
Sankore: Scaling Education in Africa
Sankore Guild Lead and CEO Kevin Imani spoke about the dapp’s national and regional efforts. Imani detailed Sankore’s three-pronged approach in Kenya and East Africa: developer training, talent scouting, and project scouting.
“We want to implement training centers around East Africa where we can have developers certified to develop on NEAR Protocol,” said Imani. He went on to explain Sankore’s ambitious goal of building a network of monthly NEAR Meet events each month in the region, while actively recruiting people and projects to build on NEAR.
Several Town Hall participants were understandably enthusiastic about Sankore’s mission to bring NEAR to new audiences in Africa.
“Really awesome to see NEAR not only advanced industrial nations but especially developing countries,” said Town Hall participant Markus Koch, while user wolfwoodphreak commented, “Love Sankore! Hopefully, one day both Sankore and OFP will join forces to bring NEAR and the GREEN to [the] Cradle of Civilization!”
Or as Magnus Dikese rather succinctly put it: “Africa is NEAR!”
Reimagining Finance with Open Forest Protocol
Open Forest Protocol, a carbon offsetting project NEAR Foundation recently profiled, makes forest monitoring and carbon financing transparent, scalable, and open-source.
Open Forest Protocol’s Ozymandius (4ntsGuild) and Aureline Grange provided updates on their goal of creating the foundation of an “inclusive, nature-based economy.” As Ozymandias said in his opening remarks, OFP is a project focused on bringing Regenerative Finance to NEAR.
“ReFi is right at the intersection of climate and crypto,” said Ozymandias. “What we’re aspiring to build with the Open Forest Protocol is an open-source forest management system for on-chain carbon accreditation and a fully on-chain carbon economy.”
“We just started onboarding forestation projects and validators at the end of last year,” said Aureline Grange. “In November, [OFP CEO] Fred [Fournier] went to COP26 and had very interesting discussions with countries, including Kenya, Ivory Coast, Malawi, and Panama. These countries are interested in using OFP at the national level to monitor their forests, and this is super huge for OFP and the planet as we scale trust and monitoring.”
OFP currently has 15 pilot projects and 14 global validators. And even though OFP has just started fundraising, the project currently has over $4 million in funds. As one Town Hall participant and OFP fan said, 2022 could indeed be the year of ReFi and OFP.
To get the full updates from OFP and Sankore, watch NEAR’s January Town Hall.
Illia on MetaBUILD 2 and What’s Next for NEAR Inc.
It wouldn’t be a Town Hall without NEAR Inc. co-founder Illia Polosukhin’s protocol updates and a roadmap for 2022.
As Illia noted, there are plans to increase the number of validator slots on the NEAR network to more than 400—a number that will continue scaling with the number of shards. He also explored “dynamic resharding” a radical new approach to blockchain design that allows the NEAR network to automatically adjust how many shards it uses to handle busy, and quiet periods more efficiently.
Also on Illia’s Town Hall agenda notes was the NEAR MetaBUILD 2 Hackathon, which launched in December 2021 and runs until February 10. In MetaBUILD 2, developers are working on various projects to build NEAR, Web3, and Metaverse projects.
“We’ve had over 2,100 people sign up, which is pretty amazing,” said Illia. “There are $1 million in prizes and there are 35 partner challenges” from Aurora, Brave, The Graph, Mintbase, Paras, and more.
There are 21 days left to submit a project, so check out the MetaBUILD homepage for hackathon details. And if you want to dive deeper into NEAR, join the NEAR Discord.
Share Your Thoughts on the Town Hall
We’d love to hear your thoughts about the ecosystem and community, so head over to the January Town Hall Reddit thread, where NEAR team members will answer all of your questions!
In the upcoming NEAR Town Hall in February, the NEAR Foundation will detail its efforts to massively scale its global expansion through regional hubs. Make sure to register for the next NEAR Town Hall on February 24th to hear all about it! |
---
sidebar_position: 4
sidebar_label: "Actions and sending NEAR"
title: "There are several Actions an account can do, including sending the winner of the crossword puzzle NEAR using the Transfer Action"
---
import {Github} from "@site/src/components/codetabs"
import allActions from '/docs/assets/crosswords/crossword-actions.png';
import transferNEAR from '/docs/assets/crosswords/transfer-brand-blue--qiqi04.near--blankworl.png';
import yoctoNEAR from '/docs/assets/crosswords/yoctoNEAR-magnifying--jrbemint.near--JrbeMad.jpg';
import signerPredecessorCurrent from '/docs/assets/crosswords/predecessor-signer-current--yasuoarts.near--YasuoArt69.png';
# Actions (including sending NEAR)
We're going to introduce a new Action: `Transfer`. In this chapter, we'd like the first person to solve the crossword puzzle to earn some prize money, sent in NEAR.
<figure>
<img src={transferNEAR} alt="Two hands exchanging a coin emblazoned with the NEAR Protocol logo. Art created by qiqi04.near" width="400"/>
<figcaption className="small">Art by <a href="https://twitter.com/blankworl" target="_blank">qiqi04.near</a></figcaption>
</figure>
<br/>
We've already used Actions in the [previous chapter](../01-basics/03-hashing-and-unit-tests.md#using-batch-actions), when we deployed and initialized the contract, which used the `DeployContract` and `FunctionCall` Action, respectively.
The full list of Actions are available at the [NEAR specification site](https://nomicon.io/RuntimeSpec/Actions.html).
By the end of this entire tutorial we'll have used all the Actions highlighted below:
<img src={allActions} alt="All Actions that will be used when the entire crossword puzzle tutorial is complete" width="600"/>
## Actions from within a contract
When we deployed and initialized the contract, we used NEAR CLI in our Terminal or Command Prompt app. At a high level, this might feel like we're lobbing a transaction into the blockchain, instructing it to do a couple actions.
It's important to note that you can also execute Actions inside a smart contract, which is what we'll be doing. In the sidebar on the left, you'll see a section called [**Promises**](/sdk/rust/promises/intro), which provides examples of this. Perhaps it's worth mentioning that for the Rust SDK, Promises and Actions are somewhat synonymous.
:::note Actions only effect the current contract
A contract cannot use the `AddKey` Action on another account, including the account that just called it. It can only add a key to *itself*, if that makes sense.
The same idea applies for the other actions as well. You cannot deploy a contract to someone else's account, or delete a different account. (Thankfully 😅)
Similarly, when we use the `Transfer` Action to send the crossword puzzle winner their prize, the amount is being subtracted from the account balance of the account where the crossword contract is deployed.
The only interesting wrinkle (and what may *seem like* an exception) is when a subaccount is created using the `CreateAccount` Action. During that transaction, you may use Batch Actions to do several things like deploy a contract, transfer NEAR, add a key, call a function, etc. This is common in smart contracts that use a factory pattern, and we'll get to this in future chapters of this tutorial.
:::
## Define the prize amount
Let's make it simple and hardcode the prize amount. This is how much NEAR will be given to the first person who solves the crossword puzzle, and will apply to all the crossword puzzles we add. We'll make this amount adjustable in future chapters.
At the top of the `lib.rs` file we'll add this constant:
<Github language="rust" start="10" end="11" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/1909630a10291081cb00b2780c1ae8889d98f620/contract/src/lib.rs" />
As the code comment mentions, this is 5 NEAR, but look at all those zeroes in the code!
That's the value in yoctoNEAR. This concept is similar to other blockchains. Bitcoin's smallest unit is a satoshi and Ethereum's is a wei.
<figure>
<img src={yoctoNEAR} alt="Depiction of bills of NEAR, coins for partial NEAR, and then a magnifying glass showing a tiny yoctoNEAR next to an ant. Art created by jrbemint.near"/>
<figcaption className="full-width">Art by <a href="https://twitter.com/JrbeMad" target="_blank">jrbemint.near</a></figcaption>
</figure>
## Adding `Transfer`
In the last chapter we had a simple function called `guess_solution` that returned `true` if the solution was correct, and `false` otherwise. We'll be replacing that function with `submit_solution` as shown below:
<Github language="rust" start="92" end="124" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/83d4d8925e6d30e04e8e4cb5e9a0a6d3763fce40/contract/src/lib.rs" />
Note the last line in this function, which sends NEAR to the predecessor.
:::info Returning a Promise
The last line of the function above ends with a semicolon. If the semicolon were removed, that would tell Rust that we'd like to return this Promise object.
It would be perfectly fine to write the function like this:
```rust
pub fn submit_solution(&mut self, solution: String, memo: String) -> Promise {
// …
// Transfer the prize money to the winner
Promise::new(env::predecessor_account_id()).transfer(PRIZE_AMOUNT)
}
```
:::
## Predecessor, signer, and current account
When writing a smart contract you'll commonly want to use `env` and the details it provides. We used this in the last chapter for:
- logging (ex: `env::log_str("hello friend")`)
- hashing using sha256 (ex: `env::sha256(solution.as_bytes())`)
There are more functions detailed in the [SDK reference docs](https://docs.rs/near-sdk/latest/near_sdk/env/index.html).
Let's cover three commonly-used functions regarding accounts: predecessor, signer, and current account.
<figure>
<img src={signerPredecessorCurrent} alt="Illustration of Alice sending a transaction to a smart contract named Banana, which does a cross-contract call to the smart contract Cucumber. Art created by yasuoarts.near"/>
<figcaption className="full-width">Alice sends a transaction to the contract on banana.near, which does a cross-contract call to cucumber.near.<br/>From the perspective of a contract on cucumber.near, we see a list of the predecessor, signer, and current account.<br/>Art by <a href="https://twitter.com/YasuoArt69" target="_blank">yasuoarts.near</a></figcaption>
</figure><br/><br/>
1. [predecessor account](https://docs.rs/near-sdk/latest/near_sdk/env/fn.predecessor_account_id.html) — `env::predecessor_account_id()`
This is the account that was the immediate caller to the smart contract. If this is a simple transaction (no cross-contract calls) from **alice.near** to **banana.near**, the smart contract at **banana.near** considers Alice the predecessor. In this case, Alice would *also* be the signer.
:::tip When in doubt, use predecessor
As we explore the differences between predecessor and signer, know that it's a more common **best practice to choose the predecessor**.
Using the predecessor guards against a potentially malicious contract trying to "fool" another contract that only checks the signer.
:::
2. [signer account](https://docs.rs/near-sdk/latest/near_sdk/env/fn.signer_account_id.html) — `env::signer_account_id()`
The signer is the account that originally *signed* the transaction that began the blockchain activity, which may or may not include cross-contract calls. If a function calls results in several cross-contract calls, think of the signer as the account that pushed over the first domino in that chain reaction.
:::caution Beware of middlemen
If your smart contract is checking the ownership over some assets (fungible token, NFTs, etc.) it's probably a bad idea to use the signer account.
A confused or malicious contract might act as a middleman and cause unexpected behavior. If **alice.near** accidentally calls **evil.near**, the contract at that account might do a cross-contract call to **vulnerable-nft.near**, instructing it to transfer an NFT.
If **vulnerable-nft.near** only checks the signer account to determine ownership of the NFT, it might unwittingly give away Alice's property. Checking the predecessor account eliminates this problem.
:::
3. [current account](https://docs.rs/near-sdk/latest/near_sdk/env/fn.current_account_id.html) — `env::current_account_id()`
The current account is "me" from the perspective of a smart contract.
:::tip Why would I use that?
There might be various reasons to use the current account, but a common use case is checking ownership or handling callbacks to cross-contract calls.
Many smart contracts will want to implement some sort of permission system. A common, rudimentary permission allows certain functions to only be called by the contract owner, AKA the person who owns a private key to the account for this contract.
The contract can check that the predecessor and current account are the same, and trust offer more permissions like changing contract settings, upgrading the contract, or other privileged modifications.
::: |
Armored Kingdom Launches New SciFi-Fantasy Media Platform on NEAR
COMMUNITY
June 10, 2022
NEAR Foundation is excited to announce a major new entertainment franchise. Armored Kingdom, a new multi-platform, global entertainment universe, is coming to NEAR to reshape Web3 trading card games, digital comics, animation, and film.
Armored Kingdom’s founders include actress, producer, and Web3 innovator Mila Kunis, superhero creator Sharad Devarajan, Lindsey McInerney, and Lisa Sterbakov. As envisioned by creator Hugh Sterbakov and writer/game designer Brian Turner, Armored Kingdom is an immersive blend of media franchise with science fiction and fantasy worldbuilding. It will also be a place for fans to interact with creators and each other.
The launch of Armored Kingdom includes a limited edition free NFT comic mint, available for only 7 days. It will precede Armored Kingdom’s first official collection—a five-issue series of digital and physical comics.
NEAR’s fast, carbon neutral, and infinitely scalable protocol were major factors in the Armored Kingdom founders’ decision to launch on the platform.
World-building in Armored Kingdom
Armored Kingdom follows several tribes of warring medieval dynasties as they battle for power with the aid of Armorite, a powerful and mysterious metal. No one has been able to mine Armorite except the Ancestors, a long-vanished, highly advanced civilization.
The magical weapons the Ancestors forged are now scattered across the lands of Armoria. As dynasties unearth new artifacts, the balance of power shifts. And as the war rages on, a greater threat lurks in the shadows.
“The mythology of Armored Kingdom chronicled in the digital comics will be further explored in the trading card game, which will be phase two for the franchise,” says McInerney. “Carefully marrying the narrative and gameplay, and using both to further explore the world, will keep the storyline evergreen and ever-developing—and above all else, fun.”
An avid TCG/MMO gamer, Kunis has previously launched a number of projects in the Web3 animation space. But Armored Kingdom is Kunis’ first official foray into comics and gaming.
“I lost a good part of my youth to gaming, from World of WarCraft to Settlers of Catan,” says Kunis. “The moment I dove into Web3, I saw the opportunity to create an immersive universe where blockchain technology deepens the gaming experience and makes it more personal and immersive for every fan. Armored Kingdom will allow gamers to relate to their characters and gear in a revolutionary way, and we can’t wait to share more of that with you very soon.”
“This is a dream project for us. Armored Kingdom has all the elements of a great fantasy meets sci-fi story that will take a global audience into a place of wonder,” says Devarajan, Founder of Graphic India, one of Asia’s leading comics, animation and creative studios. “This new storytelling experience will push Web3 technology further than ever before.”
“[We] turned to NEAR to help us make it a reality,” Devarajan adds. “Their expertise with community management, championing of the creative sector, and its carbon-neutral, user-friendly development platform won us over.”
Shaping the future of Web3 storytelling on NEAR
Alongside Paras Comic, OP Games, and other NEAR gaming platforms, Armored Kingdom is set to help shape the future of Web3 storytelling. Not only on NEAR but also across the wider Open Web world.
“We are excited to support the launch of Armored Kingdom and the storytelling opportunities it will bring to fans,” says Marieke Flament, CEO of the NEAR Foundation.
“NEAR is a perfect blockchain for an entertainment franchise as it can support various platforms, which is crucial for multiverse experiences across different mediums,” she adds. “Our focus on ease of use also allows developers to deliver intuitive experiences for a large fan base.” |
Announcing NEAR Validator Advisory Board
COMMUNITY
August 6, 2020
With MainNet Restricted quickly approaching, NEAR is onboarding additional validators to its Advisory Board. This board is run by a selected group of professional validators who, over time, become the key voices in the technical governance of NEAR Protocol.
We are glad to announce the following members of NEAR Validator’s Advisory Board (NVAB), leading organizations in the upcoming MainNet Restricted launch:
Bison Trails
Buildlinks
Certus One
Cryptium Labs
Dokia Capital
DSRV Labs
Figment Networks
Hashquark
Huobi Pool
Sparkpool
Staked
Stake.fish
OKEx Pool
Zero Knowledge Validator
These validators are actively participating in group discussions and new releases testing, to solve technical challenges and co-organize the final transition of the network into the Community Governed phase. More information on the roadmap can be found here.
Furthermore, the NVAB is helping NEAR to develop its Smart Contract based delegation for the staking of NEAR tokens, a key innovation among PoS blockchain protocols.
How Smart Contract Based Delegation Enables More Open Finance Use Cases
One of the key features that NEAR offers which differentiates it from many Proof-of-Stake networks is contract-based delegation.
Other protocols typically implement delegation at the protocol level, meaning that it is exactly the same across all validators. Validators generally compete with each other purely based on what price they offer — for example, if the protocol is providing a 5% reward for validation, these validators may provide 4% of that as return to people who delegate to them and keep the 1% for themselves. This generally results in a price war where the only differentiation between validators is what return they offer and reputational factors like how many people already delegate to them. Also, custodial centralized exchanges frequently take a large fraction of the delegation market as they allow to offer additional financial instruments that regular validators can’t.
Because delegation in NEAR is done through smart contracts, it is far more flexible. Each validator could theoretically produce its own delegation contract or configure the parameters of a widely trusted contract to offer a broad range of services. For example, one validator might offer delegators a better return if they lock up their capital for a long period of time while another might offer better returns for larger size delegations.
This contract-based delegation makes it easier to pipe together Open Finance components, so you can imagine contracts which dynamically allocate delegators’ funds to lending protocols or validators depending on the prevailing interest rates and return in the market. Essentially, staking becomes a core component of the Open Finance ecosystem while still providing security to the system as intended.
How You Can Get Involved
We have something for everyone:
Join the NEAR Contributor Program to contribute to our engineering efforts.
You love hosting events, engaging communities, and creating content? Then head over to our Guild Program.
If you are in the process of setting up your own start-up in the Web3 space, the Open Web Collective will provide guidance.
If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, join the conversation on Discord, and subscribing to our newsletter to receive updates right to your inbox
|
```bash
near view nearweek-news-contribution.sputnik-dao.near get_proposals '{"from_index": 9262, "limit": 2}'
```
<details>
<summary>Example response</summary>
<p>
```bash
[
{
id: 9262,
proposer: 'pasternag.near',
description: 'NEAR, a top non-EVM blockchain, has gone live on Router’s Testnet Mandara. With Router Nitro, our flagship dApp, users in the NEAR ecosystem can now transfer test tokens to and from NEAR onto other supported chains. $$$$https://twitter.com/routerprotocol/status/1727732303491961232',
kind: {
Transfer: {
token_id: '',
receiver_id: 'pasternag.near',
amount: '500000000000000000000000',
msg: null
}
},
status: 'Approved',
vote_counts: { council: [ 1, 0, 0 ] },
votes: { 'brzk-93444.near': 'Approve' },
submission_time: '1700828277659425683'
},
{
id: 9263,
proposer: 'fittedn.near',
description: 'How to deploy BOS component$$$$https://twitter.com/BitkubAcademy/status/1728003163318563025?t=PiN6pwS380T1N4JuQXSONA&s=19',
kind: {
Transfer: {
token_id: '',
receiver_id: 'fittedn.near',
amount: '500000000000000000000000',
msg: null
}
},
status: 'InProgress',
vote_counts: { 'Whitelisted Members': [ 1, 0, 0 ] },
votes: { 'trendheo.near': 'Approve' },
submission_time: '1700832601849419123'
}
]
```
</p>
</details>
|
---
id: count-near
title: Count on NEAR
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
Our counter example is a friendly decentralized app that stores a number and exposes methods to `increment`,
`decrement`, and `reset` it.
![img](/docs/assets/examples/count-on-near-banner.png)
---
## Obtaining the Counter Example
You have two options to start the Counter Example.
1. You can use the app through `GitHub Codespaces`, which will open a web-based interactive environment.
2. Clone the repository locally and use it from your computer.
| Codespaces | Clone locally |
| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/near-examples/counters) | 🌐 `https://github.com/near-examples/counters` |
---
## Structure of the Example
The example is divided in two main components:
1. The smart contract, available in two flavors: Rust and JavaScript
2. The frontend, that interacts with an already deployed contract.
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
┌── sandbox-ts # sandbox testing
│ ├── src
│ │ └── main.ava.ts
│ ├── ava.config.cjs
│ └── package.json
├── src # contract's code
│ └── contract.ts
├── package.json # package manager
├── README.md
└── tsconfig.json # test script
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
┌── src # contract's code
│ └── lib.rs
├── tests # sandbox test
│ └── test_basics.rs
├── Cargo.toml # package manager
├── README.md
└── rust-toolchain.toml
```
</TabItem>
</Tabs>
---
## Frontend
The counter example includes a frontend interface designed to interact seamlessly with an existing smart contract that has been deployed. This interface allows users to increase or decrease the counter as needed.
<hr class="subsection" />
### Running the Frontend
To start the frontend you will need to install the dependencies and start the server.
```bash
cd frontend
yarn
yarn start
```
Go ahead and login with your NEAR account. If you don't have one, you will be able to create one in the moment. Once logged in, use the `+` and `-` buttons to increase and decrease the counter. Then, use the Gameboy buttons to reset it and make the counter blink an eye!
![img](/docs/assets/examples/count-on-near.png)
_Frontend of the Counter_
<hr class="subsection" />
### Understanding the Frontend
The frontend is composed by a single HTML file (`/index.html`). This file defines the components displayed in the screen.
The website's logic lives in `/index.js`, which communicates with the contract through `/near-wallet.js`. You will notice in `/index.js` the following code:
<CodeTabs>
<Language value="js" language="ts">
<Github fname="index.js"
url="https://github.com/near-examples/counters/blob/main/frontend/index.js"
start="10" end="21" />
</Language>
</CodeTabs>
It indicates our app, when it starts, to check if the user is already logged in and execute either `signedInFlow()` or `signedOutFlow()`.
---
## Smart Contract
The contract presents 4 methods: `get_num`, `increment`, `decrement`, and `reset`. The method `get_num` retrieves the current value, and the rest modify it.
<CodeTabs>
<Language value="js" language="ts">
<Github fname="contract.ts"
url="https://github.com/near-examples/counters/blob/main/contract-ts/src/contract.ts"
start="3" end="29" />
</Language>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/counters/blob/main/contract-rs/src/lib.rs"
start="5" end="37" />
</Language>
</CodeTabs>
---
### Testing the Contract
The contract readily includes a set of unit and sandbox testing to validate its functionality. To execute the tests, run the following commands:
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
cd contract-ts
yarn
yarn test
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
cd contract-rs
cargo test
```
</TabItem>
</Tabs>
:::tip
The `integration tests` use a sandbox to create NEAR users and simulate interactions with the contract.
:::
<hr class="subsection" />
### Deploying the Contract to the NEAR network
In order to deploy the contract you will need to create a NEAR account.
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
# Optional - create an account
near create-account <accountId> --useFaucet
# Deploy the contract
cd contract-ts
yarn build
near deploy <accountId> ./build/counter.wasm
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
# Optional - create an account
near create-account <accountId> --useFaucet
# Deploy the contract
cd contract-rs
cargo build
near deploy <accountId> ./target/wasm32-unknown-unknown/release/counter.wasm
```
</TabItem>
</Tabs>
:::tip
To interact with your contract from the [frontend](#frontend), simply replace the variable `CONTRACT_NAME` in the `index.js` file.
:::
<hr class="subsection" />
### CLI: Interacting with the Contract
To interact with the contract through the console, you can use the following commands
```bash
# Get the current number of the counter
near view counter.near-examples.testnet get_num
# Increment the counter
# Replace <accountId> with your account ID
near call counter.near-examples.testnet increment --accountId <accountId>
# Decrement the counter
# Replace <accountId> with your account ID
near call counter.near-examples.testnet decrement --accountId <accountId>
# Reset the counter to zero
# Replace <accountId> with your account ID
near call counter.near-examples.testnet reset --accountId <accountId>
```
:::tip
If you're using your own account, replace `counter.near-examples.testnet` with your `accountId`.
:::
---
## Moving Forward
A nice way to learn is by trying to expand the contract. Modify it by adding a parameter to `increment` and `decrement`,
so the user can choose by how much to change the value. For this, you will need to use knowledge from the [anatomy](../../2.build/2.smart-contracts/anatomy/anatomy.md)
and [storage](../../2.build/2.smart-contracts/anatomy/storage.md) sections.
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `4.0.13`
- node: `18.19.1`
- rustc: `1.77.0`
:::
|
NEAR Horizon and Outlier Ventures Create Base Camp Accelerator to Propel Web3 Startups
NEAR FOUNDATION
May 11, 2023
NEAR Horizon, NEAR Foundation’s new Web3 startup platform, is joining forces with Outlier Ventures to launch the NEAR Base Camp accelerator program, an initiative aimed at supporting startups building on the NEAR Blockchain Operating System (BOS). As a Web3 startup platform, NEAR Horizon aids founders and developers along their journey of building on NEAR with credits, partnerships, services, and additional resources.
Horizon’s goals include redefining the Web3 user experience to onboard one billion users into Web3 and leveraging the Blockchain Operating System to enable developers, communities, enterprises, and users to create a more open web. The 12-week NEAR Base Camp accelerator program offers participants mentorship, education, $100,000 in funding, and $20,000 in service credits on NEAR Horizon.
With NEAR Horizon and Outlier Ventures now teaming up via the Basecamp Accelerator, even more guidance and resources will become available to help NEAR builders, founders, and creators fulfill their ambitions.
A Web3 launchpad from NEAR Horizon and Outlier Ventures
Outlier Ventures supports a wide array of projects across DeFi, NFTs, blockchain infrastructure, and more, providing tailored mentorship, funding, and strategic guidance to help companies excel in the rapidly evolving Web3 market.
Founded in 2014, Outlier Ventures is a leading global Web3 accelerator, as well as a go-to authority in Web3 for founders, investors, and enterprises alike. Now the most active venture Web3 fund by volume, Outlier has over 200 startups across its Base Camp and Ascent programs.
Raising over $350 million in seed round funding for projects, Outlier has also helped billion dollar Web3 ecosystems like Boson Protocol, Fetch.ai, and Secret Network. Their bespoke programs conducted by a team of experts help projects refine product market fit, token design, and any other aspect critical to project adoption and development.
Outlier’s venture capital network will also provide an enormous boost to projects and founders participating in the NEAR Base Camp initiative.
The NEAR Horizon and Outlier Ventures collaboration represents a joint commitment to accelerate Web3 startups and foster innovation in the industry. By pooling their resources and expertise, both organizations aim to nurture exceptional talent within the ecosystem, driving Web3 innovation in an open, diverse, and socially impactful manner.
A closer look at the NEAR Base Camp accelerator program illuminates its unique focus and offerings, poised to shape the future of Web3 technology and user experience for startups within the ecosystem.
Fostering Web3 ingenuity with NEAR Base Camp
The NEAR Base Camp Accelerator Program harnesses the power of visionary founders who aim to scale and enhance usability in the Web3 space. The program centers on development in areas like application infrastructure for scalability, real-world use cases, bridging Web2 and Web3, and AI technology.
Base Camp offers tailored support for talented early-stage teams with real-world, utility-based use cases. It attracts Web2 users and companies while leveraging Web3 in novel ways to solve problems Web2 is unable to address.
Participants will enjoy added access to the NEAR Horizon platform and $20,000 service credits that can be utilized to cover costs across services like marketing, legal, finance, product development, and more. Horizon is built on the NEAR Blockchain Operating System (BOS) and includes 15+ service providers, 40 mentors, and 300+ backers.
On Base Camp, your Web3 adventure awaits
Founders interested in the NEAR Base Camp accelerator program can apply through Outlier Ventures’ website on the application page and through the NEAR Horizon platform. Applications open on May 11th, with the 12-week program scheduled to commence in mid-July.
Successful teams will receive support from Outlier Ventures and NEAR Ecosystem’s in-house experts on product roadmaps, community building, token economy and launches, fundraising and pitching, governance, and legal support, along with mentorship from industry-leading professionals.
Don’t miss this opportunity to participate in the NEAR Base Camp accelerator program, which aims to foster innovation and growth in the Web3 space.
Join NEAR Horizon here. Embark on your Web3 journey today by visiting the Outlier Ventures website to express your interest and apply for the Base Camp accelerator program. |
---
title: Essentials
description: A brief overview of some essential tools to get started with NEAR
sidebar_position: 5
---
# Essentials
----
:::info on this page
* Wallets
* Exploring the NEAR blockchain
* Development on NEAR
:::
There are a lot of ways to interact with both NEAR protocol and the NEAR token.
While the number of tools that can interface with NEAR for different use-cases is always growing, we're going to look at a short list of essential tools to help you start using NEAR.
In addition to the tools listed below, you can also find additional resource in the [support](/development/tools-infrastructure.md) section of this wiki
## NEAR Wallet
The [MyNEARWallet](https://app.mynearwallet.com/) serves as an entry-point to using NEAR.
It is a non-custodial, web-based wallet for the NEAR blockchain.
It allows you to send and receive NEAR, stake NEAR, and create NEARdrops to easily onboard new people on NEAR.
Check out our guide to [creating a NEAR wallet](overview/tokenomics/creating-a-near-wallet.md)
## NEAR Explorer
[NEAR Explorer](https://explorer.near.org/) is an online blockchain browser which displays information about nodes, blocks, addresses, and transactions on NEAR.
The NEAR Explorer gives you information about how many nodes are online, how many nodes are validating blocks, how much NEAR each node is staking, how many delegators they have, and what their fee is.
It also gives you a historical look at [statistics](https://explorer.near.org/stats) about the NEAR protocol.
You can find detailed information about the latest block, and the latest transaction.
Alternatively, you can search for a specific block hash, or transaction hash to find out more about them.
Additionally, you can search for a specific account address to find out more about it.
## Command Line Interface (CLI)
The [NEAR CLI](https://github.com/near/near-cli) is a Node.js command line interface that allows you to interface with the NEAR blockchain from the command line.
You can use it for more granular control over common NEAR functions including:
- Creating an account
- Starting transactions
- Deploying smart contracts
- Querying transactions
- Finding information about validators
For more information about the CLI, [check out our developer documentation](https://docs.near.org/tools/near-cli)
|
NEARCON Returns: Here’s Everything You Need to Know So Far
NEAR FOUNDATION
June 15, 2023
Last year’s NEARCON was epic. NEARCON 2023 will be iconic.
While all of you have been diligently building NEAR into one of the best ecosystems in the blockchain world, NEAR Foundation has been planning a 4-day journey into an open web.
Let’s take a quick look at everything we have to share (so far).
What to expect at NEARCON 2023
For this year’s NEARCON, we’re expanding. There will be two venues — NEARCON HQ and Hack HQ.
Most of the action will happen at NEARCON HQ. But if you’re a hacker, or just like hanging with them, you can do that at Hack HQ.
At NEARCON, you can expect to:
Join 5,000+ delegates as we explore the power and possibilities of an open web
Encounter a diverse melting pot of creators, builders, policy makers, and more — you’ll even find the rare thought leader in their natural environment
Get inspired by talks from renowned authors, economists, artists, politicians, VCS, developers, entrepreneurs, and more
Explore the Blockchain Operating System (BOS), try it for yourself, and find out why it’s the driving force behind an open web
Connect with projects, speakers, community members, builders, and multi-chain enthusiasts from around the world
Hack the days and nights away for a chance to build on the BOS and win $180+k
And experience so much more that you’ll be looking around and asking yourself, “What bear market?”
Get your early bird tickets now!
NEARCON 2023 tickets are $20 off until July 1. So, don’t wait — snag your ticket for $79 now because after July 1st they are $99.
NEAR Foundation is also offering another deal. If you refer 4 friends to NEARCON 2023, you will get a special gift upon check-in at the conference.
Become a Speaker or Sponsor
Thinking about becoming a NEARCON speaker? We’d love to hear from you.
Speaking spots always go fast, so make haste. Apply to speak at NEARCON here.
Psstt… we’re looking for technical applications that don’t just shill but highlight problems being solved — on the BOS and the wider open web.
Apply for the Hackathon and get in for free
NEAR and NEARCON loves its hackers. And to show it, we’ve made it so that any builder or developer who applies for the hackathon gets in for free.
Find more information about the NEARCON 2023 hackathon here. |
---
NEP: 145
Title: Storage Management
Author: Evgeny Kuzyakov <ek@near.org>, @oysterpack
DiscussionsTo: https://github.com/near/NEPs/discussions/145
Status: Final
Type: Standards Track
Category: Contract
Created: 03-Mar-2022
---
## Summary
NEAR uses [storage staking] which means that a contract account must have sufficient balance to cover all storage added over time. This standard provides a uniform way to pass storage costs onto users.
## Motivation
It allows accounts and contracts to:
1. Check an account's storage balance.
2. Determine the minimum storage needed to add account information such that the account can interact as expected with a contract.
3. Add storage balance for an account; either one's own or another.
4. Withdraw some storage deposit by removing associated account data from the contract and then making a call to remove unused deposit.
5. Unregister an account to recover full storage balance.
[storage staking]: https://docs.near.org/concepts/storage/storage-staking
## Rationale and alternatives
Prior art:
- A previous fungible token standard ([NEP-21](https://github.com/near/NEPs/pull/21)) highlighting how [storage was paid](https://github.com/near/near-sdk-rs/blob/1d3535bd131b68f97a216e643ad1cba19e16dddf/examples/fungible-token/src/lib.rs#L92-L113) for when increasing the allowance of an escrow system.
### Example scenarios
To show the flexibility and power of this standard, let's walk through two example contracts.
1. A simple Fungible Token contract which uses Storage Management in "registration only" mode, where the contract only adds storage on a user's first interaction.
1. Account registers self
2. Account registers another
3. Unnecessary attempt to re-register
4. Force-closure of account
5. Graceful closure of account
2. A social media contract, where users can add more data to the contract over time.
1. Account registers self with more than minimum required
2. Unnecessary attempt to re-register using `registration_only` param
3. Attempting to take action which exceeds paid-for storage; increasing storage deposit
4. Removing storage and reclaiming excess deposit
### Example 1: Fungible Token Contract
Imagine a [fungible token][FT Core] contract deployed at `ft`. Let's say this contract saves all user balances to a Map data structure internally, and adding a key for a new user requires 0.00235Ⓝ. This contract therefore uses the Storage Management standard to pass this cost onto users, so that a new user must effectively pay a registration fee to interact with this contract of 0.00235Ⓝ, or 2350000000000000000000 yoctoⓃ ([yocto](https://www.metricconversion.us/prefixes.htm) = 10<sup>-24</sup>).
For this contract, `storage_balance_bounds` will be:
```json
{
"min": "2350000000000000000000",
"max": "2350000000000000000000"
}
```
This means a user must deposit 0.00235Ⓝ to interact with this contract, and that attempts to deposit more than this will have no effect (attached deposits will be immediately refunded).
Let's follow two users, Alice with account `alice` and Bob with account `bob`, as they interact with `ft` through the following scenarios:
1. Alice registers herself
2. Alice registers Bob
3. Alice tries to register Bob again
4. Alice force-closes her account
5. Bob gracefully closes his account
#### 1. Account pays own registration fee
##### High-level explanation
1. Alice checks if she is registered with the `ft` contract.
2. Alice determines the needed registration fee to register with the `ft` contract.
3. Alice issues a transaction to deposit Ⓝ for her account.
##### Technical calls
1. Alice queries a view-only method to determine if she already has storage on this contract with `ft::storage_balance_of({"account_id": "alice"})`. Using [NEAR CLI](https://docs.near.org/tools/near-cli) to make this view call, the command would be:
```shell
near view ft storage_balance_of '{"account_id": "alice"}'
```
The response:
```shell
null
```
2. Alice uses [NEAR CLI](https://docs.near.org/docs/tools/near-cli) to make a view call.
```shell
near view ft storage_balance_bounds
```
As mentioned above, this will show that both `min` and `max` are both 2350000000000000000000 yoctoⓃ.
3. Alice converts this yoctoⓃ amount to 0.00235 Ⓝ, then calls `ft::storage_deposit` with this attached deposit. Using NEAR CLI:
```shell
near call ft storage_deposit '' --accountId alice --amount 0.00235
```
The result:
```json
{
"total": "2350000000000000000000",
"available": "0"
}
```
#### 2. Account pays for another account's storage
Alice wishes to eventually send `ft` tokens to Bob who is not registered. She decides to pay for Bob's storage.
##### High-level explanation
Alice issues a transaction to deposit Ⓝ for Bob's account.
##### Technical calls
Alice calls `ft::storage_deposit({"account_id": "bob"})` with the attached deposit of '0.00235'. Using NEAR CLI the command would be:
```shell
near call ft storage_deposit '{"account_id": "bob"}' --accountId alice --amount 0.00235
```
The result:
```json
{
"total": "2350000000000000000000",
"available": "0"
}
```
#### 3. Unnecessary attempt to register already-registered account
Alice accidentally makes the same call again, and even misses a leading zero in her deposit amount.
```shell
near call ft storage_deposit '{"account_id": "bob"}' --accountId alice --amount 0.0235
```
The result:
```json
{
"total": "2350000000000000000000",
"available": "0"
}
```
Additionally, Alice will be refunded the 0.0235Ⓝ she attached, because the `storage_deposit_bounds.max` specifies that Bob's account cannot have a total balance larger than 0.00235Ⓝ.
#### 4. Account force-closes registration
Alice decides she doesn't care about her `ft` tokens and wants to forcibly recover her registration fee. If the contract permits this operation, her remaining `ft` tokens will either be burned or transferred to another account, which she may or may not have the ability to specify prior to force-closing.
##### High-level explanation
Alice issues a transaction to unregister her account and recover the Ⓝ from her registration fee. She must attach 1 yoctoⓃ, expressed in Ⓝ as `.000000000000000000000001`.
##### Technical calls
Alice calls `ft::storage_unregister({"force": true})` with a 1 yoctoⓃ deposit. Using NEAR CLI the command would be:
```shell
near call ft storage_unregister '{ "force": true }' --accountId alice --depositYocto 1
```
The result:
```shell
true
```
#### 5. Account gracefully closes registration
Bob wants to close his account, but has a non-zero balance of `ft` tokens.
##### High-level explanation
1. Bob tries to gracefully close his account, calling `storage_unregister()` without specifying `force=true`. This results in an intelligible error that tells him why his account can't yet be unregistered gracefully.
2. Bob sends all of his `ft` tokens to a friend.
3. Bob retries to gracefully close his account. It works.
##### Technical calls
1. Bob calls `ft::storage_unregister()` with a 1 yoctoⓃ deposit. Using NEAR CLI the command would be:
```shell
near call ft storage_unregister '' --accountId bob --depositYocto 1
```
It fails with a message like "Cannot gracefully close account with positive remaining balance; bob has balance N"
2. Bob transfers his tokens to a friend using `ft_transfer` from the [Fungible Token Core][FT Core] standard.
3. Bob tries the call from Step 1 again. It works.
### Example 2: Social Media Contract
Imagine a social media smart contract which passes storage costs onto users for posts and follower data. Let's say this this contract is deployed at account `social`. Like the Fungible Token contract example above, the `storage_balance_bounds.min` is 0.00235, because this contract will likewise add a newly-registered user to an internal Map. However, this contract sets no `storage_balance_bounds.max`, since users can add more data to the contract over time and must cover the cost for this storage.
So for this contract, `storage_balance_bounds` will return:
```json
{
"min": "2350000000000000000000",
"max": null
}
```
Let's follow a user, Alice with account `alice`, as she interacts with `social` through the following scenarios:
1. Registration
2. Unnecessary attempt to re-register using `registration_only` param
3. Attempting to take action which exceeds paid-for storage; increasing storage deposit
4. Removing storage and reclaiming excess deposit
#### 1. Account registers with `social`
##### High-level explanation
Alice issues a transaction to deposit Ⓝ for her account. While the `storage_balance_bounds.min` for this contract is 0.00235Ⓝ, the frontend she uses suggests adding 0.1Ⓝ, so that she can immediately start adding data to the app, rather than _only_ registering.
##### Technical calls
Using NEAR CLI:
```shell
near call social storage_deposit '' --accountId alice --amount 0.1
```
The result:
```json
{
"total": "100000000000000000000000",
"available": "97650000000000000000000"
}
```
Here we see that she has deposited 0.1Ⓝ and that 0.00235 of it has been used to register her account, and is therefore locked by the contract. The rest is available to facilitate interaction with the contract, but could also be withdrawn by Alice by using `storage_withdraw`.
#### 2. Unnecessary attempt to re-register using `registration_only` param
##### High-level explanation
Alice can't remember if she already registered and re-sends the call, using the `registration_only` param to ensure she doesn't attach another 0.1Ⓝ.
##### Technical calls
Using NEAR CLI:
```shell
near call social storage_deposit '{"registration_only": true}' --accountId alice --amount 0.1
```
The result:
```json
{
"total": "100000000000000000000000",
"available": "97650000000000000000000"
}
```
Additionally, Alice will be refunded the extra 0.1Ⓝ that she just attached. This makes it easy for other contracts to always attempt to register users while performing batch transactions without worrying about errors or lost deposits.
Note that if Alice had not included `registration_only`, she would have ended up with a `total` of 0.2Ⓝ.
#### 3. Account increases storage deposit
Assumption: `social` has a `post` function which allows creating a new post with free-form text. Alice has used almost all of her available storage balance. She attempts to call `post` with a large amount of text, and the transaction aborts because she needs to pay for more storage first.
Note that applications will probably want to avoid this situation in the first place by prompting users to top up storage deposits sufficiently before available balance runs out.
##### High-level explanation
1. Alice issues a transaction, let's say `social.post`, and it fails with an intelligible error message to tell her that she has an insufficient storage balance to cover the cost of the operation
2. Alice issues a transaction to increase her storage balance
3. Alice retries the initial transaction and it succeeds
##### Technical calls
1. This is outside the scope of this spec, but let's say Alice calls `near call social post '{ "text": "very long message" }'`, and that this fails with a message saying something like "Insufficient storage deposit for transaction. Please call `storage_deposit` and attach at least 0.1 NEAR, then try again."
2. Alice deposits the proper amount in a transaction by calling `social::storage_deposit` with the attached deposit of '0.1'. Using NEAR CLI:
```shell
near call social storage_deposit '' --accountId alice --amount 0.1
```
The result:
```json
{
"total": "200000000000000000000000",
"available": "100100000000000000000000"
}
```
3. Alice tries the initial `near call social post` call again. It works.
#### 4. Removing storage and reclaiming excess deposit
Assumption: Alice has more deposited than she is using.
##### High-level explanation
1. Alice views her storage balance and sees that she has extra.
2. Alice withdraws her excess deposit.
##### Technical calls
1. Alice queries `social::storage_balance_of({ "account_id": "alice" })`. With NEAR CLI:
```shell
near view social storage_balance_of '{"account_id": "alice"}'
```
Response:
```json
{
"total": "200000000000000000000000",
"available": "100100000000000000000000"
}
```
2. Alice calls `storage_withdraw` with a 1 yoctoⓃ deposit. NEAR CLI command:
```shell
near call social storage_withdraw '{"amount": "100100000000000000000000"}' \
--accountId alice --depositYocto 1
```
Result:
```json
{
"total": "200000000000000000000000",
"available": "0"
}
```
## Specification
NOTES:
- All amounts, balances and allowance are limited by `U128` (max value 2<sup>128</sup> - 1).
- This storage standard uses JSON for serialization of arguments and results.
- Amounts in arguments and results are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of 2<sup>53</sup>.
- To prevent the deployed contract from being modified or deleted, it should not have any access keys on its account.
### Interface
```ts
// The structure that will be returned for the methods:
// * `storage_deposit`
// * `storage_withdraw`
// * `storage_balance_of`
// The `total` and `available` values are string representations of unsigned
// 128-bit integers showing the balance of a specific account in yoctoⓃ.
type StorageBalance = {
total: string;
available: string;
};
// The below structure will be returned for the method `storage_balance_bounds`.
// Both `min` and `max` are string representations of unsigned 128-bit integers.
//
// `min` is the amount of tokens required to start using this contract at all
// (eg to register with the contract). If a new contract user attaches `min`
// NEAR to a `storage_deposit` call, subsequent calls to `storage_balance_of`
// for this user must show their `total` equal to `min` and `available=0` .
//
// A contract may implement `max` equal to `min` if it only charges for initial
// registration, and does not adjust per-user storage over time. A contract
// which implements `max` must refund deposits that would increase a user's
// storage balance beyond this amount.
type StorageBalanceBounds = {
min: string;
max: string | null;
};
/************************************/
/* CHANGE METHODS on fungible token */
/************************************/
// Payable method that receives an attached deposit of Ⓝ for a given account.
//
// If `account_id` is omitted, the deposit MUST go toward predecessor account.
// If provided, deposit MUST go toward this account. If invalid, contract MUST
// panic.
//
// If `registration_only=true`, contract MUST refund above the minimum balance
// if the account wasn't registered and refund full deposit if already
// registered.
//
// The `storage_balance_of.total` + `attached_deposit` in excess of
// `storage_balance_bounds.max` must be refunded to predecessor account.
//
// Returns the StorageBalance structure showing updated balances.
function storage_deposit(
account_id: string | null,
registration_only: boolean | null
): StorageBalance {}
// Withdraw specified amount of available Ⓝ for predecessor account.
//
// This method is safe to call. It MUST NOT remove data.
//
// `amount` is sent as a string representing an unsigned 128-bit integer. If
// omitted, contract MUST refund full `available` balance. If `amount` exceeds
// predecessor account's available balance, contract MUST panic.
//
// If predecessor account not registered, contract MUST panic.
//
// MUST require exactly 1 yoctoNEAR attached balance to prevent restricted
// function-call access-key call (UX wallet security)
//
// Returns the StorageBalance structure showing updated balances.
function storage_withdraw(amount: string | null): StorageBalance {}
// Unregisters the predecessor account and returns the storage NEAR deposit.
//
// If the predecessor account is not registered, the function MUST return
// `false` without panic.
//
// If `force=true` the function SHOULD ignore existing account data, such as
// non-zero balances on an FT contract (that is, it should burn such balances),
// and close the account. Contract MAY panic if it doesn't support forced
// unregistration, or if it can't force unregister for the particular situation
// (example: too much data to delete at once).
//
// If `force=false` or `force` is omitted, the contract MUST panic if caller
// has existing account data, such as a positive registered balance (eg token
// holdings).
//
// MUST require exactly 1 yoctoNEAR attached balance to prevent restricted
// function-call access-key call (UX wallet security)
//
// Returns `true` iff the account was successfully unregistered.
// Returns `false` iff account was not registered before.
function storage_unregister(force: boolean | null): boolean {}
/****************/
/* VIEW METHODS */
/****************/
// Returns minimum and maximum allowed balance amounts to interact with this
// contract. See StorageBalanceBounds.
function storage_balance_bounds(): StorageBalanceBounds {}
// Returns the StorageBalance structure of the valid `account_id`
// provided. Must panic if `account_id` is invalid.
//
// If `account_id` is not registered, must return `null`.
function storage_balance_of(account_id: string): StorageBalance | null {}
```
## Reference Implementation
The `near-contract-standards` cargo package of the [Near Rust SDK](https://github.com/near/near-sdk-rs) contain the following implementations of NEP-145:
- [Minimum Viable Interface](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/storage_management/mod.rs#L20)
- [Implementation](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/storage_management/mod.rs)
## Drawbacks
- The idea may confuse contract developers at first until they understand how a system with storage staking works.
- Some folks in the community would rather see the storage deposit only done for the sender. That is, that no one else should be able to add storage for another user. This stance wasn't adopted in this standard, but others may have similar concerns in the future.
## Future possibilities
- Ideally, contracts will update available balance for all accounts every time the NEAR blockchain's configured storage-cost-per-byte is reduced. That they _must_ do so is not enforced by this current standard.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
[FT Core]: ../specs/Standards/Tokens/FungibleToken/Core.md
|
---
id: callbacks
title: Cross-Contract Calls
---
While writing cross-contract calls there is a significant aspect to keep in mind: all the calls are **independent** and **asynchronous**. In other words:
- The method in which you make the call and method for the callback are **independent**.
- Between the call and the callback, people could interact with the contract.
This has important implications on how you should handle the callbacks. Particularly:
1. Your callback method needs to be public, but you want to make sure only your contract can call it.
2. Make sure you don't leave the contract in a exploitable state between the call and the callback.
3. Manually rollback any changes to the state in the callback if the external call failed.
---
## Private Callbacks
In order for your contract to call itself when a cross-contract call is done, you need to make the callback method public. However, most of the times you would want it to be private. You can make it private while keeping it public by asserting that the `predecessor` is `current_account`. In rust this is done automatically by adding the `#[private]` decorator.
---
## User's Money
When a method panics, the money attached to that transaction returns to the `predecessor`. This means that, if you make a cross-contract call and it fails, then the money **returns to your contract**. If the money came from a user calling your contract, then you should transfer it back during the callback.
![img](https://miro.medium.com/max/1400/1*Hp4TOcaBqm9LS0wkgWw3nA.png)
*If the user attached money, we need to manually return it in the callback*
:::caution
Make sure you pass have enough GAS in the callback to make the transfer
:::
---
## Async Callbacks
Between a cross-contract call and its callback **any method of your contract can be executed**. Not taking this into account is one of the main sources of exploits. It is so common that it has its own name: reentrancy attacks.
Imagine that we develop a `deposit_and_stake` with the following **wrong logic**: (1) The user sends us money, (2) we add it to its balance, (3) we try to stake it in a validator, (4) if the staking fails, we remove the balance in the callback. Then, a user could schedule a call to withdraw between (2) and (4), and, if the staking failed, we would send money twice to the user.
![img](https://miro.medium.com/max/1400/1*VweWHQYGLBa70uceiWHLQA.png)
*Between a cross-contract call and the callback anything could happen*
Luckily for us the solution is rather simple. Instead of immediately adding the money to our user’s balance, we wait until the callback. There we check, and if the staking went well, then we add it to their balance.
![img](https://miro.medium.com/max/1400/1*o0YVDCp_7l-L3njJMGhU4w.png)
*Correct way to handle deposits in a cross-contract call* |
NEAR Announces $800 Million in Funding Initiatives To Support Ecosystem Growth
NEAR FOUNDATION
October 25, 2021
The NEAR ecosystem is announcing a monumental $800 million in funding initiatives targeted at accelerating growth.
The announcement, which includes the $350 million in funding announced by Proximity Labs last week – reported in Bloomberg – is designed to build on the momentum in the NEAR ecosystem over the last 12 months.
While NEAR is giving all communities access to this record amount of funding, it will be focusing on Decentralized Finance (DeFi) teams who are actively revolutionizing and reimagining the way we interact with money.
DeFi projects on NEAR have already hit a significant milestone of more than $150M Total Value Locked (TVL). NEAR has an ambitious goal to grow that number quickly and securely. NEAR is also actively looking for projects focused on NFTs, DAOs, and gaming.
NEAR’s next chapter is all about fostering growth by helping developers access best-in-class support and providing users with a frictionless experience using and navigating the web3 world. New funding helps accelerate this process.
NEAR levels up
Of the $800 million in funding, $100 million will be allocated to Startup Grant Pools. More than 20 startups will be identified and given $5M each in funding to redistribute to key stakeholders – the ecosystem ultimately decides who gets funding.
Some $250 million will be allocated to ecosystem grants helping existing projects further develop and scale. The remaining $100M will be allocated to Regional Funds: money allocated to foster the development of NEAR’s largest community regions in Asia, Europe, and the US.
Prior to this announcement, NEAR had already spent $45M across more than 120 projects, including Core Protocol Infrastructure Grants to the likes of:
Textile
Liquality
CronCat
Kurtosis
The Grain Programming Language
The sleeping giant awakes
NEAR has been building on its roadmap steadily and securely. Later this year, it will launch the next phase sharding, nicknamed Simple Nightshade. NEAR will go from one to four shards, increasing scalability while not compromising on simplicity. Developers won’t have to add any additional code to smart contracts or adjust their platforms and users will continue to experience the same great UX, but at faster speeds.
Once complete, NEAR will be decentralizing further by lowering the barrier to entry to its validator network, increasing the number of validators first to 100, and then to a few hundred in Q1 2022. As part of this process, there will be further funding to projects helping the rollout and development of NEAR’s sharding technology.
Stay tuned for more information. |
---
title: Contact Us
description: How to contact humans working on NEAR.
sidebar_position: 4
---
NEAR is primarily community centered, so the best way to contact somebody with knowledge about NEAR when you have questions or suggestions is within the NEAR community:
- [Discord](https://discord.com/invite/UY9Xf2k)
- [Telegram](https://t.me/cryptonear)
- [NEAR Forum](https://gov.near.org/)
Alternatively, if you need to contact somebody at NEAR Foundation and the community links above weren't helpful you drop us an [email](mailto:hello@near.foundation).
If you are encountering issues with your wallet, you can open a [support ticket here](https://nearhelp.zendesk.com/hc/en-us).
**NEAR Foundation Address**
NEAR Foundation
Chamerstrasse 12C
6300 Zug
|
---
id: minting
title: Minting
sidebar_label: Minting
---
import {Github} from "@site/src/components/codetabs"
This is the first of many tutorials in a series where you'll be creating a complete NFT smart contract from scratch that conforms with all the NEAR [NFT standards](https://nomicon.io/Standards/NonFungibleToken/). Today you'll learn how to create the logic needed to mint NFTs and have them show up in your NEAR wallet. You will be modifying a bare-bones [skeleton smart contract](/tutorials/nfts/js/skeleton) by filling in the necessary code snippets needed to add minting functionalities.
## Introduction
To get started, switch to the `1.skeleton` branch in our repo. If you haven't cloned the repository, refer to the [Contract Architecture](/tutorials/nfts/js/skeleton) to get started.
```
git checkout 1.skeleton
```
If you wish to see the finished code for the minting portion of the tutorial, that can be found on the `2.minting` branch.
## Modifications to the skeleton contract {#what-does-minting-mean}
In order to implement the logic needed for minting, we should break it up into smaller tasks and handle those one-by-one. Let's step back and think about the best way to do this by asking ourselves a simple question: what does it mean to mint an NFT?
To mint a non-fungible token, in the most simple way possible, a contract needs to be able to associate a token with an owner on the blockchain. This means you'll need:
- A way to keep track of tokens and other information on the contract.
- A way to store information for each token such as `metadata` (more on that later).
- A way to link a token with an owner.
That's it! We've now broken down the larger problem into some smaller, less daunting, subtasks. Let's start by tackling the first and work our way through the rest.
### Storing information on the contract {#storing-information}
Start by navigating to `nft-contract/src/index.ts` and filling in some of the code blocks.
You need to be able to store important information on the contract such as the list of tokens that an account has.
The first thing to do is add the information to the contract class.
<Github language="js" start="16" end="22" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/index.ts" />
This allows you to get the information stored in these data structures from anywhere in the contract. The code above has created 3 token specific storages:
- **tokensPerOwner**: allows you to keep track of the tokens owned by any account. It will map the account address to a set of token ID strings owned by that account.
- **tokensById**: returns all the information about a specific token. It will map a token ID string to a `Token` object.
- **tokenMetadataById**: returns just the metadata for a specific token. It wil map a token ID string to a `TokenMetadata` object.
In addition, you'll keep track of the owner of the contract as well as the metadata for the contract.
#### Constructor Function
Next, you'll add the logic to the constructor function. This function needs to be invoked when you first deploy the contract. It will initialize all the contract's fields that you've defined above with default values.
We've added the `ownerId` and `metadata` fields as parameters to the function because those are the only ones that can be customized.
This function will default all the collections to be empty and set the `owner` and `metadata` equal to what you pass in.
<Github language="js" start="24" end="43" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/index.ts" />
More often than not when doing development, you'll need to deploy contracts several times. You can imagine that it might get tedious to have to pass in metadata every single time you want to initialize the contract. For this reason, the metadata has been defaulted with some initial data if it wasn't passed in by the user.
### Metadata and token information {#metadata-and-token-info}
Now that you've defined what information to store on the contract itself and you've defined some ways to initialize the contract, you need to define what information should go in the `Token`, `TokenMetadata`, and `NFTContractMetadata` data types.
Let's switch over to the `nft-contract/src/metadata.ts` file as this is where that information will go. If you look at the [standards for metadata](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata), you'll find all the necessary information that you need to store for both `TokenMetadata` and `NFTContractMetadata`. Simply fill in the following code.
<Github language="js" start="12" end="104" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/metadata.ts" />
This now leaves you with the `Token` struct and something called a `JsonToken`. The `Token` struct will hold all the information directly related to the token excluding the metadata. The metadata, if you remember, is stored in a map on the contract in a data structured called `tokenMetadataById`. This allows you to quickly get the metadata for any token by simply passing in the token's ID.
For the `Token` struct, you'll just keep track of the owner for now.
<Github language="js" start="106" end="117" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/metadata.ts" />
The purpose of the `JsonToken` is to hold all the information for an NFT that you want to send back as JSON whenever someone does a view call. This means you'll want to store the owner, token ID, and metadata.
<Github language="js" start="119" end="141" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/metadata.ts" />
:::tip
Some of you might be thinking _"how come we don't just store all the information in the `Token` struct?"_.
The reason behind this is that it's actually more efficient to construct the JSON token on the fly only when you need it rather than storing all the information in the token struct.
In addition, some operations might only need the metadata for a token and so having the metadata in a separate data structure is more optimal.
:::
#### Function for querying contract metadata
Now that you've defined some of the types that were used in the previous section, let's move on and create the first view function `internalNftMetadata`. This will allow users to query for the contract's metadata as per the [metadata standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata).
<Github language="js" start="143" end="150" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/metadata.ts" />
This function will get the `metadata` object from the contract which is of type `NFTContractMetadata` and will return it.
Just like that, you've completed the first two tasks and are ready to move onto last part of the tutorial.
### Minting Logic {#minting-logic}
Now that all the information and types are defined, let's start brainstorming how the minting logic will play out. In the end, you need to link a `Token` and `TokenId` to a specific owner. Let's look back at a couple data structures that might be useful:
```ts
//keeps track of all the token IDs for a given account
tokensPerOwner: LookupMap<AccountId, UnorderedSet<TokenId>>;
//keeps track of the token struct for a given token ID
tokensById: LookupMap<TokenId, Token>;
//keeps track of the token metadata for a given token ID
tokenMetadataById: UnorderedMap<TokenId, TokenMetadata>;
```
Looking at these data structures, you could do the following:
- Add the token ID into the set of tokens that the receiver owns. This will be done on the `tokensPerOwner` field.
- Create a token object and map the token ID to that token object in the `tokensById` field.
- Map the token ID to it's metadata using the `tokenMetadataById`.
With those steps outlined, it's important to take into consideration the storage costs of minting NFTs. Since you're adding bytes to the contract by creating entries in the data structures, the contract needs to cover the storage costs. If you just made it so any user could go and mint an NFT for free, that system could easily be abused and users could essentially "drain" the contract of all it's funds by minting thousands of NFTs. For this reason, you'll make it so that users need to attach a deposit to the call to cover the cost of storage. You'll measure the initial storage usage before anything was added and you'll measure the final storage usage after all the logic is finished. Then you'll make sure that the user has attached enough $NEAR to cover that cost and refund them if they've attached too much.
Now that you've got a good understanding of how everything should play out, let's fill in the necessary code.
<Github language="js" start="7" end="44" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/mint.ts" />
You'll notice that we're using some internal methods such as `refundDeposit` and `internalAddTokenToOwner`. We've described the function of `refundDeposit` and as for `internalAddTokenToOwner`, this will add a token to the set of tokens an account owns for the contract's `tokensPerOwner` data structure. You can create these functions in a file called `internal.ts`. Go ahead and create the file. Your new contract architecture should look as follows:
```
nft-contract
└── src
├── approval.ts
├── enumeration.ts
├── internal.ts
├── lib.ts
├── metadata.ts
├── mint.ts
├── nft_core.ts
└── royalty.ts
```
Add the following to your newly created `internal.ts` file.
<Github language="js" start="1" end="54" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/internal.ts" />
At this point, the core logic is all in place so that you can mint NFTs. You can use the function `nft_mint` which takes the following parameters:
- **token_id**: the ID of the token you're minting (as a string).
- **metadata**: the metadata for the token that you're minting (of type `TokenMetadata` which is found in the `metadata.ts` file).
- **receiver_id**: specifies who the owner of the token will be.
Behind the scenes, the function will:
1. Call the internal mint function.
2. Calculate the initial storage before adding anything to the contract
3. Create a `Token` object with the owner ID
4. Link the token ID to the newly created token object by inserting them into the `tokensById` field.
5. Link the token ID to the passed in metadata by inserting them into the `tokenMetadataById` field.
6. Add the token ID to the list of tokens that the owner owns by calling the `internalAddTokenToOwner` function.
7. Calculate the final and net storage to make sure that the user has attached enough NEAR to the call in order to cover those costs.
### Querying for token information
If you were to go ahead and deploy this contract, initialize it, and mint an NFT, you would have no way of knowing or querying for the information about the token you just minted. Let's quickly add a way to query for the information of a specific NFT. You'll move to the `nft-contract/src/nft_core.ts` file and edit the `internalNftToken` function.
It will take a token ID as a parameter and return the information for that token. The `JsonToken` contains the token ID, the owner ID, and the token's metadata.
<Github language="js" start="10" end="35" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/nft_core.ts" />
With that finished, it's finally time to build and deploy the contract so you can mint your first NFT.
## Interacting with the contract on-chain
Now that the logic for minting is complete and you've added a way to query for information about specific tokens, it's time to build and deploy your contract to the blockchain.
### Deploying the contract {#deploy-the-contract}
We've included a very simple way to build the smart contracts throughout this tutorial using `yarn`. The following command will build the contract and copy over the `.wasm` file to a folder `build/nft.wasm`.
```bash
yarn build:nft
```
For deployment, you will need a NEAR account with the keys stored on your local machine. Navigate to the [NEAR wallet](https://testnet.mynearwallet.com//) site and create an account.
:::info
Please ensure that you deploy the contract to an account with no pre-existing contracts. It's easiest to simply create a new account or create a sub-account for this tutorial.
:::
Log in to your newly created account with `near-cli` by running the following command in your terminal.
```bash
near login
```
To make this tutorial easier to copy/paste, we're going to set an environment variable for your account ID. In the command below, replace `YOUR_ACCOUNT_NAME` with the account name you just logged in with including the `.testnet` portion:
```bash
export NFT_CONTRACT_ID="YOUR_ACCOUNT_NAME"
```
Test that the environment variable is set correctly by running:
```bash
echo $NFT_CONTRACT_ID
```
Verify that the correct account ID is printed in the terminal. If everything looks correct you can now deploy your contract.
In the root of your NFT project run the following command to deploy your smart contract.
```bash
near deploy --wasmFile build/nft.wasm --accountId $NFT_CONTRACT_ID
```
At this point, the contract should have been deployed to your account and you're ready to move onto testing and minting NFTs.
### Initializing the contract {#initialize-contract}
The very first thing you need to do once the contract has been deployed is to initialize it. For simplicity, let's call the default metadata initialization function you wrote earlier so that you don't have to type the metadata manually in the CLI.
```bash
near call $NFT_CONTRACT_ID init '{"owner_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID
```
You've just initialized the contract with some default metadata and set your account ID as the owner. At this point, you're ready to call your first view function.
### Viewing the contract's metadata
Now that the contract has been initialized, you can call some of the functions you wrote earlier. More specifically, let's test out the function that returns the contract's metadata:
```bash
near view $NFT_CONTRACT_ID nft_metadata
```
This should return an output similar to the following:
```bash
{ spec: 'nft-1.0.0', name: 'NFT Tutorial Contract', symbol: 'GOTEAM' }
```
At this point, you're ready to move on and mint your first NFT.
### Minting our first NFT {#minting-our-first-nft}
Let's now call the minting function that you've created. This requires a `token_id` and `metadata`. If you look back at the `TokenMetadata` struct you created earlier, there are many fields that could potentially be stored on-chain:
<Github language="js" start="91" end="102" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/metadata.ts" />
Let's mint an NFT with a title, description, and media to start. The media field can be any URL pointing to a media file. We've got an excellent GIF to mint but if you'd like to mint a custom NFT, simply replace our media link with one of your choosing. If you run the following command, it will mint an NFT with the following parameters:
- **token_id**: "token-1"
- **metadata**:
- _title_: "My Non Fungible Team Token"
- _description_: "The Team Most Certainly Goes :)"
- _media_: `https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif`
- **receiver_id**: "'$NFT_CONTRACT_ID'"
```bash
near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-1", "metadata": {"title": "My Non Fungible Team Token", "description": "The Team Most Certainly Goes :)", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID --amount 0.1
```
:::info
The `amount` flag is specifying how much NEAR to attach to the call. Since you need to pay for storage, 0.1 NEAR is attached and you'll get refunded any excess that is unused at the end.
:::
### Viewing information about the NFT
Now that the NFT has been minted, you can check and see if everything went correctly by calling the `nft_token` function.
This should return a `JsonToken` which should contain the `token_id`, `owner_id`, and `metadata`.
```bash
near view $NFT_CONTRACT_ID nft_token '{"token_id": "token-1"}'
```
<details>
<summary>Example response: </summary>
<p>
```bash
{
token_id: 'token-1',
owner_id: 'goteam.examples.testnet',
metadata: {
title: 'My Non Fungible Team Token',
description: 'The Team Most Certainly Goes :)',
media: 'https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif'
}
}
```
</p>
</details>
**Go team!** You've now verified that everything works correctly and it's time to view your freshly minted NFT in the NEAR wallet's collectibles tab!
## Viewing your NFTs in the wallet
If you navigate to the [collectibles tab](https://testnet.mynearwallet.com//?tab=collectibles) in the NEAR wallet, this should list all the NFTs that you own. Currently, It should be empty.
We've got a problem. The wallet correctly picked up that you minted an NFT, however, the contract doesn't implement the specific view function that is being called. Behind the scenes, the wallet is trying to call `nft_tokens_for_owner` to get a list of all the NFTs owned by your account on the contract. The only function you've created, however, is the `nft_token` function. It wouldn't be very efficient for the wallet to call `nft_token` for every single NFT that a user has to get information and so they try to call the `nft_tokens_for_owner` function instead.
In the next tutorial, you'll learn about how to deploy a patch fix to a pre-existing contract so that you can view the NFT in the wallet.
## Conclusion
In this tutorial, you went through the basics of setting up and understand the logic behind minting NFTs on the blockchain using a skeleton contract.
You first looked at [what it means](#what-does-minting-mean) to mint NFTs and how to break down the problem into more feasible chunks. You then started modifying the skeleton contract chunk by chunk starting with solving the problem of [storing information / state](#storing-information) on the contract. You then looked at what to put in the [metadata and token information](#metadata-and-token-info). Finally, you looked at the logic necessary for [minting NFTs](#minting-logic).
After the contract was written, it was time to deploy to the blockchain. You [deployed the contract](#deploy-the-contract) and [initialized it](#initialize-contract). Finally, you [minted your very first NFT](#minting-our-first-nft) and saw that some changes are needed before you can view it in the wallet.
## Next Steps
In the [next tutorial](/tutorials/nfts/js/upgrade-contract), you'll find out how to deploy a patch fix and what that means so that you can view your NFTs in the wallet.
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `3.0.0`
- NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0`
- Metadata standard: [NEP177](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata), version `2.1.0`
:::
|
---
NEP: 0
Title: NEP Template
Authors: Todd Codrington III <satoshi@fakenews.org>
Status: Approved
DiscussionsTo: https://github.com/nearprotocol/neps/pull/0000
Type: Developer Tools
Version: 1.1.0
Created: 2022-03-03
LastUpdated: 2023-03-07
---
[This is a NEP (NEAR Enhancement Proposal) template, as described in [NEP-0001](https://github.com/near/NEPs/blob/master/neps/nep-0001.md). Use this when creating a new NEP. The author should delete or replace all the comments or commented brackets when merging their NEP.]
<!-- NEP Header Preamble
Each NEP must begin with an RFC 822 style header preamble. The headers must appear in the following order:
NEP: The NEP title in no more than 4-5 words.
Title: NEP title
Author: List of author name(s) and optional contact info. Examples FirstName LastName <satoshi@fakenews.org>, FirstName LastName (@GitHubUserName)>
Status: The NEP status -- New | Approved | Deprecated.
DiscussionsTo (Optional): URL of current canonical discussion thread, e.g. GitHub Pull Request link.
Type: The NEP type -- Protocol | Contract Standard | Wallet Standard | DevTools Standard.
Requires (Optional): NEPs may have a Requires header, indicating the NEP numbers that this NEP depends on.
Replaces (Optional): A newer NEP marked with a SupercededBy header must have a Replaces header containing the number of the NEP that it rendered obsolete.
SupersededBy (Optional): NEPs may also have a SupersededBy header indicating that a NEP has been rendered obsolete by a later document; the value is the number of the NEP that replaces the current document.
Version: The version number. A new NEP should start with 1.0.0, and future NEP Extensions must follow Semantic Versioning.
Created: The Created header records the date that the NEP was assigned a number, should be in ISO 8601 yyyy-mm-dd format, e.g. 2022-12-31.
LastUpdated: The Created header records the date that the NEP was assigned a number, should be in ISO 8601 yyyy-mm-dd format, e.g. 2022-12-31.
See example above -->
## Summary
[Provide a short human-readable (~200 words) description of the proposal. A reader should get from this section a high-level understanding about the issue this NEP is addressing.]
## Motivation
[Explain why this proposal is necessary, how it will benefit the NEAR protocol or community, and what problems it solves. Also describe why the existing protocol specification is inadequate to address the problem that this NEP solves, and what potential use cases or outcomes.]
## Specification
[Explain the proposal as if you were teaching it to another developer. This generally means describing the syntax and semantics, naming new concepts, and providing clear examples. The specification needs to include sufficient detail to allow interoperable implementations getting built by following only the provided specification. In cases where it is infeasible to specify all implementation details upfront, broadly describe what they are.]
## Reference Implementation
[This technical section is required for Protocol proposals but optional for other categories. A draft implementation should demonstrate a minimal implementation that assists in understanding or implementing this proposal. Explain the design in sufficient detail that:
* Its interaction with other features is clear.
* Where possible, include a Minimum Viable Interface subsection expressing the required behavior and types in a target programming language. (ie. traits and structs for rust, interfaces and classes for javascript, function signatures and structs for c, etc.)
* It is reasonably clear how the feature would be implemented.
* Corner cases are dissected by example.
* For protocol changes: A link to a draft PR on nearcore that shows how it can be integrated in the current code. It should at least solve the key technical challenges.
The section should return to the examples given in the previous section, and explain more fully how the detailed proposal makes those examples work.]
## Security Implications
[Explicitly outline any security concerns in relation to the NEP, and potential ways to resolve or mitigate them. At the very least, well-known relevant threats must be covered, e.g. person-in-the-middle, double-spend, XSS, CSRF, etc.]
## Alternatives
[Explain any alternative designs that were considered and the rationale for not choosing them. Why your design is superior?]
## Future possibilities
[Describe any natural extensions and evolutions to the NEP proposal, and how they would impact the project. Use this section as a tool to help fully consider all possible interactions with the project in your proposal. This is also a good place to "dump ideas"; if they are out of scope for the NEP but otherwise related. Note that having something written down in the future-possibilities section is not a reason to accept the current or a future NEP. Such notes should be in the section on motivation or rationale in this or subsequent NEPs. The section merely provides additional information.]
## Consequences
[This section describes the consequences, after applying the decision. All consequences should be summarized here, not just the "positive" ones. Record any concerns raised throughout the NEP discussion.]
### Positive
* p1
### Neutral
* n1
### Negative
* n1
### Backwards Compatibility
[All NEPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. Author must explain a proposes to deal with these incompatibilities. Submissions without a sufficient backwards compatibility treatise may be rejected outright.]
## Unresolved Issues (Optional)
[Explain any issues that warrant further discussion. Considerations
* What parts of the design do you expect to resolve through the NEP process before this gets merged?
* What parts of the design do you expect to resolve through the implementation of this feature before stabilization?
* What related issues do you consider out of scope for this NEP that could be addressed in the future independently of the solution that comes out of this NEP?]
## Changelog
[The changelog section provides historical context for how the NEP developed over time. Initial NEP submission should start with version 1.0.0, and all subsequent NEP extensions must follow [Semantic Versioning](https://semver.org/). Every version should have the benefits and concerns raised during the review. The author does not need to fill out this section for the initial draft. Instead, the assigned reviewers (Subject Matter Experts) should create the first version during the first technical review. After the final public call, the author should then finalize the last version of the decision context.]
### 1.0.0 - Initial Version
> Placeholder for the context about when and who approved this NEP version.
#### Benefits
> List of benefits filled by the Subject Matter Experts while reviewing this version:
* Benefit 1
* Benefit 2
#### Concerns
> Template for Subject Matter Experts review for this version:
> Status: New | Ongoing | Resolved
| # | Concern | Resolution | Status |
| --: | :------ | :--------- | -----: |
| 1 | | | |
| 2 | | | |
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
|
```js
const nftTokenId = "1";
Near.call([{
contractName: nftContract,
methodName: 'nft_transfer_call',
args: {
receiver_id: keypomContract,
token_id: nftTokenId,
msg: dropId.toString()
},
deposit: "1",
gas: "300000000000000"
}]);
``` |
Architecture of a distributed music streaming application
COMMUNITY
April 10, 2020
In our Reddit/r/NEARProtocol AMA with Audius’s CEO on April 10th, 2020, we will discuss the opportunities for musicians to monetize on blockchain applications better.
Disclaimer: Audius is not built using NEARProtocol. Our discussion is in the spirit of support to our musicians.
Introduction
Right now, most of the profits in the music industry are going to music labels. Musicians are left with 12% of total profits. Historically, music labels have existed for two reasons: music production and music distribution. Both have changed dramatically in recent times. The cost of producing an album was as high as $1m during the 1980s but has been drastically reduced to only $10k per album. As a result, many musicians are choosing the route of DIY publishing which allows them to skip the label.
Music distribution was usually facilitated via music labels working directly with physical stores and PR to push their music to customers. This dramatically changed with the advent of the Internet, which allows anyone to upload their music. However, the increased accessibility also makes it more difficult for artists to get discovered. Spotify, which provides distribution for labels in the online realm, primarily serves the interest of labels. For every million streams, a band only receives $6,000. Additionally, labels are still in control over what people see since social sharing is limited.
Can we create a place that serves both as a place to discover new music while at the same time changes the economy behind the content? If yes, where do we start?
Solution
We should be able to provide something valuable to musicians upfront and enable economics for the service later.
For example, a decentralized content platform would allow musicians to share re-used work of other musicians.
Even though music labels wouldn’t be on board with such a platform, it would provide much value for musicians since it will be the only service of it’s kind on the Internet.
Such a prototype should be able to do the following:
Store music on decentralized storage nodes
Have a record of all of the listens, likes, shares, and other engagement metrics, so everything is tracked
As the economy is enabled on top of this service later, it will be easy to attribute payouts
Allow people to share the music with each other
Why Blockchain?
The metadata attribution remains safe, verifiable, and immutable due to the decentralization of the network. Blockchain technology ensures that artists get paid safely and instantly as consumers listen to content. Blockchain also allows them to digitize music licenses in the form of a smart contract. |
NEAR Foundation Funding Team Report: September 2022
NEAR FOUNDATION
November 18, 2022
Welcome to the NEAR Foundation Funding Team Report that captures and highlights data for the month of September 2022. The purpose of this document is to provide transparency regarding what happened during the last month in our Funding Team, and is to be shared publicly to the ecosystem and our investor network.
Summary
1. Grant data
1.2. Approved Grant program data
1.2. Grant highlights
1.3 Completed Projects & Milestone data
1.4 Effectiveness of the funding program
2. External funding in the NEAR Ecosystem
3. Ecosystem highlights
1. Grant data
1.1. Approved Grant Program data
Data reflects projects that have applied for a Grant via the Grants Program and that have been signed by the NEAR Foundation during the month of September (01.09.2022 to 30.09.2022).
*Note: all applications have been processed.
General Grant data
Applications received* 📥 Grant Agreements signed ✅ Conversion rate Average Grant amount Committed amount in dollars 💵
139 25 17% $78 K $1.9 M
Grant tracks**
Activation (up to $10 K) 5
Small Builder (up to $25 K) 4
Builder (up to $50 K) 11
Advanced Builder (up to $100 K) 4
Partner ($ ∞) 2
** Please note that our current grant tracks have been updated. For more information please have a look at our updated grant tracks.
Grants per category
Gaming / Metaverse – 7
Infrastructure / Wallets – 6
NFTs – 4
Other – 4
Social Impact – 2
Institutional / Financial – 2
Grants per country (Top 5)
United States – 8
United Kingdom – 2
Switzerland – 2
Malaysia – 2
Ukraine – 1
1.2. Grant highlights
This section provides highlights of grants that have been signed during the month.
Gaming / Metaverse projects
Name Website Grant track Location
Arcnes website Advanced Builder Poland
Bonuz website Advanced Builder Dubai
Arhead website Builder United Arab Emirates
Bearverse website Builder United States
Gameplace by ZomboDucks website Builder Israel
Joystick website Small Builder Nigeria
Open character creator website Activation United States
Infrastructure / Wallets projects
Name Website Grant track Location
OnMachina website Partner United States
Meteor Wallet website Builder Malaysia
Verisoul website Builder United States
near.js – / Small Builder Ukraine
Java-SDK part 3 website Small Builder Switzerland
Tonana Bridge & Connectors website Activation Czech Republic
Institutional / Financial projects
Name Website Grant track Location
Defolio / Partner United Kingdom
Near Access / Activation United States
Social Impact projects
Name Website Grant track Location
BeeTogether website Builder Switzerland
GRVTY website Builder United Kingdom
NFT’s projects
Name Website Grant track Location
NEAR NFT DAO website Builder United States
Naksh website Small Builder India
3six9 NFT Marketplace website Activation Malaysia
Solar Dex website Activation United States
Other projects
Name Website Grant track Location
Three0 website Builder United States
NextHollywood website Builder United States
Crowdclass website Builder Portugal
Alpha Leaks / Activation Australia
1.3 Completed Projects & Milestone data
Grant agreements are structured with milestones. Depending on the selected grant track, a grant can have from 1 to 5 milestones. For more information the funding team invites you to explore our milestone guide.
Projects having completed a milestone ☑️ 61
Projects having completed final milestone ✅ 13
Projects completed per category
Gaming / Metaverse – 1
Infrastructure / Wallets – 5
NFTs – 1
DAOs – 3
Other – 3
Gaming / Metaverse
Alien Esports Industry website Builder United States
Alien Esports Industry is a platform to hold esports tournaments with integrated game mechanics that provide unique opportunities to gamers.
Infrastructure / Wallets
Kuutamo website Advanced Builder Denmark
Kuutamo is building out an enterprise-grade staking node management and reporting system dedicated to support NEAR and NEAR-affiliated networks. Kuutamo will provide practical tooling to enable individuals and organizations to operate secure, honest, and profitable validators in a straightforward way.
Blockperks website Advanced Builder United Kingdom
Blockperks is building a complete Web3 infrastructure and NFT marketplace for brands, artists, and creators to successfully bridge from Web2 to Web3 with NEAR. Blockperks provides the platform architecture and an adaptive social media dApp so that organizations, clients, and end-users can easily onboard and tokenize assets through the creating and trading of NFT’s.
Solace Protocol website Activation India
Solace is a program (smart-contract) based non-custodial wallet for NEAR which eases user’s onboarding and enhances security using social recovery, written in Rust.
Emblem Vault website Builder United States
Emblem Vault is an application that collects the value of a portfolio within a token, you can also add non-blockchain assets to the portfolio.
Java SDK – Part 3 website Small Builder Switzerland
From the team who delivered the Java-API part 1/2 and that took over the Borshj for maintenance. This time they would like to further enhance the Java API and implement services to create accounts, manage additional reward structure, and call other smart contracts methods.
NFTs
NFT Marketplace for Science IPs website Advanced Builder United States
NFT Marketplace for Science IPs is building a NFT marketplace for science IPs on top of our data & AI ecosystem platform, for which the project innovates with smart contracts for best services to scientists worldwide.
DAOs
Deep Skills website Builder British Virgin Islands
Deep Skills aims to diverse options of how current organizations recruit, educate, and coordinate talented individuals.
Gyde website Builder United States
Gyde connects users with helping services that they are looking for. The DAO provides incentives via a token to allocate to reviewers on the platform. The DAO also acts as a data provider selling to governments and think tanks driving incentives for power users.
NEAR Alexandria github Builder Brazil
NEAR Alexandria Is building the largest virtual library for NEAR content and academic content. The team will use metabuilders, meta designers, NEAR DAO council members and academics to build the virtual building, the objects, and the links from all the real books, papers, articles and texts in general that will be in the library.
Other
Vital Point AI website Builder Canada
Vital Point AI is focused on open-source blockchain development using NEAR Protocol. With a proven record of delivering quality tutorials and dedication to the NEAR ecosystem, helping scale Vital Point Academy will benefit NEAR and the ecosystem in various ways.
Aerx website Builder Russia
A decentralized modular social network where any user can own their content according to the create2eart principle.
NEAR NYC website Builder United States
NEAR NYC is a dedicated NEAR community in NYC that will scale NEAR awareness and education by organizing bi-weekly meetups, managing localized social media accounts (Twitter, Telegram, Instagram, Meetup, Eventbrite), establish partnerships with community leaders, and organizing a NEAR NYC hacker house.
1.4 Effectiveness of the funding program
Total external funding (overall amount) came from projects that have received a grant (around 44%).
2. External funding in the NEAR Ecosystem
This section provides information about external funding in the NEAR ecosystem
12 closed projects in Q3 ‘22 – ($92.2M)
4 finalizing rounds
18 new fundraising processes kicked off
38 VC intros made
Closed Rounds (September data)
Sender Wallet – Raised a $4.5M private round led by Pantera Capital with participation from Crypto.com, Jump, Amber Group, Woo Network, SevenX Ventures, Shima Capital, and others.
Hillridge – Raised a $2.3M seed round to address climate protection in the agriculture industry with their Insurtech solution building on NEAR.
Closed Rounds (Q3 data)
Portalverse Network – raised a multi-million $ seed round with participation from Big Brain Holdings, 2Moon Capital, and Cogitent Ventures to bring the first decentralized cloud gaming and rendering network to the NEAR ecosystem.
Scorefam – secured a capital commitment of up to $25M from GEM Digital to expand their gaming NFT suite of products.
Token Terminal – raised $6.5M to expand their crypto asset data coverage, which will soon include NEAR Protocol and NEAR ecosystem projects.
Mystiko.Network – raised a $10M round this past month. Mystiko received a grant from NEAR Foundation to support NEAR through their transaction privacy layer.
Sweat Economy – raised $13M in funding including a private token sale, to accelerate their move into Web3.
Niche – closed a $1.8M pre-seed to bring decentralized social media to NEAR.
Aurigami – raised $12M in token rounds earlier this year to continue to grow DeFi on Aurora.
Play Ember – just closed a $1.4M token seed round to bring mobile gaming to NEAR. The team is currently exploring an equity round at this moment as well.
3. Ecosystem highlights
NEARWEEK is the one-stop-shop for all NEAR related news. Each weekly newsletter and edition is made possible via news contributions from the NEARWEEK community to the NEWS DAO. Subscribe or visit NEARWEEK.com to get your weekly dose of news from the NEARverse!
For the month of September we invite you to read through the following newsletters :
Newsletter 74
Newsletter 75
Newsletter 76
Newsletter 77
If you are interested in getting funded :
explore the NEAR Funding linktree
visit NF’s website : https://pages.near.org/
contact NF Grants : [email protected]
|
---
id: enumeration
title: Enumeration
sidebar_label: Enumeration
---
import {Github} from "@site/src/components/codetabs"
In the previous tutorials, you looked at ways to integrate the minting functionality into a skeleton smart contract. In order to get your NFTs to show in the wallet, you also had to deploy a patch fix that implemented one of the enumeration methods. In this tutorial, you'll expand on and finish the rest of the enumeration methods as per the [standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration)
Now you'll extend the NFT smart contract and add a couple of enumeration methods that can be used to return the contract's state.
## Introduction
As mentioned in the [Upgrade a Contract](/tutorials/nfts/js/upgrade-contract/) tutorial, you can deploy patches and fixes to smart contracts. This time, you'll use that knowledge to implement the `nft_total_supply`, `nft_tokens` and `nft_supply_for_owner` enumeration functions.
To get started, either switch to the `2.minting` branch from our [GitHub repository](https://github.com/near-examples/nft-tutorial/), or continue your work from the previous tutorials.
If you haven't cloned it yet, refer to the [Contract Architecture](/tutorials/nfts/js/skeleton#building-the-skeleton) to check out the repository.
```bash
git checkout 2.minting
```
:::tip
If you wish to see the finished code for this _Enumeration_ tutorial, you can find it on the `3.enumeration` branch.
:::
## Modifications to the contract
Let's start by opening the `src/enumeration.ts` file and locating the empty `internalNftTotalSupply` function.
### NFT Total Supply
This function should return the total number of NFTs stored on the contract. You can easily achieve this functionality by simply returning the length of the `nftMetadataById` data structure.
<Github language="js" start="8" end="16" url="https://github.com/near-examples/nft-tutorial-js/blob/3.enumeration/src/nft-contract/enumeration.ts" />
### NFT Tokens
This function should return a paginated list of `JsonTokens` that are stored on the contract regardless of their owners.
If the user provides a `from_index` parameter, you should use that as the starting point for which to start iterating through tokens; otherwise it should start from the beginning. Likewise, if the user provides a `limit` parameter, the function shall stop after reaching either the limit or the end of the list.
<Github language="js" start="18" end="43" url="https://github.com/near-examples/nft-tutorial-js/blob/3.enumeration/src/nft-contract/enumeration.ts" />
### NFT Supply For Owner
This function should look for all the non-fungible tokens for a user-defined owner, and return the length of the resulting set.
If there isn't a set of tokens for the provided Account ID, then the function shall return `0`.
<Github language="js" start="45" end="62" url="https://github.com/near-examples/nft-tutorial-js/blob/3.enumeration/src/nft-contract/enumeration.ts" />
Next, you can use the CLI to query these new methods and validate that they work correctly.
## Redeploying the contract {#redeploying-contract}
Now that you've implemented the necessary logic for `nft_tokens_for_owner`, it's time to build and re-deploy the contract to your account. Using the build script, deploy the contract as you did in the previous tutorials:
```bash
yarn build && near deploy --wasmFile build/nft.wasm --accountId $NFT_CONTRACT_ID
```
This should output a warning saying that the account has a deployed contract and will ask if you'd like to proceed. Simply type `y` and hit enter.
```
This account already has a deployed contract [ AKJK7sCysrWrFZ976YVBnm6yzmJuKLzdAyssfzK9yLsa ]. Do you want to proceed? (y/n)
```
## Enumerating tokens
Once the updated contract has been redeployed, you can test and see if these new functions work as expected.
### NFT tokens
Let's query for a list of non-fungible tokens on the contract. Use the following command to query for the information of up to 50 NFTs starting from the 10th item:
```bash
near view $NFT_CONTRACT_ID nft_tokens '{"from_index": "10", "limit": 50}'
```
This command should return an output similar to the following:
<details>
<summary>Example response: </summary>
<p>
```json
[]
```
</p>
</details>
### Tokens by owner
To get the total supply of NFTs owned by the `goteam.testnet` account, call the `nft_supply_for_owner` function and set the `account_id` parameter:
```bash
near view $NFT_CONTRACT_ID nft_supply_for_owner '{"account_id": "goteam.testnet"}'
```
This should return an output similar to the following:
<details>
<summary>Example response: </summary>
<p>
```json
0
```
</p>
</details>
## Conclusion
In this tutorial, you have added two [new enumeration functions](/tutorials/nfts/js/enumeration#modifications-to-the-contract), and now you have a basic NFT smart contract with minting and enumeration methods in place. After implementing these modifications, you redeployed the smart contract and tested the functions using the CLI.
In the [next tutorial](/tutorials/nfts/js/core), you'll implement the core functions needed to allow users to transfer the minted tokens.
:::info Remember
If you want to see the finished code from this tutorial, you can checkout the `3.enumeration` branch.
:::
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `3.0.0`
- NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0`
- Enumeration standard: [NEP181](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration), version `1.0.0`
:::
|
# Financial Transaction
Suppose Alice wants to transfer 100 tokens to Bob.
In this case we are talking about native Near Protocol tokens, oppose to user-defined tokens implemented through a smart contract.
There are several way this can be done:
- Direct transfer through a transaction containing transfer action;
- Alice calling a smart contract that in turn creates a financial transaction towards Bob.
In this section we are talking about the former simpler scenario.
## Pre-requisites
For this to work both Alice and Bob need to have _accounts_ and an access to them through
_the full access keys_.
Suppose Alice has account `alice_near` and Bob has account `bob_near`. Also, some time in the past,
each of them has created a public-secret key-pair, saved the secret key somewhere (e.g. in a wallet application)
and created a full access key with the public key for the account.
We also need to assume that both Alice and Bob have some number of tokens on their accounts. Alice needs >100 tokens on her account
so that she could transfer 100 tokens to Bob, but also Alice and Bob need to have some tokens on balance to pay for the data they store on-chain for their accounts -- which is essentially the refundable cost of the storage occupied by the account in the Near Protocol network.
## Creating a transaction
To send the transaction neither Alice nor Bob need to run a node.
However, Alice needs a way to create and sign a transaction structure.
Suppose Alice uses near-shell or any other third-party tool for that.
The tool then creates the following structure:
```
Transaction {
signer_id: "alice_near",
public_key: "ed25519:32zVgoqtuyRuDvSMZjWQ774kK36UTwuGRZMmPsS6xpMy",
nonce: 57,
receiver_id: "bob_near",
block_hash: "CjNSmWXTWhC3EhRVtqLhRmWMTkRbU96wUACqxMtV1uGf",
actions: vec![
Action::Transfer(TransferAction {deposit: 100} )
],
}
```
Which contains one token transfer action, the id of the account that signs this transaction (`alice_near`)
the account towards which this transaction is addressed (`bob_near`). Alice also uses the public key
associated with one of the full access keys of `alice_near` account.
Additionally, Alice uses the _nonce_ which is unique value that allows Near Protocol to differentiate the transactions (in case there are several transfers coming in rapid
succession) which should be strictly increasing with each transaction. Unlike in Ethereum, nonces are associated with access keys, oppose to
the entire accounts, so several users using the same account through different access keys need not to worry about accidentally
reusing each other's nonces.
The block hash is used to calculate a transaction's "freshness". It
is used to make sure a transaction does not get lost (let's say
somewhere in the network) and then arrive days, weeks, or years later
when it is not longer relevant and would be undesirable to execute.
A transaction does not need to arrive at a specific block, instead
it is required to arrive within a certain number of blocks from the block
identified by the `block_hash`. Any transaction arriving outside this
threshold is considered to be invalid. Allowed delay is defined by
`transaction_validity_period` option in the chain’s genesis file. On
mainnet, this value is 86400 (which corresponds to roughly a day) and
on testnet it is 100.
near-shell or other tool that Alice uses then signs this transaction, by: computing the hash of the transaction and signing it
with the secret key, resulting in a `SignedTransaction` object.
## Sending the transaction
To send the transaction, near-shell connects through the RPC to any Near Protocol node and submits it.
If users wants to wait until the transaction is processed they can use `send_tx_commit` JSONRPC method which waits for the
transaction to appear in a block. Otherwise the user can use `send_tx_async`.
## Transaction to receipt
We skip the details on how the transaction arrives to be processed by the runtime, since it is a part of the blockchain layer
discussion.
We consider the moment where `SignedTransaction` is getting passed to `Runtime::apply` of the
`runtime` crate.
`Runtime::apply` immediately passes transaction to `Runtime::process_transaction`
which in turn does the following:
- Verifies that transaction is valid;
- Applies initial reversible and irreversible charges to `alice_near` account;
- Creates a receipt with the same set of actions directed towards `bob_near`.
The first two items are performed inside `Runtime::verify_and_charge_transaction` method.
Specifically it does the following checks:
- Verifies that the signature of the transaction is correct based on the transaction hash and the attached public key;
- Retrieves the latest state of the `alice_near` account, and simultaneously checks that it exists;
- Retrieves the state of the access key of that `alice_near` used to sign the transaction;
- Checks that transaction nonce is greater than the nonce of the latest transaction executed with that access key;
- Subtracts the `total_cost` of the transaction from the account balance, or throws `InvalidTxError::NotEnoughBalance`. If the transaction is part of a transaction by a FunctionCall Access Key, subtracts the `total_cost` from the `allowance` or throws `InvalidAccessKeyError::NotEnoughAllowance`;
- Checks whether the `signer` account has insufficient balance for the storage deposit and throws `InvalidTxError::LackBalanceForState` if so
- If the transaction is part of a transaction by a FunctionCall Access Key, throws `InvalidAccessKeyError::RequiresFullAccess`;
- Updates the `alice_near` account with the new balance and the used access key with the new nonce;
If any of the above operations fail all of the changes will be reverted.
## Processing receipt
The receipt created in the previous section will eventually arrive to a runtime on the shard that hosts `bob_near` account.
Again, it will be processed by `Runtime::apply` which will immediately call `Runtime::process_receipt`.
It will check that this receipt does not have data dependencies (which is only the case of function calls) and will then call `Runtime::apply_action_receipt` on `TransferAction`.
`Runtime::apply_action_receipt` will perform the following checks:
- Retrieves the state of `bob_near` account, if it still exists (it is possible that Bob has deleted his account concurrently with the transfer transaction);
- Computes the cost of processing a receipt and a transfer action;
- Computes how much reward should be burnt;
- Checks if `bob_near` still exists and if it does, deposits the transferred tokens to `bob_near`;
- Checks if `bob_near` still exists and if so, deposits the gas reward to the `bob_near` account;
- Checks if `bob_near` has enough balance for the storage deposit, the transaction's temporary state is dropped/rolled back if there is not enough balance;
|
# Bindings Specification
This is the low-level interface available to the smart contracts, it consists of the functions that the host (represented by
Wasmer inside near-vm-runner) exposes to the guest (the smart contract compiled to Wasm).
Due to Wasm restrictions the methods operate only with primitive types, like `u64`.
Also for all functions in the bindings specification the following is true:
- Method execution could result in `MemoryAccessViolation` error if one of the following happens:
- The method causes host to read a piece of memory from the guest but it points outside the guest's memory;
- The guest causes host to read from the register, but register id is invalid.
Execution of a bindings function call result in an error being generated. This error causes execution of the smart contract
to be terminated and the error message written into the logs of the transaction that caused the execution. Many bindings
functions can throw specialized error messages, but there is also a list of error messages that can be thrown by almost
any function:
- `IntegerOverflow` -- happens when guest passes some data to the host but when host tries to apply arithmetic operation
on it it causes overflow or underflow;
- `GasExceeded` -- happens when operation performed by the guest causes more gas than the remaining prepaid gas;
- `GasLimitExceeded` -- happens when the execution uses more gas than allowed by the global limit imposed in the economics
config;
- `StorageError` -- happens when method fails to do some operation on the trie.
The following binding methods cannot be invoked in a view call:
- `signer_account_id`
- `signer_account_pk`
- `predecessor_account_id`
- `attached_deposit`
- `prepaid_gas`
- `used_gas`
- `promise_create`
- `promise_then`
- `promise_and`
- `promise_batch_create`
- `promise_batch_then`
- `promise_batch_action_create_account`
- `promise_batch_action_deploy_account`
- `promise_batch_action_function_call`
- `promise_batch_action_transfer`
- `promise_batch_action_stake`
- `promise_batch_action_add_key_with_full_access`
- `promise_batch_action_add_key_with_function_call`
- `promise_batch_action_delete_key`
- `promise_batch_action_delete_account`
- `promise_results_count`
- `promise_result`
- `promise_return`
If they are invoked the smart contract execution will panic with `ProhibitedInView(<method name>)`.
|
How do Randomness Beacons based on Threshold Signatures work?
COMMUNITY
February 25, 2020
Introduction
Back in 2015, DFinity made the community extremely excited with their design of a randomness beacon that was leveraging BLS threshold signatures to produce a randomness output that is both unbiased and unpredictable.
As of 2020 building an unbiased and unpredictable randomness beacon remains extremely challenging, and very few protocols have one live. Threshold signatures are not the only proposed approach, and we previously published a short overview of various other approaches to randomness, including an approach that we considered back then in this blog post. Refer to it for the details on what the randomness beacon is, what it means to be unbiased and unpredictable, and what approaches besides threshold signatures were proposed.
After multiple iterations of design, we ultimately ended up building something very similar to what DFinity uses, and that is a great opportunity to dive deep into how such randomness beacons work.
In this article, we will describe the complex protocol of using threshold signatures to generate random numbers in very simple terms. Let’s dive in!
Crypto Fundamentals
For the purpose of understanding randomness beacons in this article, we will need to understand some very basic cryptography. We need to differentiate between two concepts: scalars, or just regular numbers, which throughout this article we will denote with lowercase letters (e.g. x, y) and elliptic curve points, which we will denote with uppercase letters.
We don’t need to understand much about elliptic curve points, besides a few properties:
Elliptic curve points can be added together, and an elliptic curve point can be multiplied by a scalar (we will denote it as xG, though a notation Gx is also very common). The result of both operations is another elliptic curve point.
Knowing G and xG it is computationally infeasible to derive x.
We will also be using a concept of a polynomial p(x) of degree k-1. For the purposes of this article it is sufficient to think about it as a function p(x) such that if one knows the value of p(x) at any k distinct values of x, they can also derive p(x) at any other x as well.
Interestingly, for the same function, and some elliptic curve point G, if one knows the value of p(x)G at any k distinct values of x, they can also derive p(x)G at any other x.
Those are the only properties of elliptic curve points we will need to understand on the high level how randomness beacons work.
The Randomness Beacon
Say there are n participants, and say we want to require that it takes at least k of them to generate a random number and that an adversary that controls up to k-1 of the participants cannot predict the output of the randomness beacon, and cannot influence it in any way.
Say there exists some polynomial p(x) of degree k-1 such that the first participant knows p(1), the second participant knows p(2), and the n-th participant knows p(n). Also, say that for some agreed-upon elliptic curve point G everybody knows p(x)G for all values of x. We will call p(i) a private share of participant i (because the only participant i knows it), and p(i)G public share of participant i (because everybody knows it). Recall from the previous section that the knowledge of p(i)G is not sufficient to derive p(i).
Generating such a polynomial in a way that each participant knows their private share, but has no insight into the private shares of other participants is the most complex part of the randomness beacon, and is what is called Distributed Key Generation. We will cover it in the next section. For now, let’s assume such a polynomial exists, and all the participants know their shares.
Let’s see how to use it to have a randomness beacon in the context of a blockchain protocol. Say a block with hash h is produced, and the participants collectively want to generate a random number seeded by h. The way they proceed is first to use some agreed-upon function to convert h into an elliptic curve point:
H = scalarToPoint(h)
Then each participant i computes H_i = p(i)H, which they can do because they know p(i) and H. Revealing H_i will not reveal their private share, so the same private shares can be reused for each block, thus the DKG only needs to be performed once.
When at least k participants revealed their shares H_i = p(i)H, everyone can reconstruct any share H_x = p(x)H for any x due to the third property in the previous section. At this point, each participant can locally compute H_0 = p(0)H, and use the hash of it as the randomness beacon output. Note that since no participant knows p(0), the only way to compute p(0)H is to interpolate p(x)H, which is only possible if at least k of p(i)H were revealed. Revealing any smaller number of p(i)H gives no insight into the value of p(0)H.
The beacon above has all the properties we desire: an adversary controlling k-1 or fewer participants cannot get any insight into the final output of the randomness beacon, while any k participants can compute the final output, and any subset of k or more participants will always arrive at the same value.
There is one issue we ignored above. For the interpolation to work, we need to make sure that the value H_i that the i-th participant revealed is indeed equal to p(i)H. Since no other participant knows p(i), they cannot naively verify that H_i is indeed correct, and without some cryptographic proof alongside H_i a malicious actor can reveal arbitrary value, and other participants will have no way of detecting it.
There are at least two ways to provide a cryptographic proof of H_i being correct, we will cover both of the two sections below after we talk about DKG.
Distributed Key Generation
For the randomness beacon in the previous section to work, we needed n participants to collectively come up with a polynomial p(x) of degree k-1 such that each participant i knows the value of p(i), but no other participant has any insight into that value. For the constructions in the next section, it will also be necessary that all the participants know p(x)G for some agreed-upon G and all x.
Throughout this section, we assume that every participant has some private key x_i associated with them, and all the participants know the public key X_i that corresponds to such a private key.
One way to go about DKG is then the following:
Each participant i locally computes some polynomial p_i(x) of degree k-1. They then send p_i(j) to each participant j encrypted with the public key X_j, so that only j-th participant can decode p_i(j). Participant i also publicly announces p_i(j)G for all j from 1 to k inclusive.
All the participants collectively agree on some set of at least k such committed polynomials. Since some participants can be offline, they can’t wait until all n of them commit, but once at least k have committed, they can use any sort of consensus algorithm (for example Tendermint) to agree on some subset Z of at least k polynomials.
The participants collectively verify that the encrypted p_i(j) corresponds to the publicly announced p_i(j)G. The polynomials for which it is not the case are removed from Z.
Each participant j computes their private share p(j) as the sum of p_i(j) for each i in Z. Each participant can also compute each public share p(x)G as the sum of p_i(x)G for each i in Z.
Observe that p(x) is indeed a polynomial of degree k-1, because it is the sum of individual p_i(x), each of which is a polynomial of degree k-1. Then, note that while each participant j knows p(j), they have no insight into the values of other p(x) for x ≠ j. Indeed, to know such a value they’d need to know all p_i(x), and for as long as the participant j doesn’t know at least one of the committed polynomials, they don’t have any information about p(x).
This constitutes the entirety of the DKG process. Steps 1, 2 and 4 above are relatively straightforward. Step 3 is where DKG gets tricky.
Specifically, we need some way to prove that each encrypted p_i(j) indeed corresponds to the publicly broadcasted p_i(j)G. Without a way to verify it, an adversary i can send some gibberish information to participant j instead of actually encrypted p_i(j), and participant j will have no way to compute their private share later.
There’s a way to create a cryptographic proof of the correctness of the encrypted share. However, the size of such a proof is prohibitively large, and given that O(nk) such proofs need to be published, the size of the proof becomes a bottleneck.
Instead of proving cryptographically that p_i(j) corresponds to p_i(j)G in NEAR we instead allocate a lot of time during DKG between the moment the set of polynomials is agreed upon and the moment the final shares are aggregated, during which each participant can provide a cryptographic proof that the encrypted share p_i(j) sent to them doesn’t correspond to the publicly broadcasted p_i(j)G. It makes an assumption that each participant will go online at least once during that time frame (which spans approximately half a day), and that the challenge they submit will make it to the blockchain. In the case of block producers, both assumptions are rather realistic, since the block producers are expected to remain online throughout the epoch, and for a message to be censored majority of block producers need to collude and not include it in their blocks, in which case they have significantly more profitable ways to attack the system.
If a particular block producer does receive an invalid share and then fails to show up during DKG and challenge it, they will not be able to participate in generating random numbers during the same epoch. Note that for as long as k other honest participants have their shares (by either not receiving any invalid shares, or challenging all the invalid shares in time), the protocol will still function.
Proofs
The last part of the randomness beacon that is still left uncovered is how one can prove that a published value H_i is equal to p(i)H without revealing p(i).
Recall that the values H, G, p(i)G are all known to everybody. The operation that computes p(i) given p(i)G and G is called discrete logarithm, or dlog for short, and what each participant wants to prove to others is that
dlog(p(i)G, G) = dlog(H_i, H)
Without revealing p(i). Constructions for such proof do exist, one such construction is called Schnorr Protocol.
With such a construction, whenever a participant submits H_i, they also submit proof of correctness of H_i.
Recall that the final randomness beacon output is the interpolated value of H_0. What information needs to be distributed along with H_0 for external participants that didn’t participate in the generation of it to be able to verify its correctness? Since everybody can locally interpolate G_0, a proof that
dlog(G_0, G) = dlog(H_0, H)
would suffice, but we cannot use the Schnorr Protocol to create such a proof since it requires the knowledge of p(0), and the randomness beacon relies on nobody knowing the value. Thus, one needs to keep all the values of H_i along with the corresponding proofs to prove the correctness of H_0 to external observers.
However, if there was some operation that semantically resembled multiplication on elliptic curve points, proving that H_0 was computed correctly would become trivial, by just verifying that
H_0 × G = G_0 × H
If the chosen elliptic curve supports so-called elliptic curve pairings, such a proof becomes possible. In such a case H_0 not only serves as an output of the randomness beacon that can be trivially verified by anyone who knows G, H and G_0 but also it serves as a collective multi-signature that attests that at least k out of n block producer signed the block.
We do not use elliptic curve pairings in NEAR today, though we might use them in the future, and then the neat trick discussed above would replace the individual signatures we use today. DFinity, on the other hand, uses BLS signatures and can leverage the pairings to make such multi signatures work.
Outro
The implementation of the randomness beacon is mostly complete in our reference client implementation (see this commit), however, the first version of the NEAR Protocol will likely launch without it, to allow more time for stabilization of the beacon. Once it is shipped, however, all the contracts on NEAR will enjoy access to unbiasable and unpredictable random number generator, which enables many uses cases not possible today on other networks.
The first release of the NEAR Protocol will use a significantly simpler randomness beacon (see this pull request), where the random value is just the output of a verifiable random function on the previous output of the random beacon by the current block producer. Such a randomness beacon is unpredictable, but is not unbiasable: the current block producer has one bit of influence because they can choose not to produce a block. It happens to be very similar to the randomness beacon that Ethereum 2.0 will use before they have the VDFs beacon available (the randomness output is the VRF by the current block producer on the epoch hash), and is also the way the randomness beacon works in Elrond.
If you are interested in how blockchain protocols work, check out our Whiteboard Series with NEAR, in which we talk to the founders and core developers of other protocols, such as Ethereum Serenity, Cosmos, Polkadot and many others, and dive deep into the details of their technology. All the video episodes are conveniently assembled into a playlist here.
NEAR Protocol is an infrastructure for the open web and a sharded blockchain protocol. You can learn more about our technology in our sharding design paper, through deep-dive videos, or by exploring our Rust reference client implementation.
Follow @NEARprotocol on Twitter to get notified about new content we post and get the latest updates on the development of the protocol
If you want to get involved, please join the conversation here! |
NEAR Powers Voting for the Djooky Music Awards
NEAR FOUNDATION
April 4, 2023
The world of music and the blockchain is about to get a lot more exciting and promising thanks to Djooky and NEAR. The ongoing Djooky Music Awards (DMA) for undiscovered artists will feature on-chain voting mechanisms powered by NEAR, allowing artists to vie for funding and recognition, while voters compete for cash prizes.
For upcoming independent artists, Djooky serves as a streaming and discovery tool that links them to fans and industry insiders. Artists can also use the platform’s virtual marketplace, DjookyX, to receive funding by fractionalizing rights to future song royalties. Bringing DMA voting to NEAR will bring further engagement and innovation between musicians and fans.
That means voting for DMA finals will be completely on-chain using NEAR, with weekly prizes being distributed in the form of NEAR tokens. Artists simply need to create a NEAR wallet to claim their prizes. In addition, any users trying to predict the next big hit with HitHunder will need a NEAR wallet to receive token rewards if their song strikes gold.
How the DMAs empower both artists and fans
The DMAs were introduced in 2020 by Djooky co-founders Andrey Dakhovskyy and Brian Malouf as a way to help fans discover new artists and aid musicians in gaining visibility. The competition runs year-round, resetting every quarter with new awards and prizes. The DMAs run tournament style, with artists competing brack-style on the national, continental, and finally global level.
In the event that a contestant makes it to the finals, their music will be featured on an 18-song NFT album, the sales of which will be divided equally among the lowest 15 projects. If their song is selected as one of the top three songs, it will have its own NFT auction with bonus artwork created by a digital artist. Djooky also provides a platform to help artists reach a global audience, even if their song doesn’t end up topping the charts.
Additionally, Djooky runs weekly HitHunter competitions where users vie with one another to identify the next likely hit song by assigning HitPoints to songs they like. Users receive 100 Hitpoints every Monday, which they can then spend on the tracks they believe will be the biggest hits. HitHunters are ranked according to how early they allocate their HPs to tracks that become hits in the Djooky charts when compared to other HitHunters.
Users allocate their Hit Points to the songs which they identify as potential hits. And depending on the progress of the songs chosen, users receive winning points calculated by the platform’s algorithm. The top five users of the special user charts will be rewarded with get cash prizes for backing the right tunes.
NEAR x DMAs fueling a new future for musicians
The Djooky team and NEAR Foundation previously collaborated to develop DjookyX, their music marketplace that’s presently transitioning from Web2 to Web3. The DMAs and DjookyX demonstrate new economic models for fans and musicians in Web3, all made possible by technology and governance mechanisms of the NEAR blockchain.
As the DMAs and DjookyX marketplace grow, so will opportunities for musicians to earn more for their creative energy, and for fans to truly support undiscovered musicians they love.
|
# NEAR Protocol Specifications and Standards
[![project chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://near.zulipchat.com/#narrow/stream/320497-nep-standards)
[![CI](https://github.com/near/NEPs/actions/workflows/build.yml/badge.svg)](https://github.com/near/NEPs/actions/workflows/build.yml)
This repository hosts the current NEAR Protocol specification and standards.
This includes the core protocol specification, APIs, contract standards, processes, and workflows.
Changes to the protocol specification and standards are called NEAR Enhancement Proposals (NEPs).
## NEPs
| NEP # | Title | Author | Status |
| ----------------------------------------------------------------- | ---------------------------------------- | -------------------------------------------- | ---------- |
| [0001](https://github.com/near/NEPs/blob/master/neps/nep-0001.md) | NEP Purpose and Guidelines | @jlogelin | Living |
| [0021](https://github.com/near/NEPs/blob/master/neps/nep-0021.md) | Fungible Token Standard (Deprecated) | @evgenykuzyakov | Deprecated |
| [0141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md) | Fungible Token Standard | @evgenykuzyakov @oysterpack, @robert-zaremba | Final |
| [0145](https://github.com/near/NEPs/blob/master/neps/nep-0145.md) | Storage Management | @evgenykuzyakov | Final |
| [0148](https://github.com/near/NEPs/blob/master/neps/nep-0148.md) | Fungible Token Metadata | @robert-zaremba @evgenykuzyakov @oysterpack | Final |
| [0171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md) | Non Fungible Token Standard | @mikedotexe @evgenykuzyakov @oysterpack | Final |
| [0177](https://github.com/near/NEPs/blob/master/neps/nep-0177.md) | Non Fungible Token Metadata | @chadoh @mikedotexe | Final |
| [0178](https://github.com/near/NEPs/blob/master/neps/nep-0178.md) | Non Fungible Token Approval Management | @chadoh @thor314 | Final |
| [0181](https://github.com/near/NEPs/blob/master/neps/nep-0181.md) | Non Fungible Token Enumeration | @chadoh @thor314 | Final |
| [0199](https://github.com/near/NEPs/blob/master/neps/nep-0199.md) | Non Fungible Token Royalties and Payouts | @thor314 @mattlockyer | Final |
| [0245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) | Multi Token Standard | @zcstarr @riqi @jriemann @marcos.sun | Review |
| [0264](https://github.com/near/NEPs/blob/master/neps/nep-0264.md) | Promise Gas Weights | @austinabell | Final |
| [0297](https://github.com/near/NEPs/blob/master/neps/nep-0297.md) | Events Standard | @telezhnaya | Final |
| [0330](https://github.com/near/NEPs/blob/master/neps/nep-0330.md) | Source Metadata | @BenKurrek | Review |
| [0366](https://github.com/near/NEPs/blob/master/neps/nep-0366.md) | Meta Transactions | @ilblackdragon @e-uleyskiy @fadeevab | Final |
| [0393](https://github.com/near/NEPs/blob/master/neps/nep-0393.md) | Sould Bound Token (SBT) | @robert-zaremba | Final |
| [0399](https://github.com/near/NEPs/blob/master/neps/nep-0399.md) | Flat Storage | @Longarithm @mzhangmzz | Final |
| [0448](https://github.com/near/NEPs/blob/master/neps/nep-0448.md) | Zero-balance Accounts | @bowenwang1996 | Final |
| [0452](https://github.com/near/NEPs/blob/master/neps/nep-0452.md) | Linkdrop Standard | @benkurrek @miyachi | Final |
| [0455](https://github.com/near/NEPs/blob/master/neps/nep-0455.md) | Parameter Compute Costs | @akashin @jakmeier | Final |
| [0514](https://github.com/near/NEPs/blob/master/neps/nep-0514.md) | Fewer Block Producer Seats in `testnet` | @nikurt | Final |
## Specification
NEAR Specification is under active development.
Specification defines how any NEAR client should be connecting, producing blocks, reaching consensus, processing state transitions, using runtime APIs, and implementing smart contract standards as well.
## Standards & Processes
Standards refer to various common interfaces and APIs that are used by smart contract developers on top of the NEAR Protocol.
For example, such standards include SDK for Rust, API for fungible tokens or how to manage user's social graph.
Processes include release process for spec, clients or how standards are updated.
### Contributing
#### Expectations
Ideas presented ultimately as NEPs will need to be driven by the author through the process. It's an exciting opportunity with a fair amount of responsibility from the contributor(s). Please put care into the details. NEPs that do not present convincing motivation, demonstrate understanding of the impact of the design, or are disingenuous about the drawbacks or alternatives tend to be poorly received. Again, by the time the NEP makes it to the pull request, it has a clear plan and path forward based on the discussions in the governance forum.
#### Process
Spec changes are ultimately done via pull requests to this repository (formalized process [here](neps/nep-0001.md)). In an effort to keep the pull request clean and readable, please follow these instructions to flesh out an idea.
1. Sign up for the [governance site](https://gov.near.org/) and make a post to the appropriate section. For instance, during the ideation phase of a standard, one might start a new conversation in the [Development » Standards section](https://gov.near.org/c/dev/standards/29) or the [NEP Discussions Forum](https://github.com/near/NEPs/discussions).
2. The forum has comment threading which allows the community and NEAR Collective to ideate, ask questions, wrestle with approaches, etc. If more immediate responses are desired, consider bringing the conversation to [Zulip](https://near.zulipchat.com/#narrow/stream/320497-nep-standards).
3. When the governance conversations have reached a point where a clear plan is evident, create a pull request, using the instructions below.
- Clone this repository and create a branch with "my-feature".
- Update relevant content in the current specification that are affected by the proposal.
- Create a Pull request, using [nep-0000-template.md](nep-0000-template.md) to describe motivation and details of the new Contract or Protocol specification. In the document header, ensure the `Status` is marked as `Draft`, and any relevant discussion links are added to the `DiscussionsTo` section.
Use the pull request number padded with zeroes. For instance, the pull request `219` should be created as `neps/nep-0219.md`.
- Add your Draft standard to the `NEPs` section of this README.md. This helps advertise your standard via github.
- Update Docusaurus documentation under the `specs/Standards` to describe the contract standard at a high level, how to integrate it into a Dapp, and a link to the standard document (ie. `neps/nep-0123.md`). This helps advertise your standard via [nomicon](https://nomicon.io/). Any related nomicon sections should be prefixed and styled using the following snippet:
```text
:::caution
This is part of proposed spec [NEP-123](https://github.com/near/NEPs/blob/master/neps/nep-0123.md) and subject to change.
:::
```
- Once complete, submit the pull request for editor review.
- The formalization dance begins:
- NEP Editors, who are unopinionated shepherds of the process, check document formatting, completeness and adherence to [NEP-0001](neps/nep-0001.md) and approve the pull request.
- Once ready, the author updates the NEP status to `Review` allowing further community participation, to address any gaps or clarifications, normally part of the Review PR.
- NEP Editors mark the NEP as `Last Call`, allowing a 14 day grace period for any final community feedback. Any unresolved show stoppers roll the state back to `Review`.
- NEP Editors mark the NEP as `Final`, marking the standard as complete. The standard should only be updated to correct errata and add non-normative clarifications.
Tip: build consensus and integrate feedback. NEPs that have broad support are much more likely to make progress than those that don't receive any comments. Feel free to reach out to the NEP assignee in particular to get help identify stakeholders and obstacles.
### Running Docusaurus
This repository uses [Docusaurus](https://docusaurus.io/) for the [Nomicon website](https://nomicon.io).
1. Move into the `/website` folder where you will run the following commands:
- Make sure all the dependencies for the website are installed:
```sh
# Install dependencies
yarn
```
- Run the local docs development server
```sh
# Start the site
yarn start
```
_Expected Output_
```sh
# Website with live reload is started
Docusaurus server started on port 3000
```
The website for docs will open your browser locally to port `3000`
2. Make changes to the docs
3. Observe those changes reflected in the local docs
4. Submit a pull request with your changes
|
---
title: 1.1 The History of the Internet
description: Review of the history of the internet and its revolutions to date.
---
# 1.1 Context: History of Internet and It’s Revolutions to Date
## Introduction
Understanding Crypto, and truly understanding the paradigm shift that crypto brings with it, starts by understanding our evolution towards ‘bits’ of data over time. While often this topic is discussed solely historically in terms of the evolution of the internet and the technology improvements in terms of hardware and software, it is also a topic that is highly influential on ethical and social fronts as well.
So to be thorough about this we will march up to the present by understanding the technical innovation of the internet in how it has evolved ethically and socially for the world at large - as the ethical and social ramifications of crypto is truly one its strongest value propositions.
## Atoms and Bits
From 10,000 feet, what has the internet brought us? Who has it benefited? And what kinds of systems has it created up until this point? These key questions are an initial skirmish with the topic that will help us become oriented on where we stand today, both in terms of the adoption of the internet in our world (horizontally) as well as the potential of leveraging the internet in more sophisticated ways (vertically).
The first revolution of the internet lies in how it has successfully_Gone Digital,_in our management of communication and systems. This is commonly introduced with the idea of bits of information, and the transmission of that information through very early infrastructure such as TCP-IP.
![](@site/static/img/bootcamp/mod-em-1.1.1.png)
This is what has been known as Web 1.0 - or the OG Web. Snowden talks about it in his book_Permanent Record_. It was also the subject of the original Cypherpunks, as well as [the Declaration of Cyberspace Independence](https://www.eff.org/cyberspace-independence). It was a time of internet optimism, when the very early forums, chat-rooms, and websites were being created and shared openly. This Web is also known as the ‘Read Only’ Web.
Key characteristics of Web 1.0 Include the following (1991 - 2004)
* Read Only.
* Static Websites.
* Personal Websites.
* Content Delivery Network.
Web 1 begins to morph into Web 2 at around the dot com bubble circa 2004. Web2, unlike the Read only world of Web1 transitions into what is usually referred to as_the social web -_ or the read-write internet.
Key characteristics of Web2 include (2003 - 2016 - present):
* Interaction between Users and Sites.
* Interaction between Users.
* Dynamic Content - that is responsive to users.
* Things like Tagging, Blogging, Podcasting, Streaming, etc.
This is most likely the Web that you grew up with. It is also the Web that has been responsible for the bulk of the wealth creation in the past 20 years in the United States.. Companies like Google, Amazon, Facebook (Meta), etc.
![](@site/static/img/bootcamp/mod-em-1.1.2.png)
Now there are some interesting presuppositions inherent in the nature of ownership from Web1 to Web2 that have had serious social and ethical impacts on our society.
**_Web 1 =_**
* One dimensional.
* Consume.
* Share, without communicating (Post).
**_Web 2 =_**
* Two dimensional, with underlying ownership.
* Interact within someone’s system.
* Consume, and Interact (Monitor).
Herein lies the major changes that are important for understanding crypto specifically. The moment we have a third party, facilitating interaction between users on the internet, is the moment we open up a subtle form of ownership, decision making, and surveillance, that is the basis of what has been coined ‘Surveillance Capitalism’ by Harvard Professor Shoshana Zuboff.
To put this simply, with the Web2 internet we enter a new Barron’s era of data collection, user surveillance, and targeted advertising all surrounding the surplus of data collected on and about users. In this internet, the user is both a consumer and a product.
There are two resultant social challenges from this model that are worth mentioning:
1. First, in terms of institutional resilience and rule of law: Keeping up! Many have probably heard about Uber’s government clashes, Social Media controversy on Twitter and Facebook, and Search results on Google. The point - which Shoshana documents quite well, is that the speed of software has led to major issues for legal infrastructure to keep up in this new domain. [Who decides, Who Decides]
_“The online world is not truly bound by terrestrial laws…it’s the world’s largest ungoverned space.” They celebrate their claim to operational spaces beyond the reach of political institutions: the twenty first century equivalent of the ‘dark continents’ that drew nineteenth century European speculators to their shores.” – 104, The Age of Surveillance Capitalism_
2. Second, in terms of education and being able to stay on the front line of this emerging digital world: There is a reason tech bootcamps sprung up in the early 2010s and remain in high demand to this day - because schools and universities were not keeping up on how best to prepare students for an internet world.
_“Any consideration of the division of learning must resolve these dilemmas expressed in three essential questions. The first question is “Who knows?” This is a question about the distribution of knowledge and whether one is included or excluded from the opportunity to learn. The second question is “Who decides?” This is a question about authority: Which people, institutions, or processes determine who is included in learning, what are they able to learn, and how they are able to act on their knowledge. What is the legitimate basis of that authority? The third question is, “Who decides who decides?” This is a question about Power. What is the source of power that undergirds the authority to share or withhold knowledge?” - 180, Age of Surveillance Capitalism._
Both of these social challenges from the rise of Web2 on a social scale, are extremely relevant for our discussions about Web3 and the world of crypto.
## Geographical Imbalances of Internet Adoption and Leap-Frogging
Equally relevant, is the geographical dissemination of the internet - and how today, after 20 years - large parts of the world are still not brought fully online.
![](@site/static/img/bootcamp/mod-em-1.1.3.png)
As the graphic shows quite thoroughly, internet adoption was largely a Western / Developed phenomenon for the first couple of decades. Balaji - someone we will speak of quite in detail in this course - has spoken much about what bringing India online will mean, for both the users and services of the internet.
Relevant for us, in this discussion of the geographical roll out of the internet, is the idea of ‘leapfrogging’. Leapfrogging refers to a country's capacities to speed-up their technological development by skipping a previous step in technology evolution and simply adopting the ‘state of play’ as it exists in the present day.
For much of the global south, that is only just coming online, the thesis is that these areas which also happen to be demographically rich in young people - are going to be huge hotbeds of focus for the future user-base of both Web 2 and Web 3.
## Web2 to Web3: The Current State of Play
Today we have an interesting state of play as we wade into the world of crypto. On the one hand, we are seeing rising developer counts from Africa, India, and SouthEast Asia.
![](@site/static/img/bootcamp/mod-em-1.1.4.png)
On the other hand, there is very, very limited exposure between active developers globally, and active developers working on ‘Web3’.
![](@site/static/img/bootcamp/mod-em-1.1.5.png)
Of the more than 26 million developers around the world - only about [20,000 are ](https://cryptoforinnovation.org/web3-developers-at-an-all-time-high-and-growing-faster-than-ever/)building in Web3.
In a similar sense, of the 5 billion people who are using the internet around the world, only about [70 million people](https://financesonline.com/number-of-blockchain-wallet-users/) have ever opened up a wallet in crypto (and that number is probably much lower due to people having multiple wallets).
All of this is to say, that when we zoom out and look at the evolution of Web3, as compared to Web1 and Web2, we stand most likely around the early internet year of 1998 in terms of users, adoption, and products developed:
![](@site/static/img/bootcamp/mod-em-1.1.6.png)
## What is Web3.0 all about?
The goal of this course is to answer the question_What is Web 3.0 all about_? And while we will do this comprehensively, we can start by hinting that Web3.0 is a radical overhaul of the Web2.0 data monopolization era, it is a synthesis of the features of both Web1.0 and Web2.0 in such a way that **we come full circle,** whereby the User can both_own_ and_interact_ in an increasingly colorful digital world.
Without giving too much more away, lets summarize what matters in the buildup to Web3:
## Summary
The most important takeaways from this overview and scene-setting can be summarized in the following main points:
* The digitization process has been an evolving process both in terms of the development of the internet itself, as well as its geographical adoption. It has also pushed new frontiers of social, education, and institutional questions.
* Rapid development in the internet era brings along with it geographical winners, new user-bases, opportunities for countries to leapfrog, and incredible amounts of wealth creation and value.
* We have to enter and understand this emerging Web3 environment keeping in mind - this evolution of the internet cannot be separated from its ethical and social implications, the fact that much of the world is only coming online today, and that there is an existing hoard of developers that remain to cross over into the world of Web3.
This is the landscape we inherit at hand!
|
```js
import { Wallet } from './near-wallet';
const TOKEN_CONTRACT_ADDRESS = "token.v2.ref-finance.near";
const wallet = new Wallet({ createAccessKeyFor: TOKEN_CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'ft_transfer',
args: {
receiver_id: 'alice.near',
amount: '100000000000000000',
},
contractId: TOKEN_CONTRACT_ADDRESS,
deposit: 1
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |
---
id: node-types
title: Node Types
sidebar_label: Node Types
sidebar_position: 2
description: Types of NEAR Nodes
---
You can run three different types of node - Validator Node, RPC Node, and Archival Node.
### Validator Node {#validator-node}
Validator nodes are the operators of the NEAR blockchain and are essential to the health of the network. Validator nodes participate in the consensus and produce blocks and/or chunks. You can see a real-time view of NEAR network validator nodes on the [NEAR Explorer](https://explorer.near.org/nodes/validators).
### RPC Node {#rpc-node}
RPC nodes are RPC service providers that provide public RPC endpoints for developers to use. The NEAR Foundation currently maintains a public RPC endpoint `http://rpc.mainnet.near.org/` that is free for everyone to use. However, any participants are encouraged to run their own RPC node and offer RPC services through [an Open Source & Public Goods grant from the NEAR Foundation](https://near.org/blog/refining-near-foundations-grant-approach/). For more information, please check out Community section in the documentation and reach out in the Validator Channels on [Discord](https://discord.gg/ZMPr3VB) and on [Telegram](https://t.me/near_validators).
### Archival Node {#archival-node}
Archival nodes store full blockchain data, and build an archive of historical states. These nodes are useful for block explorers, chain analysis, and infrastructure providers.
See [API Setup](https://docs.near.org/api/rpc/setup) section for archival RPC nodes endpoints.
> Got a question?
> <a href="https://stackoverflow.com/questions/tagged/nearprotocol">
> <h8>Ask it on StackOverflow!</h8></a>
|
Community Update: April 10th, 2020
COMMUNITY
April 10, 2020
Welcome NEAR Community,
We hope that everyone is doing well. You spoke, we listened. We’ve put together a series of interactive online events on topics you’ve let us know you want to learn more about, including Privacy and Blockchain, Decentralized Exchanges, Building on NEAR, and more. We’ve outlined a few of the upcoming events below, and thank the 65 participants who joined us virtually this week! Have a topic you’d like to explore with us? Let us know here.
Ready Layer One
We’re excited to announce Ready Layer One, a collaboration between Cosmos, NEAR, Polkadot, Protocol Labs, Tezos and more! Ready Layer One is an interactive, immersive virtual event that contains talks, workshops, and rants by everyone from well-known speakers to community-sourced contributors.
Think of it as the intersection between a hackathon, a conference, a masterclass seminar and a vaguely anarchist festival for developers and builders of the decentralized web. The content will help you learn how to build decentralized applications using the next generation of layer 1 protocols.
Tickets are free but limited, and are reserved for the developers and builders who are contributing to the decentralized web! We need to get together to figure out how crypto & blockchain tech can help prepare the foundation for our future.
You can access NEAR Community Tickets through participating in our community events; more details below. OR, sign up to host a talk, workshop or another digital event of your choice! Visit readylayer.one for details.
Ready Layer One — More info here
Community Events
We have started hosting several community events, below are the details to each. Active community members have a chance of winning a Community Ticket for Ready Layer One.
AMA: Privacy and Blockchain
This AMA is on the intersection between Privacy and Blockchain. COVID-19 will give governments and companies reason to deploy further surveillance tools.
Questions arise, such as: How can users protect themselves from privacy-infringing technology? How can Blockchain help to protect user privacy? How are dApps different to Web 2 applications?
When? — The AMA will take place in the main channel of our Discord Group on the 16th of April at 8 PM CEST, which is 2 PM EST, and 11 AM PST.
You can submit your questions to the following survey and we will get back to you with a response.
Thursday Jam
Weekly interactive Zoom call in which NEAR introduces different aspects of building dApps. From mental models and use cases, over getting our hands dirty with specific examples and real code.
When? — Every Thursday at 4 PM Pacific Time, which is 7 PM Eastern Standard Time
How to join? — Please message us on Discord and you will receive an invite, or access events over our community calendar.
Community Talk
In this call, we invite projects and researchers from the open web ecosystem to introduce and discuss different concepts and projects. This series started off last Wednesday with an introduction to decentralised exchanges. If you would like to get involved, please let us know.
When? — This call takes place on a bi-weekly basis; the next one will be on the 22nd of April at 5 PM CEST, which is 11 AM EST, on Stablecoins.
How to join? — Please message us on Discord and you will receive an invite or access events over our community calendar.
1st Community Talk: Decentralised Exchanges
Windows Ready
We’re excited to announce that our primary introductory app now works seamlessly on Windows. Before, Create NEAR App worked best on Windows Subsystem for Linux, but it now can be run natively without all the downloads and preparation. The only requirement is to install NodeJS. Our goal is to onboard folks as quickly as possible, and this update will speed up workshop and hackathon progress for PC users.
We’ve also included Window compatibility in our new examples page. We have a selection of examples tagged with Windows-friendly that include custom instructions for Windows users.
We want to thank our community members who reached out about Windows support. We’ve heard you and appreciate the feedback! ❤️
I promised Peter we would feature his puppy. Welcome to the fam, Bosco! (Just look at him, half of his face are ears ❤️)
How You Can Get Involved
Join the NEAR Contributor Program. If you would like to host events, create content or provide developer feedback, we would love to hear from you! To learn more about the program and ways to participate, please head over to the website.
If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox. |
NEAR APAC Day 2 Recap: Asia Gaming Trends, Interoperability, and Web3 for Brands
COMMUNITY
September 10, 2023
It would’ve been hard to imagine topping a jam-packed Day 1 of NEAR APAC, but Day 2 managed to do just that. The gorgeous Sunday in Saigon covered a wide range of topics, including significant discussions on the future trends in Web3 such as how brands can hop on board the Web3 bandwagon and a creative proposal to unite all Layer 1’s for mass adoption.
With each session, industry leaders shed light on challenges and the future trajectory of the fast-paced Web3 ecosystem in APAC. From the unique positioning of Web3 gaming in Asia to the potential rise of the next Web3 cycle, the discussions were varied and far-reaching. Let’s dive on into all the Day 2 happenings at NEAR APAC in Vietnam!
APAC experts discuss the next big trends in Web3
Let’s begin the Day Two recap with a standout panel diving into the next big Web3 trends. Experts agreed that it won’t just be about technological progress, but also the transformative ways that blockchain will weave into daily life. Asset tokenization, generative AI integration, and the proliferation of decentralized creator economies were some top trends on the table.
“Generative AI and asset tokenization are revolutionizing Web3 ecosystems, especially in growing economies like India,” said Sudeep Choudhari, head of blockchain at the India National Payments Corporation. “As integration across borders accelerates, we’ll also challenge traditional FX rates, anticipating a future with minimal cross-border payment costs.”
Hanna Tantoco, APAC Marketing Director at Blockdaemon, piggybacked on the transformative role of generative AI in enhancing blockchain user experiences. She also pointed out the rising prominence of gaming in Asia, particularly on NEAR. Additionally, she highlighted Singapore’s burgeoning creator economy, powered largely by NFTs, as another future trend.
How brands can futureproof themselves with blockchain
Another morning highlight was a panel discussion about how brands and enterprises can harness the potential of Web3 to adapt and thrive. Key points revolved around democratizing user data control, countering data monopolization by tech giants, tokenizing assets, and challenges in linking the physical and digital worlds.
“Enterprises often face challenges with hiring experts who may quickly move on to other projects,” observed Oleg Fomenko, founder of SWEAT. “While consultancies can provide insights, the real breakthrough comes when you start building and experimenting with MVPs. Though initial attempts might fall short, perseverance can yield surprising results.”
Alex Chiocchi, CPO of Pagoda, added that Web3 streamlines verification, challenging traditional ad networks. By using an open blockchain system, excessive fees are prevented, promoting shared value with users. This shift allows benefits like self-custody and reputation while redistributing margins back to the people.
Among the key takeaways from the session was that businesses harnessing blockchain’s capabilities can anticipate a transformative impact on the global economy, especially with asset tokenization’s projected growth through 2030. As brands navigate challenges like ensuring digital authenticity and early adoption, having a targeted strategy is crucial.
Web3 gaming: Asia’s landscape and blockchain utilization
The Asian gaming landscape is buzzing with the rise of Web3 development, promising an unprecedented era of innovation and user empowerment. Central to discussions at the “Web3 Gaming: Asia Landscape” session was the gaming community’s appetite for asset and data ownership, often prioritizing this over the complexities of Web3 itself.
After attending Korea Blockchain Week, it’s evident that Japan and Korea’s mobile giants are pioneering in Web3 gaming,” said Luke Xie, founder of gaming VC fund Press Start Capital. “As opposed to Web3 games like Axie, creating AAA games takes much longer. Given the rapid pace of crypto, former mobile developers align better with this fast-paced dynamic.”
Ishank Gupta, co-founder of Kratos Studios in India, emphasized that gamers prioritize asset and data ownership over backend Web3 tech. He predicted that blockchain games should bring benefits that gamers care about with a focus on ease of usability. For instance, leading studios in India are integrating well-known IP into Web3 games while ensuring they remain engaging.
“We’re witnessing a new golden age of gaming driven by indie studios,” added Xie. “Small teams, empowered by AI, are crafting games that punch above their weight. We believe that on-chain gaming, while difficult to execute at present, is the future. It’s all about selecting the right chain based on tech, community, and support. NEAR excels at all of the above.”
The panel agreed that the Web3 gaming industry in APAC and beyond is undergoing a transformative phase, with blockchain offering gamers more control over assets and data. As developers continue to build, the focus will be on seamless onboarding, speed, and user-centric experiences. Blockchains should be subtly integrated without disrupting the gaming experience.
Bringing Web3 together with Multichain: a call for collaboration
Today’s blockchain landscape consists of independent Layer 1’s vying for supremacy, bringing up the core question of interoperability. With users often navigating several ecosystems, creating cross-chain experiences becomes paramount. This star-studded panel explored new frameworks to address hurdles and challenges in the current siloed multi-chain user experience.
“Web3’s ethos is modularity, similar to Lego blocks,” explained NEAR CEO Marike Flament. “While we prioritize access and user growth, interoperability challenges persist. But trust and unified solutions drive adoption, not a fractured approach. It’s essential that technology seamlessly serves the end user.”
Cameron Dennis, CEO of Banyan, added that key management is a critical issue. He pointed out ways to simplify these processes with tools like FastAuth. Dennis added that addressing the noticeable gap in cross-chain liquidity should be a focus. He believes that a true multichain future that drives adoption will solve key and wallet management for a better UX.
“Reflecting on a decade in this space, the competitive landscape has shifted,” mused Mary Beth Buchanan from the Cardano Foundation who is also an advisor to NEAR, “Earlier, exchanges hesitated to collaborate, fearing a loss of advantage. Today, there’s a collective push to learn from one another, ensuring technology works seamlessly for the end user.”
Cameron believes that reinforcing the current ecosystem is paramount before extending cross-chain efforts, even though creating a decentralized internet remains a resource-intensive endeavor.
Marieke stressed the importance of open-source technology in attracting top talent. Drawing inspiration from Web2’s approach to 5G standardization, she suggested that Layer 1 leaders could unite in an ‘L20’ alliance to champion unified standards, fostering a unified vision for the industry’s future.
And that’s a wrap for the official Day 2 sessions at NEAR APAC. From gaming and brand adoption to multi-chain standards and collaboration, it was clear that this first-of-its-kind regional event was a rousing success for developers and the NEAR community alike. Sunday in Saigon rolls on with more side events and after-parties, so stay tuned for the full ICYMI tomorrow. |
---
title: 2.1 The Evolution of Blockchain
description: The World of dApps and the Universe of Chains
---
# 2.1 The World of dApps and the Universe of Chains: The Evolution of ‘blockchain’
[Writing this lecture during the FTX Nuke event, November 9th, 2022, Denver, CO]
## Introduction
This module introduces the landscape of smart-contract platforms - also known as Layer 1’s. This is what we are referring to, when we speak of ‘blockchains’. But the word ‘blockchain’ we will see, is not a great representative of the reality that is created. Layer-1 blockchains, are smart contract platforms, which are designed to support decentralized applications - or dApps. The dApps can then talk to each other, in such a way that value is moved between dApps on the Layer 1. This effectively creates what we would call, an _ecosystem_. Now before we get too deep into this - and analogies of cities and comparisons of L1s - we are going to take a step back and do a very high conceptual level of ‘what is a blockchain?’ - this is usually the boring part of introducing crypto, but for us, it is only the very, very start.
## Conceptualizing a Blockchain
A blockchain, is first and foremost, a self-sustaining software system. What do we mean by this? Traditionally, servers and databases stored data in a centralized location maintained by machines. Hence the concept of a ‘data warehouse’ or ‘data center’. With blockchain, we create a system on the internet - in cyberspace - whereby a set of nodes collaborates in maintaining the same ‘state’ of a network. This means that the different nodes must reach _‘Consensus’ _in cyber-space as opposed to a single node simply updating itself running hardware in a data center. When nodes on the network are able to reach consensus, a ‘block’ is created as a reference point of the new state of the network. This block contains batches of transactions from the network, with a hash of the previous block in the chain - thereby creating a link and historicity between past and present.
_“Blocks are batches of transactions with a hash of the previous block in the chain. This links blocks together (in a chain) because hashes are cryptographically derived from the block data. This prevents fraud, because one change in any block in history would invalidate all the following blocks as all subsequent hashes would change and everyone running the blockchain would notice.”_
At scale, and in real-time, blocks are produced such that they appear to form a ‘chain’, and in this manner, we reach a state whereby a completely digital network - sustained by a number of different nodes - all participating by the same rules of coming to ‘consensus’ about the state of the network, can update that state as more activity is done on top of the network. In earlier terminology, these network participants were referred to as ‘miners’, today, they are often referred to as validators.
In the event that there is no consensus between different miners or validators on the network, then the network splits into two separate networks - still running - which is known as a ‘Hard Fork’. In this case, a new blockchain is born from the original. When we talk about Ethereum we will see how this very thing happened after the DAO hack in 2015.
### Consensus
To stay on the topic of consensus - we use this term to refer to the ‘method by which a new block is confirmed on the blockchain.’ In a ‘proof of work’ blockchain, as what Bitcoin is, and what Ethereum used to be - we have a blockchain that requires different nodes to run complex computational algorithms in competition with one another - as a manner of validating the correctness of the state of the chain. Over time, the puzzles become more difficult, and more energy intensive computational machinery is required in order to stay competitive. Hence the energy consumption issue often associated with Bitcoin.
Entirely different from proof of work, is proof of stake. In a proof of stake system, we change up how ‘validators’ or nodes come to consensus. Instead of solving complex puzzles, using increasingly demanding computation power, we require node operators to lock the native tokens of the network onto the network as ‘collateral’ against acting poorly in maintaining the state of the network. So anyone with a token, can lock their token onto the network, run much lighter software to maintain the state, and contribute to the decentralization of the network.
In both cases, being successful in state maintenance accords you with a reward - a token of some sort native to the blockchain that you are validating.
However in the proof of stake model, if you act as a bad actor - if you attempt to sabotage the network, or direct it against the consensus as set by the other validators (by validating blocks differently) - you are at risk of losing a portion of your stake on the network. This is known as getting ‘slashed’.
Third, there is a nuanced version of proof of stake, known as ‘delegated proof of stake’ or ‘proof of authority’. And this is simply a way of saying that the network limits who is allowed to stake their tokens, to either certain ‘delegated’ validators, or those who have a certain threshold of tokens committed to them.
This discussion on Consensus, takes us to a broader discussion on the nature of a blockchain as being fundamentally public. What do we mean by this? We mean, that this decentralized network running in cyberspace is a public-permissionless network such that ANYONE willing to purchase the token, or run the necessary software computations, can participate in the maintenance of the network state.
If the network is permissioned, it means that while it is visible and operating out in the open, only special people can participate in certain state maintenance activities.
Meanwhile, if the network is private, it means that only certain people can see the network and its operations as a whole.
| Pick 1 below. | Pick 1 below. |
| --- | --- |
| Public | Permissioned |
| Private | Permissionless |
Now there is one very serious implication of a blockchain being public in its fundamental design. And that has to do with token issuance.
We said before, that after the complex computation has been solved, or the validators affirm the state of the chain, that a block is produced and a token is issued as a reward. This is two sides of the same coin: From a state maintenance and durability perspective, the token ensures proper mechanism design of the decentralized system. From a financial services perspective, the system ensures the maintenance and programming for a sound monetary economy built around a decentralized system.
Where is the elephant in the room?
Well in proof of work chains, like Bitcoin, the network has defined its total supply from the beginning, and increasingly limits issuance as the network evolves over time. That is to say, miners will keep competing, and every couple of years the rewards will ‘Halve’ such that they earn less and less, and less and less is emitted.
But in proof of stake, we face a somewhat different situation - whereby every time validators come to consensus, tokens are given out and added to the stake of existing delegators.
What this means is the following:
#### Public block production = token inflation.
This is to say, that you cannot - in any manageable way, have a network that is public, and produces blocks - whereby new tokens are not created to incentivize the validators to validate the state of the blockchain.
Bitcoin has kicked the can down the road, and proposed miners be incentivized by fees on the network - but they have until 2148 to figure this out fully. For proof of stake systems, we will show how different chains attempt to solve this problem in different ways (Specifically ETH and NEAR).
### Smart Contracts
Self-executing code, and programmability of functions into the blocks of a blockchain. A smart-contract is the programmable function that can be implemented on top of a blockchain. In other words, a smart contract is a program running on top of a blockchain that executes certain functions when pre-conditions are met to facilitate movements of money and information (value or data). At its core, the prospect of self-executing code - is a major innovation in creating permissionless, decentralized systems to handle value.
### MEV
If we zoom in even closer, we come to the mechanics of controlling what goes into each block, known as [MEV - Maximal Extractable Value](https://ethereum.org/en/developers/docs/mev/). This is a concept to file away but keep in the back of your mind, as it becomes quite relevant for DeFi and finance on blockchains. In short:
_“Maximal extractable value (MEV) refers to the maximum value that can be extracted from block production in excess of the standard block reward and gas fees by including, excluding, and changing the order of transactions in a block.”_
The main idea behind MEV is that certain players can influence what information is put into the next block on the chain, such that multiple activities can be taken on-chain in a short period of time. This definition here is more than anything a pointer to relevant topics that come up very frequently in DeFi.
[https://twitter.com/SalomonCrypto/status/1592762567952257024?s=20&t=zwJscjBFhMVufKcxkKxwHQ](https://twitter.com/SalomonCrypto/status/1592762567952257024?s=20&t=zwJscjBFhMVufKcxkKxwHQ)
### Virtual Machines
Last but not least, we should allude to and address the concept of a Virtual Machine, and specifically the Ethereum Virtual Machine. Because as we will see, an EVM is the common basis for many other blockchains in the space. A virtual machine is a setup that allows the rules and programmability of a blockchain to be re-implemented in other environments.
_“Ethereum Virtual Machine (EVM) is designed as the runtime environment for [smart contracts](https://www.geeksforgeeks.org/smart-contracts/) in [Ethereum](https://www.geeksforgeeks.org/introduction-to-ethereum-part-1/). It is sandboxed and isolated from the other parts of the system. This means that any operation on EVM should not affect your data or programs in any way, no matter how many times you call a particular function on it.” ([Geeks](https://www.geeksforgeeks.org/what-is-ethereum-virtual-machine-and-how-it-works/#:~:text=Ethereum%20Virtual%20Machine%20(EVM)%20is,a%20particular%20function%20on%20it.))_
This means that someone could use an EVM to create a clone of Ethereum, with slightly different parameters but still running the core logic and turing-complete programming language of Solidity, to make it easy to recreate smart contracts just as they are done on Ethereum.
#### Some other fast facts about the EVM:
* It is the computer that stores data on blockchain, like bitcoin, but it also executes code in smart contracts on the Ethereum network.
* The machine is made to be able to run any kind of Crypto-contract that can be built on Ethereum’s blockchain. It does this by using a programming language called Solidity, which is compiled into the EVM for execution.
* The intention behind writing code on the Ethereum network is to create smart contracts and programs that automatically execute things when certain conditions are met. If a terms or condition is not met, the system can execute it in an “exit” function as well.
### Summary / Recap: What is the idea behind a smart contract platform?
Taking what we have said above, we can summarize our understanding of what a blockchain is by saying the following:
_A Blockchain is a decentralized network of participants, who are collaboratively participating in the maintenance of the state of the network, through the routine generation of blocks of data. These participants form consensus according to the design of the chain, and earn rewards for their participation in the maintenance of the network. These rewards are in the form of a digital token._
What is fascinating, is that these networks are gigantic, self-sustained artifacts of cyberspace. They are quite literally software living on their own in cyberspace, thanks to the active participation of the different network participants. But the underlying value proposition remains the same: The system lives on its own, the system creates its own value, and the individuals move in and out of the system according to its pre-defined rules.
This is how you should think of a blockchain - as a system of self-executing code living in cyberspace and incentivizing participants with token incentives.
Every blockchain thus must make certain decisions as it pertains to its fundamental design. And this has led some - notably the Founder and GP of DragonFly Capital - Haseeb Qureshi - to propose the quite fitting analogy of blockchains to cities – one might be able to go so far as countries. What does Haseeb mean?
## L1 - Blockchains as Cities
The analogy of different L1 blockchain ecosystems as different cities has to do with the fact that each blockchain has to make certain fundamental design decisions that impacts how the blockchain works, and in a similar vein, the types of builders and culture that accrues to that network.
These decisions can be summarized in the following manner:
* **Validation design / Consensus mechanism.** This is usually, Proof of Work, Proof of Stake, Delegated Proof of Stake, Proof of Authority, Proof of History, and so forth.
* **Transaction speed**. How quickly can new blocks be processed on-chain, by all of the different validators on the network?
* **Crypto-economics.** How many tokens are rewarded to validators, how many total tokens are there on the network, and is there a deflationary mechanism built in?
* **Scalability design**. How is the network designed to scale? Sharding, side-chains, rollups, high-throughput machinery, etc.
* **Programming languages**. What kinds of programming languages can developers build applications with?
* **Other differentiating features**. The account model for users participating on the chain. Automatic fees for developers deploying smart contracts.
As we will see in the video from Haseeb, the different unique design specs of each L1 blockchain, gives way to an ecosystem that is not dissimilar to a city or a country. There is a currency (L1 token), a programming language (set of languages), certain monetary policies like inflationary or deflationary pressure, and then a host of decentralized applications built on top.
And this is where we start our discussion of the landscape of L1s, and _The World of Dapps_ vs. _The Universe of Chains_ models of Blockchains. This specifically has to do with the focus on the ‘ecosystem component’ of a blockchain. Once we have a digitally self-sustaining network that is maintained by a suite of decentralized stakeholders - what can you do with it? You can build decentralized applications on top of it, or connect parallel ‘side-chains’ to the mother chain such that an ecosystem can grow around the core L1 chain.
## The World of Dapps and the Universe of Chains
The idea behind the World of Dapps vs. the Universe of Chains dichotomy is that there is fundamentally two ways of looking at scaling a blockchain: Either the blockchain maintains its state - and by default its fundamental design - in such a way that all dApps build _on top of that chain _to create a world of dapps. Think of this option like a single unified country, or cloud-of-services. Examples of this would be ETH 2.0, NEAR, Solana, and Elrond.
Or, the L1 chain designs their system in such a way, that another chain - following extremely similar design logic as the mother-chain, is spun up to accommodate specific applications, or to ensure the scalability of the chain into the future. This would be known as a Universe of Chains model. Examples of this would be Polkadot and Cosmos.
This is an extremely helpful framework to make sense of the L1 landscape, and then by extension the crypto product stack.
## The Crypto Product Stack
The goal of this lecture has been an initial orientation into what is a blockchain, how that translates into an L1 ecosystem, and then how that is a helpful framework for making sense of what kinds of applications are built in crypto. The final piece we will cover is how to connect the larger product stack to this ecosystem design.
The first thing to consider is the idea of infrastructure - what is infrastructure? In essence, it is support for access to services, assets, or users inside of an ecosystem. So when we speak of infrastructure we are talking about things like:
* **Bridges** - between different ecosystems (think of it like highways).
* **Oracles** - connecting data from the rest of the internet in the ecosystem.
* **Storage solutions** - holding additional data from which can be stored inside of the specific L1 in question.
* **Indexers** - for keeping track of participation and activities across ecosystems.
* **On** - **Ramps** and **Off** - **Ramps** for moving fiat currency into an ecosystem.
* **Stablecoins** - either native, or from outside as a form of stable money markets.
* **Custody Platforms** - For bringing in outside investors and institutions.
If we think analogously of crypto L1s as cities, we can think of this infrastructure as the early banks, schools, hospitals, and grocery stores of this digital frontier.
Going forward, keep this framework in mind as we evaluate different dApps, ecosystems and products. You should always attempt to orient yourself to the solution by identifying - what L1 is it built on, how is it designed, and what infrastructure does it require?
|
---
NEP: 178
Title: Non Fungible Token Approval Management
Author: Chad Ostrowski <@chadoh>, Thor <@thor314>
DiscussionsTo: https://github.com/near/NEPs/discussions/178
Status: Final
Type: Standards Track
Category: Contract
Created: 03-Mar-2022
Requires: 171
---
## Summary
A system for allowing a set of users or contracts to transfer specific Non-Fungible Tokens on behalf of an owner. Similar to approval management systems in standards like [ERC-721].
## Motivation
People familiar with [ERC-721] may expect to need an approval management system for basic transfers, where a simple transfer from Alice to Bob requires that Alice first _approve_ Bob to spend one of her tokens, after which Bob can call `transfer_from` to actually transfer the token to himself.
## Rationale and alternatives
NEAR's [core Non-Fungible Token standard][NFT Core] includes good support for safe atomic transfers without such complexity. It even provides "transfer and call" functionality (`nft_transfer_call`) which allows a specific token to be "attached" to a call to a separate contract. For many Non-Fungible Token workflows, these options may circumvent the need for a full-blown Approval Management system.
However, some Non-Fungible Token developers, marketplaces, dApps, or artists may require greater control. This standard provides a uniform interface allowing token owners to approve other NEAR accounts, whether individuals or contracts, to transfer specific tokens on the owner's behalf.
Prior art:
- Ethereum's [ERC-721]
- [NEP-4](https://github.com/near/NEPs/pull/4), NEAR's old NFT standard that does not include approved_account_ids per token ID
## Specification
## Example Scenarios
Let's consider some examples. Our cast of characters & apps:
- Alice: has account `alice` with no contract deployed to it
- Bob: has account `bob` with no contract deployed to it
- NFT: a contract with account `nft`, implementing only the [Core NFT standard][NFT Core] with this Approval Management extension
- Market: a contract with account `market` which sells tokens from `nft` as well as other NFT contracts
- Bazaar: similar to Market, but implemented differently (spoiler alert: has no `nft_on_approve` function!), has account `bazaar`
Alice and Bob are already [registered][Storage Management] with NFT, Market, and Bazaar, and Alice owns a token on the NFT contract with ID=`"1"`.
Let's examine the technical calls through the following scenarios:
1. [Simple approval](#1-simple-approval): Alice approves Bob to transfer her token.
2. [Approval with cross-contract call (XCC)](#2-approval-with-cross-contract-call): Alice approves Market to transfer one of her tokens and passes `msg` so that NFT will call `nft_on_approve` on Market's contract.
3. [Approval with XCC, edge case](#3-approval-with-cross-contract-call-edge-case): Alice approves Bazaar and passes `msg` again, but what's this? Bazaar doesn't implement `nft_on_approve`, so Alice sees an error in the transaction result. Not to worry, though, she checks `nft_is_approved` and sees that she did successfully approve Bazaar, despite the error.
4. [Approval IDs](#4-approval-ids): Bob buys Alice's token via Market.
5. [Approval IDs, edge case](#5-approval-ids-edge-case): Bob transfers same token back to Alice, Alice re-approves Market & Bazaar. Bazaar has an outdated cache. Bob tries to buy from Bazaar at the old price.
6. [Revoke one](#6-revoke-one): Alice revokes Market's approval for this token.
7. [Revoke all](#7-revoke-all): Alice revokes all approval for this token.
### 1. Simple Approval
Alice approves Bob to transfer her token.
##### High-level explanation
1. Alice approves Bob
2. Alice queries the token to verify
3. Alice verifies a different way
##### Technical calls
1. Alice calls `nft::nft_approve({ "token_id": "1", "account_id": "bob" })`. She attaches 1 yoctoⓃ, (.000000000000000000000001Ⓝ). Using [NEAR CLI](https://docs.near.org/tools/near-cli) to make this call, the command would be:
```shell
near call nft nft_approve \
'{ "token_id": "1", "account_id": "bob" }' \
--accountId alice --depositYocto 1
```
The response:
```shell
''
```
2. Alice calls view method `nft_token`:
```shell
near view nft nft_token '{ "token_id": "1" }'
```
The response:
```json
{
"token_id": "1",
"owner_id": "alice.near",
"approved_account_ids": {
"bob": 1
}
}
```
3. Alice calls view method `nft_is_approved`:
```shell
near view nft nft_is_approved '{ "token_id": "1", "approved_account_id": "bob" }'
```
The response:
```shell
true
```
### 2. Approval with cross-contract call
Alice approves Market to transfer one of her tokens and passes `msg` so that NFT will call `nft_on_approve` on Market's contract. She probably does this via Market's frontend app which would know how to construct `msg` in a useful way.
##### High-level explanation
1. Alice calls `nft_approve` to approve `market` to transfer her token, and passes a `msg`
2. Since `msg` is included, `nft` will schedule a cross-contract call to `market`
3. Market can do whatever it wants with this info, such as listing the token for sale at a given price. The result of this operation is returned as the promise outcome to the original `nft_approve` call.
##### Technical calls
1. Using near-cli:
```shell
near call nft nft_approve '{
"token_id": "1",
"account_id": "market",
"msg": "{\"action\": \"list\", \"price\": \"100\", \"token\": \"nDAI\" }"
}' --accountId alice --depositYocto 1
```
At this point, near-cli will hang until the cross-contract call chain fully resolves, which would also be true if Alice used a Market frontend using [near-api-js](https://docs.near.org/tools/near-api-js/quick-reference). Alice's part is done, though. The rest happens behind the scenes.
2. `nft` schedules a call to `nft_on_approve` on `market`. Using near-cli notation for easy cross-reference with the above, this would look like:
```shell
near call market nft_on_approve '{
"token_id": "1",
"owner_id": "alice",
"approval_id": 2,
"msg": "{\"action\": \"list\", \"price\": \"100\", \"token\": \"nDAI\" }"
}' --accountId nft
```
3. `market` now knows that it can sell Alice's token for 100 [nDAI](https://explorer.mainnet.near.org/accounts/6b175474e89094c44da98b954eedeac495271d0f.factory.bridge.near), and that when it transfers it to a buyer using `nft_transfer`, it can pass along the given `approval_id` to ensure that Alice hasn't changed her mind. It can schedule any further cross-contract calls it wants, and if it returns these promises correctly, Alice's initial near-cli call will resolve with the outcome from the final step in the chain. If Alice actually made this call from a Market frontend, the frontend can use this return value for something useful.
### 3. Approval with cross-contract call, edge case
Alice approves Bazaar and passes `msg` again. Maybe she actually does this via near-cli, rather than using Bazaar's frontend, because what's this? Bazaar doesn't implement `nft_on_approve`, so Alice sees an error in the transaction result.
Not to worry, though, she checks `nft_is_approved` and sees that she did successfully approve Bazaar, despite the error. She will have to find a new way to list her token for sale in Bazaar, rather than using the same `msg` shortcut that worked for Market.
##### High-level explanation
1. Alice calls `nft_approve` to approve `bazaar` to transfer her token, and passes a `msg`.
2. Since `msg` is included, `nft` will schedule a cross-contract call to `bazaar`.
3. Bazaar doesn't implement `nft_on_approve`, so this call results in an error. The approval still worked, but Alice sees an error in her near-cli output.
4. Alice checks if `bazaar` is approved, and sees that it is, despite the error.
##### Technical calls
1. Using near-cli:
```shell
near call nft nft_approve '{
"token_id": "1",
"account_id": "bazaar",
"msg": "{\"action\": \"list\", \"price\": \"100\", \"token\": \"nDAI\" }"
}' --accountId alice --depositYocto 1
```
2. `nft` schedules a call to `nft_on_approve` on `market`. Using near-cli notation for easy cross-reference with the above, this would look like:
```shell
near call bazaar nft_on_approve '{
"token_id": "1",
"owner_id": "alice",
"approval_id": 3,
"msg": "{\"action\": \"list\", \"price\": \"100\", \"token\": \"nDAI\" }"
}' --accountId nft
```
3. 💥 `bazaar` doesn't implement this method, so the call results in an error. Alice sees this error in the output from near-cli.
4. Alice checks if the approval itself worked, despite the error on the cross-contract call:
```shell
near view nft nft_is_approved \
'{ "token_id": "1", "approved_account_id": "bazaar" }'
```
The response:
```shell
true
```
### 4. Approval IDs
Bob buys Alice's token via Market. Bob probably does this via Market's frontend, which will probably initiate the transfer via a call to `ft_transfer_call` on the nDAI contract to transfer 100 nDAI to `market`. Like the NFT standard's "transfer and call" function, [Fungible Token][FT Core]'s `ft_transfer_call` takes a `msg` which `market` can use to pass along information it will need to pay Alice and actually transfer the NFT. The actual transfer of the NFT is the only part we care about here.
##### High-level explanation
1. Bob signs some transaction which results in the `market` contract calling `nft_transfer` on the `nft` contract, as described above. To be trustworthy and pass security audits, `market` needs to pass along `approval_id` so that it knows it has up-to-date information.
##### Technical calls
Using near-cli notation for consistency:
```shell
near call nft nft_transfer '{
"receiver_id": "bob",
"token_id": "1",
"approval_id": 2,
}' --accountId market --depositYocto 1
```
### 5. Approval IDs, edge case
Bob transfers same token back to Alice, Alice re-approves Market & Bazaar, listing her token at a higher price than before. Bazaar is somehow unaware of these changes, and still stores `approval_id: 3` internally along with Alice's old price. Bob tries to buy from Bazaar at the old price. Like the previous example, this probably starts with a call to a different contract, which eventually results in a call to `nft_transfer` on `bazaar`. Let's consider a possible scenario from that point.
##### High-level explanation
Bob signs some transaction which results in the `bazaar` contract calling `nft_transfer` on the `nft` contract, as described above. To be trustworthy and pass security audits, `bazaar` needs to pass along `approval_id` so that it knows it has up-to-date information. It does not have up-to-date information, so the call fails. If the initial `nft_transfer` call is part of a call chain originating from a call to `ft_transfer_call` on a fungible token, Bob's payment will be refunded and no assets will change hands.
##### Technical calls
Using near-cli notation for consistency:
```shell
near call nft nft_transfer '{
"receiver_id": "bob",
"token_id": "1",
"approval_id": 3,
}' --accountId bazaar --depositYocto 1
```
### 6. Revoke one
Alice revokes Market's approval for this token.
##### Technical calls
Using near-cli:
```shell
near call nft nft_revoke '{
"account_id": "market",
"token_id": "1",
}' --accountId alice --depositYocto 1
```
Note that `market` will not get a cross-contract call in this case. The implementers of the Market app should implement [cron](https://en.wikipedia.org/wiki/Cron)-type functionality to intermittently check that Market still has the access they expect.
### 7. Revoke all
Alice revokes all approval for this token.
##### Technical calls
Using near-cli:
```shell
near call nft nft_revoke_all '{
"token_id": "1",
}' --accountId alice --depositYocto 1
```
Again, note that no previous approvers will get cross-contract calls in this case.
## Reference-level explanation
The `Token` structure returned by `nft_token` must include an `approved_account_ids` field, which is a map of account IDs to approval IDs. Using TypeScript's [Record type](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype) notation:
```diff
type Token = {
token_id: string,
owner_id: string,
+ approved_account_ids: Record<string, number>,
}
```
Example token data:
```json
{
"token_id": "1",
"owner_id": "alice.near",
"approved_account_ids": {
"bob.near": 1,
"carol.near": 2
}
}
```
### What is an "approval ID"?
This is a unique number given to each approval that allows well-intentioned marketplaces or other 3rd-party NFT resellers to avoid a race condition. The race condition occurs when:
1. A token is listed in two marketplaces, which are both saved to the token as approved accounts.
2. One marketplace sells the token, which clears the approved accounts.
3. The new owner sells back to the original owner.
4. The original owner approves the token for the second marketplace again to list at a new price. But for some reason the second marketplace still lists the token at the previous price and is unaware of the transfers happening.
5. The second marketplace, operating from old information, attempts to again sell the token at the old price.
Note that while this describes an honest mistake, the possibility of such a bug can also be taken advantage of by malicious parties via [front-running](https://users.encs.concordia.ca/~clark/papers/2019_wtsc_front.pdf).
To avoid this possibility, the NFT contract generates a unique approval ID each time it approves an account. Then when calling `nft_transfer` or `nft_transfer_call`, the approved account passes `approval_id` with this value to make sure the underlying state of the token hasn't changed from what the approved account expects.
Keeping with the example above, say the initial approval of the second marketplace generated the following `approved_account_ids` data:
```json
{
"token_id": "1",
"owner_id": "alice.near",
"approved_account_ids": {
"marketplace_1.near": 1,
"marketplace_2.near": 2
}
}
```
But after the transfers and re-approval described above, the token might have `approved_account_ids` as:
```json
{
"token_id": "1",
"owner_id": "alice.near",
"approved_account_ids": {
"marketplace_2.near": 3
}
}
```
The marketplace then tries to call `nft_transfer`, passing outdated information:
```bash
# oops!
near call nft-contract.near nft_transfer '{ "approval_id": 2 }'
```
### Interface
The NFT contract must implement the following methods:
```ts
/******************/
/* CHANGE METHODS */
/******************/
// Add an approved account for a specific token.
//
// Requirements
// * Caller of the method must attach a deposit of at least 1 yoctoⓃ for
// security purposes
// * Contract MAY require caller to attach larger deposit, to cover cost of
// storing approver data
// * Contract MUST panic if called by someone other than token owner
// * Contract MUST panic if addition would cause `nft_revoke_all` to exceed
// single-block gas limit. See below for more info.
// * Contract MUST increment approval ID even if re-approving an account
// * If successfully approved or if had already been approved, and if `msg` is
// present, contract MUST call `nft_on_approve` on `account_id`. See
// `nft_on_approve` description below for details.
//
// Arguments:
// * `token_id`: the token for which to add an approval
// * `account_id`: the account to add to `approved_account_ids`
// * `msg`: optional string to be passed to `nft_on_approve`
//
// Returns void, if no `msg` given. Otherwise, returns promise call to
// `nft_on_approve`, which can resolve with whatever it wants.
function nft_approve(
token_id: TokenId,
account_id: string,
msg: string | null
): void | Promise<any> {}
// Revoke an approved account for a specific token.
//
// Requirements
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security
// purposes
// * If contract requires >1yN deposit on `nft_approve`, contract
// MUST refund associated storage deposit when owner revokes approval
// * Contract MUST panic if called by someone other than token owner
//
// Arguments:
// * `token_id`: the token for which to revoke an approval
// * `account_id`: the account to remove from `approved_account_ids`
function nft_revoke(token_id: string, account_id: string) {}
// Revoke all approved accounts for a specific token.
//
// Requirements
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security
// purposes
// * If contract requires >1yN deposit on `nft_approve`, contract
// MUST refund all associated storage deposit when owner revokes approved_account_ids
// * Contract MUST panic if called by someone other than token owner
//
// Arguments:
// * `token_id`: the token with approved_account_ids to revoke
function nft_revoke_all(token_id: string) {}
/****************/
/* VIEW METHODS */
/****************/
// Check if a token is approved for transfer by a given account, optionally
// checking an approval_id
//
// Arguments:
// * `token_id`: the token for which to revoke an approval
// * `approved_account_id`: the account to check the existence of in `approved_account_ids`
// * `approval_id`: an optional approval ID to check against current approval ID for given account
//
// Returns:
// if `approval_id` given, `true` if `approved_account_id` is approved with given `approval_id`
// otherwise, `true` if `approved_account_id` is in list of approved accounts
function nft_is_approved(
token_id: string,
approved_account_id: string,
approval_id: number | null
): boolean {}
```
### Why must `nft_approve` panic if `nft_revoke_all` would fail later?
In the description of `nft_approve` above, it states:
> Contract MUST panic if addition would cause `nft_revoke_all` to exceed
> single-block gas limit.
What does this mean?
First, it's useful to understand what we mean by "single-block gas limit". This refers to the [hard cap on gas per block at the protocol layer](https://docs.near.org/docs/concepts/gas#thinking-in-gas). This number will increase over time.
Removing data from a contract uses gas, so if an NFT had a large enough number of approved_account_ids, `nft_revoke_all` would fail, because calling it would exceed the maximum gas.
Contracts must prevent this by capping the number of approved_account_ids for a given token. However, it is up to contract authors to determine a sensible cap for their contract (and the single block gas limit at the time they deploy). Since contract implementations can vary, some implementations will be able to support a larger number of approved_account_ids than others, even with the same maximum gas per block.
Contract authors may choose to set a cap of something small and safe like 10 approved_account_ids, or they could dynamically calculate whether a new approval would break future calls to `nft_revoke_all`. But every contract MUST ensure that they never break the functionality of `nft_revoke_all`.
### Approved Account Contract Interface
If a contract that gets approved to transfer NFTs wants to, it can implement `nft_on_approve` to update its own state when granted approval for a token:
```ts
// Respond to notification that contract has been granted approval for a token.
//
// Notes
// * Contract knows the token contract ID from `predecessor_account_id`
//
// Arguments:
// * `token_id`: the token to which this contract has been granted approval
// * `owner_id`: the owner of the token
// * `approval_id`: the approval ID stored by NFT contract for this approval.
// Expected to be a number within the 2^53 limit representable by JSON.
// * `msg`: specifies information needed by the approved contract in order to
// handle the approval. Can indicate both a function to call and the
// parameters to pass to that function.
function nft_on_approve(
token_id: TokenId,
owner_id: string,
approval_id: number,
msg: string
) {}
```
Note that the NFT contract will fire-and-forget this call, ignoring any return values or errors generated. This means that even if the approved account does not have a contract or does not implement `nft_on_approve`, the approval will still work correctly from the point of view of the NFT contract.
Further note that there is no parallel `nft_on_revoke` when revoking either a single approval or when revoking all. This is partially because scheduling many `nft_on_revoke` calls when revoking all approved_account_ids could incur prohibitive [gas fees](https://docs.near.org/docs/concepts/gas). Apps and contracts which cache NFT approved_account_ids can therefore not rely on having up-to-date information, and should periodically refresh their caches. Since this will be the necessary reality for dealing with `nft_revoke_all`, there is no reason to complicate `nft_revoke` with an `nft_on_revoke` call.
### No incurred cost for core NFT behavior
NFT contracts should be implemented in a way to avoid extra gas fees for serialization & deserialization of `approved_account_ids` for calls to `nft_*` methods other than `nft_token`. See `near-contract-standards` [implementation of `ft_metadata` using `LazyOption`](https://github.com/near/near-sdk-rs/blob/c2771af7fdfe01a4e8414046752ee16fb0d29d39/examples/fungible-token/ft/src/lib.rs#L71) as a reference example.
## Reference Implementation
[NFT Approval Receiver Interface](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/non_fungible_token/approval/approval_receiver.rs)
[NFT Approval Implementation](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/non_fungible_token/approval/approval_impl.rs)
## Errata
- **2022-02-03**: updated `Token` struct field names. `id` was changed to `token_id` and `approvals` was changed to `approved_account_ids`. This is to be consistent with current implementations of the standard and the rust SDK docs.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
[ERC-721]: https://eips.ethereum.org/EIPS/eip-721
[NFT Core]: ../specs/Standards/Tokens/NonFungibleToken/Core.md
[Storage Management]: ../specs/Standards/StorageManagement.md
[FT Core]: ../specs/Standards/Tokens/FungibleToken/Core.md
|
---
title: Behavioral Interview Questions
sidebar_label: Behavioral Interview Questions
sidebar_position: 4
---
## What are Behavioral Interview Questions?
Behavioral interview questions are those that focus on how a candidate has handled various situations in the workplace and reveal character traits, abilities, and skills. These questions give an interviewer an idea of how someone would behave in a similar situation were to arise, the logic being that your success in the past will show success in the future.
Unlike traditional interview questions, behavior job interview techniques look for concrete examples of skills and experiences that relate to the position. Strong answers to these questions should provide a brief story that illustrates the skills and strengths if hired.
## How to assess
When using behavioral interview questions, candidates should provide situations that are specific, personal, and professional. By asking behavioral interview questions, you will learn more about the thought process, and the strategies and skills the candidate uses to solve problems.
* Assessing using the STAR method: Use the STAR method to answer any question. STAR stands for situation, task, action, and result. For Situation, briefly share context and relevant details for the challenge or problem you were facing. For Task, describe your role in overcoming the challenge or handling the situation. For Action, explain what action was taken by you or your team, although it's important to focus on the role you played, specifically. For the Result, share the successful outcome. If possible, provide quantifiable results or concrete examples of the effect of your effort.
## **Behavioral interview questions**
Here are some common behavioral interview questions and suggestions for good answers. They are listed by competencies:
### Time management
Interviewers ask questions about time management to gain an understanding of how someone handles multiple responsibilities, prioritizes time, and delegates tasks to meet deadlines. Listen for responses that include approaches, tools, and strategies on how they prioritize their to-do list. Consider highlighting your organizational skills as a tool that keeps you on track.
1. Tell me about a goal you set and reached and how you achieved it.
2. Tell me about the last time your workday ended before you were able to get everything done.
3. Give me an example of a time you had to prioritize certain tasks or projects over others.
4. Give me an example of a time when you had to handle multiple responsibilities at once. How did you prioritize your time?
5. Tell me about the last time you handle a long-term project. How did you keep the project on track?
### Adaptability
Plans may not always work as planned, but the ability to adjust an approach shows the resolve to succeed. Look for answers that demonstrate growth, even if they weren’t successful at the time.
1. Can you share about a time you had to be flexible or adaptable?
2. Tell me about a time when you had to be creative to solve a problem.
3. Tell me about a time you had to learn quickly.
4. Tell me about a time you made a difficult decision.
5. Tell me about how you work under pressure.
### Overcoming challenges
Employers ask questions about overcoming a challenging situation to gauge the level of perseverance. They want to gain a better understanding of how you handle stress and if you’re able to break down larger problems into smaller tasks.
1. Tell me about a time when you handled a challenging situation.
2. Tell me about a time when you made a mistake. What did you do to correct it?
3. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.
4. Tell me about a goal you failed to achieve.
5. Tell me about a time you felt you went above and beyond.
### Motivation and values
Asking questions about values and motivations allows employers to gain insight into what they are passionate about, how they stay focused and what makes them excited.
1. Give me an example of how you set goals.
2. Tell me about the proudest moment in your professional career why it was meaningful to you.
3. Can you give me an example of a time when you felt dissatisfied with your work?
4. Tell me about a body of work you felt was most impactful for you or your company.
5. How do you stay motivated when a job requires you to perform repetitive tasks?
### Communication
The ability to communicate effectively is needed in and out of the workplace.
1. Tell me about a time when you had to say “no.”
2. Give me an example of a time when you persuaded someone. How’d you do it and why?
3. Talk about a time when you’ve had to manage up.
4. Tell me about a time when you had to explain a complex topic to people with less subject knowledge. How did you make sure everyone could understand you?
5. Tell me about a time you had to build rapport with a coworker or client whose personality was different than yours?
### Teamwork
Whether working directly with other people or working with stakeholders, the ability to interact and communicate with others effectively is key.
1. Tell me about a time when you collaborated with others who were different than you.
2. Tell me about the best presentation you’ve given. Why was it good?
3. Tell me about a time when you felt like a good leader.
4. Can you give me an example of how you’ve contributed to the culture of previous teams, companies or groups?
5. Share an example of how you were able to motivate a coworker, your peers or your team.
### Conflict resolution
To successfully answer questions about tension in the workplace, highlight a situation where they took the lead to resolve conflict—not their manager or coworker. Watch for how others are framed as a signal of how they interact with others. A disagreement with a coworker doesn’t always mean the relationship is damaged or that the other person is inherently wrong. These questions are meant to surface stories about how they can view an issue from someone else’s perspective to reach an understanding.
1. Tell me about a time you disagreed with a supervisor.
2. Tell me about a time you had to stand up for your beliefs.
3. Tell me about a time when you disagreed with your manager’s leadership style or team culture.
4. Tell me about a time when you were in conflict with a peer and how the situation was resolved.
5. Tell me about a time you wish you’d handled a situation with a coworker differently.
## **Example Behavioral interview answers:**
### 1. Tell me about a time when you handled a challenging situation.
Example: _"My manager left town unexpectedly when we were in the middle of pitching large sponsors for an upcoming conference. I was tasked with putting together the slide decks for the presentations to secure these sponsors but all I had was a few notes left behind by my manager. Because he was unavailable, I called a meeting with members of our team and we generated a list of the biggest selling points that would be most impactful with potential sponsors. After creating the slide deck, I presented the presentation successfully and we got the sponsorship. I'm incredibly proud of the results we achieved when we worked together."_
### 2. Tell me about a time when you made a mistake. What did you do to correct it?
Example: _"When I was working at a printing company, I misquoted the fees for a particular job. I realized the mistake, I went directly to my manager and explained what happened. He said he appreciated my honesty and suggested that we waive the setup fee for the job as an apology to the customer. I spoke to the customer directly and explained what happened and that the quoted price was actually higher than my original estimate, but that we would be happy to waive the setup fee. The customer understood and appreciated the effort to make the situation right. After that happened, I printed our price sheet to have it quickly at hand and implemented a new process for quoting estimates, one in which I double-check the final estimate before sending it."_
### 3. Tell me about a time when you were in conflict with a peer and how the situation was resolved.
Example: _"I had a sales manager who was great about stepping in to help when members of our team were struggling with meeting goals. However, she had a single approach that didn't work for everyone and members of our team were getting frustrated and felt they were being micromanaged. I suggested that I sit down one-on-one with our manager, having heard the frustrations of the team. I avoided us all sitting down because I didn't want her to feel ganged up on and become defensive. After talking, we decided that she would let team members know her door was open if they needed help but that she would let them be in charge of the strategy they used to meet their goals. We also implemented a monthly, optional training program where we had different team members present what was working for them in order to offer a variety of approaches."_
### 4. Tell me about how you work under pressure.
Example: _"I had been working on a large project that my team committed to turning around for the client in 60 days. My manager came to me and said that the client wanted it back in 45 days and that we would need to speed up our work without losing momentum on our other projects. I met with our team and we reviewed the calendar. We eliminated team meetings and shifted lower-priority tasks until the end of the 45-day period to add extra hours to our workweeks. I challenged my team to complete the project in 45 days or left and as a reward promised two days of extra PTO time. Our team got the job done in 42 days."_
### 5. Give me an example of how you set goals.
Example: _"Within a few weeks of beginning my job as a server at a restaurant, I knew I wanted to work in the foodservice industry as a chef. I decided I would learn all I could in my current position until an opening became available in the kitchen, even for less pay. I wanted the experience of working in a restaurant kitchen environment. I also started saving up money at that time to go to the culinary academy. I knew that by the time I finished school, I would have been working in the kitchen for a number of years and would be highly competitive as a candidate for chef roles."_
### 6. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.
Example: _"I took over management of a gym where the trainers were allowed to cover one another's shifts without the knowledge or approval of management. I didn't like the uncertainty involved, because if someone failed to show up for a class, there was no way to know which trainer was supposed to be there. I implemented a new policy that required trainers to go through management to make schedule changes. I also explained the problem with the previous approach and how this would resolve any possible issues."_
### 7. Share an example of how you were able to motivate a coworker, your peers or your team.
Example: _"I noticed that one of my coworkers was having a hard time meeting her sales quotas each month. I told her that not every sales technique works for every personality and that it can take time to figure out what will work best for her. I suggested we find time over the next day or two and I would show her some techniques I was using that I found highly effective. And it worked! After a couple of weeks of practice and trial and error, she was consistently hitting her quota."_
### 8. Tell me about a goal you set and reached and how you achieved it.
Example: _"In my last role, I managed all social media content. One quarter, I set a stretch goal to increase conversions to our website by 75%. I broke it down into weekly goals and researched what other brands were experimenting with. I noticed they were using videos and seeing great engagement from their customers, so I asked my boss if we could do a low-budget test. She agreed, so I produced a video cheaply in-house that drove double the engagement we normally saw on our social channels during the first week. With the new strategy, I not only met my stretch goal, but I also exceeded it by 5% increasing total conversions by 80% over the quarter.”_
### 9. Tell me about the last time your workday ended before you were able to get everything done.
Example: _"We had a client who wanted us to deliver new social media content to them by Wednesday of each week to get it scheduled for the following week. One week they requested double the content in order to increase their online activity in advance of a big launch. I decided to stay late the night before the deliverable was due. I also let the manager know that we might be a few hours behind for our content that week. A coworker and I went in early the next morning, together, made our deadline."_
### 10. Tell me about a goal you failed to achieve.
Example: _"I was working on a start-up where our goal was to create content that would educate parents about why it's important to spend time as a family around the dinner table. Unfortunately, we were never able to figure out a way to monetize the business. We polled our audience and tried many different ideas, but after a year we had to move on. However, I learned so much from the process. I developed numerous skills and realized I'm incredibly good at shifting direction when something isn't working. I realized I don't let defeats discourage me for long. Each time something didn't work, I picked myself back up and moved forward."_
|
Introducing NearPay: the First Bridge to Fiat Debit Card on NEAR
COMMUNITY
March 8, 2022
Web3 users looking for an easy bridge between fiat (currencies like the US Dollar and the Euro) and crypto needn’t wait any longer. NearPay, the first debit card and payments widget in the NEAR ecosystem, now bridges fiat and the crypto world in one seamless user experience.
Launched in late 2021 by Switzerland-based Kikimora Labs, NearPay announced its debit card wait list in early March. NearPay initially hoped to attract 1,000 users to its wait list, but had more than 18,000 in under a week.
“We hoped that people would welcome our card product, but we definitely didn’t expect that so many people would show interest,” said Ilya Romanov, Chief Marketing Officer at NearPay. “We highly appreciate the support of the community. And now we are working hard to deliver a product that people are waiting for.”
How the NearPay card works
Set to release later this year, NearPay is a debit card that comes as both a physical card and a mobile-based app. NearPay offers a number of features for consumers, developers, and merchants to make instant transactions and payments using their preferred cryptocurrency, including NEAR.
“You will see no difference between crypto and fiat payments,” reads the NearPay website. “Simple. Fast. Both directions.”
NearPay also allows users to track their spending through the app, and offers world-class security to keep accounts safe. Though some particulars are still in the works, the NearPay card will support 3DSecure and is already secured through Verified by Visa. There will also be features such as spending limits, with the full feature set becoming available by the end of March or early April.
A seamless Web3 gateway
The NearPay team believes that the crypto debit card will be amongst the easiest ways to dive into crypto, making it a seamless part of daily life.
Consumers can top up their NearPay card balances, and use it to make purchases immediately. “The cards will be NEAR-oriented but support other cryptocurrencies as well,” says Ivan Ilin, Chief Operating Officer at NearPay.
NearPay offers several tools to developers interested in using the card for their apps and projects. To get started, NearPay offers a plug-and-play widget, simple documentation, webhooks and APIs, and a developer console.
“For developers, we provide a simple API with an SDK,” says Ilin. “The integration is possible with a website or a mobile application. We provide a merchant dashboard where one can see all the transaction statistics.”
NearPay also helps onboard traditional businesses into the global Web3 ecosystem. The team built a payment gateway for merchants with no transaction or setup fees, allowing businesses to accept crypto for all of their goods and services, while a handy dashboard allows businesses to see data on payments, invoices, and more.
“For businesses, we support two scenarios: fiat-to-crypto to a user’s wallet and fiat-to-crypto to a merchant’s wallet for a certain order,” Ilin explains. “We work with NFT marketplaces, DeFi projects, and many others.”
Countries supporting NearPay
The NearPay widget is currently covered in 56 countries and supports 27 currencies. The NearPay team is currently working on adding more supported countries and currencies, as well as making the transaction fee lower for the users.
“Our first cards will be made for Europe,” says Ilin. “But we have plans to cover all of the countries, including the United States and Asia.”
To see the full list of countries currently supporting NearPay, visit Kikimora Labs’ Notion website. |
---
id: indexing
title: Indexing Solutions on NEAR
sidebar_label: "Indexing Solutions"
---
# Indexing Solutions on NEAR
Here's a quick overview of Indexer projects on the NEAR ecosystem:
- [QueryAPI](../2.build/6.data-infrastructure/query-api/intro.md): Near QueryAPI is a fully managed solution to build indexer functions, extract on-chain data, store it in a database, and be able to query it using GraphQL endpoints.
- [BigQuery](../2.build/6.data-infrastructure/big-query.md): Blockchain data indexing in NEAR Public Lakehouse is for anyone wanting to understand blockchain data.
- [NEAR Lake Framework](../2.build/6.data-infrastructure/lake-framework/near-lake.md): a companion library to NEAR Lake. It allows you to build your own indexer that watches a stream of blocks **from a NEAR Lake data source** and allows you to **create your own logic to process that data**. Keep in mind this is **the one you want to use for future projects**, instead of the Indexer Framework. Read [why is better](https://docs.near.org/concepts/advanced/near-indexer-framework#why-is-it-better-than-near-indexer-framework).
- [Indexer.xyz Multichain Indexer](https://indexer.xyz/): Indexer.xyz is an application layer that you can build your NFT or DeFi applications entirely on top of. In addition to raw transaction indexing, Indexer.xyz provides you with a standardized GraphQL API layer to easily tap into transactions across contracts and chains.
- [Pagoda NEAR Lake](https://docs.pagoda.co/near-lake): with this fully managed solution by [Pagoda Inc.](https://pagoda.co), you don't need to run your own NEAR Lake Nodes and AWS S3 buckets.
- [The Graph](https://thegraph.com/docs/en/cookbook/near/): development tools to process blockchain events and make the resulting data easily available via a GraphQL API, known individually as a subgraph. [Graph Node](https://github.com/graphprotocol/graph-node) is able to process NEAR events, which means that NEAR developers can build subgraphs to index their smart contracts.
- [GetBlock](https://getblock.io/explorers/near/blocks/): developer tools offering a simple and reliable API access to multiple blockchains including NEAR Protocol.
- [NearBlocks](https://api.nearblocks.io/api-docs/#/): build precise & reliable dApps with NearBlocks APIs.
- [Octopus Network NEAR Indexer](https://github.com/octopus-network/octopus-near-indexer-s3): an indexing solution based on NEAR Lake framework.
- [Covalent](https://www.covalenthq.com/docs/networks/aurora/): for [Aurora EVM](https://aurora.dev/) indexing, Covalent provides a unified API bringing visibility to billions of Web3 data points.
- [NEAR Indexer Framework](https://docs.near.org/concepts/advanced/near-indexer-framework): a micro-framework providing you with a "live" stream of blocks. Useful to handle on-chain real-time `events`.
- [NEAR Indexer for Explorer](https://docs.near.org/tools/indexer-for-explorer): an indexer built on top of the indexer microframework. It watches and stores all events/data from the blockchain to a **PostgreSQL database**.
You can clone the [GitHub repository](https://github.com/near/near-indexer-for-explorer) and customize your own indexer solution.
- [SubQuery](https://academy.subquery.network/quickstart/quickstart_chains/near.html): is an end to end multi-blockchain indexing solution that provides NEAR developers with fast, flexible, universal, open source and decentralised APIs for web3 projects. The [NEAR starter project](https://github.com/subquery/near-subql-starter/tree/main/Near/near-starter) provides a template for developers to get up and running within minutes.
|
# Multi Token
:::caution
This is part of the proposed spec [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) and is subject to change.
:::
Version `1.0.0`
## Summary
A standard interface for a multi token standard that supports fungible, semi-fungible,non-fungible, and tokens of any type, allowing for ownership, transfer, and batch transfer of tokens regardless of specific type.
## Motivation
In the three years since [ERC-1155] was ratified by the Ethereum Community, Multi Token based contracts have proven themselves valuable assets. Many blockchain projects emulate this standard for representing multiple token assets classes in a single contract. The ability to reduce transaction overhead for marketplaces, video games, DAOs, and exchanges is appealing to the blockchain ecosystem and simplifies transactions for developers.
Having a single contract represent NFTs, FTs, and tokens that sit in-between greatly improves efficiency. The standard also introduced the ability to make batch requests with multiple asset classes reducing complexity. This standard allows operations that currently require _many_ transactions to be completed in a single transaction that can transfer not only NFTs and FTs, but any tokens that are a part of same token contract.
With this standard, we have sought to take advantage of the ability of the NEAR blockchain to scale. Its sharded runtime, and [storage staking] model that decouples [gas] fees from storage demand, enables ultra low transaction fees and greater on chain storage ( see [Metadata] extension).
With the aforementioned, it is noteworthy to mention that like the [NFT] standard the Multi Token standard, implements `mt_transfer_call`,
which allows, a user to attach many tokens to a call to a separate contract. Additionally, this standard includes an optional [Approval Management] extension. The extension allows marketplaces to trade on behalf of a user, providing additional flexibility for dApps.
Prior art:
- [ERC-721]
- [ERC-1155]
- [NEAR Fungible Token Standard][FT], which first pioneered the "transfer and call" technique
- [NEAR Non-Fungible Token Standard][NFT]
## Rationale
Why have another standard, aren't fungible and non-fungible tokens enough? The current fungible token and non-fungible token standards, do not provide support for representing many FT tokens in a single contract, as well as the flexibility to define different token types with different behavior in a single contract. This is something that makes it difficult to be interoperable with other major blockchain networks, that implement standards that allow for representation of many different FT tokens in a single contract such as Ethereum.
The standard here introduces a few concepts that evolve the original [ERC-1155] standard to have more utility, while maintaining the original flexibility of the standard. So keeping that in mind, we are defining this as a new token type. It combines two main features of FT and NFT. It allows us to represent many token types in a single contract, and it's possible to store the amount for each token.
The decision to not use FT and NFT as explicit token types was taken to allow the community to define their own standards and meanings through metadata. As standards evolve on other networks, this specification allows the standard to be able to represent tokens across networks accurately, without necessarily restricting the behavior to any preset definition.
The issues with this in general is a problem with defining what metadata means and how is that interpreted. We have chosen to follow the pattern that is currently in use on Ethereum in the [ERC-1155] standard. That pattern relies on people to make extensions or to make signals as to how they want the metadata to be represented for their use case.
One of the areas that has broad sweeping implications from the [ERC-1155] standard is the lack of direct access to metadata. With Near's sharding we are able to have a [Metadata Extension](Metadata.md) for the standard that exists on chain. So developers and users are not required to use an indexer to understand, how to interact or interpret tokens, via token identifiers that they receive.
Another extension that we made was to provide an explicit ability for developers and users to group or link together series of NFTs/FTs or any combination of tokens. This provides additional flexiblity that the [ERC-1155] standard only has loose guidelines on. This was chosen to make it easy for consumers to understand the relationship between tokens within the contract.
To recap, we choose to create this standard, to improve interoperability, developer ease of use, and to extend token representability beyond what was available directly in the FT or NFT standards. We believe this to be another tool in the developer's toolkit. It makes it possible to represent many types of tokens and to enable exchanges of many tokens within a single `transaction`.
## Reference-level explanation
**NOTES**:
- All amounts, balances and allowance are limited by `U128` (max value `2**128 - 1`).
- Token standard uses JSON for serialization of arguments and results.
- Amounts in arguments and results are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of `2**53`.
- The contract must track the change in storage when adding to and removing from collections. This is not included in this core multi token standard but instead in the [Storage Standard](../../StorageManagement.md).
- To prevent the deployed contract from being modified or deleted, it should not have any access keys on its account.
### MT Interface
```ts
// The base structure that will be returned for a token. If contract is using
// extensions such as Approval Management, Enumeration, Metadata, or other
// attributes may be included in this structure.
type Token = {
token_id: string,
owner_id: string | null
}
/******************/
/* CHANGE METHODS */
/******************/
// Simple transfer. Transfer a given `token_id` from current owner to
// `receiver_id`.
//
// Requirements
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes
// * Caller must have greater than or equal to the `amount` being requested
// * Contract MUST panic if called by someone other than token owner or,
// if using Approval Management, one of the approved accounts
// * `approval_id` is for use with Approval Management extension, see
// that document for full explanation.
// * If using Approval Management, contract MUST nullify approved accounts on
// successful transfer.
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the token
// * `token_id`: the token to transfer
// * `amount`: the number of tokens to transfer, wrapped in quotes and treated
// like a string, although the number will be stored as an unsigned integer
// with 128 bits.
// * `approval` (optional): is a tuple of [`owner_id`,`approval_id`].
// `owner_id` is the valid Near account that owns the tokens.
// `approval_id` is the expected approval ID. A number smaller than
// 2^53, and therefore representable as JSON. See Approval Management
// standard for full explanation.
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer
function mt_transfer(
receiver_id: string,
token_id: string,
amount: string,
approval: [owner_id: string, approval_id: number]|null,
memo: string|null,
) {}
// Simple batch transfer. Transfer a given `token_ids` from current owner to
// `receiver_id`.
//
// Requirements
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes
// * Caller must have greater than or equal to the `amounts` being requested for the given `token_ids`
// * Contract MUST panic if called by someone other than token owner or,
// if using Approval Management, one of the approved accounts
// * `approval_id` is for use with Approval Management extension, see
// that document for full explanation.
// * If using Approval Management, contract MUST nullify approved accounts on
// successful transfer.
// * Contract MUST panic if called with the length of `token_ids` not equal to `amounts` is not equal
// * Contract MUST panic if `approval_ids` is not `null` and does not equal the length of `token_ids`
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the token
// * `token_ids`: the tokens to transfer
// * `amounts`: the number of tokens to transfer, wrapped in quotes and treated
// like an array of strings, although the numbers will be stored as an array of unsigned integer
// with 128 bits.
// * `approvals` (optional): is an array of expected `approval` per `token_ids`.
// If a `token_id` does not have a corresponding `approval` then the entry in the array
// must be marked null.
// `approval` is a tuple of [`owner_id`,`approval_id`].
// `owner_id` is the valid Near account that owns the tokens.
// `approval_id` is the expected approval ID. A number smaller than
// 2^53, and therefore representable as JSON. See Approval Management
// standard for full explanation.
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer
function mt_batch_transfer(
receiver_id: string,
token_ids: string[],
amounts: string[],
approvals: ([owner_id: string, approval_id: number]| null)[]| null,
memo: string|null,
) {}
// Transfer token and call a method on a receiver contract. A successful
// workflow will end in a success execution outcome to the callback on the MT
// contract at the method `mt_resolve_transfer`.
//
// You can think of this as being similar to attaching native NEAR tokens to a
// function call. It allows you to attach any Multi Token, token in a call to a
// receiver contract.
//
// Requirements:
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security
// purposes
// * Caller must have greater than or equal to the `amount` being requested
// * Contract MUST panic if called by someone other than token owner or,
// if using Approval Management, one of the approved accounts
// * The receiving contract must implement `mt_on_transfer` according to the
// standard. If it does not, MT contract's `mt_resolve_transfer` MUST deal
// with the resulting failed cross-contract call and roll back the transfer.
// * Contract MUST implement the behavior described in `mt_resolve_transfer`
// * `approval_id` is for use with Approval Management extension, see
// that document for full explanation.
// * If using Approval Management, contract MUST nullify approved accounts on
// successful transfer.
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the token.
// * `token_id`: the token to send.
// * `amount`: the number of tokens to transfer, wrapped in quotes and treated
// like a string, although the number will be stored as an unsigned integer
// with 128 bits.
// * `owner_id`: the valid NEAR account that owns the token
// * `approval` (optional): is a tuple of [`owner_id`,`approval_id`].
// `owner_id` is the valid Near account that owns the tokens.
// `approval_id` is the expected approval ID. A number smaller than
// 2^53, and therefore representable as JSON. See Approval Management
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer.
// * `msg`: specifies information needed by the receiving contract in
// order to properly handle the transfer. Can indicate both a function to
// call and the parameters to pass to that function.
function mt_transfer_call(
receiver_id: string,
token_id: string,
amount: string,
approval: [owner_id: string, approval_id: number]|null,
memo: string|null,
msg: string,
): Promise {}
// Transfer tokens and call a method on a receiver contract. A successful
// workflow will end in a success execution outcome to the callback on the MT
// contract at the method `mt_resolve_transfer`.
//
// You can think of this as being similar to attaching native NEAR tokens to a
// function call. It allows you to attach any Multi Token, token in a call to a
// receiver contract.
//
// Requirements:
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security
// purposes
// * Caller must have greater than or equal to the `amount` being requested
// * Contract MUST panic if called by someone other than token owner or,
// if using Approval Management, one of the approved accounts
// * The receiving contract must implement `mt_on_transfer` according to the
// standard. If it does not, MT contract's `mt_resolve_transfer` MUST deal
// with the resulting failed cross-contract call and roll back the transfer.
// * Contract MUST implement the behavior described in `mt_resolve_transfer`
// * `approval_id` is for use with Approval Management extension, see
// that document for full explanation.
// * If using Approval Management, contract MUST nullify approved accounts on
// successful transfer.
// * Contract MUST panic if called with the length of `token_ids` not equal to `amounts` is not equal
// * Contract MUST panic if `approval_ids` is not `null` and does not equal the length of `token_ids`
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the token.
// * `token_ids`: the tokens to transfer
// * `amounts`: the number of tokens to transfer, wrapped in quotes and treated
// like an array of string, although the numbers will be stored as an array of
// unsigned integer with 128 bits.
// * `approvals` (optional): is an array of expected `approval` per `token_ids`.
// If a `token_id` does not have a corresponding `approval` then the entry in the array
// must be marked null.
// `approval` is a tuple of [`owner_id`,`approval_id`].
// `owner_id` is the valid Near account that owns the tokens.
// `approval_id` is the expected approval ID. A number smaller than
// 2^53, and therefore representable as JSON. See Approval Management
// standard for full explanation.
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer.
// * `msg`: specifies information needed by the receiving contract in
// order to properly handle the transfer. Can indicate both a function to
// call and the parameters to pass to that function.
function mt_batch_transfer_call(
receiver_id: string,
token_ids: string[],
amounts: string[],
approvals: ([owner_id: string, approval_id: number]|null)[] | null,
memo: string|null,
msg: string,
): Promise {}
/****************/
/* VIEW METHODS */
/****************/
// Returns the tokens with the given `token_ids` or `null` if no such token.
function mt_token(token_ids: string[]) (Token | null)[]
// Returns the balance of an account for the given `token_id`.
// The balance though wrapped in quotes and treated like a string,
// the number will be stored as an unsigned integer with 128 bits.
// Arguments:
// * `account_id`: the NEAR account that owns the token.
// * `token_id`: the token to retrieve the balance from
function mt_balance_of(account_id: string, token_id: string): string
// Returns the balances of an account for the given `token_ids`.
// The balances though wrapped in quotes and treated like strings,
// the numbers will be stored as an unsigned integer with 128 bits.
// Arguments:
// * `account_id`: the NEAR account that owns the tokens.
// * `token_ids`: the tokens to retrieve the balance from
function mt_batch_balance_of(account_id: string, token_ids: string[]): string[]
// Returns the token supply with the given `token_id` or `null` if no such token exists.
// The supply though wrapped in quotes and treated like a string, the number will be stored
// as an unsigned integer with 128 bits.
function mt_supply(token_id: string): string | null
// Returns the token supplies with the given `token_ids`, a string value is returned or `null`
// if no such token exists. The supplies though wrapped in quotes and treated like strings,
// the numbers will be stored as an unsigned integer with 128 bits.
function mt_batch_supply(token_ids: string[]): (string | null)[]
```
The following behavior is required, but contract authors may name this function something other than the conventional `mt_resolve_transfer` used here.
```ts
// Finalize an `mt_transfer_call` or `mt_batch_transfer_call` chain of cross-contract calls. Generically
// referred to as `mt_transfer_call` as it applies to `mt_batch_transfer_call` as well.
//
// The `mt_transfer_call` process:
//
// 1. Sender calls `mt_transfer_call` on MT contract
// 2. MT contract transfers token from sender to receiver
// 3. MT contract calls `mt_on_transfer` on receiver contract
// 4+. [receiver contract may make other cross-contract calls]
// N. MT contract resolves promise chain with `mt_resolve_transfer`, and may
// transfer token back to sender
//
// Requirements:
// * Contract MUST forbid calls to this function by any account except self
// * If promise chain failed, contract MUST revert token transfer
// * If promise chain resolves with `true`, contract MUST return token to
// `sender_id`
//
// Arguments:
// * `sender_id`: the sender of `mt_transfer_call`
// * `receiver_id`: the `receiver_id` argument given to `mt_transfer_call`
// * `token_ids`: the `token_ids` argument given to `mt_transfer_call`
// * `amounts`: the `token_ids` argument given to `mt_transfer_call`
// * `approvals (optional)`: if using Approval Management, contract MUST provide
// set of original approvals in this argument, and restore the
// approved accounts in case of revert.
// `approvals` is an array of expected `approval_list` per `token_ids`.
// If a `token_id` does not have a corresponding `approvals_list` then the entry in the
// array must be marked null.
// `approvals_list` is an array of triplets of [`owner_id`,`approval_id`,`amount`].
// `owner_id` is the valid Near account that owns the tokens.
// `approval_id` is the expected approval ID. A number smaller than
// 2^53, and therefore representable as JSON. See Approval Management
// standard for full explanation.
// `amount`: the number of tokens to transfer, wrapped in quotes and treated
// like a string, although the number will be stored as an unsigned integer
// with 128 bits.
//
//
//
// Returns total amount spent by the `receiver_id`, corresponding to the `token_id`.
// The amounts returned, though wrapped in quotes and treated like strings,
// the numbers will be stored as an unsigned integer with 128 bits.
// Example: if sender_id calls `mt_transfer_call({ "amounts": ["100"], token_ids: ["55"], receiver_id: "games" })`,
// but `receiver_id` only uses 80, `mt_on_transfer` will resolve with `["20"]`, and `mt_resolve_transfer`
// will return `["80"]`.
function mt_resolve_transfer(
sender_id: string,
receiver_id: string,
token_ids: string[],
approvals: (null | [owner_id: string, approval_id: number, amount: string][]) []| null
):string[] {}
```
### Receiver Interface
Contracts which want to make use of `mt_transfer_call` and `mt_batch_transfer_call` must implement the following:
```ts
// Take some action after receiving a multi token
//
// Requirements:
// * Contract MUST restrict calls to this function to a set of whitelisted
// contracts
// * Contract MUST panic if `token_ids` length does not equals `amounts`
// length
// * Contract MUST panic if `previous_owner_ids` length does not equals `token_ids`
// length
//
// Arguments:
// * `sender_id`: the sender of `mt_transfer_call`
// * `previous_owner_ids`: the account that owned the tokens prior to it being
// transferred to this contract, which can differ from `sender_id` if using
// Approval Management extension
// * `token_ids`: the `token_ids` argument given to `mt_transfer_call`
// * `amounts`: the `token_ids` argument given to `mt_transfer_call`
// * `msg`: information necessary for this contract to know how to process the
// request. This may include method names and/or arguments.
//
// Returns the number of unused tokens in string form. For instance, if `amounts`
// is `["10"]` but only 9 are needed, it will return `["1"]`. The amounts returned,
// though wrapped in quotes and treated like strings, the numbers will be stored as
// an unsigned integer with 128 bits.
function mt_on_transfer(
sender_id: string,
previous_owner_ids: string[],
token_ids: string[],
amounts: string[],
msg: string,
): Promise<string[]>;
```
[ERC-721]: https://eips.ethereum.org/EIPS/eip-721
[ERC-1155]: https://eips.ethereum.org/EIPS/eip-1155
[storage staking]: https://docs.near.org/concepts/storage/storage-staking
[gas]: https://docs.near.org/concepts/basics/transactions/gas
[Metadata]: Metadata.md
[NFT]: ../NonFungibleToken/Core.md
[Approval Management]: ApprovalManagement.md
[FT]: ../FungibleToken/Core.md
|
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
# Non-Fungible Tokens
<DocCardList items={useCurrentSidebarCategory().items}/>
|
TheFunPass™ Debuts at North America’s Largest Night Market with The Littles and NEAR
NEAR FOUNDATION
July 13, 2023
Everyone’s a winner playing carnival games thanks to TheFunPass™, a groundbreaking leap in Web3 that will redefine loyalty rewards and transform the way we engage and connect with events and experiences. From the popular Web3 project, the littles, this innovative Web3 rewards app on the NEAR blockchain offers a solution that will transform the event landscape, that benefits event-goers but also empowers event operators.
It’s all about bridging the gap between the physical and digital worlds, as TheFunPass™ creates a seamless and immersive experience for users while driving value for businesses.
TheFunPass™ presents a brand-new model of interaction that empowers users, business operators, and The Littles holders alike. The Littles’ TheFunPass™ rewards app will debut at the Richmond Night Market, rethinking the entire carnival experience by connecting people through interactive missions, rewards, and personalized engagement.
Now every carnival-goer can win prizes, food, and once-in-a-lifetime trips — even if their skeeball doesn’t land in the bullseye — breathing new life into the classic carnival games.
TheFunPass™ is the best way to win at carnival games
Wil Lee and Cass Chan created the Web3 children’s media company, the littles, in 2021 offering a creative blend of animation, gaming, and real-world activations. The Littles is even joining up with TIME Studios to produce a children’s animation series. TheFunPass™, their latest endeavor, showcases their commitment to pushing the boundaries of interactive entertainment. Meanwhile, Lee is also the CEO and creator of Wun2Free Entertainment, a Company that has been producing events for over 10 years and hires over one hundred people each season, with TheFunPass™ as their latest endeavor.
TheFunPass™ is a rewards application that utilizes Web3 technology to enhance the way people emotionally engage with events. The application will debut at the Richmond Night Market in British Columbia, the largest night market in North America. TheFunPass™ engages user participation through missions, allowing them to earn digital and physical rewards unlocking exclusive benefits, digital collectibles, and unforgettable experiences.
TheFunPass™ not only engages event attendees but also presents a game-changing opportunity for businesses and operators. The app will also enable event operators and businesses to create customized missions and campaigns driving attendee participation and extending engagement before, during, and after the event. It’s a win-win scenario, where attendees enjoy immersive experiences and rewards, while businesses drive revenue growth and forge stronger connections with their audience.
TheFunPass™ is a new and innovative way to experience the Richmond Night Market, which boasts over 500 food stalls, 100 retail shops, and an average attendance of over 1 million visitors per season. TheFunPass™ can reach tens of thousands of carnival-goers and engage them in unprecedented ways. The partnership between The Littles and NEAR will change the way people emotionally engage with events.
The Littles and TheFunPass™ are a NEAR perfect match
TheFunPass™, powered by NEAR, revolutionizes the traditional carnival experience, offering dynamic gameplay with location-based missions and rewarding social engagements. The app’s integration of digital and physical missions enables users to accrue reward points beyond the physical space confines, effectively turning the standard carnival participation model on its head thanks to the development support of LaunchBadge, a leading software development team trusted by the littles and NEAR.
“800 users for a soft launch has reaffirmed our decision to support The Fun Pass and the team’s vision to reimagine how we experience the night market with blockchain technology,” said Dillon Freeman, Blockchain Success Manager on NEAR Foundation’s BD team. “The team has been executing at a high level and we’re excited to see what they deliver in the coming months.”
Beyond the in-person carnival fun, TheFunPass™ also facilitates year-round engagement with unique missions and reward opportunities, making the carnival-style fun available wherever and whenever. This innovative blend of phygital experiences is a game changer, enabling events to expand their reach and engage audiences more effectively.
The mechanics of TheFunPass™ are simple: Play Games, Collect STARs, Win Rewards! Attendees participate in carnival games, scan QR codes or tap to gather STARs on TheFunPass™, and subsequently exchange these STARs for various rewards, regardless of their game outcomes. The participation model offers a tangible sense of achievement, transforming the carnival experience.
TheFunPass™ ensures an exciting and ongoing engagement with its mission-based gameplay and reward system. After the carnival, users can continue to engage in digital missions, games, and rewards, offering an immersive experience that extends beyond its physical boundaries.
Debuting at Richmond Night Market, the partnership between The Littles and NEAR, with the development expertise from Launchbadge, showcases a unique use case of Web3 technology. By using TheFunPass™, every visitor stands a chance to win prizes, while also partaking in a unique Web3 event experience, thereby redefining event participation.
Empowering all stakeholders in the events industry
TheFunPass™ empowers The Littles holders by integrating them into its growth through a unique referral program, reflecting the app’s commitment to decentralization and community empowerment. This groundbreaking approach enables Littles holders to earn commissions by referring businesses and operators to the app’s expanding network.
Beyond rewarding users, TheFunPass™ is an invaluable tool for businesses and operators. It enhances customer engagement, fosters loyalty, and promotes revenue growth. Additionally, the app provides businesses with valuable consumer behavior insights, enabling them to customize their offerings and establish meaningful connections with their audience.
The Littles are poised to lead the web3 industry into the future with the launch of TheFunPass™, powered by NEAR. By introducing gamification and immersive experiences to events, concerts, and festivals worldwide, TheFunPass™ aims to revolutionize the event experience, heralding a new frontier of interaction for fans.
TheFunPass™ presents a unique convergence of loyalty rewards, immersive experiences, and Web3 technology. As we step into the future of truly phygital experiences, every event-goer can look forward to a redefined, gamified, and winning event experience like never before. |
P2P Validator Joins NEAR as a Node Operator
COMMUNITY
February 19, 2021
All decentralized platforms have their own disadvantages and difficulties that developers face when building decentralized applications. Ethereum scaling limitations and spiked transaction fees make operating dApps challenging, causing tangible limitations for many users.
NEAR Protocol has been in continuous design for the last few years to address the most pressing issues of blockchain application development lowering the entry barrier for end users. Successfully implemented solutions can effectively offer dApp creators high-quality toolkits improving end user experience.
NEAR’s homogeneous sharding design is specifically adapted to give developers the simplicity they need providing dynamic scalability and stabilized fees. The ultimate goal is to make building dApps simple, thus accelerating their development.
In light of the evolving nature of blockchains, P2P Validator is excited to announce the launch of NEAR node on mainnet to facilitate the development of new open financial instruments giving access to permissionless economies for the users.
Please follow this link for a guide to staking your NEAR with P2P Validator.
Our team has extensive experience in setting up secure infrastructure for more than 15 blockchains. P2P Validator maintains high-availability nodes and provides secure staking services for the most groundbreaking projects in the blockchain space. The node infrastructure is under advanced monitoring with 24/7 technical support, backups and alerts.
About NEAR
NEAR exists to enable community-driven innovation to benefit people around the world. NEAR is a decentralized application platform that secures high value assets like money and identity with the performance necessary to make them useful for everyday people, putting the power of Open Finance and the Open Web in their hands. NEAR’s unique account model allows developers to build secure apps that consumers can actually use similarly to today’s web apps, something which requires multiple second-layer add-ons on other blockchains.
If you’re a developer, be sure to sign up for a developer program and join the conversation in NEAR Discord chat. You can also keep up to date on future releases, announcements, and event invitations by subscribing to NEAR newsletter, or following @NEARProtocol on Twitter for the latest news.
About P2P Validator
P2P Validator is a world-leading staking provider with the best industry security practices and proven expertise. At the time of publishing, more than one billion of USD value is staked with P2P Validator by over 6000 delegators across 15+ networks. We provide comprehensive due-diligence of digital assets and offer top-notch staking opportunities. |
NEAR Community in Focus: The Future of Community on NEAR
COMMUNITY
June 23, 2022
What will the world look like 20 years from now? By then, Web3 will be mainstream rather than in its nascent stages. It will be reality, not hype. So how can the NEAR community work towards a future that makes everyone proud?
One question is whether Web3 will live up to its promises of creator empowerment through the coordination of decentralized systems.
Community is at the center of it all.
“For NEAR, community is not about owning the narrative by trying to eat into each others’ share of the pie,” says Harshit Tiwari, Community Activation and Adoption Specialist at NEAR. “NEAR is committed to building a Web3 ecosystem where every human can find and build a digital home. We believe that true inclusion begins at the grassroots level.”
Let’s take a look at the future of community on NEAR.
Embracing timeless, unbreakable foundations
The future of community on NEAR starts with commitments that the ecosystem is making now. From Tiwari’s perspective, several pillars define the NEAR community experience.
With a commitment to diversity, NEAR is working towards one of the most vibrant ecosystems in the world. In this diverse community, the vision is for people to have the freedom to pursue their passions and make an impact. Through shared governance, every community member will have a toolkit to protect the integrity of their ecosystem.
The culture, throughout NEAR, will inspire a sense of belonging so that everyone can find a home in the NEAR ecosystem. The overall impact is to facilitate collaborative uplifting, to make sure every person gets to enjoy upward socio-economic mobility while collaborating with people around the world.
Tiwari believes that in the coming months and years the NEAR community will become increasingly decentralized.
“NEAR is really letting community members steer the community governance and building a safe environment for people from diverse backgrounds to come and thrive,” says Tiwari. “How the community decides to govern itself and organize around ideas is decided by the community through DAOs.”
“The biggest things we are all collectively trying to figure out are equitable distribution of resources, opportunities, participation in governance experiments and decentralized ownership of ecosystem responsibilities,” adds Tiwari.
‘Phygital’ community building across cultures
India is known for its vibrant artist communities, traditional craftspersonship, and vibrant in-person marketplaces. Imagine being able to experience the rich beauty and cultural tradition of rural artists, from anywhere in the world.
It’s this “what if” that led to the creation of Naksh Marketplace, an NFT marketplace fueled by communities all over India. Founded by Srilakshmi Barathi and Nivedita Hail, Naksh grew out of the duo’s time in London working on a project in which Indian artists and artisans taught their skills to the world using a stitch kit.
“That’s when we realized the value a traditional artwork holds in the art space and we understood that there was a demand for such artwork which is associated with a cultural background of its own,” they adds. “We also saw the lack of artists in the NFT space who create their work on physical media, and lack of platforms that were accessible by the Indian audience and Indian artists.”
Initially, Naksh focused on product instead of community building. But during the build, Barathi and Hail received support from many individuals. Through this feedback, a Naksh community evolved organically.
“That’s when we started interacting way more with our communities,” says Barathi. “We set up events and spaces for them to join and give us their opinions.”
Since Naksh focuses on onboarding artists who produce work physically and not digitally, almost all onboarding efforts happen in person.
“We’ve been going to a lot of regional exhibitions and art galleries, meeting artists through some amazing curators,” say Barathi and Hail. “We have also found artists through virtual exhibitions.”
The duo see Web3 as a pathway to connect the ingenuity of rural artists with the rest of the world.
“Most rural artists are not aware of technology that can empower, educate, monetize and preserve their work,” explains Barathi. “The need for a vehicle to help Indian artists access the larger digital ecosystem with their physical products gave us an incentive to build Naksh.”
Naksh’s next iteration will invite and onboard traditional artists from around the world. Envision a platform where traditional Indian artists—oftentimes individuals who have never left the country—can join the same communities as fellow creators from around the world. It’s a first-in-history mind-meld.
“We are also trying to make our platform ‘phygital’ since all our traditional artworks have a physical asset,” says Barathi. “We aim to be the future of art exchanges.”
Once Naksh launches digital and self-minting features for artists, Barathi expects more people to join. At that point, new communities will spring up around digital artists, just as with Naksh’s traditional Indian and fine artists.
Facilitating unique collaboration
“Boo.”
In a time of widespread negativity and distrust, that’s how Capardano, one of the project managers at BOO Monsters, has begun greeting people and signing off on emails. “It’s one of my favorite things to say,” says Capardano, who goes by “Cap” for short.
This perspective encapsulates the spirit of BOO Monsters, a collection of 100 NFT monikers roaming the internet. So what are these BOOs about?
“We’re a group of people, who live across the world, who otherwise had no ties together,” says Cap. “We’re a DAO with decentralized project management.”
In total, there are currently 37 BOOs roaming Web3. With BOO NFTs costing as much as $300,000 USD due to supply and demand economics, the community is exclusive to high net worth individuals.
“Many of our members come from an investment perspective, with unique experiences and insights,” says Cap. “NFTs are just one gateway into our community. The money goes into the DAO to be spent across our endeavors and benefit the NEAR community.”
One vision that the BOOs are building towards is evolutionary art. So what exactly does that mean, in practical terms?
With their RPG NEAR Future, built natively into Discord, a tribe of robots evolve beyond their initial programming. BOOs also created Antisocial Ape Club, a collection of 3,333 unique, generative pixel art NFTs. And Ev3reth, a machine learning artist and composer, is partnering with artists such as GDM, whose work blends surrealism and fantasy. The BOOs also offer expertise and support to other NFT projects, like Skellies Secret Society and Few and Far.
“It’s about keeping growing, moving, and adding value to NEAR as a whole,” says Cap, who has been helping bring AnonymousFox to market.
“It’s about helping people for the sake of doing good,” says Cap. “The Boos are curious and giving. We envision a future on NEAR built on empathy. There are people here in their 20s and people here in their 50s with a lot more life experience. What we share in common is that we’re curious. We embrace that there’s a lot we don’t know. It’s an environment built on love, where we are always learning and moving forward.”
“Decentralization can be messy,” says Cap. “But we’re figuring it out with good intentions and mutual support. We see a future on NEAR built on these foundations.”
Welcoming people who are hesitant to enter the space
Understandably, many people stay away from cryptocurrencies and blockchain for reasons ranging from personal safety to confusion and barriers to technical adoption.
“I think working towards mass adoption with massive educational efforts and onboarding for more diverse folks — namely women, people of diverse genders, people of color, and people in vulnerable social and financial situations is how I would like to see NEAR shaping its community infrastructure,” says Maria Neu, community manager at Mintbase, an NFT platform.”
“It’s about giving them access not only to information but skills to work in the NEAR ecosystem,” she adds. “In terms of infrastructure and tooling, what I believe could help is a better overview of the existing guilds — and a place to research. Think of a place to insert keywords to find communities already working on certain subjects. For example: art, utility NFTs, translation, education, etc.”
In other words, the future of NEAR begins with a commitment to listening, observing, learning, and questioning assumptions.
“The NEAR ecosystem is a very friendly and open place to start getting involved with Web3 but could be optimized and simplified for those who are still reluctant to enter the space,” says Wend.
The road ahead
It’s important to remember that these are still early days for NEAR. As Cap likes to say, “Web3 is the wild west.”
It’s up to NEAR communities to create the future that they want to see. It also means that NEAR users must stretch their minds, and meet each other in a space of respect and kindness.
“My biggest takeaway about the NEAR Community is that it’s in fact a ‘Community of Communities,’” says Rebecca Hallquist, a Community Team Lead at NEAR Foundation.
“It contains incredible and ever-changing multitudes,” she says. “Whether it’s a group of digital artists in the Philippines, Web3 educators in Venezuela, or digital nomads hopping from crypto conference to crypto conference, they’re finding like-minded people here sharing similar interests, language, and enthusiasm for NEAR’s mandate and vision.”
NEAR is a place where communities help new members settle in. It’s like a new family settling into a neighborhood, explains Halquist. It’s about helping people contribute where best they can.
In the future, communities on NEAR will likely fulfill several functions. They could become gathering spaces and networks for social support, hobbies, income, learning, and so much more. For this to happen, the tools, platforms, and other means of organizing will have to be as multifaceted as the communities needs. And what NEAR communities build will manifest in the real world. They have the opportunity to be counterforces to the world’s more destabilizing forces.
“It’s a steady process of organic evolving self-organization with the potential for an increasing number of connections to emerge between the different communities, between communities and dapps, and between communities and projects, the more any new group ‘settles in,’” says Halquist.
“We will need to be multifaceted enough to accommodate those needs more robustly.” |
Interaction with NEAR is done with [JSON RPC API](../../5.api/rpc/introduction.md) via HTTP calls.
With the API, you can call smart contracts, send transactions, manage keys and get information about blockchain data and status.
The NEAR CLI abstracts some actions, such as deploying a contract, but eventually, all actions are done via JSON RPC.
:::info
We recommend using the CLI for deploying contracts. In a CI/CD environment, you can write a shell script to utilize the CLI for deployments.
:::
### API requests flow
There are different types of [Nodes on NEAR](./validators.md): RPC Nodes, Validators, and Archival Nodes.
When calling an endpoint on `near.org`, it resolves to a server that chooses an available RPC node to handle the request.
Then the RPC node passes the request to an available Validator node. Finally, the validator node spawns a VM environment to execute the contract.
Due to the decentralized nature of a blockchain network, there are many RPC nodes, and a request can reach any one of them, after which it can pass it to any one of the validators.
![JSON Network Arch](/docs/assets/JSONNetworkArch.png) |
```bash
export COUNCIL='["bob.near"]'
export ARGS=`echo '{"config": {"name": "Primitives", "purpose": "Building primitives on NEAR", "metadata":""}, "policy": '$COUNCIL'}' | base64`
near call sputnikv2.testnet create "{\"name\": \"primitives\", \"args\": \"$ARGS\"}" --accountId bob.near --amount 6 --gas 150000000000000
```
:::note
The full list of roles and permissions you can find [here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions).
::: |
---
id: marketplace
title: Integrating FT Payments into an NFT Marketplace
sidebar_label: Adding FTs to a Marketplace
---
import {Github} from "@site/src/components/codetabs"
In this tutorial, you'll learn the basics of how an NFT marketplace contract works and how you can modify it to allow for purchasing NFTs using Fungible Tokens. In the previous tutorials, you went through and created a fully fledged FT contract that incorporates all the standards found in the [FT standard](https://nomicon.io/Standards/Tokens/FungibleToken/Core).
## Introduction
Throughout this tutorial, you'll learn how a marketplace contract could work on NEAR. This is meant to be an example and there is no canonical implementation. Feel free to branch off and modify this contract to meet your specific needs.
Using the same repository as the previous tutorials, if you visit the `market-contract` directory, you should have the necessary files to complete the tutorial.
## File structure {#file-structure}
This directory contains both the build script, dependencies as well as the actual contract code as outlined below.
```
market-contract
├── Cargo.lock
├── Cargo.toml
├── README.md
├── build.sh
└── src
├── external.rs
├── ft_balances.rs
├── internal.rs
├── lib.rs
├── nft_callbacks.rs
├── sale.rs
└── sale_views.rs
```
Let's start by building both the finished FT contract and the marketplace contract. Make sure you're in the root directory and run the following command in your terminal:
```bash
yarn build && cd market-contract && ./build.sh && cd ..
```
This will install the dependencies for the marketplace contract as well as the FT contract. In addition, it will compile them to `wasm` such that your `ft-tutorial/out` directory looks like this:
```
ft-tutorial
└── out
├── contract.wasm
├── nft-contract.wasm
└── market.wasm
```
Note that there's also a pre-build nft contract wasm file in the directory which you'll use to place the NFTs for sale.
## Understanding the contract
The marketplace contract used in this tutorial is a modified version of the contract created at the end of the NFT zero to hero tutorial. If you'd like to learn about the backbone of how the NFTs are put for sale and the process by which they are minted / sold, check out the [NFT zero to hero tutorial](/tutorials/nfts/marketplace).
The core functionalities are the same in the sense that both this contract and the marketplace contract built in the NFT zero to hero have the following features:
- Users can put NFTs for sale and specify sale conditions
- Users must pay for storage deposit to put NFTs for sale and they can withdraw the storage at any time
- Users can update the price of an NFT or remove the sale entirely
- Buyers can purchase the NFTs by calling `offer`.
The only difference is that this marketplace has removed the ability to purchase NFTs for `$NEAR` and instead allows users to buy them with Fungible Tokens. The fungible token is specified when the contract is initialized and only **1 type of fungible token** can be used to purchase NFTs. You can't, for example, offer 100 Team Tokens for an NFT and 5000 Mike Tokens for another.
In addition, the marketplace does **not** support royalties. This is because FT transfers are less Gas efficient than regular $NEAR transfers. In addition, each user would have to be registered and it's much easier to say "hey seller, make sure you're registered before your NFT is sold" rather than enforcing that the seller and **all** accounts in the payout object are registered. When an NFT is sold, the entire price is sent directly to the seller.
### Purchasing Flow
In order to purchase an NFT, the contract utilizes the "transfer and call" workflow that the FT contract provides. The marketplace contract implements the `ft_on_transfer` method that is called whenever someone transfers FTs to the marketplace contract.
The marketplace keeps track of a balance for each user that outlines how many FTs they've sent to the contract. Each time `ft_on_transfer` is called, the marketplace contract will update the balance for the user. When that user wishes to purchase an NFT, they call `offer` and pass in the amount of tokens they're willing to spend. The marketplace will then decrement from their balance and transfer the NFT to the buyer / send the FTs to the seller.
It's important to note that the seller **must** be registered in the FT contract before a sale is made otherwise the `ft_transfer` method will panic and the seller won't receive any tokens.
## Looking at the Code
Most of the code is the same as what's been outlined in the [NFT zero to hero tutorial](/tutorials/nfts/marketplace) but we'll go through a refresher in case you're new or have forgotten some of the details.
### Main Library File
Starting at the `lib.rs` file, this outlines what information is stored on the contract as well as some other crucial functions that you'll learn about below.
### Initialization function {#initialization-function}
The first function you'll look at is the initialization function. This takes an `owner_id` as well as the `ft_id` as the parameters and will default all the storage collections to their default values. The `ft_id` outlines the account ID for the fungible token that the contract will allow.
<Github language="rust" start="94" end="118" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/lib.rs" />
### Storage management model {#storage-management-model}
Next, let's talk about the storage management model chosen for this contract. Users will need to deposit $NEAR onto the marketplace to cover the storage costs. Whenever someone puts an NFT for sale, the marketplace needs to store that information which costs $NEAR. Users can either deposit a large amount of $NEAR so that they never have to worry about storage again or they can deposit the minimum amount to cover 1 sale on an as-needed basis.
You might be thinking about the scenario when a sale is purchased. What happens to the storage that is now being released on the contract? This is why we have a storage withdrawal function. This allows users to withdraw any excess storage that is not being used. Let's go through some scenarios to understand the logic. The required storage for 1 sale is 0.01 NEAR on the marketplace contract.
**Scenario A**
- Benji wants to list his NFT on the marketplace but has never paid for storage.
- He deposits exactly 0.01 NEAR using the `storage_deposit` method. This will cover 1 sale.
- He lists his NFT on the marketplace and is now using up 1 out of his prepaid 1 sales and has no more storage left. If he were to call `storage_withdraw`, nothing would happen.
- Dorian loves his NFT and quickly purchases it before anybody else can. This means that Benji's sale has now been taken down (since it was purchased) and Benji is using up 0 out of his prepaid 1 sales. In other words, he has an excess of 1 sale or 0.01 NEAR.
- Benji can now call `storage_withdraw` and will be transferred his 0.01 NEAR back. On the contract's side, after withdrawing, he will have 0 sales paid for and will need to deposit storage before trying to list anymore NFTs.
**Scenario B**
- Dorian owns one hundred beautiful NFTs and knows that he wants to list all of them.
- To avoid having to call `storage_deposit` everytime he wants to list an NFT, he calls it once. Since Dorian is a baller, he attaches 10 NEAR which is enough to cover 1000 sales. He now has an excess of 9 NEAR or 900 sales.
- Dorian needs the 9 NEAR for something else but doesn't want to take down his 100 listings. Since he has an excess of 9 NEAR, he can easily withdraw and still have his 100 listings. After calling `storage_withdraw` and being transferred 9 NEAR, he will have an excess of 0 sales.
With this behavior in mind, the following two functions outline the logic.
<Github language="rust" start="120" end="183" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/lib.rs" />
In this contract, the storage required for each sale is 0.01 NEAR but you can query that information using the `storage_minimum_balance` function. In addition, if you wanted to check how much storage a given account has paid, you can query the `storage_balance_of` function.
## FT Deposits
If you want to learn more about how NFTs are put for sale, check out the [NFT zero to hero tutorial](/tutorials/nfts/marketplace). Once NFTs are put for sale, the owner has three options:
- Update the price of the NFT
- Remove the sale from the marketplace
- Wait for somebody to purchase it
In order to purchase NFTs, buyers need to deposit FTs in the contract and call the `offer` function. All the logic for FT deposits is outlined in the `src/ft_balances.rs` file. Starting with the `ft_on_approve` function, this is called when a user transfers FTs to the marketplace contract. The logic can be seen below.
<Github language="rust" start="35" end="77" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/ft_balances.rs" />
Once FTs are deposited into the contract, users can either withdraw their FTs or they can use them to purchase NFTs. The withdrawing flow is outlined in the `ft_withdraw` function. It's important to note that you should decrement the user's balance **before** calling the `ft_transfer` function to avoid a common exploit scenario where a user spams the `ft_withdraw`. If you were to decrement their balance in the callback function (if the transfer was successful), they could spam the `ft_withdraw` during the time it takes the callback function to execute. A better pattern is to decrement their balance before the transfer and then if the promise was **unsuccessful*, revert the balance back to what it was before.
<Github language="rust" start="79" end="149" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/ft_balances.rs" />
## Purchasing NFTs
Now that you're familiar with the process of both adding storage and depositing FTs on the marketplace, let's go through what you can do once a sale has been listed. The `src/sale.rs` file outlines the functions for updating the price, removing, and purchasing NFTs. In this tutorial, we'll focus **only** on the purchasing flow. If you'd like to learn about the sale objects, updating the price, and removing a sale, check out the [NFT zero to hero tutorial](/tutorials/nfts/marketplace).
For purchasing NFTs, you must call the `offer` function. It takes an `nft_contract_id`, `token_id`, and the amount you wish to offer as parameters. Behind the scenes, this function will make sure your offer amount is greater than the list price and also that you have enough FTs deposited. It will then call a private method `process_purchase` which will perform a cross-contract call to the NFT contract to invoke the `nft_transfer` function where the NFT will be transferred to the seller.
<Github language="rust" start="67" end="144" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/sale.rs" />
Once the transfer is complete, the contract will call `resolve_purchase` where it will check the status of the transfer.If the transfer succeeded, it will send the FTs to the seller. If the transfer didn't succeed, it will increment the buyer's FT balance (acting as a refund).
<Github language="rust" start="146" end="192" url="https://github.com/near-examples/ft-tutorial/blob/main/market-contract/src/sale.rs" />
## View Methods
There are several view functions that the marketplace contract exposes. All of these functions are the same as the [NFT zero to hero tutorial](/tutorials/nfts/marketplace) except for one extra function we've added. In the `src/ft_balances.rs` file, we've added the `ft_balance_of` function. This function returns the balance of a given account.
## Testing
Now that you *hopefully* have a good understanding of how the marketplace contract works and how you can use the powers of the FT standard to purchase NFTs, let's move onto testing everything.
### Deploying and Initializing the Contracts
The first thing you'll want to do is deploy a new FT, NFT, and marketplace contract. Start by building and then you can use `dev-accounts` to quickly deploy.
```bash
yarn build && cd market-contract && ./build.sh && cd ..
```
To deploy the FT contract and export an environment variable, run the following command:
```bash
export FT_CONTRACT=<new-ft-account-id>
near create-account $FT_CONTRACT --useFaucet
near deploy $FT_CONTRACT out/contract.wasm
```
Next, you'll deploy the NFT and marketplace contracts.
```bash
export NFT_CONTRACT=<new-nft-account-id>
near create-account $NFT_CONTRACT --useFaucet
near deploy $NFT_CONTRACT out/nft-contract.wasm
export MARKETPLACE_CONTRACT=<new-marketplace-account-id>
near create-account $MARKETPLACE_CONTRACT --useFaucet
near deploy $MARKETPLACE_CONTRACT out/market.wasm
```
Check and see if your environment variables are all correct by running the following command. Each output should be different.
```bash
echo $FT_CONTRACT && echo $MARKETPLACE_CONTRACT && echo $NFT_CONTRACT
```
An example output is:
```bash
dev-1660831615048-16894106456797
dev-1660831638497-73655245450834
dev-1660831648913-23890994169259
```
Once that's finished, go ahead and initialize each contract by running the following commands.
```bash
near call $FT_CONTRACT new_default_meta '{"owner_id": "'$FT_CONTRACT'", "total_supply": "1000000000000000000000000000"}' --accountId $FT_CONTRACT
```
```bash
near call $MARKETPLACE_CONTRACT new '{"owner_id": "'$MARKETPLACE_CONTRACT'", "ft_id": "'$FT_CONTRACT'"}' --accountId $MARKETPLACE_CONTRACT
```
```bash
near call $NFT_CONTRACT new_default_meta '{"owner_id": "'$NFT_CONTRACT'"}' --accountId $NFT_CONTRACT
```
Let's check if each contract was initialized correctly. You can do this by checking the metadata of the FT and NFT contracts:
```bash
near view $FT_CONTRACT ft_metadata && near view $NFT_CONTRACT nft_metadata
```
In addition, you can check the sales of the marketplace contract and it should return 0.
```bash
near view $MARKETPLACE_CONTRACT get_supply_sales
```
### Placing a Token For Sale
Now that the marketplace and NFT contracts are initialized, let's place a token for sale. Start by creating a new buyer and seller account by running the following command. In this case, we'll create a sub-account of the FT contract.
```bash
near create-account buyer.$FT_CONTRACT --masterAccount $FT_CONTRACT --initialBalance 25 && export BUYER_ID=buyer.$FT_CONTRACT
```
```bash
near create-account seller.$FT_CONTRACT --masterAccount $FT_CONTRACT --initialBalance 25 && export SELLER_ID=seller.$FT_CONTRACT
```
Check if everything went well by running the following command.
```bash
echo $BUYER_ID && echo $SELLER_ID
```
This should return something similar to:
```bash
buyer.dev-1660831615048-16894106456797
seller.dev-1660831615048-16894106456797
```
The next thing you'll want to do is mint a token to the seller.
```bash
near call $NFT_CONTRACT nft_mint '{"token_id": "market-token", "metadata": {"title": "Marketplace Token", "description": "testing out the marketplace", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$SELLER_ID'"}' --accountId $NFT_CONTRACT --amount 0.1
```
Now you'll need to place the token for sale. This requires paying for storage as well as calling the `nft_approve` function.
```bash
near call $MARKETPLACE_CONTRACT storage_deposit --accountId $SELLER_ID --amount 0.1
```
In this case, we'll place the token for sale for `10 gtNEAR`.
```bash
near call $NFT_CONTRACT nft_approve '{"token_id": "market-token", "account_id": "'$MARKETPLACE_CONTRACT'", "msg": "{\"sale_conditions\":\"10000000000000000000000000\"}"}' --accountId $SELLER_ID --amount 0.1
```
If you now query for the supply of sales again on the marketplace, it should be 1.
```bash
near view $MARKETPLACE_CONTRACT get_supply_sales
```
In addition, if you query for the sales by the owner ID, it should reflect the `10 gtNEAR` price.
```bash
near view $MARKETPLACE_CONTRACT get_sales_by_owner_id '{"account_id": "'$SELLER_ID'"}'
```
Expected output:
```bash
[
{
owner_id: 'seller.dev-1660831615048-16894106456797',
approval_id: 0,
nft_contract_id: 'dev-1660831648913-23890994169259',
token_id: 'market-token',
sale_conditions: '10000000000000000000000000'
}
]
```
### Deposit FTs into the Marketplace
Now that you have an NFT up for sale for `10 gtNEAR` on the marketplace contract, the buyer needs to deposit some FTs. The first thing you need to do is register both the marketplace contract and the buyer on the FT contract otherwise you won't be able to transfer any FTs.
```bash
near call $FT_CONTRACT storage_deposit '{"account_id": "'$MARKETPLACE_CONTRACT'"}' --accountId $FT_CONTRACT --amount 0.1
```
```bash
near call $FT_CONTRACT storage_deposit '{"account_id": "'$BUYER_ID'"}' --accountId $FT_CONTRACT --amount 0.1
```
After this, you should transfer the buyer some FTs so that they can deposit at least `10 gtNEAR`. Lets start with 50 `gtNEAR`. Run the following command to send the buyer FTs on behalf of the FT contract owner.
```bash
near call $FT_CONTRACT ft_transfer '{"receiver_id": "'$BUYER_ID'", "amount": "50000000000000000000000000", "memo": "Go Team!"}' --accountId $FT_CONTRACT --depositYocto 1
```
You'll now need to deposit those tokens into the marketplace contract.
```bash
near call $FT_CONTRACT ft_transfer_call '{"receiver_id": "'$MARKETPLACE_CONTRACT'", "amount": "50000000000000000000000000", "msg": "Wooooooo!"}' --accountId $BUYER_ID --depositYocto 1 --gas 200000000000000
```
If you now query for your balance on the marketplace contract, it should be `50 gtNEAR`.
```bash
near view $MARKETPLACE_CONTRACT ft_deposits_of '{"account_id": "'$BUYER_ID'"}'
```
### Purchasing the NFT
Now that the buyer has deposited FTs into the marketplace and the token is up for sale, let's go ahead and make an offer! If you try to offer more FTs than what you have, the contract will panic. Similarly, if you try to offer lower than the sale price, the contract will also panic. Since the sale price is `10 gtNEAR`, let's try to offer `20 gtNEAR` and see what happens. The expected outcome is:
- The NFT will be transferred to the buyer
- `20 gtNEAR` will be sent to the seller
- The buyer will have `30 gtNEAR` left to withdraw.
There is one thing we're forgetting, however. We need to make sure that the seller is registered on the FT contract so let's go ahead and do that now.
```bash
near call $FT_CONTRACT storage_deposit '{"account_id": "'$SELLER_ID'"}' --accountId $FT_CONTRACT --amount 0.1
```
Now let's make an offer!
```bash
near call $MARKETPLACE_CONTRACT offer '{"nft_contract_id": "'$NFT_CONTRACT'", "token_id": "market-token", "amount": "20000000000000000000000000"}' --accountId $BUYER_ID --depositYocto 1 --gas 300000000000000
```
If everything went well, you should see 2 events in your terminal. One event is the NFT transfer coming from the NFT contract when the token was transferred from the seller to the buyer. The other event is the FT transfer for when the seller receives their fungible tokens.
```bash
Log [dev-1660831638497-73655245450834]: Memo: payout from market
Log [dev-1660831638497-73655245450834]: EVENT_JSON:{"standard":"nep171","version":"nft-1.0.0","event":"nft_transfer","data":[{"authorized_id":"dev-1660831638497-73655245450834","old_owner_id":"seller.dev-1660831615048-16894106456797","new_owner_id":"buyer.dev-1660831615048-16894106456797","token_ids":["market-token"],"memo":"payout from market"}]}
Receipt: BBvHig5zg1n2vmxFPTpxED4FNCAU1ZzZ3H8EBqqaeRw5
Log [dev-1660831638497-73655245450834]: EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_transfer","data":[{"old_owner_id":"dev-1660831638497-73655245450834","new_owner_id":"seller.dev-1660831615048-16894106456797","amount":"20000000000000000000000000","memo":"Sale from marketplace"}]}
```
Let's call some view methods to double check if everything went well. First let's check if the seller now has `20 gtNEAR`.
```bash
near view $FT_CONTRACT ft_balance_of '{"account_id": "'$SELLER_ID'"}'
```
Next, let's check if the buyer has `30 gtNEAR` left to withdraw.
```bash
near view $MARKETPLACE_CONTRACT ft_deposits_of '{"account_id": "'$BUYER_ID'"}'
```
Finally, let's check if the NFT is now owned by the buyer.
```bash
near view $NFT_CONTRACT nft_token '{"token_id": "market-token"}'
```
### Withdrawing the Excess Deposits
Now that the buyer purchased the NFT with `20 gtNEAR`, they should have `30 gtNEAR` left to withdraw. If they withdraw the tokens, they should be left with a balance of `30 gtNEAR` on the FT contract.
```bash
near call $MARKETPLACE_CONTRACT ft_withdraw '{"amount": "30000000000000000000000000"}' --accountId $BUYER_ID --depositYocto 1 --gas 300000000000000
```
If you now query for the buyer's balance, it should be `30 gtNEAR`.
```bash
near view $FT_CONTRACT ft_balance_of '{"account_id": "'$BUYER_ID'"}'
```
And just like that you're finished! You went through and put an NFT up for sale and purchased it using fungible tokens! **Go team 🚀**
## Conclusion
In this tutorial, you learned about the basics of a marketplace contract and how it works. You went through the core logic both at a high level and looked at the code. You deployed an NFT, marketplace, and FT contract, initialized them all and then put an NFT for sale and sold it for fungible tokens! What an amazing experience! Go forth and expand these contracts to meet whatever needs you have. The world is your oyster and thank you so much for following along with this tutorial series. Don't hesitate to ask for help or clarification on anything in our discord or social media channels. **Go Team!**
|
---
sidebar_position: 3
title: "Nesting"
---
# Collections Nesting
<!-- TODO --> |
BitGo Becomes First Qualified Custodian to Support NEAR Protocol and its Assets
COMMUNITY
July 19, 2022
NEAR Foundation is excited to announce its partnership with BitGo, the leader in digital asset financial services, to create secure custodial support on the Protocol. This partnership will enable institutions to custody their tokens on BitGo’s platform using hot wallets and Qualified Custody wallets. BitGo clients will also be able to stake NEAR tokens and earn rewards through their BitGo wallets.
“BitGo is proud to become the first qualified custodian to provide services to the entire NEAR Protocol ecosystem, including holders of the NEAR token who have been searching for a secure way to store and stake their assets,” says Mike Belshe, BitGo CEO. “We are excited to deliver them safe and secure custody and staking services for their NEAR tokens and other valuable assets.”
BitGo shares with NEAR Foundation a commitment to the evolution of the Open Web.
Currently, BitGo is the largest processor of on-chain Bitcoin transactions, processing a whopping 20% (approximately) of all Bitcoin transactions around the world and supports over 500 other coins and tokens, now including the NEAR token. NEAR is so confident in BitGo that the Foundation has chosen to custody its own treasury with them and stake part of this treasury using BitGo’s wallets.
Customers of BitGo include the largest exchanges of crypto-assets in the world as well as institutional investors across 50+ countries. Backed by Goldman Sachs, Craft Ventures, Digital Currency Group, DRW, Galaxy Digital Ventures, Redpoint Ventures, and Valor Equity Partners, BitGo is the global leader in digital asset financial services, providing liquidity, custody, and security solutions.
NEAR Foundation CEO Marieke Flament sees the BitGo partnership as proof of the community’s commitment to widening the ecosystem, as well as creating a more diverse community of users.
“This is a significant step for NEAR and its foray into the world of institutional enterprise,” Flament adds. “With BitGo, we will support their clients and give them the ability to stake NEAR assets, both safely and securely. We are also putting our confidence into BitGo by putting a part of our own treasury in its custody because it is simply the best at what it does.”
Together we can truly make significant inroads in broadening the number of people leveraging our ecosystem and ultimately bring us closer to achieving our goal for mass web3 adoption.”
In 2020 BitGO launched Prime Trading and Lending, in addition to BitGo Portfolio and Tax, providing clients with a full-stack solution for digital assets. In 2018, it launched BitGo Trust Company, the first qualified custodian purpose-built for storing digital assets. Approaching a decade since its 2013 inception, BitGo, like NEAR, is in it for the long-haul. |
---
title: 5.4 Network States and the Future of Governance
description: Defining and understanding the network state and its implications
---
# 5.4 Network States and the Future of Governance
The final lecture of the DAO module, focuses on one of the most exciting and disruptive concepts surrounding decentralized governance: The Network State. The context behind the theory of network state’s is as follows:
DAOs are fundamentally political - after all, we are dealing with the governance of protocols, value, and mechanics of systems that inherently hold value on their own. This time, however, the politics is not one that traces back to a physical company or entity, but rather it's the digital polis with all of the enhancements of smart contracts, automated function calls, AI governed behavior, and trustless access / permissioning. In short, when self-executing code, intermingles with value-laden systems, we have the opportunity to create entire countries - online.
No individual has advanced the Network State thesis more than Ex-CTO of Coinbase, and Ex-partner at a16z, Balaji Srinivasan.
**_Balaji’s thesis on the network state can be summarized as follows:_**
In one sentence:
**_“A network state is a highly aligned online community with a capacity for collective action that crowdfunds territory around the world and eventually gains diplomatic recognition from pre-existing states.”_**
And a slightly more complex definition:
**_“A network state is a social network with a moral innovation, a sense of national consciousness, a recognized founder, a capacity for collective action, an in-person level of civility, an integrated cryptocurrency, a consensual government limited by a social smart contract, an archipelago of crowdfunded physical territories, a virtual capital, and an on-chain census that proves a large enough population, income, and real-estate footprint to attain a measure of diplomatic recognition.”_**
![](@site/static/img/bootcamp/mod-em-5.4.1.png)
Summarized succinctly, Balaji’s argument is the following:
_Many countries around the world have less than 10mm people in total, with quite low GDP. Now that value can be maintained on the level of software itself - outside of any physical reality - or polity (in political terms), it is not that outlandish to believe that communities of participants in these value laden software systems will move to organize themselves into digital countries, that eventually manifest themselves in physical locations. In fact, it is likely that this will happen because of the common values, shared future, and disenchantment with existing nation-states._
![](@site/static/img/bootcamp/mod-em-5.4.2.png)
## The Seven Steps To Moving From Startup Society To Network State - According to Balaji
1. **Found A Startup Society:** An online community based upon a common mission, objective, or shared identity, from which followers can strengthen their vision of the future.
2. **Organize It Into A Group Capable of Collective Action:** _“Unlike a social network, a network union has a purpose: it coordinates its members for their mutual benefit. And unlike a traditional union, a network union is not set up solely in opposition to a particular corporation, so it can take a variety of different collective actions."_[^3](https://thenetworkstate.com/footnotes#fn.3) Unionization is a key step because it turns an otherwise ineffective online community into a group of people working together for a common cause.” This is to say, while an online community is necessary, it requires further organization such that it can ‘coordinate’ its members for their mutual benefit.’ This is the ‘strengthening process’ that move beyond a simple online community.
3. **Build Trust Offline and a Crypto-Economy Online:** With an organized group, then natural next step is to strengthen the economic rails of the in-group itself, while also deepening relationships in the real world from the different members. Balaji often references the following graphic below to indicate time frames for such communities:
![](@site/static/img/bootcamp/mod-em-5.4.3.png)
4. **Crowdfund Physical Nodes:** The creation of physical nodes can range in size from buildings, and apartments, to plots of land and physical space itself - to the extent of new towns. The point here, is that the digital community with a strengthened economy, has now manifested their values and vision of the future in a physical space that can then develop a culture and atmosphere of its own.
5. **Digitally Connect Physical Communities:** With a strengthened internal economy, and a close-knit group familiar with one another in the physical world with designated spaces, the network state is able to begin developing their ‘digital archipelago’ - which is the slow process of creating physical spaces for the community in question.
_“Link these physical nodes together into a network archipelago, a set of digitally connected physical territories distributed around the world. Nodes of the network archipelago range from one-person apartments to in-person communities of arbitrary size.”_
6. **Conduct an On-Chain Census:** The sixth point is somewhat more arbitrary, but the underlying thesis is that in order to become more legitimate, the network-state must make it clear based on the data of their community, their economy, and their geography that they are a legitimate community. Once this is done it further legitimizes the future of the digital country.
7. **Gain Diplomatic Recognition:** Moving from a startup society, to a digital country transitions critically at the point in which at least one country recognizes the digital country in some manner. This should be understood as a multi-decade process from which more and more countries will see strategic benefits from recognizing the network states, and conversely, with the network state being able to trade, support, and even fight with an existing country.
This pathway is Balaji’s thesis for how to move from a startup society to a digital country / network state. What is not as evident is how a network state is distinct from a startup community, a religion, or some other political organization. Such characteristics are what Balaji outlines further.
## The Key Characteristics of a Network State
There are roughly a dozen characteristics of a network state that Balaji lists off - it should be noted that these are non-exhaustive, and most likely will evolve over time. However for the time being, Balaji has identified them as essential for being known as a network state.
_A Social Network:_ One integrated community - that is primarily social and secondarily geographical. Membership can be removed, and members must abide by the rules of the community.
_“The people of a network state form their nation online. Social rather than geographic proximity is the core organizing principle”_
_A Moral Innovation:_ “Missionary societies outcompete mercenary ones.” The idea here is that a network state must be grounded in a vision of the future that is fundamentally normative - that is to say, the reason there is a community that has acquired geographical space and attempts to become legitimized as a nation is for an improved understanding of ‘the good life’. This improved understanding is moral at root, and thus seeks to change the ‘status quo’ from the societies in which members are coming from.
_“Everyone within the society thinks some principle X is good that the rest of the world thinks is bad, or vice versa. This is the proposition part of a proposition nation.”_
_A Sense of National Consciousness: _National consciousness is defined by Balaji to mean, _“Everyone in a network state feels like they’re part of the same community, sharing the same values and culture.”_ The key emphasis on values and culture means that a network state identifies as one cohesive whole as opposed to multiple separate parts.
_A Recognized Founder:_ A recognized founder, is akin to a leader willing to drive the direction and set the vision for the future of the network state. This is not necessarily one single individual - it could be a board, a multi-sig, or a collective - but the important thing is that there is unity around the person(s) and vision set by those persons, such that the direction of the network state can be set and improved over time.
_A Capacity for Collective Action:_ Purpose + action determines the capacity for collective action. Closely related to national consciousness, this characteristic focuses on the capacity to set and create an envisioned future. This collective vision and enaction, has a unifying impact on the citizenry (According to Balaji).
_“It’s a combination of collective purpose (which is like the mission statement of a company, but for a community) and the capacity to act on that purpose.”_
Example given by Balaji from the past include the following:
_“The Puritans wanted to build a “[City on a Hill](https://www.americanyawp.com/reader/colliding-cultures/john-winthrop-dreams-of-a-city-on-a-hill-1630/).” The Japanese after the Meiji Restoration replaced their previous mission statement of “Revere the Emperor, Expel the Barbarians” with “[Enrich the Country, Strengthen the Military](https://en.wikipedia.org/wiki/Fukoku_ky%C5%8Dhei),” turning their society around 180 degrees and thereby building the first non-white industrialized power.”_
_An In-Person Level of Civility:_ Decency and respect for fellow citizens requires civility. In order for a common consciousness and capacity for collective action to develop, the members of the society must be capable of interacting with one another in healthy and open manners.
_“So whether one is coming from the left or right, pulling together a high-trust society means in-person levels of civility towards community fellow members, both offline and online. High trust in turn comes from alignment towards a collective purpose and a sense of national consciousness.”_
_An Integrated Crypto-Currency:_ An integrated crypto-currency is simply a modern version of saying, a shared system of value keeping. Beyond simply monetary value, an integrated crypto-currency can operate as the backbone for record keeping, identification, and data of all of the citizens inside of the society.
_“It manages the internal digital assets, the smart contracts, the web3 citizen logins, the birth and marriage certificates, the property registries, the public national statistics, and essentially every other bureaucratic process that a nation state manages via pieces of paper.”_
_An Archipelago Of Crowd-Funded Physical Territories:_ The underlying point here is not just the ownership of physical property, but the integration of physical property with the digital network. Whether that means NFT gated access to certain buildings, visibility of certain flags with certain VR glasses, or some other digital-physical interaction point, a real network state requires land - that is integrated with the ‘network’.
_“You network these clusters together using the internet into a network archipelago, eventually using newer technologies to make them more real.”_
_A Consensual Government Limited By A Social Smart Contract:_ This is the ‘legal’ ‘governance framework’ of the consensual government. Notably Balaji only puts this characteristic in, _after_ those dealing with collective action, national consciousness and leadership. This characteristic is the officially enshrined ‘code-base’ for how the network operates on an administrative and granular level.
_“Many people make the mistake of thinking the laws (or the land) come first when starting a new state, but laws should only come after the formation of an organic people – of a network nation – not before.”_
However, the reality of a binding governance framework - that collects and manages one’s identity and reputation, is a very real and serious decision that citizens must be willing to take. The full scope of consensual governance by smart contract is outlined by Balaji below:
_“when we say that a network state has “consensual government limited by a social smart contract”, we mean that it exercises authority over a digital (and, eventually, physical) sphere constituted solely of those people who’ve opted in to its governance by signing a social smart contract with their ENS names, in much the same way they might “opt in” to the governance of a centralized exchange by depositing coins there._
_A Virtual Capital:_ The idea behind a network state is ‘cloud first’ and ‘last’. And the virtual capital piece strictly refers to the ‘cloud last’ concept. In short, virtual capital means that the value inherent in the network state is predominantly virtual and accessible by the different members of the community - whether that is through VR glasses, a special metaverse, or an architecture engine.
The final two characteristics of a network state are legitimizers of the digital nation, in the eyes of existing state criteria among countries: Demographics and data on the size of the country, and diplomatic recognition in the eyes of other countries.
_An on-chain census that proves a large enough population, income, and real estate footprint._ Note this is not only for legitimacy in the eyes of the outside world but also for reputation among other emerging network states. In essence, this is the new frontier of ‘crypto products’ whereby there is not a list of the top tokens, but instead a list of the most successful, affluent and populated digital countries.
_“By accumulating the censuses of all startup societies in a hypothetical nationrealestatepop.com site similar to coinmarketcap.com, you could track in real time the number of startup society members, the acreage of real estate owned by those members, and their on-chain GDP.”_
_Attain a Measure of Diplomatic Recognition:_ Diplomatic recognition finalizes the legitimacy of the network state, and enshrines their capacity to act not only amongst themselves, but on the global stage to some degree.
_“Diplomatic recognition requires a putative state to have clout, and clout is in turn established by a publicly verifiable on-chain census of population, income, and real estate, to prove that your growing society is as large as you say it is.”_
## DAOs in the Context of Crypto
The Network State Thesis, when taken together with the Composability Thesis (as discussed in Module 2) turns the promise of crypto into an entirely new animal: Crypto is by definition political, as on-chain governance cross-pollinates with composable value systems, allowing individuals to autonomously govern themselves outside of the domain of the nation-state, legacy tech companies, and geographical boundaries.
When one considers the political bent of crypto, in line with other emerging technologies such as Virtual Reality, the Internet of Things, advanced manufacturing and 3D printing, it becomes evident that composability of value, and coordination of decision making inherent to smart contracts, is a ‘general purpose technology’ much like the steam engine in its wide and vast array of potential applications.
## Actively Building Network States and How L1 Ecosystems Can Understand Them
To conclude this module on DAOs, OO’s and specifically on the emergence of Network States, it is useful to look at some of the most promising and innovative examples of network states. For full visibility into the list, see [https://thenetworkstate.com/dashboard](https://thenetworkstate.com/dashboard):
![](@site/static/img/bootcamp/mod-em-5.4.4.png)
* **Afropolitan:** One of Africa’s largest communities spanning the entire continent (Pan-Africa) that is now organizing into a formal network state and working towards agreements with multiple African governments for visa-free travel and other benefits.
* **Praxis Society:** Praxis is [focused on creating a new city focused around revitalizing](https://www.cityofpraxis.com/) how life is lived, in line with the technologies and values that will create a better future. It’s five step plan, only launching now in 2022 intends to migrate 10,000 residents to a new city in the coming decade.
* **City DAO:** City DAO has set its sights on creating a digital city, of 10,000 people, built around a system of guilds. Its key metric of success is the [number of citizens ](https://city.mirror.xyz/OQ-VjksyKPgdswhN8vmnk3o_CNPym6PJ0EAFdX6h5TA)spending time on CityDAO property. Notably, CityDAO believes the city itself is the ‘product’ under construction from which multiple governance and social benefits can be derived.
* **Nation3:** Aspires to build a [Solarpunk City from the cloud.](https://nation3.org/) Already backed with the $NATION currency, and[ its own manifesto](https://nation3.org/manifesto) on the power of crypto-communities creating a new frontier for political organization and individual sovereignty.
Other mentions include [Porta Norte (Panama) ](https://en.portanorte.com/masterplan)and [W3ST](https://en.w3st.xyz/nodos).
Some open questions that have yet to be addressed include:
* **Timeframes:** How long does it take to progress from a startup society to a network state? Is there a playbook for managing and tracking the evolution from one into the other?
* **Incumbent Reaction:** How will existing countries react to such entities? Including the United Nations and other Non-Governmental Organizations?
* **National Opportunism:** Will existing stateless nations capitalize on such movements to organize into their own digital countries? Examples like Catalonia and Kurdistan, as well as Tibet are prime examples of cross-pollination between existing stateless nations, and emergent digital states.
## Some inadvertent effects of Nation State’s Include the Following
* **Low Cost, High Impact:** They are low cost, and hold the promise of bringing entire communities and plots of physical land to an L1 ecosystem. Things like NFT infrastructure, robust data models, storage, invoicing, and identity management, are all presupposed for the ‘network state toolkit’.
* **A revolution in political science:** The academic world has yet to comprehend or keep up with the vast revolution of digital governance - and how it challenges the traditional concept of the ‘nation-state’. Network States specifically, and DAOs more generally signal the transition from the Westphalian world order, into something entirely new.
* **A new geopolitical opportunity:** Existing groups of peoples, religions, entrepreneurs, and existing countries all stand to benefit from leveraging the potential of network states and DAOs in clever ways - whether it is for tourism, financial benefits, or network benefits. From Wyoming’s DAO law to El Salvador promoting businesses in country, there is a large opportunity to educate and act quickly in this new framework of digital governance. |
---
id: unit-test
title: Unit Testing
#sidebar_label: 🧫 Unit Testing
---
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
Unit tests allow you to test the contract methods individually. They are suitable to check the storage is updated correctly, and that methods return their expected values. They are written in the contract's language and execute locally.
If you used one of our [examples](https://github.com/near-examples/docs-examples) as template, then you simply need to navigate to the contract's folder, and use `yarn test`. In case you didn't, then we recommend you copy the necessary node files (e.g. `package.json`) from one of our templates.
:::tip
You can run `yarn test` from the root folder of each project to run both unit and [integration](integration-test.md) tests.
:::
---
## Snippet I: Testing a Counter
The tests in the [Counter Example](https://github.com/near-examples/counters) rely on basic functions to check that the `increment`, `decrement`, and `reset` methods work properly.
<CodeTabs>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/counters/blob/main/contract-rs/src/lib.rs"
start="50" end="71" />
</Language>
</CodeTabs>
---
## Snippet II: Modifying the Context
While doing unit testing you can modify the [Environment variables](../anatomy/environment.md) through the `VMContextBuilder`. This will enable you to, for example, simulate calls from different users, with specific attached deposit and GAS. Here we present a snippet on how we test the `donate` method from our [Donation Example](https://github.com/near-examples/donation-examples) by manipulating the `predecessor` and `attached_deposit`.
<CodeTabs>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/donation-examples/blob/main/contract-rs/src/lib.rs"
start="59" end="117" />
</Language>
</CodeTabs>
---
## ⚠️ Limitations
Unit tests are useful to check for code integrity, and detect basic errors on isolated methods. However, since unit tests do not run on a blockchain, there are many things which they cannot detect. Unit tests are not suitable for:
- Testing [gas](../anatomy/environment.md) and [storage](../anatomy/storage.md) usage
- Testing [transfers](../anatomy/actions.md)
- Testing [cross-contract calls](../anatomy/crosscontract.md)
- Testing complex interactions, i.e. multiple users depositing money on the contract
For all these cases it is necessary to **complement** unit tests with [integration tests](integration-test.md).
|
---
title: Best Practices
description: Playbook for NEAR development at every stage
sidebar_position: 2
---
# Best Practices
## Pre-Development
* Understand NEAR Protocol: Get acquainted with the NEAR protocol by reading the “[NEAR Whitepaper](https://near.org/papers/the-official-near-white-paper)” and to learn some key aspects such as Design principles, Economics and Technology used in the NEAR protocol. Something that's highly recommended to read are [Account model ](https://docs.near.org/concepts/basics/accounts/model), [Access keys](https://docs.near.org/concepts/basics/accounts/access-keys#full-access-keys), [Asynchronous by design](https://docs.near.org/concepts/basics/transactions/overview), and [Sharding](https://near.org/papers/nightshade) to name a few. Familiarize yourself with the [NEAR Protocol documentation](https://docs.near.org/develop/welcome), the NEAR GitHub repository, and other resources such as NEAR University or the NEAR YouTube channel.
* Design [Smart Contracts](https://docs.near.org/develop/quickstart-guide): Plan your smart contracts in advance. Remember that smart contract updates can be complex on blockchain, so good initial design is crucial. Some source code examples can be found at this [Github repo](https://github.com/near/near-sdk-js/tree/develop/examples/src). Please visit this link to learn more about how to “[upgrade NEAR smart contracts](https://docs.near.org/tutorials/nfts/upgrade-contract)”.
* Select the Right Tools: NEAR provides Rust and Javascript for smart contract development. Choose based on your team's expertise and project requirements.
## Development Stage
* Use [Test Driven Development](https://docs.near.org/develop/testing/integration-test#test-driven-design) (TDD): NEAR provides tools like the simulation testing framework for Rust and as-pect for JS. TDD allows you to ensure your contract behaves as expected. Some code samples can be found at this [github repo](https://github.com/near/workspaces).
* Utilize [NEAR SDKs](https://docs.near.org/sdk/welcome): NEAR SDKs offer handy utilities and abstractions for account management, contract interaction, transaction construction, and more.
* Ensure [Efficient Gas Usage](https://docs.near.org/concepts/basics/transactions/gas): Be mindful of computational and storage costs in smart contracts to ensure efficient usage of gas.
* [Optimizing contracts](https://docs.near.org/sdk/rust/contract-size) - Avoid the pitfalls of chunky (expensive) contracts which can also result in high gas fees. Please refer to the best practices for contract optimization.
## Pre-Mainnet Deployment
* Code Review and Auditing: Have your smart contracts reviewed and audited by third parties to detect potential security vulnerabilities and inefficiencies.Please contact your account manager who can guide you with some of the preferred smart contract partners we have in the NEAR Ecosystem such as Hacken, Ottersec, Certik, Halborn, etc.
* Test on [NEAR Testnet](https://explorer.testnet.near.org/): [Deploy your contract to NEAR Testnet](https://docs.near.org/develop/deploy#deploying-the-contract) to verify that it operates correctly in a live network environment.
* Create a Rollout Plan: This should include contingency plans for any problems or bugs discovered after deployment.
## Building on BOS
* [BOS overview video ](https://www.youtube.com/watch?v=NGX4_ZlzFzs)
* [Longer Technical Workshop](https://www.youtube.com/watch?v=Z3mVpZiy_gc&t=347s) (video)
* [Technical Workshop](https://docs.google.com/presentation/d/14DvgrjS5mElo1V9g0PQFYVDQnMFT55lF1yNOwCEsbnk/edit#slide=id.p) (slides)
* [Technical docs](https://docs.near.org/discovery/) (site)
* [Ecosystem projects on BOS](https://www.youtube.com/watch?v=ImKMvoD0W14)
* [EVM decentralized frontends on BOS](https://bos.gg/#/)
* [BOS telegram community channel](https://t.me/NEARisBOS)
## Maintenance and DevOps
* Monitoring: Set up [monitoring](https://docs.near.org/tools/realtime) for your contract. Explorers like [NEAR explorer](https://explorer.near.org/), [NEAR blocks](https://nearblocks.io/) and indexers like [near lake](https://docs.near.org/concepts/advanced/near-lake-framework) can help with this.
* [Updating Contracts](https://docs.near.org/develop/upgrade): Design your contracts to be upgradable or, alternatively, make sure you have a way to migrate state to a new contract if needed. There are two different ways to update your smart contracts:
1. Through tools such as [NEAR CLI](https://docs.near.org/tools/near-cli) or [near-api-js](https://docs.near.org/tools/near-api-js/quick-reference) (requires the account's [full access key](https://docs.near.org/concepts/basics/accounts/access-keys)).
2. Programmatically, by implementing a method that [takes the new code and deploys it](https://docs.near.org/develop/upgrade#programmatic-update).
## Community Resources
* Community Engagement: Regularly communicate updates with your user base. This includes being active in [NEAR community](https://gov.near.org/) forums, hosting AMAs, etc.
* Join NEAR community channels to stay up to date about NEAR:
3. Technical docs - [https://docs.near.org/](https://docs.near.org/)
4. Github - [https://github.com/near](https://github.com/near)
5. Telegram - [t.me/cryptonear](https://t.co/qwGrKk951Z)
6. Community - [https://t.me/nearprotocolnews](https://t.me/nearprotocolnews) (announcements)
7. Discord - [near.chat](https://t.co/orPJHp4ZcC)
8. Blockchain Operating System -[ near.org](https://near.org/)
9. Twitter - [https://twitter.com/NEARProtocol](https://twitter.com/NEARProtocol)
10. Companies & projects building on NEAR - [NEAR Horizon](https://near.org/nearhorizon.near/widget/Index)
---
_Queries and suggestions ! email us [blockchain-success@near.foundation](mailto:blockchain-success@near.foundation)_ |
---
sidebar_position: 3
---
# Build
> Creating Decentralized Frontends and components w/ BOS Web Engine
A BWE component looks, for the most part, like a standard React component. There are some syntactical variations and essential enhancements to adapt seamlessly to the engine's framework.
## Terms
- **Outer Window Application (OWA)** - The application responsible for rendering Components and brokers messages between containers.
- **Components** - The functions returning JSX to be rendered in BOS Web Engine. Their source is stored on chain in the SocialDB contract.
- **Root Component** - The top-level Component loaded by the outer application.
- **Containers** - Provide the runtime context for one or more Components. They are implemented as sandboxed `<iframe>`s,
communicating with other containers via the outer window application's `window.postMessage` method.
|
---
id: royalty
title: Royalty
sidebar_label: Royalty
---
import {Github} from "@site/src/components/codetabs"
In this tutorial you'll continue building your non-fungible token (NFT) smart contract, and learn how to implement perpetual royalties into your NFTs. This will allow people to get a percentage of the purchase price when an NFT is sold.
## Introduction
By now, you should have a fully fledged NFT contract, except for the royalties support.
To get started, go to the `nft-contract-approval/` folder from our [GitHub repository](https://github.com/near-examples/nft-tutorial/), or continue your work from the previous tutorials.
```bash
cd nft-contract-approval/
```
:::tip
If you wish to see the finished code for this _Royalty_ tutorial, you can find it in the `nft-contract-royalty` folder.
:::
---
## Thinking about the problem
In order to implement the functionality, you first need to understand how NFTs are sold. In the previous tutorial, you saw how someone with an NFT could list it on a marketplace using the `nft_approve` function by passing in a message that could be properly decoded. When a user purchases your NFT on the marketplace, what happens?
Using the knowledge you have now, a reasonable conclusion would be to say that the marketplace transfers the NFT to the buyer by performing a cross-contract call and invokes the NFT contract's `nft_transfer` method. Once that function finishes, the marketplace would pay the seller for the correct amount that the buyer paid.
Let's now think about how this can be expanded to allow for a cut of the pay going to other accounts that aren't just the seller.
<hr class="subsection" />
### Expanding the current solution
Since perpetual royalties will be on a per-token basis, it's safe to assume that you should be changing the `Token` and `JsonToken` structs. You need some way of keeping track of what percentage each account with a royalty should have. If you introduce a map of an account to an integer, that should do the trick.
Now, you need some way to relay that information to the marketplace. This method should be able to transfer the NFT exactly like the old solution but with the added benefit of telling the marketplace exactly what accounts should be paid what amounts. If you implement a method that transfers the NFT and then calculates exactly what accounts get paid and to what amount based on a passed-in balance, that should work nicely.
This is what the [royalty standards](https://nomicon.io/Standards/NonFungibleToken/Payout) outlined. Let's now move on and modify our smart contract to introduce this behavior.
---
## Modifications to the contract
The first thing you'll want to do is add the royalty information to the structs. Open the `nft-contract-approval/src/metadata.rs` file and add `royalty` to the `Token` struct:
```rust
pub royalty: HashMap<AccountId, u32>,
```
Second, you'll want to add `royalty` to the `JsonToken` struct as well:
```rust
pub royalty: HashMap<AccountId, u32>,
```
<hr class="subsection" />
### Internal helper function
**royalty_to_payout**
To simplify the payout calculation, let's add a helper `royalty_to_payout` function to `src/internal.rs`. This will convert a percentage to the actual amount that should be paid. In order to allow for percentages less than 1%, you can give 100% a value of `10,000`. This means that the minimum percentage you can give out is 0.01%, or `1`. For example, if you wanted the account `benji.testnet` to have a perpetual royalty of 20%, you would insert the pair `"benji.testnet": 2000` into the payout map.
<Github language="rust" start="5" end="8" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/internal.rs" />
If you were to use the `royalty_to_payout` function and pass in `2000` as the `royalty_percentage` and an `amount_to_pay` of 1 NEAR, it would return a value of 0.2 NEAR.
<hr class="subsection" />
### Royalties
**nft_payout**
Let's now implement a method to check what accounts will be paid out for an NFT given an amount, or balance. Open the `nft-contract/src/royalty.rs` file, and modify the `nft_payout` function as shown.
<Github language="rust" start="22" end="67" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/royalty.rs" />
This function will loop through the token's royalty map and take the balance and convert that to a payout using the `royalty_to_payout` function you created earlier. It will give the owner of the token whatever is left from the total royalties. As an example:
You have a token with the following royalty field:
```rust
Token {
owner_id: "damian",
royalty: {
"benji": 1000,
"josh": 500,
"mike": 2000
}
}
```
If a user were to call `nft_payout` on the token and pass in a balance of 1 NEAR, it would loop through the token's royalty field and insert the following into the payout object:
```rust
Payout {
payout: {
"benji": 0.1 NEAR,
"josh": 0.05 NEAR,
"mike": 0.2 NEAR
}
}
```
At the very end, it will insert `damian` into the payout object and give him `1 NEAR - 0.1 - 0.05 - 0.2 = 0.65 NEAR`.
**nft_transfer_payout**
Now that you know how payouts are calculated, it's time to create the function that will transfer the NFT and return the payout to the marketplace.
<Github language="rust" start="70" end="135" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/royalty.rs" />
<hr class="subsection" />
### Perpetual royalties
To add support for perpetual royalties, let's edit the `src/mint.rs` file. First, add an optional parameter for perpetual royalties. This is what will determine what percentage goes to which accounts when the NFT is purchased. You will also need to create and insert the royalty to be put in the `Token` object:
<Github language="rust" start="6" end="80" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/mint.rs" />
Next, you can use the CLI to query the new `nft_payout` function and validate that it works correctly.
### Adding royalty object to struct implementations
Since you've added a new field to your `Token` and `JsonToken` structs, you need to edit your implementations accordingly. Move to the `nft-contract/src/internal.rs` file and edit the part of your `internal_transfer` function that creates the new `Token` object:
<Github language="rust" start="184" end="192" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/internal.rs" />
Once that's finished, move to the `nft-contract-approval/src/nft_core.rs` file. You need to edit your implementation of `nft_token` so that the `JsonToken` sends back the new royalty information.
<Github language="rust" start="160" end="177" url="https://github.com/near-examples/nft-tutorial/blob/main/nft-contract-royalty/src/nft_core.rs" />
---
## Deploying the contract {#redeploying-contract}
As you saw in the previous tutorial, adding changes like these will cause problems when redeploying. Since these changes affect all the other tokens and the state won't be able to automatically be inherited by the new code, simply redeploying the contract will lead to errors. For this reason, you'll create a new account again.
### Deployment and initialization
Next, you'll deploy this contract to the network.
```bash
export ROYALTY_NFT_CONTRACT_ID=<accountId>
near create-account $ROYALTY_NFT_CONTRACT_ID --useFaucet
```
Using the cargo-near, deploy and initialize the contract as you did in the previous tutorials:
```bash
cargo near deploy $ROYALTY_NFT_CONTRACT_ID with-init-call new_default_meta json-args '{"owner_id": "'$ROYALTY_NFT_CONTRACT_ID'"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send
```
### Minting {#minting}
Next, you'll need to mint a token. By running this command, you'll mint a token with a token ID `"royalty-token"` and the receiver will be your new account. In addition, you're passing in a map with two accounts that will get perpetual royalties whenever your token is sold.
```bash
near call $ROYALTY_NFT_CONTRACT_ID nft_mint '{"token_id": "royalty-token", "metadata": {"title": "Royalty Token", "description": "testing out the new royalty extension of the standard", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$ROYALTY_NFT_CONTRACT_ID'", "perpetual_royalties": {"benjiman.testnet": 2000, "mike.testnet": 1000, "josh.testnet": 500}}' --accountId $ROYALTY_NFT_CONTRACT_ID --amount 0.1
```
You can check to see if everything went through properly by calling one of the enumeration functions:
```bash
near view $ROYALTY_NFT_CONTRACT_ID nft_tokens_for_owner '{"account_id": "'$ROYALTY_NFT_CONTRACT_ID'", "limit": 10}'
```
This should return an output similar to the following:
```json
[
{
"token_id": "royalty-token",
"owner_id": "royalty.goteam.examples.testnet",
"metadata": {
"title": "Royalty Token",
"description": "testing out the new royalty extension of the standard",
"media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif",
"media_hash": null,
"copies": null,
"issued_at": null,
"expires_at": null,
"starts_at": null,
"updated_at": null,
"extra": null,
"reference": null,
"reference_hash": null
},
"approved_account_ids": {},
"royalty": {
"josh.testnet": 500,
"benjiman.testnet": 2000,
"mike.testnet": 1000
}
}
]
```
Notice how there's now a royalty field that contains the 3 accounts that will get a combined 35% of all sales of this NFT? Looks like it works! Go team :)
### NFT payout
Let's calculate the payout for the `"royalty-token"` NFT, given a balance of 100 yoctoNEAR. It's important to note that the balance being passed into the `nft_payout` function is expected to be in yoctoNEAR.
```bash
near view $ROYALTY_NFT_CONTRACT_ID nft_payout '{"token_id": "royalty-token", "balance": "100", "max_len_payout": 100}'
```
This command should return an output similar to the following:
```bash
{
payout: {
'josh.testnet': '5',
'royalty.goteam.examples.testnet': '65',
'mike.testnet': '10',
'benjiman.testnet': '20'
}
}
```
If the NFT was sold for 100 yoctoNEAR, josh would get 5, benji would get 20, mike would get 10, and the owner, in this case `royalty.goteam.examples.testnet` would get the rest: 65.
## Conclusion
At this point you have everything you need for a fully functioning NFT contract to interact with marketplaces.
The last remaining standard that you could implement is the events standard. This allows indexers to know what functions are being called and makes it easier and more reliable to keep track of information that can be used to populate the collectibles tab in the wallet for example.
:::info remember
If you want to see the finished code from this tutorial, you can go to the `nft-contract-royalty` folder.
:::
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `4.0.13`
- cargo-near `0.6.1`
- NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.1.0`
- Enumeration standard: [NEP181](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration), version `1.0.0`
- Royalties standard: [NEP199](https://nomicon.io/Standards/Tokens/NonFungibleToken/Payout), version `2.0.0`
:::
|
---
description: Frequently asked questions about NEAR
title: FAQs
sidebar_position: 6
---
---
### What is NEAR?
It’s a decentralized application platform running on its own blockchain, that solves usability and scaling via sharding.
### What is The Difference Between Pagoda (formerly NEAR Inc) and The NEAR Protocol?
Generally, we differentiate between many of the different entities who are building the NEAR platform. Two of those different entities are the NEAR Foundation and Pagoda.
#### The NEAR Protocol
A permissionless, Proof-of-Stake blockchain protocol that anyone can access, add transactions to, or read from. The public NEAR blockchain is an instantiation of the reference code [here](http://github.com/near/nearcore), but theoretically, this repo could be forked and deployed as a separate chain, as much as many protocols have done to build upon the core Bitcoin code.
#### The NEAR Foundation
A non-profit foundation headquartered in Switzerland, and is responsible for contracting protocol maintainers, funding ecosystem development, and shepherding core governance of the protocol.
#### Pagoda (Formely Near Inc)
A US-based software research and development company that did much of the early development of the protocol and its tooling. While [Pagoda](https://www.pagoda.co//), which is the new branding of Near Inc, does not own or run the NEAR Protocol (which is decentralized), it continues to propose changes to the reference implementation codebase as one of multiple third-party entities performing R&D work for the protocol.
### Who is Building The NEAR Protocol?
Much of the early development of the protocol and its tooling has been done by Pagoda (formerly NEAR Inc).
### Where Can I Learn More About NEAR?
This wiki is a great place to start!
For developers looking for more technical information, have a look at - [docs.near.org](https://docs.near.org).
And if you want a deep dive into the NEAR technical specification, check out : [nomicon.io/](https://nomicon.io)
If you want to learn more about the NEAR Protocol design, take a look at:
- Our YouTube channel https://youtube.com/nearprotocol
- Our blog http://near.org/blog
- Our technical papers https://near.org/papers/the-official-near-white-paper
## Troubleshooting
### I Encountered a Problem With My Wallet
For help and support with wallet issues and errors, have a look at the [wallet FAQ](hhttps://nearhelp.zendesk.com/hc/en-us/articles/1500002248242-Creating-a-NEAR-Wallet-account) to see if your problem was addressed.
If you're problem wasn't solved, you can [open a ticket](https://nearhelp.zendesk.com/hc/en-us/requests/new) with the support team.
## Contact Information
### What is The Official NEAR Email?
Official email [hello@near.org](mailto:hello@near.org).
For proposals and suggestions, please create a post in our [forum](https://gov.near.org/).
### Where Can I Sign up to The Newsletter?
You want to receive updates on the latest and greatest in the NEAR ecosystem, then head over to https://near.org/
## Contributing to NEAR
### How Can I Get Involved?
It depends on what you are excited about doing.
Do you want to develop on NEAR?
Build tutorials?
Answer questions?
Expand our [documentation]?
Write on the wiki?
We recommend you have a look at the [NEAR Community Page](https://near.org/ecosystem/community).
If you are looking for something a little different, or you have questions, please reach out to the team on [Telegram](https://t.me/cryptonear) or [Discord](http://near.chat/).
## Tools
### What Tools Are Currently Available on NEAR?
Our [essential tools](essential-tools.md) include the NEAR-wallet, NEAR CLI, block explorer, and the actual blockchain.
We also have a large and growing list of community-led tools that you can find on [AwesomeNEAR](https://awesomenear.com/)
## More Questions?
Join our community channel ([Telegram](https://t.me/cryptonear) and [Discord](http://near.chat/)), we are here to help and answer any questions you may have.
|
NEAR Community Update: February 28th, 2020
COMMUNITY
February 28, 2020
Welcome to the NEAR community update!
In this community update, we want to introduce Stardust, which is one of the projects that is building on NEAR. The Stardust API just went live, and within a few weeks of its launch, they are already supporting over 2,000 players daily. If you are creating a game, collectible art house, or any other business with NFTs (non-fungible tokens), you can use their API to help you leverage blockchain technology in under 10 lines of code. How cool is that? Reach out to Canaan to learn more and check out their website at https://stardust.gg/.
We are really excited to see what projects are building on NEAR. If you would like to contribute to NEAR or start your own project, we would love to hear from you.
Content Highlight
We released a blog post in which Alex explains “How Randomness Beacons based on Threshold Signatures work”. Modern Proof-of-Stake protocols need a source of unbiased randomness. Dfinity pioneered the idea of using threshold signatures as such a beacon. This post explains in simple terms how such randomness beacons work.
Engineering
The engineering work on the unbiased randomness beacon is in full swing. We pushed the cryptographic primitives and are almost done with the integration.
It will take time to stabilize the beacon, and the initial launch of NEAR will use a simpler beacon, in which block producers have one bit of influence. The simple beacon is done and pushed.
The team is largely in the stabilization mode, preparing to restart Stake Wars. In the past two weeks we have fixed a variety of issues:
Distribution of reward based on the stake, not seats:
https://github.com/nearprotocol/nearcore/commit/3e6b14a5ba7112223e6aea69a4eda1991c873cf4
Fixing the pricing of storage:
https://github.com/nearprotocol/nearcore/commit/4d9b1a45a2804ffed31f560807e2ce2757f0e352
Using the correct epoch for approvals on epoch switch:
https://github.com/nearprotocol/nearcore/commit/fcb0746d9b629716e58b575638b14d0f4d36086d
Fixing an inconsistency in the epoch manager:
https://github.com/nearprotocol/nearcore/commit/fc4e26852fbe40734fe6e2c3edfecfbbe3d49ce4
Fixing a bug with empty method names:
https://github.com/nearprotocol/nearcore/commit/29cb2522870d4a33824a25f9e2fe8d897251a5b5
Batman (Alex’ dog) wishes you a great weekend!
How You Can Get Involved
Join theNEAR Contributor Program. If you would like to host events, create content or provide developer feedback, we would love to hear from you! To learn more about the program and ways to participate, please head over to the website.
If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox. |
NEAR Foundation Partners with Hibiki Run on Open Web Digital Gachapon
NEAR FOUNDATION
July 5, 2023
NEAR Foundation is thrilled to announce a new strategic partnership with Hibiki Run, a platform lying at the nexus of innovation in music streaming and digital collectibles. Hibiki Run is revolutionizing music discovery by melding gaming thrills with crypto-driven Listen-to-Earn (L2E) incentives.
Together, NEAR Foundation and Hibiki Run will explore innovative paths for creating engagement between Web3 content creators and end users. With the Japanese “Gachapon” vending machine capsule toys as a model, the collaboration will meld NEAR’s cutting-edge blockchain technology with Hibiki Run’s expertise in digital music, art, and exercise, new opportunities in each vertical for creation, distribution, and ownership.
Bringing a ‘Digital Gachapon’ economy to the open web
With “Digital Gachapon”, NEAR and Hibiki Run will bring a powerful economic tool to creators. When interacting with a Japanese Gachapon, layers insert coins into the machine, turn the knob, and receive a capsule with a random item.
Hibiki Run has innovatively digitized this exciting concept, integrating it with blockchain technology. In the digital Gachapon system, users utilize their tokens to receive digital items such as NFTs or unique digital assets — anything from exclusive music tracks, collectible art pieces, and rare gaming items, to access tokens for specific events or experiences.
The digital Gachapon’s strength lies in its element of surprise and the potential for rare, high-value rewards — transforming the token expenditure into an exciting event while providing a way for creators to distribute their content in a fun and engaging manner.
Hibiki Run and NEAR hope that with these types of innovative concepts, blockchain technology, and user-friendly interfaces, a new frontier of digital arts will open up. One that is interactive and immersive for creators and consumers alike. Like NEAR, Hibiki Run is committed to creating a decentralized, fair, and accessible ecosystem for artists.
|
An Update On the NEAR Validator Upgrade
DEVELOPERS
January 28, 2022
At NEAR Foundation, our goal has always been to provide the best experience for validators, delegators, community members, and project builders. As part of NEAR Protocol’s goal to increase the number of validators securing the network and improve decentralization, we invited the community to submit an application through our call for applications on December 2, 2021.
We received an overwhelming interest of more than 160 applications for delegation.
After the latest upgrade, which now allows up to 100 validators to the Mainnet and a lowered seat price of 64,000 $NEAR, many validators (73) managed to enter the validator pool with their own funds. The Foundation only had 27 seats available for delegation, which means that the selection process was extremely competitive.
As NEAR Protocol is certified carbon neutral by South Pole, we ask validators to think through how they offset their validator operation’s carbon footprint, and communicate any CO2 offsetting that they implement on their end, such as using a renewable energy source to operate the nodes. An important criteria in the selection for delegation was ecological, and validators who took steps to offset their carbon footprint were selected.
Additionally, please note that the minimum criteria to qualify for delegation, such as keeping commission to 7% and maintaining high uptime on testnet node or mainnet node, is essential and the Foundation reserves the right to withdraw delegation and re-delegate to another validator.
Additional Opportunities
For any validators that were not selected in this round, there will be many more opportunities to be involved in the NEAR Ecosystem.
NEAR Protocol will introduce a new type of validator, Chunk-Only Producer, in mid-2022 to further decentralize NEAR and increase the number of validators on Mainnet from 100 to 300.
For those interested in being considered for a Chunk-Only Producer, please fill out this typeform.
For additional information about Chunk-Only Producers, please visit the Decentralize page. Additional details can be found on the NEAR protocol roadmap.
Another route to helping secure the network is via the Open Shards Alliance. The Open Shards Alliance (OSA) and the GuildNet network have been an ecosystem guild since the Mainnet launch. It’s been a home for validators, those interested in becoming one, and new devs that enter the ecosystem. Ideas are bootstrapped in the OSA and often move on into their own projects. The OSA is comprised of technical aficionados, sysadmins, and devs.
Please join the Open Shards Alliance server at the OSA Discord. |
NEAR.ai → NEAR Protocol
COMMUNITY
August 23, 2018
A bit more than a year ago Alexander Skidanov and I started NEAR.ai. We strongly believed that program synthesis, the field that studies automated programming from a human specification, was going to transform software development and the world in general.
Program synthesis is aiming to generate computer programs from user specification, unlocking currently scarce skills to everybody in the world.
Last year at ICLR 2017 we saw a number of papers from various research labs and got really excited about the opportunity to bring that technology to the market. Both Alex and I had tried to explore program synthesis in our university days, but machine learning was so early back then that it wasn’t really possible to make progress.
After the conference, we imagined what the company would look like and realized that the first priority was to establish a benchmark for the community to use. Just as the ImageNet benchmark advanced the field of Computer Vision by leaps and bounds by giving practitioners a clear metric for comparison, we believed that a complex dataset would challenge the community as well as guide research.
We started NEAR.ai with the hypothesis that we could both expand the boundaries of research in the field of program synthesis and at the same time deliver a transformative product powered by this technology.
Alex and I have both participated in programming competitions (Alex won Gold in ACM ICPC 2008) and we naturally thought that the problems which were designed for human participants in these challenges would be a great starting point for computers doing program synthesis.
Programming competitions generate great data for machine learning. Each programming competition usually involves solving 5–10 problems of increasing difficulty stated in natural language. Problems are then solved by participants in various programming languages, producing the “parallel corpus” of description — code pairs.
Over a year, we collected more than 30k+ problems and 10M+ solutions. Many of the problems were hard even for a regular software engineer to solve, so we focused on problems that are simple (e.g. A and B on CodeForces or 250 on TopCoder). Even then, the task descriptions were complex: the variety of concepts and language used in the descriptions were too much for the model to capture. Furthermore, some problems required logical reasoning steps and external mathematical knowledge. To simplify the first task, we crowdsourced to the CodeForces community to rewrite the descriptions of the problems into a “solution description”.
Results published at ICML 2018 on NAPS dataset
We published part of the dataset we collected in our ICML 2018 paper “NAPS: Natural Program Synthesis dataset”. However, despite all this work and after running state-of-the-art models (which combined deep learning and regular search techniques) on this dataset , we found that results were far from usable in practice (around 12% for our best model).
Alongside the technical work, we gathered feedback from prospective users to make sure there was a real demand in the market for our solution. We built prototypes (without any ML) and tested the experience using Wizard-of-OZ (or human-in-the-loop) model.
After several iterations of this, we realized that ML, specifically natural language understanding, is not there yet.
Meanwhile, there were a few ideas that lead to our transition:
Given our work in program synthesis, our advisors suggested looking into the field of generating smart contracts for Ethereum. At the moment, it’s hard to program provable contracts for a regular engineer, an issue that can be effectively addressed by program synthesis.
The more we spoke with people who want to build applications, the more buzz we heard about building apps using blockchain to provide monetary incentives and better privacy & security.
Blockchain connects various devices into a single cloud that provides developers readily available database, compute and ease of transacting money
We sat down with our friends David “Pieguy” Stolp and Evgeny Kuzyakov, who have been playing with blockchain on the side over last year to learn more about this space. As we dug deeper into the rabbit hole, we realized both the opportunity and the limitations of the current blockchain systems.
For developers, blockchain provides the infrastructure that currently requires months to setup: partition resilient networking, always available database and compute, ease of GDPR compliance, and reduced need in local regulatory compliance. Additionally, entrepreneurs can come up with entirely new business models for businesses built on top of the blockchain.
For users, blockchain ensures data privacy and security. The smart contracts provide guarantees and can be studied (probably not by the user, but news about the malicious contract would spread really fast while data leaks in walled gardens can be covered up).
On the other hand, there is a reason why currently new applications are not built on the blockchain. Ethereum, the most popular decentralized app platform currently, has 14 transactions per second worldwide. I repeat, 14 API calls per second worldwide, the big part of which is taken by exchanges and speculative trading, making it more complicated to use. As a result, each transaction takes from minutes to hours to actually make it into the ledger.
There are newer protocols that suppose to fix the problem with the performance of blockchain:
EOS — recently launched and had one of the largest ICOs, but at the end uses 21 people to sign the blocks, meaning that these 21 people decide on how ledger will be composed. They know each other and have a huge monetary incentive to not slash for bad behavior, even when they had already approved “double spends” or if they decide to rewrite history.
IOTA — great idea from the distance: no blocks, each IOT device can post transactions and they get confirmed by others posting transactions. The problem lies in details : each node must do 5 minutes of proof of work to post the transactions (or they would spam it), which means that finality is >5 minutes. Additionally, each IOT device should maintain a huge part of the DAG that has been built or it will be easily tricked into approving “double spends”, which prevents the protocol from running on real IOT devices. To make things worse, there is Coordinator, a centrally maintained checkpointing system to prevent long-range attacks.
There are other protocols, many of which are still building their tech, but each and every one of them is missing a conceptual thing. All the successful platforms started by bringing developers closer to users, instead of building better tools for developers.
This is what gave birth to NEAR protocol:
Allow developers to build blockchain native mobile dApps and run it where the users are (mobile phones), giving developers a key onramp into dApps
Through sharding by state, allow the blockchain to scale linearly with the number of nodes in a network (we are targeting ~100k tps @ 1 million mobile nodes)
Allow blockchain entrepreneurs to quickly iterate and come up with successful business models since they both have scalable blockchain and easy access to users via first mobile-native blockchain
In other words: NEAR is a fully sharded, proof-of-stake blockchain that is specifically designed so mobile phones can fully participate from day 1.
To achieve this, we are redesigning every component of the protocol, from networking to consensus to sharding the state and execution to how user client works. You can read our first position paper and stay tuned for more: we will release sharding and consensus technical papers next.
We got together a dream team of builders: 3 ICPC Gold medallist (Mikhail was 2-time world champion), 3 early MemSQL (built sharding for the distributed database), 4 Xooglers (built distributed systems at scale).
Over the next several weeks, we will be sharing technical details, how we are thinking about the blockchain space and applications we believe our protocol will unlock.
To follow our progress you can use:
Twitter — https://twitter.com/nearprotocol,
Medium — https://medium.com/nearprotocol,
Telegram — http://t.me/cryptonear,
Lastly,
https://upscri.be/633436/
Thanks to Alexander Skidanov, Maksym Zavershynskyi, Erik Trautman, Aliaksandr Hudzilin, Bowen Wang for helping to put together this post. |
NEAR & Social Good: Bringing Web3 to the Fringes
COMMUNITY
July 21, 2022
Web3 is sometimes labeled niche and even elitist. Blockchain products can be costly, difficult to understand, and not everyone has easy access to the space. Think NFTs and their explosion. Media coverage would suggest a subculture where only celebrities with absurd amounts of cash blow it on cartoon ape pictures. Some even go so far as to say that Web3 is redundant and provides no value.
But the mainstream narrative is only one narrow perspective—and an inaccurate one.
Beyond the noise and hype, people are building real projects with real value. In Web3, everyone can find a place to build inclusive apps and communities. Ones that bring people or groups historically marginalized by tech and society into the space.
And they’re using NEAR’s blockchain to do it.
Africa’s underprivileged communities building on Web3
In the dusty city of Jos, central Nigeria, locals cram into a bright blue classroom to watch a flat screen television. It’s (online) class time. And in this part of the world where access to tech and the Internet is limited, students of all ages are learning something new and exciting—how to mint NFTs.
Chapter One Foundation (C1) is a non-government organization built on NEAR, whose mission is to “spread positivity, opportunities and good art.” Through NFT sales, C1 helps aspiring artists get into recording studios, art facilities, and other spaces where they otherwise might have limited or no access.
It works like this: the C1 team helps mint traditional artists’ work as NFTs using NEAR’s NEP-171 NFT standard. The work is then sold on Mintbase, where 70% goes to the artist. C1 reinvests the remaining 30% in the organization to help it grow and buy more resources for creatives.
C1 co-founder, engineer, and musician Justin Burkholder says such an opportunity would not be possible without the Internet. In this case, the next iteration of the internet: Web3.
“It creates revenue streams in art which would normally involve a lot of interference from big business without Web3 and NFT technology,” he says. “It acts as a natural onboarding mechanism to the Web3 ecosystem—and NEAR in particular—while giving people opportunities to generate revenue and become productive members of their communities.”
The project is going well, too. People are gaining a greater understanding of Web3 and NEAR, and are even creating their own DAOs and building their own communities.
Feeding communities with Web3-enabled urban farming
In Lisbon, Portugal, the vertical farm startup Raiz is feeding local communities, including homeless people. In vertical farming, crops are grown indoors, with plants stacked on top of each other using hydroponic barrels and a combination of natural light and dynamic LEDs. It requires less land, water and pesticides, making it a more efficient and sustainable way of food harvesting.
To grow its food, Raiz is working to use unused urban spaces. Just recently it set up its first flagship farm in Lisbon and has also been donating its surplus crops to the Salvation Army. But Raiz won’t stop there, says Raiz CEO Emiliano Guittierez. The project will eventually help poor, food-insecure communities become self-sustainable.
“We aim to empower communities to build their own farms,” says Emiliano. “We can have investors from all over the world who can have a piece of ownership of farms, while people in Africa, South America, South East Asia or other developing parts of the world can deploy and build their own farms and have revenue from sales from the farms.”
How does Web3 fit into this picture? It boils down to scalability and traceability. Using NEAR’s technology, Raiz is building a token model that represents the farms, allowing people to invest, have a stake, and keep the vertical farm network growing in a traceable manner.
Further down the road, Raiz wants to introduce “impact tokens” that represent emissions avoided, and water and land saved as co-benefits.
Using DAOs for social good
This past June in New York City, NEAR-based Primordia—the “DAO of DAOs”—launched its campaign to create 100 DAOs that will work toward significant global social impact.
Launched by Kin DAO, a cooperative that helped over 55,000 people access critical services and resources during the pandemic before transforming into a project to help artists mint NFTs, Primordia is helping many little DAOs get set up to make a difference.
Primordia co-founder and San Francisco-based artist Asya Abdrahman says these DAOs will use “NEAR Protocol’s ethical blockchain” to help “people typically marginalized, overlooked or excluded.”
Some of these DAOs are already up and running. EFAM DAO is currently working to give food and medicine to displaced people in the US, while Petgas DAO is building a fossil fuel sustainability project in Mexico.
Why choose NEAR?
With a number of blockchains available, why are so many projects building on NEAR to help marginalized communities?
For one, it’s user friendly. A recurring theme for those building on NEAR’s blockchain is its ease of use. Web3 can be daunting, especially for those with no tech background.
“It’s an easy ecosystem to navigate and get involved with in transitioning from the Web2 to Web3,” says C1’s Burkholder.
“Although the mainstream is still hesitant about getting digital wallets, NEAR wallets are the easiest digital wallets that I’ve so far experienced using,” adds Asya.
NEAR is also the go-to blockchain for those concerned about the environment. Using a proof-of-stake (PoS) blockchain, it naturally uses less energy than proof-of-work chains, like Bitcoin.
The NEAR Protocol is also climate neutral. Last year, the NEAR Foundation enlisted South Pole, a global climate solutions firm, to help reduce NEAR’s carbon footprint, and offset its carbon footprint with green projects. This makes NEAR a natural draw for socially conscious projects, as social good often intersects with ecological balance.
Primoria’s Abdrahman adds that Ethereum, a blockchain she was using previously, kept promising to move to the more environmentally-friendly PoS chain, but it took too long. “For blockchain users that are concerned about climate-friendly solutions, NEAR is the go-to blockchain,” she adds.
All three projects also mention NEAR’s fast transaction speeds and low gas fees as attractive. Both are vital in onboarding people who aren’t exactly ‘tech-savvy,’ or who have typically been locked out from the Web3 world. Now they can take part. |
NEAR at ETHCC: Step into the Open Web on the BOS
NEAR FOUNDATION
June 13, 2023
NEAR Foundation is excited to announce that NEAR will be returning to ETHCC 2023. The Foundation will be hosting a 2-day side event at the Paris tech conference on July 16-17.
NEAR experts will be on hand at ETHCC to share the latest updates for building apps on the open web with the BOS — an industry-first OS that makes it easy to use the tools you already know to build apps that engage users, while fostering an open web untethered from centralized platforms.
Also, learn how your project can get funding and other support from NEAR Horizon, the new Web3 startup platform built on the BOS.
NEAR at ETHCC — What to expect
NEAR is hosting a two-day ETHCC side event on July 16-17th, that will feature Technical Workshops (BOS) hosted by Pagoda, a Horizon Pitch Competition, small ETH research group workshops (invite only), and other speaker sessions, keynotes, and panels. You can’t forget about our exclusive networking and happy hours!
Learn from the best in the NEAR ecosystem about what makes the BOS so revolutionary. Ask your questions. Learn in-person. Make connections!
Agenda: NEAR at ETHCC
NEAR’s 2-day ETHCC side event will be located at the Museum National D’Histoire Naturelle: Verniquet.
Day 1: Technical Day
11am – 12pm: Breakfast bites & Networking – Cafe au laits and pastries
12-12:30pm: Stateless Validation – Invite Only Research Group
12:30-1pm: Token Economics – Invite Only Research Group
1-1:30pm: BOS Vision
1:30-2pm: BOS for Devs
2-2:30pm: BOS Tech Breakdown for Partners
2:30-3pm: Simona/ETH Session
3pm-4pm: Programming Break, Happy hour guests arrive
4pm – 7pm: Happy Hour – Appetizers and drinks
Structure for Day 2: Founders Day
11am – 12pm: Networking and Co-working: Cafe au laits and pastries
12pm-12:30pm: Pantera Capital Workshop
12:30-1pm: Proximity Workshop
1-1:30pm: Simona/ETH Session
1:30-2pm: Pitchfest Guests arrive
2-4pm: Horizon Pitch Fest
4pm – 7pm: Horizon Pitch Competition Happy Hour: Aperol spritz and appetizers
NEAR Speakers at ETHCC
Illia Polosukhin, CEO of Pagoda, Co-Founder of NEAR
Matt Stephenson, Head of Cryptoeconomics, Pantera Capital
Vy Le, Bain Capital
Kendall Cole, Co-Founder and Director of Proximity
Mya Shofany, Regulatory Lead, NEAR Foundation
Bowen Want, Director of Protocol, Pagoda
And more!
|
---
sidebar_position: 6
---
# Tools
Currently, the only tool which supports authoring and publishing BWE components is the BWE sandbox. This is a web-based development environment built by the BWE team at Pagoda.
The sandbox can be found at [bos-web-engine-sandbox.vercel.app](https://bos-web-engine-sandbox.vercel.app/)
Code for the sandbox can be found under `apps/sandbox` in the BWE repository [here](https://github.com/near/bos-web-engine/tree/main/apps/sandbox)
We look forward to supporting other tool developers as they adopt BWE.
<details>
<summary>Want to build tooling for BWE?</summary>
<p>The main thing to know is that BWE is still highly subject to change as we receive feedback on DevX and functionality. If you don't mind potential rework due to engine changes and want to start building now:</p>
<p>Our sandbox package was built from the start to be reusable in other web implementations. Feel free to fork our project or pull out pieces you need. In the future we hope to publish many of our packages on NPM to make it easier to receive future updates.</p>
</details> |
---
id: account-model
title: NEAR Accounts
sidebar_label: Overview
---
Users participate in the NEAR ecosystem through their NEAR accounts. These accounts are identified by a [unique address](./account-id.md), can optionally hold a [smart contract](./smart-contract.md), and are controlled through [Access Keys](./access-keys.md).
By signing [transactions](./transactions.md) with their account, users can:
1. Send and receive **digital assets** (such as tokens or collectibles)
2. Create and interact with on-chain applications known as **smart contracts**
3. Control accounts in **other chains** (such as Ethereum or Bitcoin) ✨
4. Help onboard new users by **covering the costs** of their transactions (gas fees)
:::tip Want to create an account?
You have multiple ways to create an account, you can [sign-up using your email](https://near.org/), get a mobile wallet through [telegram](https://web.telegram.org/k/#@herewalletbot), or create a [web wallet](https://app.mynearwallet.com).
:::
---
## Account Model Overview
Let's take a closer look at the different elements that compose the NEAR account model.
![img](@site/static/docs/assets/welcome-pages/accounts.png)
#### [Account ID](account-id.md)
NEAR implements two types of accounts IDs: **named accounts** such as `alice.near`, which are simple to remember and share, and the classic alphanumeric IDs (`fb9243ce...`) that other chains also implement.
#### [Permissions Through Access Keys](access-keys.md)
NEAR accounts can have multiple [keys](access-keys.md), each with their own set of permissions. This allows to easily swap keys if one gets compromised, and to use keys as authorization tokens for third-parties.
#### [Simple to Develop Smart Contracts](smart-contract.md)
NEAR accounts can optionally hold a simple program, known as a [smart contract](smart-contract.md). In NEAR, developers can create smart contracts using languages such as Javascript or Rust.
---
## Comparison With Ethereum {#compared-to-ethereum}
If you're familiar with development on Ethereum, it's worth making a quick note about how accounts are different. The table below summarizes some key differences:
| | Ethereum Wallet | NEAR Account |
|-------------------|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| Public Identifier | Public Key (`0x123...`) | Named IDs (`alice.near`) and implicit accounts (Public Key `0x123...`) |
| Secret Key | Private Key (`0x456...`) | Multiple key-pairs with permissions:<br />- `FullAccess` key<br />- `FunctionCall` key |
| Characteristics | - Private key gives full access<br />- Account doesn't have to be created via a transaction | - Permission-based keypair<br />- Account ID must be created via blockchain transaction |
|
Coin98 Launches Decentralized Dapp Store for its 7 Million Users on NEAR’s Blockchain Operating System (B.O.S)
NEAR FOUNDATION
November 2, 2023
Coin98, the multichain wallet and DeFi platform, has today launched a decentralized dapp store for its 7 million users across 170 countries, built on NEAR.
The company behind the Super app, designed to seamlessly connect a billion users to the crypto world safely and securely, has created an innovative marketplace that allows users to access a range of apps on prominent Ethereum Layer-2 ecosystems such as Polygon zkEVM, zkSync, Base, and Linea, greatly increasing accessibility and discoverability for users.
The result is a both a web app and mobile app (details below) that provides a gateway to more than 70 chains and 15,000 dapps including cross-chain bridging, money markets, and decentralized exchanges — all in a single interface. Coin98 has achieved this by harnessing the power of NEAR’s B.O.S, the Blockchain Operating System.
“At Coin98, we are dedicated to providing our users with the very best one-stop DeFi experience in our pursuit of the vision to make Web3 accessible for everyone.” says Thanh Le, Coin98 Founder.
“With NEAR’s B.O.S, we can create a user-friendly interface thanks to its composability, while enabling decentralization under the hood,” he said. “Our dapp store offers hassle-free interaction with the most exciting L2s in the market. Soon, we will expand our collection to offer even more ecosystems and dapps, as B.O.S greatly reduces the development process, enabling a fast and scalable way to integrate new applications.”
Coin98 selected NEAR’s B.O.S thanks to the ease in the development process. All the widgets and components running on the B.O.S are fully composable, enabling developers to freely combine them to fit their needs.
Coin98 utilized the B.O.S as a frontend layer to fully decentralize the user experience. Instead of routing parts of the process through centralized servers, all the featured dapps on the Coin98 gateway have frontend components whose code are stored on-chain on NEAR, which directly interact with the smart contracts on the original chains. No centralized servers are used.
“The NEAR ecosystem is excited to see Coin98 build their decentralized app store on the B.O.S and deliver much better experiences to their users,” says Illia Polosukhin, co-founder of NEAR Protocol.
“This is exactly why we set out to build the B.O.S: because NEAR’s technology can help founders achieve decentralization and discoverability in parallel,” he added. “Now Coin98’s users can explore multiple L2 ecosystems all in one app, through the wallet of their choice, in seconds, with no complexity or switching costs. NEAR’s mission is to drive mainstream adoption of the Open Web through great user experiences and we hope more founders and projects will join us on the B.O.S.”
Coin98’s decentralized app store offering follows the launches of major B.O.S gateways by Polygon zkEVM and Mantle, two top L2 ecosystems. The success of these wallet gateway partners highlights the benefits that B.O.S helps Web3 founders deliver to end-users, demonstrating NEAR’s commitment to enabling products that simplify the blockchain experience and globally expand access to the Open Web.
Want to try the new B.O.S integration? Download the mobile app on Apple or Google Play store today. |
NEARCON ’23: Developer, Founder, and Creative Talks You Shouldn’t Miss
NEAR FOUNDATION
October 31, 2023
NEARCON ’23 in scenic Lisbon, Portugal is your go-to event for everything AI, the open web, and more. Whether you’re a developer, entrepreneur, or artist, there’s a session for you. Web3 regulatory aficionados, we’ve got you covered too (more on that later).
Here’s a rundown of sessions that are a must-see.
Developer track: build better on NEAR
NEAR: The Open Web Stack
NEAR co-founder Illia Polosuhin reveals game-changing updates for the NEAR ecosystem. A lot of new and exciting NEAR products and tools are in the works for developers. So, if you’re a dev, you won’t want to miss this talk from Illia.
Why Build Web3 Games
Hosted by PlayEmber’s Hugo Furneaux, this panel dissects the massive potential of gaming on the open web. Learn about player-owned economies and why you should consider NEAR for your next gaming project. An essential session for forward-thinking game developers.
Unlocking NEAR Data
Data extraction got you puzzled? Pavel Kudinov, senior engineering manager at NEAR, will walk you through using SQL queries on NEAR BigQuery Datasets and the NEAR Query API to build and analyze. This is the toolkit you’ve been waiting for.
Inside the BUILD Incubator
Will Russell, Michael Yu, and Max Mizzi from student hackathon league Major League Hacking take a deep dive into the BUILD Incubator Fellowship. Hear firsthand experiences and gather invaluable insights that could jump-start your open web development journey.
Entrepreneurial track: jumpstart your journey
Building Web3 Communities
This panel brings together experts from community building collective KryptoSeoul, decentralized identity project Galxe, NEAR DevHub, and Web incubator CryptoOracle Collective to discuss the art of fostering a vibrant, diverse community around any project.
CryptoEconomics 101
Lisa Jy Tan, CEO of tokenomics consulting firm Economics Design, dives into the world of cryptoeconomics, helping you understand the fundamentals and real-world applications of economic principles, drivers, and incentives at play in the open web.
Hiring Smart in Web3
Hiring in the open web is both exciting and fraught with potential landmines. Dan Eskow, founder of specialized Web3 talent agency Up Top, will share valuable tips on sourcing top talent, effective company branding, and red flags to look out for during the interview process.
Funding Trends in Web3
A frontline perspective on open web investment from venture capital firms Accomplice VC, a_capital, RockawayX, and Generative Ventures. The expert VC panel will offer insights into funding trends and standout pitch decks to help founders stay ahead of the curve.
Creative track: redefining art, marketing, and gaming
Asia’s Impact on Web3 Gaming
This panel explores Asia’s key role in Web3 gaming, particularly Korea’s leadership in the space. Hear from Jay Hoonjai Lee, CEO of Vortex Gaming DAO, and NEAR Korea Hub’s general manager Scott Lee on what the entire blockchain gaming space can learn from Asia.
Marketing in the Open Web
Learn how decentralization and the open web is changing marketing and branding from Lex B., co-founder of NEAR Studio, a creative agency dedicated to the NEAR ecosystem. Everything you need to know about marketing in the open web, including real-life case studies and successes.
Advertising in Web3
Anjali Young from Collab.Land, an innovative project helping implement token-gated communities, discusses how Web3 is transforming the advertising landscape, allowing for more effective brand-customer engagement and immediate feedback.
The Power of NFTs
Explore how NFTs are driving decentralized creativity, redefining loyalty, and reshaping cultural norms. Hear from the likes of Wilson Lee, co-founder of blockchain-based carnival app TheFunPass™, and Stipe Plejic, CEO of social NFT marketplace Endemic.
NEARCON ‘23: get in on the action
If you’re passionate about the transformative power of the open web, NEARCON ’23 is a can’t-miss conference. We’ve carefully curated speaker tracks and sessions to fuel your imagination and skills, whether you’re a developer, entrepreneur, or creative mind. And the policy-minded need not fret, there’s a special Regulatory Track chock full of insights about evolving legal frameworks, governance, and more.
With NEAR’s unique approach — super cheap, super fast, super secure — you’ll discover how the open web is solving real-world problems today.
So why wait? Register for NEARCON ’23 now to secure your spot!
Special offers are available for Ukrainians, students in Spain and Portugal, and hackathon registrants. Head over to those pages and register for your free NEARCON ‘23 pass! |
---
id: introduction
title: About JS SDK
---
JavaScript is the most popular programming language, used by nearly 14 million developers worldwide. You can write smart-contracts in JavaScript or Typescript, and our SDK will pack them with a lightweight runtime. This can then be compiled into a single Wasm file that can be deployed into the NEAR network.
:::info Help contribute!
- [Report issues you encounter](https://github.com/near/near-sdk-js/issues) 🐞
- [Provide suggestions or feedback](https://github.com/near/near-sdk-js/discussions) 💡
- [Show us what you've built!](https://github.com/near/near-sdk-js/discussions/categories/show-and-tell) 💪
:::
---
## Create Your First Javascript Contract
Create your first **Javascript contract** in minutes:
1. Download and install [Node.js](https://nodejs.org/en/download/).
2. Create a new **javascript** project using our [quickstart guide](../../2.build/2.smart-contracts/quickstart.md).
3. Read our docs on **[how to write smart contract](../../2.build/2.smart-contracts/anatomy/anatomy.md)**. |
Staking Rewards are now live on NEAR
COMMUNITY
October 21, 2020
Just one week after the NEAR community voted to enter Phase 2, NEAR Validators completed a major milestone: the upgrade to enable inflationary rewards. Now all NEAR token holders have the opportunity to earn Staking rewards from the network.
NEAR Protocol uses Proof-of-Stake (PoS) consensus to secure and validate transactions on the blockchain. The blockchain is run by a decentralized network of Validators, a community of operators who run the servers needed to keep the network operational.
Validators earn NEAR Token rewards for producing new blocks in the form of a static inflation rate of 4.5% each year.
Token holders who are not interested in being a Validator themselves can stake to a Validator’s staking pool and earn a portion of token rewards too. This incentivizes token holders to stay involved with the community and support Validators who are keeping the network running smoothly.
Inflationary Rewards Are Live
The community of NEAR Validators completed this update, activating the inflationary rewards for all token holders who stake their $NEAR.
This upgrade creates a unique opportunity for the community to potentially earn additional tokens: based on the current estimations, as much as 45 million NEAR tokens will be distributed to NEAR token holders who stake to active pools over the next 12 months.
Because NEAR utilizes Proof of Stake for consensus, inflation rewards are distributed to incentivize participation in the network through Staking. This means that every NEAR token in circulation can mint new tokens to its owner if they are staked to an active staking pool.
For more information on staking, create an account in the NEAR Wallet and check out our recent Wallet update post. Note: Today, in order to stake, you will need to withdraw your tokens from an exchange into a NEAR wallet.
Staking Rewards Calculations
It’s important to understand how the NEAR protocol calculates and distributes token rewards. The amount of staking rewards one can earn is proportionate to the total amount of tokens staked to the Network. For example, if there are 1000 total tokens staked and you have staked 100 of them, you can earn 10% of the total rewards which are distributed to the network. If there are 2000 total tokens staked and you have staked 100 of them, you’ll only earn 5% of the total rewards.
Today, NEAR staking pools are holding approximately 200 million NEAR tokens, so if you Stake 200 tokens (representing a share of 0.0001% of the total staked) you could receive ~45 newly generated tokens over one year, or 0.0001% of the ~45 million tokens minted by the network as inflationary rewards.
However, as is common with Proof of Stake Networks, as the network matures and more people become familiar with it, the total amount of staked tokens will increase. This means that while today Staking rewards are split between a pool of 200 million tokens, in the coming weeks, months, or years, that total amount of tokens staked could be as much as 600 or 700 million or even the full 1 billion NEAR tokens in existence. Of course there is no way to tell what the future will bring so we can only provide these calculations to explain how the protocol works at the technical level and can not guarantee that it will not change in the future. In theory, if 800 million tokens were staked instead of 200 million, you would receive ¼ of the amount of rewards as you would today with only 200 million tokens staked.
Keep this framework in mind as you consider staking to the network to earn Token Rewards on NEAR.
UPDATE: NEAR has been added to StakingRewards.com list of protocols with a staking calculator you can use to estimate potential rewards with additional information about staking.
Five things to know if you want to stake your tokens today
If you’re interested in staking, we suggest getting connected with our community on Discord. Here some important things to know:
Where to Stake: NEAR ecosystem is still evolving, guides and tooling for staking are still being created and wallets are being updated continually to improve your experience. In addition to the official NEAR wallet, you can also stake using Dokia Capital Staking application, and Moonlet’s Wallet.
How to Stake: There are two main ways to stake tokens: via your existing lockup contract (if you have one), or transferring tokens from exchanges to your personal wallet. Both require that you plan your token custody, as introduced by the token documentation here. Also, remember to leave at least 35 unstaked NEAR on your lockup contract, to pay for the storage and the gas fees, until the vesting is complete.
Staking for Decentralization: Staking is not only about the rewards, it is the basis for security and stability of the NEAR Protocol. To avoid centralization, split your stake between smaller staking pools instead of putting everything in the largest one. Community members like Zavodil Validator have created excellent alternatives to NEAR’s official explorer, embedding metadata from the active staking pools to help you choose which Validators to Stake with. Also, consider joining the #staking channel on https://near.chat and ask questions!
Choosing a Validator: You will notice each validator has a “Pool Fees” amount listed. This % is the amount of fees the Validator will keep to manage their operation. For example, if 100 token rewards are created, 10% of them (10 tokens) will be kept by the validator and 90% will go to the token holders that staked to that Validator. That said, Zero fees are not always good. Being a Validator requires time from qualified professionals operating high-quality infrastructure – which are expensive to maintain. If something so valuable is offered for free, ask questions. Also, Validators can change their fees at any time, so make sure to keep an eye on the fees in your pools and join Validator’s community chats or mailing lists for updates.
Unstaking: You can unstake your tokens anytime, and the minimum staking period is only 12 hours. However, you have to wait four epochs (equivalent to about two days) before being allowed by the protocol to withdraw your funds from the staking pool into your wallet. This waiting period is also necessary if you want to unstake and restake to a different Validator. It’s worth mentioning that staking is done via smart contracts, so it is possible that a bug in the Validator’s code may have an impact on the funds staked into that pool.
Wrapping up
In less than four weeks the NEAR Community has transitioned from a small group of validators taking the lead over NEAR Foundation and MainNet PoA, to a thriving ecosystem of tools, guides, and community resources launching every day. This is still very (very) early, which means that you will have to be a bit patient and open to providing constructive feedback to everyone involved. We are building this together, and in exchange for that, we are getting a first look at the growth and excitement in store for the NEAR Community.
Questions? Ideas? If you haven’t already, join the conversation in the #staking channel at https://near.chat!
If you’re just learning about NEAR for the first time and are seeing this post, we invite you to join us on the journey to make blockchain accessible to everyday people who are excited for the future of the Open Web with NEAR. If you’re a developer, be sure to sign up for our developer program and join the conversation in our Discord chat. You can also keep up to date on future releases, announcements, and event invitations by subscribing to our newsletter for the latest news on NEAR.
Disclaimer: Please note that the statements expressed above about staking and rewards are not a recommendation by NEAR core team members or the NEAR Foundation to take any action with NEAR tokens. It is up to individual token holders to educate themselves on the risks and tax implications involved in Staking tokens relative to their own personal situations. |
NEAR MetaBUILD 2: Join the Hackathon and Build an App
DEVELOPERS
December 21, 2021
NEAR MetaBUILD 2, a hackathon series where anyone can start building an app on NEAR, is nearly upon us. The first edition, held August 27th to September 19, was a smashing success, with a number of winners and prizes for work hacks, play hacks, and other categories.
For NEAR MetaBUILD 2, which runs December 22nd to February 10th, 2022, we’re changing things up a bit. In place of work and play hacks, developers can choose to participate in the Welcome track or Natives track. This gives everyone, from novice blockchain builders to crypto-natives, an opportunity to help build on and expand the NEAR ecosystem, the Open Web, and Metaverse.
How the NEAR MetaBUILD Hackathon Works
MetaBUILD hackathons are held for a couple of reasons. Part of the hackathon is to introduce both crypto-natives and non-blockchain users to the platform. But perhaps more importantly, MetaBUILD is a fantastic opportunity to showcase NEAR’s hassle-free wallet, lightning fast transaction speeds (thanks to our Nighshade sharding), global fiat on/off ramps, and the sustainable, carbon neutral blockchain.
For now, MetaBUILD is a virtual hackathon. In the future, the format will be a hybrid physical-virtual contest. Throughout a MetaBUILD hackathon, developers learn to write, test, and deploy scalable decentralized applications (dapps) in mere minutes.
MetaBUILD participants can use Rust or any other languages they already know to build DeFi, Web3, Gaming, Digital Art/Collectibles, infrastructure app and tools, or migrate an existing EVM app to NEAR.
What to Build for MetaBUILD 2
As hinted at above, MetaBUILD developers can build an app using one of two tracks—Welcome or Native. The Welcome track is intended for those who have an app and want to integrate it into the NEAR blockchain. This track is also for non-blockchain developers (newbs) who either want to get familiar with the technology or have an idea for an app and want to learn how to develop on NEAR. The Natives track, on the other hand, is designed for developers who are already familiar with NEAR, Aurora, or Octopus blockchain, or who want want to build ecosystem and tooling apps (using blockchain data, not the technology).
To see the lists of build tasks and sponsors, visit the MetaBUILD 2 Hackathon homepage.
Bonus: Include the requirements of any of the Sponsor Challenges to be eligible for the applicable prizes. Sponsor Challenges from Brave and others will be announced shortly.
MetaBUILD 2 Submission Materials
There are currently over 300 participants for NEAR MetaBUILD 2. Up to $1,000,000 in prize money will be awarded to winning projects and teams.
Below is the complete list of materials needed to submit your project for MetaBUILD 2:
Provide a URL to your Open Source code repository. All project repositories must be public and have an open source license.
Select the Track your project is submitting into.
Include a video (about 3 minutes long) that demonstrates your submission. (Note: Videos must be uploaded to YouTube, Vimeo, or Facebook Video and made public.)
Optional: Select the Sponsor Challenge you are submitting your project into, if applicable.
Before submitting your materials, please read the full list of NEAR MetaBUILD 2 rules.
|
Introducing 4 NEAR apps at Consensus Distributed
COMMUNITY
May 6, 2020
It’s only halfway through the week and it’s been busy at NEAR — the just-announced MainNet has now produced over 1.5 million blocks since genesis and we’ve hosted over a dozen talks, workshops and events as part of organizing the epic Ready Layer One conference (which ends today). This rolls into the RL1 Hackathon over the next two weeks and… we’ll probably find time to sleep someday.
At this point, we’ve told the story of Open Money, Open Finance and the Open Web but the best way to make this concrete is to see real examples. With MainNet out, we want to begin surfacing some of the fantastic applications that are building on NEAR and use them to help explain why the NEAR platform is so special. That’s why we’re firing up the coffee pot for another leap onto the virtual stage to showcase the following teams at next week’s Consensus: Distributed conference:
1inch Exchange (Anton Bukov), a decentralized exchange (DEX) aggregation platform which allows teams to find the best prices on the market. Typically, trying to move high volumes on DEXes results in poor fills and price slippage but they help spread the volume out across multiple exchanges to prevent this. Their platform relies on fast and low cost transactions, which is part of what brought them to build on NEAR.
TessaB (Tanuj Nigam), a company which facilitates the secondary market for mobile devices by removing multiple middlemen from the process. They track provenance, power financial transactions and offer on-device app stores using the blockchain.
Stardust (Canaan Linder), a platform which allows game developers to both increase revenue and improve their players’ experiences by easily adding a secondary marketplace for digital goods. NEAR gives them a set of UX tools and flexible accounts that no one else can so they can offer the end-users of their game developers a fantastic experience while introducing them to blockchain.
Flux (Peter Mitchell), a protocol which powers easy markets for a variety of applications including helping Twitch streamers create live betting experiences around their streams. NEAR gives them performance and usability.
Mark your calendar!
NEAR and the four Open Web builders will be presenting at Consensus: Distributed on
Tuesday, May 12, 2020 @ 6-7pm EST
At the event, we’ll provide a brief overview of the NEAR MainNet, take questions from the audience and then allow the projects to shine:
Changelog: The NEAR MainNet is Live (Illia Polosukhin, Co-founder of Near Inc)
Construct: The Open Web Collective with Anton @ 1inch, Tanuj @ TessaB, Canaan @ Stardust and Peter @ Flux.
Closing remarks
In addition, Amos Zhang (Strategic Lead – China @ NEAR) from our team will join forces with Jieli (Jerry) Li (Ant Financial & Alibaba), Harriet Cao (Co-founder @ IRISnet), and Jan Xie (Co-founder @ Nervos ) on a session hosted by Coindesk China at Consensus Distributed. The session will start at 1:00 AM – 2:00 AM EST (or 1:00 PM – 2:00 PM Beijing Time) on May 12th. |
---
id: marketplace
title: Marketplace
sidebar_label: Marketplace
---
import {Github} from "@site/src/components/codetabs"
In this tutorial, you'll learn the basics of an NFT marketplace contract where you can buy and sell non-fungible tokens for $NEAR. In the previous tutorials, you went through and created a fully fledged NFT contract that incorporates all the standards found in the [NFT standard](https://nomicon.io/Standards/NonFungibleToken).
---
## Introduction
Throughout this tutorial, you'll learn how a marketplace contract **could** work on NEAR. This is meant to be **an example** as there is no **canonical implementation**. Feel free to branch off and modify this contract to meet your specific needs.
```bash
cd market-contract/
```
This folder contains both the actual contract code and dependencies as outlined below.
```
market-contract
├── Cargo.lock
├── Cargo.toml
├── README.md
└── src
├── external.rs
├── internal.rs
├── lib.rs
├── nft_callbacks.rs
├── sale.rs
└── sale_views.rs
```
---
## Understanding the contract
At first, the contract can be quite overwhelming but if you strip away all the fluff and dig into the core functionalities, it's actually quite simple. This contract was designed for only one thing - to allow people to buy and sell NFTs for NEAR. This includes the support for paying royalties, updating the price of your sales, removing sales and paying for storage.
Let's go through the files and take note of some of the important functions and what they do.
---
## lib.rs {#lib-rs}
This file outlines what information is stored on the contract as well as some other crucial functions that you'll learn about below.
### Initialization function {#initialization-function}
The first function you'll look at is the initialization function. This takes an `owner_id` as the only parameter and will default all the storage collections to their default values.
<Github language="rust" start="92" end="107" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/lib.rs" />
<hr className="subsection" />
### Storage management model {#storage-management-model}
Next, let's talk about the storage management model chosen for this contract. On the NFT contract, users attached $NEAR to the calls that needed storage paid for. For example, if someone was minting an NFT, they would need to attach `x` amount of NEAR to cover the cost of storing the data on the contract.
On this marketplace contract, however, the storage model is a bit different. Users will need to deposit $NEAR onto the marketplace to cover the storage costs. Whenever someone puts an NFT for sale, the marketplace needs to store that information which costs $NEAR. Users can either deposit as much NEAR as they want so that they never have to worry about storage again or they can deposit the minimum amount to cover 1 sale on an as-needed basis.
You might be thinking about the scenario when a sale is purchased. What happens to the storage that is now being released on the contract? This is why we've introduced a storage withdrawal function. This allows users to withdraw any excess storage that is not being used. Let's go through some scenarios to understand the logic. The required storage for 1 sale is 0.01 NEAR on the marketplace contract.
**Scenario A**
- Benji wants to list his NFT on the marketplace but has never paid for storage.
- He deposits exactly 0.01 NEAR using the `storage_deposit` method. This will cover 1 sale.
- He lists his NFT on the marketplace and is now using up 1 out of his prepaid 1 sales and has no more storage left. If he were to call `storage_withdraw`, nothing would happen.
- Dorian loves his NFT and quickly purchases it before anybody else can. This means that Benji's sale has now been taken down (since it was purchased) and Benji is using up 0 out of his prepaid 1 sales. In other words, he has an excess of 1 sale or 0.01 NEAR.
- Benji can now call `storage_withdraw` and will be transferred his 0.01 NEAR back. On the contract's side, after withdrawing, he will have 0 sales paid for and will need to deposit storage before trying to list anymore NFTs.
**Scenario B**
- Dorian owns one hundred beautiful NFTs and knows that he wants to list all of them.
- To avoid having to call `storage_deposit` everytime he wants to list an NFT, he calls it once. Since Dorian is a baller, he attaches 10 NEAR which is enough to cover 1000 sales. Then he lists his 100 NFTs and now he has an excess of 9 NEAR or 900 sales.
- Dorian needs the 9 NEAR for something else but doesn't want to take down his 100 listings. Since he has an excess of 9 NEAR, he can easily withdraw and still have his 100 listings. After calling `storage_withdraw` and being transferred 9 NEAR, he will have an excess of 0 sales.
With this behavior in mind, the following two functions outline the logic.
<Github language="rust" start="111" end="139" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/lib.rs" />
<Github language="rust" start="144" end="175" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/lib.rs" />
In this contract, the storage required for each sale is 0.01 NEAR but you can query that information using the `storage_minimum_balance` function. In addition, if you wanted to check how much storage a given account has paid, you can query the `storage_balance_of` function.
With that out of the way, it's time to move onto the `sale.rs` file where you'll look at how NFTs are put for sale.
---
## sale.rs {#sale}
This file is responsible for the internal marketplace logic.
### Listing logic {#listing-logic}
In order to put an NFT on sale, a user should:
1. Approve the marketplace contract on an NFT token (by calling `nft_approve` method on the NFT contract)
2. Call the `list_nft_for_sale` method on the marketplace contract.
#### nft_approve
This method has to be called by the user to [approve our marketplace](5-approval.md), so it can transfer the NFT on behalf of the user. In our contract, we only need to implement the `nft_on_approve` method, which is called by the NFT contract when the user approves our contract.
In our case, we left it blank, but you could implement it to do some additional logic when the user approves your contract.
<Github language="rust" start="23" end="33" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/nft_callbacks.rs" />
#### list_nft_for_sale
The `list_nft_for_sale` method lists an nft for sale, for this, it takes the id of the NFT contract (`nft_contract_id`), the `token_id` to know which token is listed, the [`approval_id`](5-approval.md), and the price in yoctoNEAR at which we want to sell the NFT.
<Github language="rust" start="33" end="74" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
The function first checks if the user has [enough storage available](#storage-management-model-storage-management-model), and makes two calls in parallel to the NFT contract. The first is to check if this marketplace contract is authorized to transfer the NFT. The second is to make sure that the caller (`predecessor`) is actually the owner of the NFT, otherwise, anyone could call this method to create fake listings. This second call is mostly a measure to avoid spam, since anyways, only the owner could approve the marketplace contract to transfer the NFT.
Both calls return their results to the `process_listing` function, which executes the logic to store the sale object on the contract.
#### process_listing
The `process_listing` function will receive if our marketplace is authorized to list the NFT on sale, and if this was requested by the NFTs owner. If both conditions are met, it will proceed to check if the user has enough storage, and store the sale object on the contract.
<Github language="rust" start="264" end="344" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
<hr class="subsection" />
### Sale object {#sale-object}
It's important to understand what information the contract is storing for each sale object. Since the marketplace has many NFTs listed that come from different NFT contracts, simply storing the token ID would not be enough to distinguish between different NFTs. This is why you need to keep track of both the token ID and the contract by which the NFT came from. In addition, for each listing, the contract must keep track of the approval ID it was given to transfer the NFT. Finally, the owner and sale conditions are needed.
<Github language="rust" start="5" end="20" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
<hr className="subsection" />
### Removing sales {#removing-sales}
In order to remove a listing, the owner must call the `remove_sale` function and pass the NFT contract and token ID. Behind the scenes, this calls the `internal_remove_sale` function which you can find in the `internal.rs` file. This will assert one yoctoNEAR for security reasons.
<Github language="rust" start="76" end="87" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
<hr className="subsection" />
### Updating price {#updating-price}
In order to update the list price of a token, the owner must call the `update_price` function and pass in the contract, token ID, and desired price. This will get the sale object, change the sale conditions, and insert it back. For security reasons, this function will assert one yoctoNEAR.
<Github language="rust" start="90" end="118" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
<hr className="subsection" />
### Purchasing NFTs {#purchasing-nfts}
For purchasing NFTs, you must call the `offer` function. It takes an `nft_contract_id` and `token_id` as parameters. You must attach the correct amount of NEAR to the call in order to purchase. Behind the scenes, this will make sure your deposit is greater than the list price and call a private method `process_purchase` which will perform a cross-contract call to the NFT contract to invoke the `nft_transfer_payout` function. This will transfer the NFT using the [approval management](https://nomicon.io/Standards/Tokens/NonFungibleToken/ApprovalManagement) standard that you learned about and it will return the `Payout` object which includes royalties.
The marketplace will then call `resolve_purchase` where it will check for malicious payout objects and then if everything went well, it will pay the correct accounts.
<Github language="rust" start="121" end="151" url="https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale.rs" />
---
## sale_view.rs {#sale_view-rs}
The final file is [`sale_view.rs`](https://github.com/near-examples/nft-tutorial/blob/main/market-contract/src/sale_view.rs) file. This is where some of the enumeration methods are outlined. It allows users to query for important information regarding sales.
---
## Deployment and Initialization
Next, you'll deploy this contract to the network.
```bash
export MARKETPLACE_CONTRACT_ID=<accountId>
near create-account $MARKETPLACE_CONTRACT_ID --useFaucet
```
Using the build script, deploy the contract as you did in the previous tutorials:
```bash
near deploy $MARKETPLACE_CONTRACT_ID out/market.wasm
cargo near deploy $MARKETPLACE_CONTRACT_ID with-init-call new json-args '{"owner_id": "'$MARKETPLACE_CONTRACT_ID'"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' network-config testnet sign-with-keychain send
```
<hr className="subsection" />
### Minting and approving
Let's mint a new NFT token and approve a marketplace contract:
```bash
near call $NFT_CONTRACT_ID nft_mint '{"token_id": "token-1", "metadata": {"title": "My Non Fungible Team Token", "description": "The Team Most Certainly Goes :)", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$NFT_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID --amount 0.1
near call $NFT_CONTRACT_ID nft_approve '{"token_id": "token-1", "account_id": "'$MARKETPLACE_CONTRACT_ID'"}' --accountId $NFT_CONTRACT_ID --deposit 0.1
```
<hr className="subsection" />
### Listing NFT on sale
```bash
near call $MARKETPLACE_CONTRACT_ID list_nft_for_sale '{"nft_contract_id": "'$NFT_CONTRACT_ID'", "token_id": "token-1", "approval_id": 0, "msg": "{\"sale_conditions\": \"1\"}"}' --accountId $NFT_CONTRACT_ID --gas 30000000000000
```
<hr className="subsection" />
### Total supply {#total-supply}
To query for the total supply of NFTs listed on the marketplace, you can call the `get_supply_sales` function. An example can be seen below.
```bash
near view $MARKETPLACE_CONTRACT_ID get_supply_sales
```
<hr className="subsection" />
### Total supply by owner {#total-supply-by-owner}
To query for the total supply of NFTs listed by a specific owner on the marketplace, you can call the `get_supply_by_owner_id` function. An example can be seen below.
```bash
near view $MARKETPLACE_CONTRACT_ID get_supply_by_owner_id '{"account_id": "'$NFT_CONTRACT_ID'"}'
```
<hr className="subsection" />
### Total supply by contract {#total-supply-by-contract}
To query for the total supply of NFTs that belong to a specific contract, you can call the `get_supply_by_nft_contract_id` function. An example can be seen below.
```bash
near view $MARKETPLACE_CONTRACT_ID get_supply_by_nft_contract_id '{"nft_contract_id": "'$NFT_CONTRACT_ID'"}'
```
<hr className="subsection" />
### Query for listing information {#query-listing-information}
To query for important information for a specific listing, you can call the `get_sale` function. This requires that you pass in the `nft_contract_token`. This is essentially the unique identifier for sales on the market contract as explained earlier. It consists of the NFT contract followed by a `DELIMITER` followed by the token ID. In this contract, the `DELIMITER` is simply a period: `.`. An example of this query can be seen below.
```bash
near view $MARKETPLACE_CONTRACT_ID get_sale '{"nft_contract_token": "'$NFT_CONTRACT_ID'.token-1"}'
```
In addition, you can query for paginated information about the listings for a given owner by calling the `get_sales_by_owner_id` function.
```bash
near view $MARKETPLACE_CONTRACT_ID get_sales_by_owner_id '{"account_id": "'$NFT_CONTRACT_ID'", "from_index": "0", "limit": 5}'
```
Finally, you can query for paginated information about the listings that originate from a given NFT contract by calling the `get_sales_by_nft_contract_id` function.
```bash
near view $MARKETPLACE_CONTRACT_ID get_sales_by_nft_contract_id '{"nft_contract_id": "'$NFT_CONTRACT_ID'", "from_index": "0", "limit": 5}'
```
---
## Conclusion
In this tutorial, you learned about the basics of a marketplace contract and how it works. You went through the [lib.rs](#lib-rs) file and learned about the [initialization function](#initialization-function) in addition to the [storage management](#storage-management-model) model.
You went through the [NFTs listing process](#listing-logic). In addition, you went through some important functions needed after you've listed an NFT. This includes [removing sales](#removing-sales), [updating the price](#updating-price), and [purchasing NFTs](#purchasing-nfts).
Finally, you went through the enumeration methods found in the [`sale_view`](#sale_view-rs) file. These allow you to query for important information found on the marketplace contract.
You should now have a solid understanding of NFTs and marketplaces on NEAR. Feel free to branch off and expand on these contracts to create whatever cool applications you'd like. In the [next tutorial](9-series.md), you'll learn how to take the existing NFT contract and optimize it to allow for:
- Lazy Minting
- Creating Collections
- Allowlisting functionalities
- Optimized Storage Models
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `4.0.13`
- cargo-near `0.6.1`
- NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.1.0`
:::
|
NEAR Foundation’s Response to the UK Crypto Asset Consultation
NEAR FOUNDATION
May 3, 2023
Introduction
The NEAR Foundation (the “Foundation”) submits this letter in response to the consultation and call for evidence by His Majesty’s Treasury (“HMT”), concerning the ‘Future Financial Services Regulatory Regime for Crypto Assets’[1] in the United Kingdom (“UK”) (“Consultation”). The Foundation believes that a clear and proportionate regulatory framework is essential for the meaningful global adoption of Web3 technology and welcomes HMT’s proactive engagement with industry participants towards achieving this goal.
The Foundation is a Swiss-based regulated non-profit organisation created in September 2019, with a core mission (and legal mandate) of supporting the development and growth of the NEAR protocol (the “NEAR Protocol”) and its associated ecosystem (as well as the global adoption of open-web technologies more generally). The NEAR Protocol is a permissionless, open source, decentralised, proof-of-stake blockchain network.[2] There are more than 550,000 participants in the NEAR Protocol ecosystem, including over 4,000 developers and 1,000 projects building on the NEAR Protocol.
A key aspect of the Foundation’s mission is advocating for clear, fair, and proportionate regulation of Web3 technology, and we recently publishedPolicy Principles[3] setting out the core values driving our advocacy work. We believe that the policy outcomes advanced by HMT are reasonable and capable of being achieved in the Web3 context with the right approach (i.e. regulatory equivalence is possible). In fact, we believe that many of Web3’s core characteristics (particularly decentralisation, disintermediation, transparency and immutability) make it uniquely well-suited to effectively achieving these policy outcomes.
The Consultation comes at a key crossroads for Web3 in general and Decentralised Finance (“DeFi”) more specifically. While DeFi currently represents a small fraction of the Traditional Finance (“TradFi”) markets, its potential for growth and broader positive impact is significant. As of January 2023, total volume on decentralised exchanges (“DEXes”) (a proxy for the total DeFi market cap) stood at $56 billion,[4] compared with the total value of traded shares on the largest exchanges worldwide of $41.8 billion as of June 2022[5]. As of 2022, there exists roughly 4.8 million DeFi users globally, and within Europe, the UK is marked as the most prominent DeFi player.[6] Beyond DeFi, UK’s cryptoasset activity is significant, with the UK occupying a place among the top 20 nations with high adoption of crypto activity.[7]
Given its comparative infancy, DeFi offers an opportunity for regulators to establish proportional, adaptable, and clear regulatory frameworks that attract investment, job creation, and innovation to the UK and ultimately position the UK as a leader in the evolving DeFi landscape.
Chapter 11 Responses
36. Do you agree with the assessment of the challenges of regulating DeFi? Are there any additional challenges HM Treasury should consider?
The Foundation broadly agrees with the challenges of regulating DeFi listed by HMT in the Consultation.[8] When compared to TradFi, DeFi raises different risks, involves different actors, and engages different policy considerations. While DeFi systems can be built to replicate the functional result of some existing TradFi activities, DeFi and TradFi use different technology and employ different legal and social/incentivisation arrangements. A different regulatory approach is therefore required.
This different regulatory approach is likely to, and should at least in many respects, share the same principles and goals as existing TradFi regulation. However, it is essential for any effective DeFi regulatory framework to recognise and facilitate DeFi’s unique features (particularly decentralisation and disintermediation). Failure to do so risks stifling innovation and undermining the very policy objectives HMT is seeking to achieve.
At a fundamental level, TradFi relies on rights and obligations defined by external legal contracts and laws, while DeFi operates on the basis of powers and incentives defined by internal deterministic peer-to-peer or peer-to-software systems. These are fundamentally different approaches to solving the problem of trust in transactions, with different risk profiles and regulatory outcomes.
It is also important to note that while DeFi can be built to replicate certain TradFi activities, DeFi can be structured to operate in a fundamentally different way to achieve those outcomes. For example, consider a ‘transaction’ in the DeFi context. Even a very basic DeFi transaction – e.g. transferring cryptoassets from one cryptoasset wallet to another – involves several different actors (end-user(s), network miner/validator, network relayer, and possibly many others depending on the underlying blockchain network and the apps/services which the end-user opts to use) and complex technological processes (broadcasting a signed data package to a network’s memory pool (“Mempool”), selecting data packages/transactions from the Mempool by network miner/validators based on cryptoasset incentive structures, creating of new network blocks etc.).
Consider further a ‘lending’ transaction in the context of a DeFi interest rate protocol. Although the term ‘lending’ is broadly used and easily understood in common parlance, it misrepresents the economic activity that these protocols enable. Users of these protocols “do not extend credit or incur debt, which are the essential characteristics of a loan transaction,”[9] and instead earn interest securely through overcollateralization and free market liquidation, not through lending. While collateralization exists in both DeFi and TradFi, the latter still depends on credit and debt relationships, making DeFi ‘secured loans’ fundamentally different from TradFi. Moreover, DeFi interest rate protocols are permissionless — enabling pseudonymous participation — and employ a “peer-to-pool” model, making it hard or impossible to directly identify borrowers. Because DeFi transactions are conducted on a “peer-to-pool” or “peer-to-protocol” basis, meaning users supply and borrow fungible assets to and from a pool of liquidity stored within the protocol, not to and from specified counterparties, suppliers rely on overcollateralization and liquidation to ensure that they can withdraw their assets at any time, and not on trust of a counterparty.
Grafting the language and concepts of TradFi onto Defi — including by mislabeling DeFi transactions as loans — can lead to misunderstandings and muddy the distinction between DeFi and TradFi, making it difficult for regulators to design appropriate and proportionate frameworks for DeFi. Any comparison of DeFi to TradFi should therefore carefully analyse the different participants, systems, technologies and risks involved.[10]
We broadly agree with the different characteristics of DeFi identified by HMT in the Consultation. We wanted, however, to highlight two of DeFi’s defining characteristics that are particularly relevant from a regulatory perspective and should inform any proposed cryptoasset regulatory framework:
Decentralised. Decentralisation (as HMT appropriately notes[11]) can exist on a spectrum and in our view is most appropriately defined in terms of various forms of intrinsic network power/control being more or less distributed (we discuss these different forms of network power/control in more detail below). Where a project sits on the ‘spectrum’ of decentralisation is impacted, among other things, by factors such as decisions subjected to cryptoasset holder voting, governance participants, cryptoasset ownership distribution, the scope and extent of the original development team’s involvement, whether authority to alter, pause or shut down the protocol is present, the presence of a multi-signature wallet (“Multisig”) with elevated privileges, the members of the Multisig, the responsibility for addressing security issues, and treasury management methods. Decentralisation should be a critical aspect of any approach to cryptoasset regulation because it can impact the nature, number and geographic distribution of participants involved in a DeFi system (a much larger, distributed, fluctuating body of actors) as compared to any TradFi system.
Dis-intermediated. Fully transparent/auditable ledgers and deterministic smart contracts enable trustless (or significantly trust-minimised) interactions and so facilitate systems that are resistant to extrinsic influence or control. This underpins two key features of DeFi: (i) the self-custody of assets; and (ii) the ability to transact on a peer-to-peer basis. Together these features enable genuine user autonomy and also change the potential risks which users are exposed to; and so (as with decentralisation) a thorough understanding of DeFi’s dis-intermediation features should inform any approach to cryptoasset regulation.
Decentralisation and dis-intermediation in DeFi have the potential to offer powerful advantages over TradFi, creating robust systems that can enable a more secure, transparent, and efficient financial landscape. Key benefits of DeFi include reduced information asymmetry, increased transparency, faster settlements, enhanced liquidity, innovation enablement, streamlined processes, automation, lower transaction costs, and improved user control. By leveraging these attributes when regulating DeFi, HMT can fulfil its overarching objectives of fostering innovation, encouraging growth and competition while protecting the market and its users. Moreover, DeFi has the potential to benefit a wider range of participants and surpass some of the known limitations of TradFi.[12]
By way of example, the recent collapse of FTX (previously one of the largest centralised cryptoasset exchanges in the world) has exposed the risks and challenges of centralised actors in the cryptoasset space. As an initial matter, customers did not control or self-custody their assets at FTX (and the use of customer funds by FTX remains at issue).[13] FTX was also a highly centralised organisation, with most of its control and decision-making allegedly concentrated in the hands of its founder and former CEO, Sam Bankman-Fried, and other key individuals.[14] FTX also had a close and opaque relationship with Alameda Research, a trading firm also run by Bankman-Fried, which held a large position in FTT, the native token of FTX.[15] FTX offered bundled service offerings, such as derivatives, futures, options, and leveraged tokens, which increased its complexity and risk exposure.[16] FTX faced a liquidity crisis, a possible hack, and criminal charges against Bankman-Fried and FTX’s subsequent collapse significantly impacted many other centralised cryptoasset actors.
By contrast, DeFi networks and systems have demonstrated their resilience and strength during this market shock. As J.P. Morgan noted in a weekly report following the FTX collapse: “while the news of the collapse of FTX is empowering crypto sceptics, we would point out that all of the recent collapses in the crypto ecosystem have been from centralised players and not from decentralised protocols”.[17] Moreover, the turmoil in centralised exchanges wrought by the FTX collapse reinforced the clarion call for self-custody embodied by the crypto ethos of “not your keys, not your coins”, leading market participants to seek out decentralised alternatives.[18]
We note that a large part of HMT’s focus in the Consultation is on centralised cryptoasset actors and intermediaries, and we believe this is appropriate because it is in the context of large centralised actors that systemic risks are most likely to arise, engendered by (for example) the potential for conflicts of interest, anti-competitive behaviours (including market manipulation), and a lack of transparency. Similar risks can potentially exist in the DeFi context where some projects might be less decentralised and/or dis-intermediated because (for example) certain forms of intrinsic network power are concentrated in the hands of a small number of actors. This could lead to potentially harmful concentrations of power within DeFi networks which we believe are an appropriate focus for regulation (and which the disclosure and registration approaches to regulation described below are intended at least in part to mitigate).
Regulators and academics along with the Web3 and DeFi industry globally have been considering how best to protect against the potentially harmful concentrations of power discussed above (particularly in the early stages of a network’s development) while still facilitating and protecting DeFi’s unique features and ensuring that responsible innovation can continue to take place.
Some examples that are already being explored and could serve as a useful starting point to any Financial Services and Markets Act 2000 (“FSMA”)-based registration and disclosure regime include: (i) a tailored ‘lite’ registration and disclosure regime for cryptoasset issuance by initial development teams (which could serve as a ‘lite’ version of a FMSA-based registration & disclosure regime for cryptoassets); (ii) a safe harbour regime; (iii) self-regulatory approaches; (iv) new technologically-mediated approaches to disclosure such as Disclosure non-fungible tokens (“NFTs”) and Decentralised Autonomous Organisations (“DAOs”).
Before looking at examples of each of these potential approaches in more detail, it is worth noting in what follows that we focus on approaches emphasising disclosure and reporting, rather than authorisation-based approaches. This is driven by the fact that DeFi’s decentralised character gives rise to novel jurisdiction issues, given that the potentially large and constantly fluctuating body of network participants can be operating from multiple (and constantly fluctuating) jurisdictions; for which there is no direct analogue in the TradFi context.
We would therefore caution HMT against implementing an authorisation-based regime in the DeFi context because in our view that would risk: (i) requiring network participants to go through the (potentially complex and costly) exercise of determining whether certain DeFi-related activities in certain jurisdictions require authorisation, thereby potentially creating ‘moats’ where only more sophisticated, well-resourced actors can participate in DeFi systems; (ii) requiring DeFi projects to evaluate potential authorisation requirements across a large (and constantly fluctuating) number of jurisdictions in a way that TradFi projects do not; and (iii) perhaps most importantly of all, compromising DeFi’s inherently permissionless, cross-border nature and so undermining decentralisation and dis-intermediation.
Instead, we believe that a tailored disclosure and registration regime would help to preserve DeFi’s unique features (decentralisation and dis-intermediation) while also reducing information asymmetry, and enhancing transparency and the UK’s attractiveness as a jurisdiction for DeFi entrepreneurs, projects and investors.
38. Do you agree with HM Treasury’s overall approach in seeking the same regulatory outcomes across comparable “DeFi” and “CeFi” activities, but likely through a different set of regulatory tools, and different timelines?
We broadly agree with HMT’s overall approach. We refer to our answer to question 36 above, and in particular would emphasise the fact that any comparison of DeFi to CeFi/TradFi should be approached with caution on the basis that such comparisons are a useful heuristic but do not capture and risk obscuring DeFi’s qualitative differences. We believe that it is possible to achieve HMT’s desired overarching policy objectives — innovation, competition, consumer protection, financial stability and market integrity — in the DeFi context provided any regulatory framework proposed by HMT reinforces (rather than undermines) DeFi’s essential features.
Indeed, it is these essential features that make DeFi a potentially more effective substrate for achieving policy objectives than TradFi — given features like transparency, auditability, decentralisation, and disintermediation can be built in and deterministically enforced by smart contracts in a trustless (or significantly trust-minimised) manner — which, in turn, can create an environment where financial regulations can be applied and monitored more efficiently and effectively.
As we have noted above, opting for a ‘tech-agnostic’ approach in regulating DeFi presents obvious challenges and limitations, such as creating a framework that may not fully recognize or accommodate DeFi’s technical idiosyncrasies, or fails to provide adequate certainty for market participants. To address these challenges, policymakers and regulators should craft adaptive and flexible regulations suited to the unique characteristics of DeFi while working to keep pace with its technological advancements. This approach will help ensure that the regulatory framework remains effective and supportive of DeFi’s future development, ultimately promoting a robust, transparent, and secure DeFi ecosystem, which will evolve with DeFi technology and mature over time. Further details on our suggested approach below.
Tailored Disclosure Regimes
Improved and tailored disclosure in DeFi would be an important first step towards greater protection of DeFi participants. As an initial matter, it is important to recognise that disclosure in equity markets is ill-suited to elicit material information for token purchasers because such disclosure does not “cover a number of features unique to digital assets that would undoubtedly be considered important when making an investment decision”.[19] Instead, traditional disclosures are “designed for traditional corporate entities that typically issue and register equity and debt securities” and “focus on disclosure about companies, their management, and their financial results”.[20] Tailored disclosure regimes exist elsewhere, for example, with respect to asset-backed securities.[21]
Several models for bespoke cryptoasset disclosures already exist. There have been domestic and international legislative proposals, such as European Markets in Crypto-Assets (MiCA) legislation,[22] recent bills in the US Congress,[23] the safe harbour proposals set out below, and other proposals by academics and lawyers including those referred to in this response.
Potential disclosure elements for DeFi platforms could incorporate governance tokenholding data and any changes to this data (like listed equity holdings), and information about admin keys or other centralised controls, their scope, and arrangements. Additionally, such disclosure can include information regarding source code, token economics(e.g., asset supply schedule or protocol governance), information regarding the development team, network development plan, prior token sales, and trading platforms listing the tokens.[24] Another related element could require ongoing reporting of decentralisation efforts. This could encompass a variety of areas, such as the distribution of network nodes or the degree of participation from community members.
Another important aspect of disclosure could centre around the technology component of each network. This could include regular code audits to ensure that the technology is secure, reliable, and able to perform its intended function. Additionally, the governance of the token could be subject to voting audits to ensure transparency in the decision-making process of each network. In some cases, financial reporting could also be required under a disclosure-based regime. This could include the provision of proof-of-reserves to demonstrate that the network has sufficient funds to back its operations, as well as the disclosure of revenue and expenses to provide insight into the financial health of the network.[25]
Mandated disclosures should also include a set of risk factors for the review of participants in DeFi, including risks such as regulatory, cybersecurity, operational, liquidity, smart contract, and interoperability risk. Such risk factors should be informed by guidelines crafted for DeFi that are similar to the European Securities and Market Authority ‘Guidelines on risk factors under the Prospectus Regulation’[26] and the Financial Conduct Authority’s Prospectus Directive under FSMA,[27] and may be crafted both by regulators or in connection with potential self-regulatory initiatives discussed below.
Potential Safe Harbour Approaches
A potential safe harbour could provide numerous benefits by fostering innovation and flexibility alongside regulatory certainty (and could incorporate elements of the tailored disclosure regime referenced above). It has the added advantage, as compared to sandbox approaches, of providing a clear rules-based framework to the industry that is applicable in the same way for all actors (while sandboxes are typically more discretionary in how they operate and so can often have a more limited scope; although in our view sandboxes do also have their merits). Several proposals have been made along these lines that are worthy of consideration and although they were not drafted with the UK regulation in mind, they are good source of information to guide HMT’s approach: (i) Hester Peirce’s “Token Safe Harbor Proposal 2.0” published in April 2021[28]; (ii) the Responsible Financial Innovation Act (“RFIA”)[29]; and (iii) LeXPunk’s “Safe Harbour X/Reg X”[30]. All of these approaches could also include a cross-border or interoperable sandbox approach.
SEC Commissioner Hester Peirce’s Token Safe Harbor Proposal 2.0 provides a time-limited exemption for cryptoassets, affording initial development teams a three-year period to establish their networks as functional or decentralised, while exempting them from US federal securities registration. The exemption would continue to apply provided that the developer (i) complied with anti-fraud rules, (ii) provided semi-annual updates to the plan of development disclosure and a block explorer and (iii) made certain disclosures, including an explanation of governance mechanism for implementing changes to the protocol); a block explorer, and sufficient information for a third party to create tools for verifying the transaction history of the token. Lastly, upon the cessation of the grace period, the developer would be required to draft and disclose an exit report explaining why the network is sufficiently decentralised and the token is not a security (or otherwise register the token as a security).
An analogue of the Token Safe Harbor Proposal 2.0 is the Safe Harbor X proposal by LeXpunK Army — a community of lawyers and technologists who advocate for decentralised and peer-to-peer protocols — published in April 2022, which aims to address three key issues that the authors believe have impeded the adoption of Commissioner Peirce’s proposal:
The proposal’s focus on tokens without distinguishing between different types of transactions.
The wide-ranging exemption covering the entire three-year network maturation period.
The risk of regulatory arbitrage and unfair advantages for traditional or incapable issuers.
SafeHarbor X aims to address these concerns by modifying the approach in three key ways:
Focusing on exempting “qualifying distributions” of tokens to users and builders, rather than the token itself, allowing regulators to address potential abuses or unanticipated issues.
Requiring eligible projects to be permissionless, open source, autonomous ‘public goods’ software to qualify for the exemption.
Mandating an initial development team to be subject to a 12-month post-public-launch lockup for their autonomous crypto tokens, similar to the holding period for restricted securities under Rule 144.[31]
LeXpunK have also proposed a targeted disclosure and registration regime called Regulation X (“Reg X”)[32], which is designed to work alongside the SafeHarbor X proposal by affording projects that are not able to meet its (deliberately) strict requirements. The proposed Reg X offering exemption allows token projects to raise up to $75 million from accredited investors and up to $15 million from non-accredited investors in a 12-month period, subject to certain disclosure,anti-fraud requirements, and trading restrictions. The disclosure requirements include providing information about the network, its purpose, development plan, token economics, governance, risk factors, and insiders. The secondary market beneficial ownership reporting regime would require persons and groups who constitute large holders at the time of offering requiring them to file reports where ownership thresholds are exceeded and exit reports where holdings drop below the reporting threshold. Additional disclosures regarding extrinsically affiliated persons are also expected to be developed under the proposed framework, as well as to comply with certain trading restrictions and reporting obligations.The anti-fraud requirements require projects to comply with the federal securities laws and regulations, as well as adopt a code of conduct and dispute resolution mechanism.
The trading restrictions include limiting the amount of tokens that can be sold by insiders and affiliates in any 90-day period, and requiring them to file a notice of their intended sales with the SEC. The reporting obligations include filing annual and quarterly reports with the SEC, as well as disclosing any material events or changes that affect the network or the tokens.[33]
By contrast to the Safe Harbor 2.0 and Safe Harbor and Regulation X proposals, the Lummis-Gillibrand Responsible Financial Innovation Act (RFIA)[34] aims to establish comprehensive disclosure requirements for ancillary assets[35] and their issuers. It mandates a one-year period following the submission of disclosure, during which issuers must detail their plans to support or discontinue the use and development of the ancillary asset, as well as information about markets and platforms utilising the asset.
Both of these proposals should be analysed in the context of US security laws and its unique applications (and, in particular, the classification of cryptoassets for the purposes of US securities laws which has proven to be an extremely complex and somewhat controversial issue in the jurisdiction). The RFIA necessitates extensive corporate information about the issuer, including their history, experience, legal proceedings, and risk factors associated with the ancillary asset. While it shares some commonalities with Hester Peirce’s Token Safe Harbor Proposal 2.0 in terms of promoting transparency and addressing regulatory challenges, the RFIA has a broader scope and encompasses various aspects related to ancillary assets, including ownership information and related person transactions.
HMT could also consider encouraging the adoption of a cross-border sandbox for DeFi. For example, the FCA is part of the Global Financial Innovation Network (“GFIN”) — a collection of 20 regulators from countries including the UK, Canada, USA, and Australia — enabling firms to test innovative financial products, services, business models or regulatory technology. The GFIN model has not proven easy to implement. Indeed, in its first cross-border testing cohort, a total of 38 applications were received with only two firms successfully taking forward propositions to the live testing phase given the failure to implement testing plans that satisfied each jurisdiction’s criteria. Accordingly, it is crucial that any cross-border or interoperable sandbox format be attempted first with jurisdictions that are taking a similar approach to the DeFi space.
Within a cross-border sandbox or collaborative law-making framework, regulators could work together to clarify the treatment of various DeFi components, such as DAO frameworks[36], decentralisation models, risk factors and other disclosure requirements, KYC requirements, and the treatment of proof-of-stake versus proof-of-work networks.[37]
The safe harbour and cross-border sandbox approaches referenced above can be a valuable addition to any FMSA-based registration and disclosure regime for cryptoassets. Similarly, a RegX type approach serves as an intriguing ‘lite’ version of the same registration and disclosure framework that can facilitate access to capital for innovative DeFi projects. These methods are promising and potentially effective ways to achieve desired policy outcomes while fostering responsible innovation in the crypto space. By incorporating these approaches, regulators can promote the development of new, groundbreaking technologies in the cryptoasset ecosystem in a responsible and compliant manner.
Self-Regulatory Approaches
The self-regulating nature of DeFi protocols also makes them well-suited to governance by self-regulation, whether in a traditional or DAO form. Such a self-regulatory body could, among other things, establish disclosure standards for DeFi to promote investor protection. These standards could include, for example, disclosure standards regarding the operation of any DeFi protocol and potential risks to users, standards relating to decentralised governance, decentralisation policies, terms of service and terms of use, risk assessment, safety modules and self-insurance, open source standards, and listing standards that seek to limit accessibility.
Technologically-mediated approaches to disclosure
Technologically-mediated approaches to disclosure also present new opportunities for developing methods of verifying knowledge for DeFi participants. In his article “Introducing Disclosure NFTs, Disclosure DAOs, and Disclosure DIDs”[38] and “Disclosure, Dapps, and DeFi”,[39] Professor Christopher Brummer introduced two technologically-mediated approaches to DeFi disclosure of particular interest, both of which draw upon DeFi’s unique strengths: (i) disclosure NFTs or decentralised identities (DIDs) and (ii) disclosure libraries.
Disclosure NFTs can be employed to validate a user’s engagement with and understanding of the available disclosures. Users would interact with the available disclosures by reading or navigating through them and then complete tests or games designed to assess their comprehension. Upon successful completion, unique disclosure tokens would be issued, serving as proof that the user has thoroughly engaged with and internalised the relevant disclosures. These tokens, stored in the user’s digital wallet, could offer additional benefits, such as governance rights or access to specific services within the project, further incentivizing users to engage in the disclosure process.
DeFi disclosures could also be linked to unique decentralised identifiers (“DIDs”) tied to a given individual. A DID is a unique text string that links an individual or entity to a set of data (“DID Document”) describing them. This data contains public keys, verification methods, and ways to communicate or interact with them, including network addresses like HTTP URLs. The DID Document acts as an authentication tool for the person or entity and helps build trust in their interactions. Upon completing disclosure comprehension, an individual’s DID could be provisioned with a credential to verify successful engagement. This credential can be stored off-chain in a personal datastore, wallet, or integrated into a digital driver’s licence as part of the individual’s disclosure DID. The information would be self-sovereign, granting the holder control over data access and usage.
Decentralised Apps (“Dapps”) could verify delivery and engagement with disclosure, which may occur off-chain as in the Disclosure NFT example. Once confirmed, users can transact on the Dapp or others with similar risk profiles or disclosures, creating a decentralised, immutable chronological event record providing metadata related to past disclosure engagement.
Disclosure Libraries aim to create a more collaborative and accessible environment for developing DeFi-specific disclosures, built as an online repository. Disclosure libraries could function as a platform where developers, lawyers, and nonprofits come together to access, share, and contribute to open-source disclosures for Web3 applications. These disclosure libraries could also form a repository for DeFi self regulatory initiatives efforts. These libraries would lower the entry barrier for startups, reduce development costs, and foster a culture of transparency, collaboration, and shared expertise within the ecosystem. The LeXpunK github repository on open source law, which includes open source templates and other materials for DAOs, is an example of how such a library could be structured.[40]
39. What indicators should be used to measure and verify “decentralisation” (e.g. the degree of decentralisation of the underlying technology or governance of a DeFi protocol)?
We refer to our response to question 36 above.
As discussed above, decentralisation is most appropriately defined as the distribution of various types of intrinsic network power across participants in DeFi systems. A thorough understanding of decentralisation is essential for crafting an effective DeFi regulatory framework, as the nature and level of decentralisation fundamentally alters the number, nature and distribution of participants, and the way DeFi systems operate.
There are various types of intrinsic network power, including:
Validator Power: The power to read or access a blockchain network’s data. The validator power in open, permissionless blockchain networks is typically quite decentralised because the data is freely available to anyone (but this might not be the case in private, permissioned blockchain networks which we are not considering in our responses here). The more decentralised the validator power, the less likely any single validator can control or manipulate the network, leading to reduced risks of fraud or collusion. Elements that can be assessed to evaluate the decentralisation of validator power include node count and distribution of ownership of these nodes..
Consensus Power: How agreement is reached among network participants on the validity of transactions and the overall state of the blockchain, including the power to write data to the blockchain in what is typically a two step process of (a) proposing a block; and (b) that proposed block being accepted by the other network nodes because it is consistent with the network’s consensus mechanism. Decentralisation in consensus power ensures that no single entity can dictate or manipulate the decision-making process, resulting in a robust and secure network.
Protocol/Client Power: Protocol/client power refers to the control over the protocols and software clients used in DeFi networks. Decentralising protocol/client power through open-sourcing mitigates the risks of single points of failure, monopoly power, or a centralised entity driving the direction of the network without consideration for its users and stakeholders.
Governance/User Power: This pertains to the influence users and stakeholders have over the rules, policies, and decision-making within a DeFi network. A decentralised governance structure, where users have a say in shaping the network’s future, ensures a more inclusive, democratic, and responsive system, which better aligns with the interests and needs of its participants. Related to governance and user power is contributor diversity, referring to the number and variety of developers who contribute to the source code of a DeFi network. A higher contributor diversity indicates a more decentralised software development process and reduces key person or team risk arising from dependence on a single developer or a core team.
We note that there is not yet a standardised or industry-accepted set of standards for evaluating and/or verifying decentralisation, although there have been and will no doubt continue to be efforts to create a standardised framework.[41] The various disclosure approaches outlined in this response would be extremely helpful in this regard by helping to enhance transparency and reduce information asymmetry. As discussed above, we agree with HMT’s observation that decentralisation exists on a spectrum; and we would stress that, although some projects may claim to be decentralised when they are not, this does not mean that no projects are genuinely and substantially decentralised. We refer to our response to question 36 and, in particular, our discussion with respect to the critical role that decentralisation (and dis-intermediation) plays in mitigating potentially harmful concentrations of power in DeFi networks/systems.
Relatedly, we acknowledge HMT’s observation that once certain DeFi networks/systems (or elements or those networks/systems) reach a certain level of decentralisation then they may not be practical to regulate. This is a significant observation because in our view: (i) it highlights that an authorisation-based regulatory approach to DeFi might risk being too inflexible to cater for this type of ‘transition’ as compared to a disclosure-based approach; (ii) it recognises the importance of decentralisation as a critical feature of DeFi networks/systems that qualitatively distinguishes it from TradFi, with different regulatory consequences; and (iii) decentralisation in this manner provides various consequential benefits to DeFi system components (as we have already described above – including increased transparency and reduced information asymmetry) that can ensure desired policy outcomes are still maintained even in the absence (or impracticability) of traditional regulation.
Chapter 12: Other Crypto Asset Activities (Miners and Validators)
44. Is there merit in regulating mining and validation activities in the UK? What would be the main regulatory outcomes beyond sustainability objectives?
We broadly agree that there could be some merit in bringing certain types of mining/validation activities within the scope of a suitably targeted, light-touch disclosure-based regulatory regime. However, as with any other element of a DeFi network/system, great care has to be taken to ensure the specific technical details and idiosyncrasies are being appropriately taken into account — along with related opportunities and risks — when bringing any regulatory framework to bear.
At the outset, it is important to highlight that mining (in proof-of-work networks) and validation (in proof-of-stake networks) activities take many different forms with different technological implementations. What is consistent across all of these forms is that mining/validation processes typically play an absolutely essential role in the functioning of a DeFi system (and blockchain networks more generally) via a host of processes including, for example, proposing new blocks for addition to the blockchain, choosing which transactions to include in proposed blocks, accepting or attesting proposed blocks, receiving block rewards and/or transactions fees and (taking these various processes together) maintaining network security. These processes are typically embodied in and form an integral part of crypto asset-based incentive frameworks that are deterministically enforced.
Given the vitally important role that mining/validation activities play in DeFi (and other cryptoasset) networks and systems, great care should be taken to ensure that any proposed regulatory approach does not inhibit these activities, and in so doing stifle innovation or create uncertainty for market participants.
It is also important to note that discussing ‘mining and validation activities’ writ large or as a monolithic category risks missing various critical technical, operational, and risk profile differences that should inform the regulatory approach. First and foremost it is important to situate these functions within the specific consensus mechanism and network in question. Proof-of-work and proof-of-stake are two different consensus mechanisms used in blockchain technology. Proof-of-work involves miners solving complex mathematical problems to validate transactions (most notably, Bitcoin), while proof-of-stake involves validators holding a certain amount of cryptocurrency and using it as collateral to validate transactions (NEAR Protocol, Polkadot, Ethereum, etc).[42] The Foundation’s focus will be on proof-of-stake networks, given that the NEAR Protocol is a layer-1 proof-of-stake network.[43]
Validation activities
A validator in a layer-1 network is a key role. Validators stake their cryptoassets in a shared pool[44] and then analyse blocks based on the rules set by the network and receive rewards in the form of network fee for verified transactions.[45] The network rewards can vary based on the amount of cryptoassets staked in the validators pool (generally with the more cryptoassets staked the higher the rewards). Each network determines its own reward and commission fee structure, which is generally enshrined in the deterministic rules of the network.[46]
Consider further the following high-level examples of different types of validation activities:
Single participant running a validator node. A participant operates their own validator node, contributing their resources to maintain network security and earn rewards in return.
Delegated staking. Users delegate their cryptoassets to a trusted validator, who then stakes on their behalf, generally sharing the rewards and risks proportionally.
Pooled staking. Participants pool their tokens together to create a shared validator node, distributing rewards and risks among the group based on each individual’s stake.
Custodial staking. Users entrust their tokens to a third-party custodial service, which stakes on their behalf and manages rewards and risks, often for a fee.
Liquid validator staking. Users stake their cryptoassets through a smart contract, with such staking contributions themselves made freely transferable (often in tokenised form), providing liquidity while still participating in staking.
These (and other) categories of validation activities clearly function very differently and present different potential risks. Across all of these categories however it is crucial to recognise that validation activities are typically controlled by the underlying networks and protocols, which utilise complex technical and cryptoasset-based incentivisation structures. Such structures are generally pre-determined and can be deterministically enforced, providing full transparency to all network participants.
Given the vitally important role that validator activities play in DeFi networks and systems, regulators should exercise great care when proposing any approaches to avoid unduly restraining these activities, stifling innovation, or creating uncertainty for market participants.
Collective Investment Scheme (“CIS”)
One potential source of uncertainty for UK-based DeFi participants in the UK arises in connection with certain types of mining or validator activities and the definition of ‘Collective Investment Scheme’ under section 235 of the FSMA.[47] The definition includes arrangements with respect to property (including money) that allow participants to engage in or receive profits or income that stem from the acquisition, holding, management, or disposal of property, or sums paid out of such profits or income. The arrangements falling under the CIS definition must be such that the persons who are to participate (“Participants”) do not have day-to-day control over the management of the property, whether or not they have the right to be consulted or to give directions. They must also have the following characteristics: (i) the contributions of the Participants and the profits or income out of which payments are to be made to them are pooled, and (ii) the property is managed as a whole by or on behalf of the operator of the scheme.
Presently, it is extremely unclear the extent to which different types of mining and validation activities — particularly pooled validator staking — might fall within the CIS definition. The current definition of CIS may not be suitable for DeFi practices primarily because: (i) it predates blockchain technology and therefore it is unable to address the nuanced aspects of decentralised technology; and (ii) it is a definition unique to the UK which focuses on scenarios where capital or assets are pooled and entrusted to third parties with significant investment discretion, which is not the case in DeFi. Moreover, with the borderless nature of blockchain technology in general, and permissionless nature of DeFi in particular, it would be challenging to pigeonhole validating activities under CIS. Schemes within the scope of s.235 are generally more centralised with a significant potential for abuse of power and conflicts of interest concentrated on a small number of people responsible for investment decisions (amongst other issues), as well as the fact that typically such ‘products’ are highly illiquid and/or carry significant risk.
In the context of pooled validator staking, the risks present in TradFi do not apply because validation activities contribute to network functioning and security, rather than passive capital contribution as is the case under a CIS, and compensation for that work is often pre-determined and deterministically enforced by the relevant network or smart contracts (rather than dependent on the efforts or discretion of others).[48] Indeed, the discretion offered to a manager under a CIS is different to the narrow role of a validator in a proof of stake network that can be deterministically enforced on-chain through cryptoasset based incentivization structures to protect mining and validation function in networks. Regulation should not interfere or jeopardise the inherent on-chain cryptoasset-based incentivization structures that protect mining and validation functions within networks. Also, creating barriers to entry for staking could potentially concentrate validation power into the hands of a smaller number of well-resourced validators, negatively impacting DeFi’s key characteristics: decentralisation and dis-intermediation. We suggest that HMT considers exercising its power to carve-out pooled validator staking arrangements from the CIS definition, which would help promote certainty, encourage decentralisation, and support HMT’s overarching policy objectives.
More generally, in our view any proposed approach to regulating mining and validation activities should focus on addressing potentially harmful concentrations of power – for example, where a large amount of a DeFi network’s consensus power is concentrated in the hands of a small number of actors, sometimes termed ‘validator dominance’. As with the other forms of potentially harmful concentrations of power in DeFi systems, validator dominance can reduce transparency and competition, and also raise consumer protection risks.
A regulatory approach to tackle these potential risks could involve a light-touch disclosure regime targeting validators operating at a certain scale, by way of a business. Disclosure requirements could be congruent with policy principles, ensuring that the regulatory environment remains conducive to the growth and development of DeFi networks and their participants.
The eventual disclosure requirements could be designed by a joint regulator and self-regulatory initiative, and could include: (i) basic information about validators such as their identity, location of nodes, stake amount, uptime, security measures, technical specifications and performance metrics of the validator’s hardware and software; (ii) a standard set of risk factors applying to validators; and (iii) any fees/commission charged by validators. As mentioned above, in order to avoid potentially stifling validation activities or creating barriers to entry for individual network participants, we would suggest that any such regime should only apply to validators operating at scale and by way of a business (i.e. as a service offering to end users).
Maximal Extractable Value (“MEV”)
MEV refers to the profit that network miners and validators can obtain by strategically ordering or including transactions in the blocks they mine or validate within a blockchain network. MEV arises due to the decentralised nature of blockchain networks, where transactions are not processed simultaneously and miners/validators have some degree of control over transaction ordering in a block. HMT has identified MEV as an area of potential consideration.
MEV is a critical component of DeFi systems (and blockchain networks more generally) because it underpins and typically forms an integral part of cryptoasset-based incentive structures which are designed to maintain and reinforce (amongst other things) the security and consensus of blockchain networks. MEV is also a highly nascent issue with very little data to inform the long-term impact of different types of MEV activities and strategies. Any regulation of MEV should therefore be carefully considered.[49]
At a high level MEV-based activities or strategies are typically categorised by industry participants into so-called positive (value-add) and negative (potentially harmful) strategies.
Positive (value-add) MEV strategies. These strategies are generally seen as beneficial or neutral to the network and its participants. They involve miners/validators extracting value without negatively impacting other users or the overall ecosystem. Examples of so-called positive MEV strategies include: (i) transaction prioritisation (transactions with higher fees are prioritised, which helps maintain a free market and the network’s incentivisation system); and (ii) arbitrage (exploitation of price differences across different cryptoasset markets, contributing to market efficiency).
Negative (potentially harmful) MEV strategies. These strategies can potentially have adverse effects on the network and its participants, raising (amongst other things) consumer protection risks. They involve miners extracting value at the expense of other users or manipulating the network in a way that undermines its trustworthiness and efficiency. Examples of so-called negative MEV strategies include: (i) identifying lucrative transactions and replicating them before they are finalised on-chain, thereby capturing that value; and (ii) front-running (deliberately placing transactions before and after another transaction in an attempt to influence pricing of relevant cryptoassets).
There are already various efforts underway by industry participants to attempt to mitigate so-called negative MEV strategies, including:
MEV Auctions (e.g. Flashbots). Flashbots is a research organisation[50] that focuses on addressing the negative externalities of MEV. They have introduced a system called MEV-Geth, which enables miners to participate in sealed-bid auctions for transaction ordering rights. Users can submit their transactions directly to miners along with a bid representing the tip they are willing to pay. This system creates a more transparent marketplace for MEV, reducing the likelihood of potentially harmful strategies.
Fair Sequencing Services (“FSS”). Fair Sequencing Services[51] is a proposal to modify the way transactions are ordered within blocks. Instead of miners having complete control over transaction ordering, an FSS provider would decide the order based on predefined rules or algorithms that aim to reduce the potential for negative MEV strategies. FSS can be combined with other solutions like commit-reveal schemes, where users submit encrypted transactions that are revealed and processed only after a specific time, reducing the possibility of potentially harmful MEV strategies being deployed.
Transaction Privacy Solutions. Privacy-enhancing technologies, such as zero-knowledge proofs and confidential transactions, can help obscure transaction details and make it harder for miners to identify and potentially exploit MEV opportunities.
As we identified above, MEV can play a vital role in DeFi networks and is a complex, nascent area. There is also very little data regarding the impact of different MEV activities/strategies and the potential issues to which they give rise. Therefore at this stage we do not believe any regulatory intervention by HMT would be wise or desirable (although that does not mean there may not be scope for regulatory intervention in the future). Instead, we would suggest that HMT continues to monitor the MEV environment and consider revisiting the area once there is more clarity regarding the longevity and impact of different MEV activities and strategies.
45. Should staking (excluding “layer 1 staking”) be considered alongside crypto asset lending as an activity to be regulated in phase 2?
Staking refers to a range of activities that involve locking up crypto assets in DeFi platforms or applications to earn rewards, such as provision of liquidity, yield farming, or other token-based incentives. These staking activities differ from layer 1 staking, which as described in more detail in our response to question 44, is the process of securing a blockchain network by validating transactions and creating new blocks. Staking in DeFi platforms or applications often involves complex mechanisms and contracts that expose participants to various types of risks, such as counterparty risk (the risk of default or fraud by the other party), liquidity risk (the risk of not being able to withdraw or exchange the staked assets), market risk (the risk of price fluctuations or volatility), and technology risk (the risk of hacking, bugs, or errors in the platform or application).
So-called cryptoasset ‘lending’, on the other hand, involves the ‘lending’ and ‘borrowing’ crypto assets through platforms that use digital assets as collateral (we would emphasise again – as already noted in our response to question 36 – that any comparison of DeFi to CeFi/TradFi (and the use of TradFi terms to describe certain DeFi processes) should be approached with caution on the basis that such comparisons are a useful heuristic but do not capture and risk obscuring DeFi’s qualitative differences). This activity allows borrowers to access capital without selling their crypto assets and enables lenders to earn interest on their idle assets. However, cryptoasset lending also entails risks, such as collateral risk (the risk of insufficient or devalued collateral), platform risk (the risk of insolvency or failure of the platform), and regulatory risk (the risk of non-compliance with existing or future regulations).
Given the significant differences in the nature, risks, benefits, and potential systemic implications of both staking (excluding layer 1 staking) and crypto asset lending, it is essential to thoroughly examine these aspects before deciding whether they should be regulated in tandem in phase 2. Factors regulators should consider include:
The types and levels of risks associated with these activities and how they can be mitigated or managed by the participants or the platforms.
The degree of investor/consumer protection required in each case, considering that some staking and lending platforms might lack strict know-your-customer (KYC) and anti-money laundering (AML) processes or adequate disclosure of information and terms and conditions.
The potential impact of these activities on the broader financial ecosystem and whether they could contribute to systemic risks or financial instability by creating interdependencies, contagion effects, or market distortions.
The accessibility and transparency of staking and lending platforms for different types of investors, such as retail or institutional investors, and whether they provide fair and equal opportunities and treatment for all participants. By considering these factors, regulators can make an informed decision on whether staking, excluding layer 1 staking, should be considered alongside crypto asset lending for regulation in phase 2.
We do not think that consumer-based permissionless staking for network security should be regulated in the same way as staking in DeFi platforms or applications. Consumer-based permissionless staking for network security is a simpler and more transparent activity that involves locking up cryptoassets in a blockchain network to secure its operations and earn rewards. This activity does not involve complex mechanisms that create additional risks for the participants. Moreover, consumer-based permissionless staking for network security does not pose significant systemic risks or financial stability concerns, as it is decentralised and distributed across many nodes that validate transactions and create new blocks. Therefore, we believe that consumer-based permissionless staking for network security should be treated differently from staking in DeFi platforms or applications for regulatory purposes.
46.What do you think the most appropriate regulatory hooks for layer 1 staking activity would be (e.g. the staking pools or the validators themselves)?
Please refer to the comprehensive answer to question 44 above.
[1] Future Financial Services Regulatory Regime for Crypto Assets Consultation and call for evidence, HM Treasury, 2023 (available here)
[2] The NEAR Whitepaper (available here).
[3] NEAR Foundation Announces Policy Principles (available here).
[4] Consensys, DeFi Market Commentary – January 2023 (available here).
[5] Largest stock exchanges worldwide as of June 2022, by value of electronic order book share trading published by Statista (available here).
[6] Dunja Radonic, Bankless Times, Eye-Opening DeFi Statistics & Facts for 2023 (available here).
[7] See, e.g., Written Evidence Submitted by Chainalysis. Chainalysis, UK Parliament Committees, September 2022, (available here).
[8] See note 1.
[9] Jake Chervisnky, DeFi lending doesn’t exist (yet), Why DeFi protocols are mislabeled as lending protocols (available here).
[10] See further Table 1, Crypto vs. traditional finance system, DeFi risks and the decentralisation illusion, BIS Quarterly Review, 06 December 2021 (available here).
[11] Future Financial Services Regulatory Regime for Crypto Assets Consultation and call for evidence, paragraph 11.7, pg. 67, HM Treasury, 2023 (available here).
[12] See paragraph 1.11 in the Consultation paper.
[13] CFTC v. FTX Trading Ltd. et al., 1:22-cv-10503-PKC, SDNY, paras 56-62 (available here). See also, e.g., Sandali Handagama, CoinDesk,, FTX Violated Its Own Terms of Service and Misused User Funds, Layers Say, 10 November 2022 (available here),
[14] See KPMG, The collapse of FTX, Lessons and implications for stakeholders in the crypto industry, November 2022( available here).
[15] Ibid.
[16] Ibid.
[17] J.P. Morgan, U.S. Mid- and Small-Cap Banks Crypto Banking Weekly, November 11, 2022 (available here).
[18] See, e.g., Lang Mei, Nasdaq, 5 January 2023, Learning the Hard Way: The FTX Debacle Once Again Demonstrates DeFi’s Strengths (available here) (“[b]lockchain analytics platform Nansen has reported a double-digit percentage increase in DeFi users in the aftermath of the FTX collapse”).
[19] Hester M. Peirce, Remarks before the Digital Assets at Duke Conference, 20 June 2023 (available here).
[20] Ibid.
[21] Kennedy and Crypto, Chair Gary Gensler, 8 September 2022 (“[g]iven the nature of crypto investments, I recognize that it may be appropriate to be flexible in applying existing disclosure requirements. Tailored disclosures exist elsewhere — for example, asset-backed securities disclosure differs from that for equities”) (available here).
[22] The EU Markets in Crypto-Assets (MiCA) text is available here. MiCa was approved in April 2023.
[23] The Responsible Financial Innovation Act (a.k.a the Lummis-Gillibrand bill) presented to the US Senate in 2022 here.
[24] The Current SEC Disclosure Framework Is Unfit for Crypto, Paradigm Policy, Rodrigo Seira, Justin Slaughter, Katie Biber, 20 April 2023 (available here).
[25] In the past year, a few CeFi entities (Alameda, Celsius, Voyager etc) failed due to lack of reserve funds and transparency (among other things). In the Bankruptcy report filed re FTX, the major pitfalls of the exchange were based on its lack of appropriate controls, concentrated power, and commingled funds which also led to poor accounting and lack of reserves.
[26] Guidelines on risk factors under the Prospectus Regulation, European Securities and Markets Authority, 29 March 2019, (available here).
[27]PRR 2 – FCA Handbook, Financial Conduct Authority, 01 January 2021, (available here).
[28] SEC Commissioner Hester M. Peirce, Token Safe Harbor Proposal 2.0” (available here).
[29] See note 11.
[30] Safe Harbor X, LeXpunK-Army, 7 March 2023 (proposing a rule that would provide an exemption for the distribution of autonomous cryptoassets to users and builders of autonomous software systems, based on the Token Safe Harbor Proposal 2.0, but with some modifications and additions, such as requiring semi-annual updates, an exit report, guidance on decentralisation criteria, and clarifying the definition and scope of autonomous cryptoassets and autonomous cryptosystems). These safe harbour proposals would operate to effectively provide projects with conditioned routes to compliance, based on each project meeting various requirements (including disclosures, smart contract audits, and degree of decentralisation) (available here).
[31] 17 CFR § 230.144. Rule 144 under US securities laws allows for the sale of restricted securities under certain conditions one of which is a holding period. See SEC, Rule 144: Selling Restricted and Control Securities, 16 January 2013 (available here).
[32] LeXpunK Army, Reg-X-Proposal-An-Exempt-Offering-Framework-for-Token-Issuances, 25 April 2022 (available here).
[33] Ibid.
[34] See note 11.
[35] See Mayer Brown’s comments on the Lummis-Gillibrand bill referring to ‘ancillary assets’ as: ‘An ancillary asset includes any “intangible, fungible asset that is offered, sold, or otherwise provided to a person in connection with the purchase and sale of a security through an arrangement or scheme that constitutes an investment contract” but, importantly, does not include assets that have debt or equity-like characteristics’” (available here).
[36] Model law consultations and proposals can serve as guidance or inspiration for other jurisdictions that are considering similar reforms or initiatives. COALA created a model law for DAO’s, organising industry players, academics, and regulators to collaborate on the language. The intention is to work with local governments to allow adoption of the Model Law. See, e.g., Model Law For Decentralised Autonomous Organizations, Constance Choi, Primavera De Filippi, Rick Dudley, Silke Not Elrifia, Coalition of Automated Legal Applications (COALA), 2021 (available here).
[37] Fahad Saleh, The Review of Financial Studies, Blockchain without Waste: Proof-of-Stake, Volume 34, Issue 3, March 2021, Pages 1156–1190 ( available here).
[38] Chris Brummer, Introducing Disclosure NFTs, Disclosure DAOs, and Disclosure DIDs, 24 March 2022, Medium (available here).
[39] Chris Brummer, Disclosure, Dapps and DeFi, Stanford Journal of Blockchain Law & Policy, 29 June 2022 (available here).
[40] See LexPunK Github materials here.
[41] The Edinburgh Decentralisation Index is a proposed framework for measuring and comparing the degree of decentralisation in different blockchain systems. The framework consists of four layers: network, protocol, governance, and application. Each layer has a set of features that capture different aspects of decentralisation, such as node distribution, consensus mechanism, upgrade process, and smart contract functionality, and is assigned a score from 0 to 5 which is then aggregated (available here). Also, Consensys has analysed metrics of decentralisation on the Ethereum mainnet, including network size, node diversity, node geography, client diversity, miner diversity, gas usage, gas fees, and transaction volume. Another analysis computes the distribution of mining power in Bitcoin and Ethereum using three metrics (Gini coefficient, Shannon entropy, and Nakamoto coefficient) and three granularities (days, weeks, and months), while the so-called decentralised quotient measures decentralisation by calculating the number of nodes by the number of validators or miners in a blockchain network (available here).
[42] See, e.g.,Coinbase, What Is ‘Proof of Work’ or ‘Proof of Stake’? (available here).
[43] See e.g., NEAR Protocol, Network NEAR Protocol, September 2022 (available here).
[44] See note 23.
[45] See note 23.
[46] The NEAR Protocol has recently launched the Blockchain Operating System (“BOS”), which serves as a single platform that developers can build into and users can interact on, including by browsing and discovering Web3 products such as crypto exchanges, non-fungible token (NFT) galleries and social networks. The BOS will be compatible with all blockchains (currently supporting NEAR Protocol and Ethereum Virtual Machine chains), with NEAR protocol acting as the common entry point. The BOS offers a decentralised and composable and front end framework for building, launching, and using dApps, while leveraging common user experience frameworks such as profiles, notifications, and searching. With BOS, the NEAR protocol is transitioning from being only a layer 1 blockchain to a cross-chain solution aiming at lowering the barriers of entry into Web3. For more information on the BOS, see, e.g., Near Protocol Announces the Blockchain Operating System, NEAR Foundation, 2 March 2023 (available here);
[47] Financial Services Market Act 2000 (FSMA), s.235 (available here).
[48] See ‘MEV’ section below.
[49] For an excellent, detailed discussion of MEV, see Evan Zinaman, Where the Rubber Meets the Road: A MEV-aware, Functionalist Review of OFAC Risk ‘On the Base Layer,’ 29 April 2023 (available here).
[50] See further Flashbots Docs with more information on its work (available here).
[51] Aru Juels et al., Chainlink, Fair Sequencing Services: Enabling a Provably Fair DeFi Ecosystem, 22 September 2020 (available here).
|
NEAR at Consensus: Get Started on the Blockchain Operating System
NEAR FOUNDATION
April 3, 2023
NEAR Foundation is excited to announce that NEAR is heading to the 2023 edition of Coindesk’s Consensus from April 26-28.
NEAR has a massive base at this year’s Consensus, from which we will introduce devs and end users to the Blockchain Operating System. The Blockchain Operating System is an industry-first category, functioning as a common layer for browsing and discovering open web experiences with any blockchain.
Here is what to expect from NEAR at Consensus 2023.
The Blockchain Operating System at Consensus
If you saw NEAR’s big announcement out of ETHDenver, NEAR isn’t just a Layer 1 blockchain. It’s a Blockchain Operating System for the Open Web — your easy entry point into Web3.
With the BOS, NEAR has built an industry first, with decentralized frontends and forkable components for developers. For end users, the BOS makes app discovery easy and social. All designed to bring billions of people into Web3, on any blockchain.
The BOS and much more will be on display at Consensus!
The NEAR booth at Consensus
Consensus is the world’s largest and longest-running crypto gathering, bringing together devs, VCs, founders, policymakers and many others in the Web3, blockchain, and cryptocurrency communities. NEAR will be at Consensus for three days of talks, panels, demos, parties, and more.
The NEAR booth at Consensus will be souped-up and multi-faceted, delivering the latest tech and ecosystem updates for the Web3 community at Consensus!
NEAR’s booth will feature 4 different components. Let’s explore them.
BOS for Devs
If you’re a developer, get onboarded into the Blockchain Operating System. Talk to NEAR and BOS experts.
Get started learning how to build widgets and experiences within the BOS. Create interfaces, fork components, and much more, with NEAR experts as your guides.
BOS for End Users
If you’re an end user who loves Web3, experience how the Blockchain Operating System is revolutionizing the access to and discovery of Web3 apps and experiences. Set up an account and get access to all of the latest exciting experiences that are now live or being built on NEAR.
NEAR ecosystem members will be there to guide you throughout your Blockchain Operating System experience with demos, tutorials, and more!
NEAR Ecosystem Showcase
NEAR’s booth will also feature an Ecosystem Showcase component. Here you will learn about the latest game-changing announcements, and discover the apps and experiences being built on NEAR.
NEAR Horizon Accelerator
The booth will also feature a space for NEAR Horizon, the ecosystem’s new accelerator. Meet with the Horizon team and get started on the Web3 funding and building journey.
NEAR speakers at Consensus
Catch a number of exciting NEAR speakers and sessions at Consensus. The final list of participants and sessions is still being solidified. However, we do have some confirmed speakers to highlight.
April 28th from 12:45pm – 1:30pm on Main Stage — Illia Polosukhin, CEO of Pagoda and Co-Founder of NEAR on “Devs Doing Something: BUIDLing in a Bear Market” panel with Sergey Nazarov, Co-Founder of Chainlink and Emin Gun Sirer, CEO of Ava Labs.
April 28th from 3pm – 3:20pm on Protocol Village Stage — Illia Polosukhin, CEO of Pagoda and Co-Founder of NEAR, and Alex Chiocchi, Chief Product Officer of Pagoda will present on the latest Blockchain Operating System insights.
April 28th from 3:20pm – 3:35pm on Protocol Village Stage — Marieke Flament, CEO of Near Foundation and Special Guest VC
April 28th from 3:35pm – 3:45pm on Protocol Village Stage — Alex Shevchenko, CEO and Co-Founder of Aurora: Web3 Cloud Containers
April 28th from 3:45pm – 4pm on Protocol Village Stage — Web3 Media Tech Panel. Special guests TBA.
Stay updated on the complete slate of confirmed speakers at Near.org/Consensus. |
Near Announces the Blockchain Operating System
NEAR FOUNDATION
March 2, 2023
Near announced today that it is becoming the Blockchain Operating System (BOS). The BOS is an industry-first category: a common layer for browsing and discovering open web experiences, compatible with any blockchain.
The Blockchain Operating System will make Near the entry point for the Open Web, for users and developers alike. And it will make both Web3 and Web2 easier than ever to access and navigate.
Becoming more than just a blockchain
Since inception, Near’s mission has been to onboard 1 billion users to the Open Web. The first step in the journey was to focus on building a best in class L1 blockchain that was easy to build on and easy to use.
Near was designed to be simple, with a flexible account model and human readable accounts — any name a user wants instead of a string of letters and numbers. And with Near’s Nightshade sharding approach, the Near blockchain was designed to be infinitely scalable and secure. At the same time, Near concentrated on building out tooling to support builders developing on the protocol, including the JavaScript SDK that now gives 15 million developers access to building on Near.
This has created and sustained a thriving Near ecosystem with more than 23 million accounts and over a thousand project building, but these were only the first steps toward delivering the vision of Web3 to a mainstream audience.
Now, Near is building up the Web3 stack to integrate experiences from across the open web and streamline the discovery and onboarding experience for users and developers alike.
Enter Near: the Blockchain Operating System
Today, Near is launching near.org — a composable frontend for Web3. It will allow end users to easily and frictionlessly discover all of Web3’s possibilities in one seamless experience. It will also empower developers to create and code interfaces in a single environment with the ability to fork a host of components to build apps faster, and more efficiently than ever before.
Anyone in the Open Web ecosystem can create their own frontends (i.e., their own versions of near.org), compatible with the blockchain of their choice. This means that builders from any ecosystem can create components in just a few lines of code, and take advantage of fast onboarding to help make new and custom Web3 experiences.
This is an industry first. With the addition of composable frontends to the tech stack, Near now becomes the Blockchain Operating System, allowing seamless, one-time onboarding and removing friction points like making accounts for every experience, while supercharging development from a collection of over 1,800 components.
Near.org is the first step in Near’s Blockchain Operating System journey. It’s the Alpha version, where builders can see the frontend come to life.
Try it out at near.org to experience the world’s first Blockchain Operating System — a revolutionary moment in Web3. If you’re a developer, see how easy it is to fork components and create new experiences. If you’re an end user, see how easy it is to explore Web3 experiences, social, and news all in one place.
The Blockchain Operating System is Near and it’s here. #NearistheBOS |
Community Update: June 19th, 2020
COMMUNITY
June 19, 2020
Summer is knocking on the door and we are getting NEAR ready for the next steps of decentralizing MainNet and our community efforts. We have already accepted over 20 communities into our Guild Program, who are now starting local community initiatives including AMAs, translating content, and engaging new community members. If you would like to get involved with your existing community or start a local NEAR presence, we would love to hear from you.
Partnerships
We are supporting Coinbase Rosetta (https://rosetta-api.org), an open-source specification and set of tools that makes integrating with blockchains simpler, faster, and more reliable. It enables projects to
Onboard faster with exchanges and apps;
Build while ensuring strict security constraints are met; and
Grow adoption by making code predictable & easier to debug.
Learn All About Building the Open Web
The Open Web Collective has launched a Podcast “Building the Open Web”. Sasha will be exploring entrepreneurship in Web3 with founders, investors, and industry leaders. To access the latest episodes, subscribe here (Apple) or here (for Spotify).
The first four episodes are already out
Episode #1 is with @roneilr from @AudiusProject on Building a Decentralized Music Streaming Platform
Episode #2 is with @MariaShen from @ElectricCapital covering Startup Advice for Blockchain Entrepreneurs
Episode #3 is with @yanivgraph from @graphprotocol to talk about Getting Initial Customers and Finding Product-Market Fit
Episode #4 is with @taratan from @ideocolab on Bridging Web 2.0 and Web 3.0 Product Design
Events
Protect Privacy Hackathon on Gitcoin from June 15th to June 29th; you can still sign-up and show us how you would enhance user privacy in the web3 space.
Community Talk: AI and Blockchain by Arif, the CEO and Co-founder of Alethea.AI on Wednesday the 24th at 5PM CEST (Check out this video to get an idea of what the call is going to be about)
NEAR-Shell AMA for validators and builders (next week, stay tuned for the date & time)
Content Highlight
Deep dive on Optimistic Rollups and scaling Ethereum smart contracts with Optimism Co-Founder Ben Jones and NEAR Co-Founder & CTO, Alex Skidanov
Community Spotlight
Flux Community Update June 2020, including
Market Creator Fee
Affiliate Fees
Selling Shares – @UniswapProtocol
Crowdsourced Dispute
Resolution Fee
A contributor created a NEAR Prometheus Exporter, which is a service that exports various metrics from a NEAR node.
We started hosting engineering syncs with our contributors; this Trello board will provide a high-level overview of our initiatives, currently featuring devx.
Thanks to all the amazing people who joined. (Names are blurred out)
How You Can Get Involved
We have something for everyone
Join the NEAR Contributor Program to contribute to our engineering efforts.
You love hosting events, engaging communities, and creating content? Then head over to our Guild Program.
If you are in the process of setting up your own start-up in the Web3 space, the Open Web Collective will provide guidance.
If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, join the conversation on Discord, and subscribing to our newsletter to receive updates right to your inbox. |
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs className="file-tabs">
<TabItem value="near-api-js" label="near-api-js">
```js
import { KeyPair } from 'near-api-js';
const newKeyPair = KeyPair.fromRandom('ed25519');
newKeyPair.public_key = newKeyPair.publicKey.toString();
```
</TabItem>
<TabItem value="Keypom API" label="Keypom API">
```js
const state = {};
const dropsNumber = "2";
const keysGeneratorUrl = "https://keypom.sctuts.com/keypair/";
fetch(keysGeneratorUrl + dropsNumber + "/rootEntrophy").then((res) => {
const keyPairs = JSON.parse(res.body);
const pubKeys = [];
const privKeys = [];
keyPairs.forEach((e) => {
pubKeys.push(e.pub);
privKeys.push(e.priv);
});
state.publicKeys = pubKeys;
state.privKeys = privKeys;
});
```
</TabItem>
</Tabs> |
International Cricket Council and NEAR Foundation Sign Multiyear Partnership to Boost Global Fan Engagement Through Web3
NEAR FOUNDATION
September 27, 2023
The International Cricket Council (ICC) and the NEAR Foundation are entering into a groundbreaking new partnership that will utilize Web3 tools built on the NEAR Blockchain to deepen engagement in the sport.
The NEAR Foundation will become the ICC’s official blockchain partner, helping cricket’s governing body create new ways for fans to get closer to their favorite teams and players using Web3 technology.
“We are excited to embark on this partnership with NEAR Foundation and to use their technology and network of talent to create better and deeper fan engagement around the globe,” says Finn Bradshaw, Head of Digital at the ICC.
“We are looking forward to exploring ways in which we can use new technology to create lasting, valuable experiences for our fans.”
The partnership will launch its first collaboration as part of the ICC Men’s Cricket World Cup, starting on October 5 in India. Built on NEAR’s Blockchain Operating System (B.O.S), the ICC will release a pre-match strategy challenge that pits players against each other to pick the best team.
Each player can make choices across three key facets of the challenge: batting, bowling and fielding. Once a player has built their perfect strategy, as the ICC Men’s Cricket World Cup unfolds, their team will receive points based on the real life performance of the players they picked.
A leaderboard will track each fans’ performance and weekly winners will be awarded prizes including match tickets, exclusive events, Men’s Cricket World Cup merchandise, and more. This new type of engagement, built thanks to the B.O.S, helps to place fans at the center of the action, bringing them closer to the game than ever before.
A new era in sports engagement
“We are extremely excited to be working with the ICC in this multi year deal. This is one of our biggest partnership announcements to date and solidifies our reputation as a go-to blockchain technology provider in the sporting world,” says Chris Donovan, CEO of the NEAR Foundation
“Given the immense size and popularity of cricket, the NEAR ecosystem will potentially be exposed to hundreds of millions of cricket fans who will have the opportunity to learn about NEAR Foundation’s mission of increasing the adoption of an open web, and get the chance to interact with Web3 use cases built on the Blockchain Operating System. We look forward to opportunities that this mutually beneficial agreement will bring to cricket fans and to playing a key role in using Web3 to make the world of sport more inclusive and exciting for everyone.”
After the Men’s Cricket World Cup, the partnership between the NEAR Foundation and the ICC will continue to the end of 2025. During that time, both sides have committed to work together to develop other Web3 use cases that help fans get closer to the sport.
Initial use cases include development of a fan passport that allows fans to record their actions and memories, in a tamper proof way across every touchpoint, both online and off.
These innovations are all made possible thanks to the B.O.S. With its full stack of Web3 tools and easy onboarding, partners like the ICC can take advantage of the world’s most highly scalable, community-driven, and secure blockchains that deliver proven, best-in-class performance that can support any kind of Web3 strategy. |
Berry Cards: a DeFi NFT Marketplace for Pixel Art
CASE STUDIES
March 18, 2021
A few of the most highly valued Berry Cards NFTs
What are Berry Cards?
Berry Cards is a marketplace for pixel art NFTs, which runs on the NEAR protocol, allowing people to buy artwork created with Berry Club. People buy the cards they like using NEAR, and then sell those cards again on the marketplace. However, Berry Cards has a number of features that separate it from other NFT marketplaces.
Dynamic pricing
For starters, owners of an NFT are not able to set a price for their work; instead, Berry Cards does it for them, using a number of methods. An individual pixel art (AKA a Berry Card) first gets its value by people voting on which art they prefer. Everybody with a NEAR wallet is able to sign into Berry Cards and begin voting on which cards they prefer. By going to the homepage, a user will be presented with two random cards and will be prompted to pick the one they like best. The card they choose will then increase in value by 10%, while the other card will lose value by 10%. This is a simple and elegant way of creating fair prices for NFTs as it reflects what the community as a whole considers most valuable, rather than one person. It is “voting with your wallet” in the most literal sense.
Each Berry Card is a shared board
Berry Cards are not made by one individual person, but rather they are designed by a community of people all working together. Berry Club users collaborate on individual cards by organizing themselves using individual chatrooms, where they discuss what changes they would like to work on together, and what designs they would like to make. This encourages a sense of unity among users. It also makes Berry Cards more special, as it means that multiple people have worked on them, and will continue to work on them indefinitely. This is one of the reasons why no individual person is able to set the price for a Berry Card, because Berry Cards are community-driven, and so it would be unfair for one person to set the price, rather than letting the community itself set the price.
People are able to add pixels to a project on Berry Club by using avocados, a token that runs on the NEAR network. As of writing this article, 1 NEAR = 250 avocados. When you use (or plant) these tokens onto a piece of work, you can earn a yield each day (more info on yield farming with Berry Club can be found here).
Berry Cards cannot be taken off the market
Unlike marketplaces like OpenSea, you cannot take the Berry Cards you have bought off the marketplace. Instead, after buying a Berry Card, it is automatically re-added to the marketplace, but with its price increased to reflect your purchase. This is because Berry Cards are not about ownership of rights, but rather about engaging with a community, and earning profits while you do so. When you buy a Berry Card, the majority of the money goes to the previous owner, although 10% of the money will go to the art DAO, with a 1% commission also going to the application itself. The art DAO is an important part of the NEAR ecosystem, where the profits handed to it are then used as an incentive to bring onboard new artists to Berry Cards and other NFT marketplaces which use the NEAR network. After the card is bought, the price of the card rises by 20%, so if somebody was to buy your card from you, you would then make a profit.
I tried this out for myself, by purchasing a Berry Card which costs 2.41 NEAR. This card had a previous owner, and so they got the majority of those profits, although the Art DAO also got 10%. Afterward, the card got re-added to the marketplace with a new, higher, price of 2.89 NEAR. If somebody buys that card off me, then I would get 2.57 NEAR. This might not seem like a lot, but those profits rise significantly when looking at more expensive cards, and if the value of NEAR rises, then those profits would also increase. *Note – the price of a card can increase or decrease by people voting on it.
Another reason why Berry Cards cannot be taken off the market is because they are always live. Even when you buy a card, people over at Berry Club can still edit that card by using their avocados to add pixels. To take the card off the market would be to harm the community as a whole, which goes against the project’s design philosophy of connectivity and unity.
Cards owned by nobody
If you explore the Berry Cards marketplace, you will find that many cards are not owned by anybody. These are cards created by Berry Club, but which nobody over at the Berry Cards marketplace has purchased yet. By default, these cards belong to the Art DAO, and so if you purchase them, 99% of the profits go to that account, which is then used to support other artists, and 1% goes to the app commission, which is used to keep Berry Cards running and keeps contracts funded.
Why use Berry Cards?
There are several things that make Berry Cards appealing to crypto, blockchain, and NFT fans. NEAR’s scalability and cheap transactions allow for deeply interactive projects, like Berry Cards and Berry Club, to exist. Both of these projects encourage a great deal of user-activity and input, two things that Ethereum simply cannot handle at the moment. This means that people can confidently use Berry Cards with the knowledge that it will always be user-friendly and efficient, both for traders and for creators over at Berry Club. The knowledge that these projects will stay cheap and fast is a strong incentive for people to explore them with the confidence that they are future-proof.
Berry Cards are fair
Another positive of Berry Cards is its fairness of pricing. If you take a quick look at places like OpenSea, and other NFT markets, you will see a plethora of art that seems overpriced compared to what the art actually looks or sounds like. This is largely because people are hopping onto the NFT bandwagon and setting their work extremely high with the hopes that newcomers will be duped into paying for it so they can make a profit, too. However, Berry Cards prevents this from happening by dynamically pricing its work, where users of Berry Cards help to set the price of each piece. This means that everything is algorithmically and mathematically priced. It might have the fairest pricing system of any NFT marketplace I have come across.
A final major reason to use Berry Cards is that it is designed to support the digital art community. As mentioned above, 10% of earnings from any card purchase go to the Art DAO (or if nobody owns the card, then 99% goes there). The funds being held by the Art DAO are then used by NEAR developers to put money into the growing NFT market, and encourage artists to participate in the world of NFTs. So, by buying and selling Berry Cards, you are actively supporting the digital art community.
Final Words
Berry Cards is one of many innovative NFT projects running on NEAR. By allowing people to buy and sell community-driven pixel art, using its funds to help artists, and setting its prices dynamically via user participation, it is creating a project that supports the art world, encourages collaboration, and sets fair prices for its content. It is an innovative and creative project that shows the world just how efficient and cost-effective the NEAR protocol is.
If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR documentation to get started. |
```js
import { Wallet } from './near-wallet';
const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
const NFT_CONTRACT_ADDRESS = "nft.primitives.near";
const DROP_AMOUNT = "10000000000000000000000";
const keypomConnectedWallet = new Wallet({ createAccessKeyFor: KEYPOM_CONTRACT_ADDRESS });
const nftConnectedWallet = new Wallet({ createAccessKeyFor: NFT_CONTRACT_ADDRESS });
await wallet.callMethod({
method: "create_drop",
contractId: KEYPOM_CONTRACT_ADDRESS,
args: {
public_keys: state.publicKeys,
deposit_per_use: DROP_AMOUNT,
nft: {
// Who will be sending the NFTs to the Keypom contract
sender_id: accountId, // TODO How to get it
// NFT Contract Id that the tokens will come from
contract_id: NFT_CONTRACT_ADDRESS,
},
},
deposit: "23000000000000000000000" // state.publicKeys.length * dropAmount + 3000000000000000000000,
gas: "100000000000000",
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |
```rust
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct PoolInfo {
/// Pool kind.
pub pool_kind: String,
/// List of tokens in the pool.
pub token_account_ids: Vec<AccountId>,
/// How much NEAR this contract has.
pub amounts: Vec<U128>,
/// Fee charged for swap.
pub total_fee: u32,
/// Total number of shares.
pub shares_total_supply: U128,
pub amp: u64,
}
// Validator interface, for cross-contract calls
#[ext_contract(ext_amm_contract)]
trait ExternalAmmContract {
fn get_pools(&self, from_index: u64, limit: u64) -> Promise;
}
// Implement the contract structure
#[near_bindgen]
impl Contract {
#[private] // Public - but only callable by env::current_account_id()
pub fn external_get_pools_callback(&self, #[callback_result] call_result: Result<Vec<PoolInfo>, PromiseError>) -> Option<Vec<PoolInfo>> {
// 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 pools_data = call_result.unwrap();
return Some(pools_data);
}
pub fn get_amm_pools(&self, from_index: u64, limit: u64) -> Promise {
let promise = ext_amm_contract::ext(self.amm_contract.clone())
.get_pools(from_index, limit);
return promise.then( // Create a promise to callback query_greeting_callback
Self::ext(env::current_account_id())
.external_get_pools_callback()
)
}
}
``` |
Transitioning NEAR MainNet to the Next Phase: It is Time to Stake, Delegate and Vote
COMMUNITY
September 15, 2020
As announced in April by this roadmap blog post, NEAR is entering into Phase I, called “MainNet Restricted.” This transition will be complete on September 24th.
Since August, a decentralized set of validators has been onboarding to MainNet to replace the NEAR Foundation nodes, thus decentralizing the protocol’s consensus. The NEAR Validators Advisory Board represents the core group of community members, distinguished validators from the Stake Wars incentivized testnet program and recognized players from the Proof of Stake ecosystem.
In the meantime, the ecosystem is already thriving on the current configuration of the network, called “MainNet PoA”, with examples that include the custody provider Finoa and applications like Zed.run and Flux. For them, this transition will proceed without interruptions: the four NEAR Foundation nodes are working as any other validator, and the Phase I network will simply reach a higher number of block producers.
The upgrade to a decentralized, validator-run Phase I will kick off a new wave of opportunities like the Rainbow Bridge, the upcoming EVM support, and several as-yet-unannounced applications.
This activity lays down the groundwork for Phase II, a full community governed MainNet, as validators can also start voting to enable transfers and protocol’s inflationary rewards. The decision will be entirely in their hands, and this vote might occur right after transitioning into Phase I, depending on how they choose to proceed.
This post will describe how validators join MainNet: Restricted (Phase I), how tokenholders can delegate to these validators, and how the vote to enter Phase II will happen.
Laying down the Infrastructure for Phase I
Validators joining MainNet Restricted have to follow three steps:
Generate a MainNet wallet. NEAR Foundation is sending invitation emails containing the instructions to create a MainNet wallet. Accounts names must use a .near suffix, e.g. “satoshi” will have to be “satoshi.near”. Once the wallet is generated, the Foundation will provide 40 tokens to deploy a staking pool from the core contracts.
Deploy the node and the staking pool. Supported staking pools (as they appear on the block explorer) will have the .poolv1.near suffix. For example, a validator passing the parameter “satoshi” to the staking pool factory will be seen by the community as “satoshi.poolv1.near”.
Receive delegation. Validators can reply to the NEAR Foundation email as soon as their node is ready to receive the initial staking transaction. Once this transaction is complete, the node is included in the active set within two epochs (<86,400 blocks, or less than 24 hours).
NEAR Foundation allocated a stake of 28.8 million tokens to enable Phase I validators, as follows:
16.8 million to the 14 members of the NEAR Validator Advisory Board, 1.2 million NEAR tokens each
12 million to the first 30 ecosystem validators that joined MainNet, 400k NEAR tokens each
These funds are temporarily delegated to help these validators onboard the community of NEAR contributors, supporters, and CoinList sale participants.
As soon as the protocol enters Phase II, NEAR Foundation will progressively unstake all the funds, starting from the organizations that raised enough to keep a seat on their own. The blog post Introduction to NEAR’s Protocol Economics, in the “Selection” part, provides more information about validator seat dynamics.
Community, it is now your turn to stake!
While NEAR Foundation ran MainNet PoA, hundreds of validators participated in the Stake Wars and prepared their nodes to receive staking from the community.
It is now your turn: all NEAR tokens in circulation can be staked immediately and will begin to earn rewards right after the transition to Phase II.
In practical terms, during Phase II all staked tokens generate returns that become transferable immediately, even if your account will be vesting its tokens for years to come!
Staking today is beneficial for the entire ecosystem:
More community staking helps Validators to build their popularity, making them independent from the Foundation early on.
Token holders get to know NEAR validators and prepare for Phase II rewards.
More tokens are used to vote for Phase II, improving the governance decentralization.
NEAR wallet will soon provide a user interface to stake with any MainNet validator. Other platforms are ready to announce their staking tools, making this process more accessible and intuitive for everyone.
In the meantime, NEAR tokens can be delegated only via command-line interface, following the instructions contained in the delegation docs. Heads up! This operation is suggested only to users who have familiarity with near-cli and know how to handle the private key material generated by the `near login` command.
The vote to launch Phase II
As soon as the Foundation shuts down its PoA nodes (operation planned for September 24th), NEAR Protocol is technically ready to transition into Phase II, called “MainNet: Community Governed.”
Phase II will enable token transfers and protocol rewards, and will need validators to accomplish two distinct actions:
An on-chain vote to enable token transfers.
A nearcore update to enable inflationary rewards.
Staking pool owners will vote on behalf of their users by signing a specific transaction, displaying an on-chain agreement that makes NEAR Protocol completely permissionless.
As soon as ⅔ of the staked funds voted to unlock transfers, transfers are enabled instantly. More specifically, all relevant lockup contracts will set users free to send and receive their available tokens.
Once the on-chain vote activates token transfers, NEAR Protocol is ready to enable inflationary rewards via a new nearcore release.
This transition, initially coordinated over email and the validator chat channels, will happen after 80% of the validators (counted by their stake) complete the upgrade. At this point, the upgradability function will recognize the shift, automatically enabling the rewards within two epochs (24 hours).
Inflationary rewards will introduce essential economic incentives, making the network consensus decentralized and entirely self-sufficient, as described in the Protocol Economics blog post and the documentation page.
Wrapping up
Four months after its Genesis Block, NEAR Protocol is transitioning into Phase I, onboarding a group of validators from the ecosystem.
These validators will:
Run the consensus, replacing Foundation’s PoA nodes.
Receive staking from the Foundation and the community of NEAR token holders.
Vote for Phase II, as introduced by the roadmap blog post.
During Phase I, the network limits token transfers and has no staking rewards, features that will be enabled after the vote to begin Phase II. This vote will be entirely orchestrated by validators, using the stake provided by NEAR Foundation and their early delegators.
Finally, Phase II will introduce inflationary rewards, activating the economic incentives to make NEAR consensus decentralized and self-sufficient.
Interested to know more? If you haven’t already, join the conversation at https://near.chat. If you want to be the first to know about NEAR progress, sign up to the newsletter.
|
- Proposal Name: `wasm_bindings`
- Start Date: 2019-07-22
- NEP PR: [nearprotocol/neps#0000](https://github.com/near/NEPs/blob/master/nep-0000-template.md)
# Summary
[summary]: #summary
Wasm bindings, a.k.a imports, are functions that the runtime (a.k.a host) exposes to the Wasm code (a.k.a guest) running on the virtual machine.
These functions are arguably the most difficult thing to change in our entire ecosystem, after we have contracts running on our blockchain,
since once the bindings change the old smart contracts will not be able to run on the new nodes.
Additionally, we need a highly detailed specification of the bindings to be able to write unit tests for our contracts,
since currently we only allow integration tests. Currently, writing unit tests is not possible since we cannot have
a precise mock of the host in the smart contract unit tests, e.g. we don't know how to mock the range iterator (what does it do
when given an empty or inverted range?).
In this proposal we give a detailed specification of the functions that we will be relying on for many months to come.
# Motivation
[motivation]: #motivation
The current imports have the following issues:
* **Trie API.** The behavior of trie API is currently unspecified. Many things are unclear: what happens when we try
iterating over an empty range, what happens if we try accessing a non-existent key, etc. Having a trie API specification
is important for being able to create a testing framework for Rust and AssemblyScript smart contracts, since in unit
tests the contracts will be running on a mocked implementation of the host;
* **Promise API.** Recently we have discussed the changes to our promise mechanics. The schema does not need to change,
but the specification now needs to be clarified;
* `data_read` currently has mixed functionality -- it can be used both for reading data from trie and to read data from
the context. In former it expects pointers to be passed as arguments, in later it expects enum to be passed. It achieves
juxtaposition by casting pointer type in enum when needed;
* **Economics API.** The functions that provide access to balance and such might need to be added or removed since we
now consider splitting attached balance into two.
# Specification
## Registers
Registers allow the host function to return the data into a buffer located inside the host oppose to the buffer
located on the client. A special operation can be used to copy the content of the buffer into the host. Memory pointers
can then be used to point either to the memory on the guest or the memory on the host, see below. Benefits:
* We can have functions that return values that are not necessarily used, e.g. inserting key-value into a trie can
also return the preempted old value, which might not be necessarily used. Previously, if we returned something we
would have to pass the blob from host into the guest, even if it is not used;
* We can pass blobs of data between host functions without going through the guest, e.g. we can remove the value
from the storage and insert it into under a different key;
* It makes API cleaner, because we don't need to pass `buffer_len` and `buffer_ptr` as arguments to other functions;
* It allows merging certain functions together, see `storage_iter_next`;
* This is consistent with other APIs that were created for high performance, e.g. allegedly Ewasm have implemented
SNARK-like computations in Wasm by exposing a bignum library through stack-like interface to the guest. The guest
can manipulate then with the stack of 256-bit numbers that is located on the host.
#### Host → host blob passing
The registers can be used to pass the blobs between host functions. For any function that
takes a pair of arguments `*_len: u64, *_ptr: u64` this pair is pointing to a region of memory either on the guest or
the host:
* If `*_len != u64::MAX` it points to the memory on the guest;
* If `*_len == u64::MAX` it points to the memory under the register `*_ptr` on the host.
For example:
`storage_write(u64::MAX, 0, u64::MAX, 1, 2)` -- insert key-value into storage, where key is read from register 0,
value is read from register 1, and result is saved to register 2.
Note, if some function takes `register_id` then it means this function can copy some data into this register. If
`register_id == u64::MAX` then the copying does not happen. This allows some micro-optimizations in the future.
Note, we allow multiple registers on the host, identified with `u64` number. The guest does not have to use them in
order and can for instance save some blob in register `5000` and another value in register `1`.
#### Specification
```rust
read_register(register_id: u64, ptr: u64)
```
Writes the entire content from the register `register_id` into the memory of the guest starting with `ptr`.
###### Panics
* If the content extends outside the memory allocated to the guest. In Wasmer, it returns `MemoryAccessViolation` error message;
* If `register_id` is pointing to unused register returns `InvalidRegisterId` error message.
###### Undefined Behavior
* If the content of register extends outside the preallocated memory on the host side, or the pointer points to a
wrong location this function will overwrite memory that it is not supposed to overwrite causing an undefined behavior.
---
```rust
register_len(register_id: u64) -> u64
```
Returns the size of the blob stored in the given register.
###### Normal operation
* If register is used, then returns the size, which can potentially be zero;
* If register is not used, returns `u64::MAX`
## Trie API
Here we provide a specification of trie API. After this NEP is merged, the cases where our current implementation does
not follow the specification are considered to be bugs that need to be fixed.
---
```rust
storage_write(key_len: u64, key_ptr: u64, value_len: u64, value_ptr: u64, register_id: u64) -> u64
```
Writes key-value into storage.
###### Normal operation
* If key is not in use it inserts the key-value pair and does not modify the register;
* If key is in use it inserts the key-value and copies the old value into the `register_id`.
###### Returns
* If key was not used returns `0`;
* If key was used returns `1`.
###### Panics
* If `key_len + key_ptr` or `value_len + value_ptr` exceeds the memory container or points to an unused register it panics
with `MemoryAccessViolation`. (When we say that something panics with the given error we mean that we use Wasmer API to
create this error and terminate the execution of VM. For mocks of the host that would only cause a non-name panic.)
* If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`;
###### Current bugs
* `External::storage_set` trait can return an error which is then converted to a generic non-descriptive
`StorageUpdateError`, [here](https://github.com/nearprotocol/nearcore/blob/942bd7bdbba5fb3403e5c2f1ee3c08963947d0c6/runtime/wasm/src/runtime.rs#L210)
however the actual implementation does not return error at all, [see](https://github.com/nearprotocol/nearcore/blob/4773873b3cd680936bf206cebd56bdc3701ddca9/runtime/runtime/src/ext.rs#L95);
* Does not return into the registers.
---
```rust
storage_read(key_len: u64, key_ptr: u64, register_id: u64) -> u64
```
Reads the value stored under the given key.
###### Normal operation
* If key is used copies the content of the value into the `register_id`, even if the content is zero bytes;
* If key is not present then does not modify the register.
###### Returns
* If key was not present returns `0`;
* If key was present returns `1`.
###### Panics
* If `key_len + key_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`;
* If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`;
###### Current bugs
* This function currently does not exist.
---
```rust
storage_remove(key_len: u64, key_ptr: u64, register_id: u64) -> u64
```
Removes the value stored under the given key.
###### Normal operation
Very similar to `storage_read`:
* If key is used, removes the key-value from the trie and copies the content of the value into the `register_id`, even if the content is zero bytes.
* If key is not present then does not modify the register.
###### Returns
* If key was not present returns `0`;
* If key was present returns `1`.
###### Panics
* If `key_len + key_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`;
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
* If returning the preempted value into the registers exceed the memory container it panics with `MemoryAccessViolation`;
###### Current bugs
* Does not return into the registers.
---
```rust
storage_has_key(key_len: u64, key_ptr: u64) -> u64
```
Checks if there is a key-value pair.
###### Normal operation
* If key is used returns `1`, even if the value is zero bytes;
* Otherwise returns `0`.
###### Panics
* If `key_len + key_ptr` exceeds the memory container it panics with `MemoryAccessViolation`;
---
```rust
storage_iter_prefix(prefix_len: u64, prefix_ptr: u64) -> u64
```
Creates an iterator object inside the host.
Returns the identifier that uniquely differentiates the given iterator from other iterators that can be simultaneously
created.
###### Normal operation
* It iterates over the keys that have the provided prefix. The order of iteration is defined by the lexicographic
order of the bytes in the keys. If there are no keys, it creates an empty iterator, see below on empty iterators;
###### Panics
* If `prefix_len + prefix_ptr` exceeds the memory container it panics with `MemoryAccessViolation`;
---
```rust
storage_iter_range(start_len: u64, start_ptr: u64, end_len: u64, end_ptr: u64) -> u64
```
Similarly to `storage_iter_prefix`
creates an iterator object inside the host.
###### Normal operation
Unless lexicographically `start < end`, it creates an empty iterator.
Iterates over all key-values such that keys are between `start` and `end`, where `start` is inclusive and `end` is exclusive.
Note, this definition allows for `start` or `end` keys to not actually exist on the given trie.
###### Panics:
* If `start_len + start_ptr` or `end_len + end_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`;
---
```rust
storage_iter_next(iterator_id: u64, key_register_id: u64, value_register_id: u64) -> u64
```
Advances iterator and saves the next key and value in the register.
###### Normal operation
* If iterator is not empty (after calling next it points to a key-value), copies the key into `key_register_id` and value into `value_register_id` and returns `1`;
* If iterator is empty returns `0`.
This allows us to iterate over the keys that have zero bytes stored in values.
###### Panics
* If `key_register_id == value_register_id` panics with `MemoryAccessViolation`;
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
* If `iterator_id` does not correspond to an existing iterator panics with `InvalidIteratorId`
* If between the creation of the iterator and calling `storage_iter_next` any modification to storage was done through
`storage_write` or `storage_remove` the iterator is invalidated and the error message is `IteratorWasInvalidated`.
###### Current bugs
* Not implemented, currently we have `storage_iter_next` and `data_read` + `DATA_TYPE_STORAGE_ITER` that together fulfill
the purpose, but have unspecified behavior.
## Context API
Context API mostly provides read-only functions that access current information about the blockchain, the accounts
(that originally initiated the chain of cross-contract calls, the immediate contract that called the current one, the account of the current contract),
other important information like storage usage.
Many of the below functions are currently implemented through `data_read` which allows to read generic context data.
However, there is no reason to have `data_read` instead of the specific functions:
* `data_read` does not solve forward compatibility. If later we want to add another context function, e.g. `executed_operations`
we can just declare it as a new function, instead of encoding it as `DATA_TYPE_EXECUTED_OPERATIONS = 42` which is passed
as the first argument to `data_read`;
* `data_read` does not help with renaming. If later we decide to rename `signer_account_id` to `originator_id` then one could
argue that contracts that rely on `data_read` would not break, while contracts relying on `signer_account_id()` would. However
the name change often means the change of the semantics, which means the contracts using this function are no longer safe to
execute anyway.
However there is one reason to not have `data_read` -- it makes `API` more human-like which is a general direction Wasm APIs, like WASI are moving towards to.
---
```rust
current_account_id(register_id: u64)
```
Saves the account id of the current contract that we execute into the register.
###### Panics
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
---
```rust
signer_account_id(register_id: u64)
```
All contract calls are a result of some transaction that was signed by some account using
some access key and submitted into a memory pool (either through the wallet using RPC or by a node itself). This function returns the id of that account.
###### Normal operation
* Saves the bytes of the signer account id into the register.
###### Panics
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
###### Current bugs
* Currently we conflate `originator_id` and `sender_id` in our code base.
---
```rust
signer_account_pk(register_id: u64)
```
Saves the public key fo the access key that was used by the signer into the register.
In rare situations smart contract might want to know the exact access key that was used to send the original transaction,
e.g. to increase the allowance or manipulate with the public key.
###### Panics
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
###### Current bugs
* Not implemented.
---
```rust
predecessor_account_id(register_id: u64)
```
All contract calls are a result of a receipt, this receipt might be created by a transaction
that does function invocation on the contract or another contract as a result of cross-contract call.
###### Normal operation
* Saves the bytes of the predecessor account id into the register.
###### Panics
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
###### Current bugs
* Not implemented.
---
```rust
input(register_id: u64)
```
Reads input to the contract call into the register. Input is expected to be in JSON-format.
###### Normal operation
* If input is provided saves the bytes (potentially zero) of input into register.
* If input is not provided does not modify the register.
###### Returns
* If input was not provided returns `0`;
* If input was provided returns `1`; If input is zero bytes returns `1`, too.
###### Panics
* If the registers exceed the memory limit panics with `MemoryAccessViolation`;
###### Current bugs
* Implemented as part of `data_read`. However there is no reason to have one unified function, like `data_read` that can
be used to read all
---
```rust
block_index() -> u64
```
Returns the current block index.
---
```rust
storage_usage() -> u64
```
Returns the number of bytes used by the contract if it was saved to the trie as of the
invocation. This includes:
* The data written with `storage_*` functions during current and previous execution;
* The bytes needed to store the account protobuf and the access keys of the given account.
## 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_balance`
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`;
###### Current bugs
* Use a different name;
---
```rust
prepaid_gas() -> u64
used_gas() -> u64
```
## Math
```rust
random_seed(register_id: u64)
```
Returns random seed that can be used for pseudo-random number generation in deterministic way.
###### Panics
* If the size of the registers exceed the set limit `MemoryAccessViolation`;
---
```rust
sha256(value_len: u64, value_ptr: u64, register_id: u64)
```
Hashes the random sequence of bytes using sha256 and returns it into `register_id`.
###### Panics
* If `value_len + value_ptr` points outside the memory or the registers use more memory than the limit with `MemoryAccessViolation`.
###### Current bugs
* Current name `hash` is not specific to what hash is being used.
* We have `hash32` that largely duplicates the mechanics of `hash` because it returns the first 4 bytes only.
---
```rust
check_ethash(block_number_ptr: u64,
header_hash_ptr: u64,
nonce: u64,
mix_hash_ptr: u64,
difficulty_ptr: u64) -> u64
```
-- verifies hash of the header that we created using [Ethash](https://en.wikipedia.org/wiki/Ethash). Parameters are:
* `block_number` -- `u256`/`[u64; 4]`, number of the block on Ethereum blockchain. We use the pointer to the slice of 32 bytes on guest memory;
* `header_hash` -- `h256`/`[u8; 32]`, hash of the header on Ethereum blockchain. We use the pointer to the slice of 32 bytes on guest memory;
* `nonce` -- `u64`/`h64`/`[u8; 8]`, nonce that was used to find the correct hash, passed as `u64` without pointers;
* `mix_hash` -- `h256`/`[u8; 32]`, special hash that avoid griefing attack. We use the pointer to the slice of 32 bytes on guest memory;
* `difficulty` -- `u256`/`[u64; 4]`, the difficulty of mining the block. We use the pointer to the slice of 32 bytes on guest memory;
###### Returns
* `1` if the Ethash is valid;
* `0` otherwise.
###### Panics
* If `block_number_ptr + 32` or `header_hash_ptr + 32` or `mix_hash_ptr + 32` or `difficulty_ptr + 32` point outside the memory or registers use more memory than the limit with `MemoryAccessViolation`.
###### Current bugs
* `block_number` and `difficulty` are currently exposed as `u64` which are casted to `u256` which breaks Ethereum compatibility;
* Currently, we also pass the length together with `header_hash_ptr` and `mix_hash_ptr` which is not necessary since
we know their length.
## Promises API
```rust
promise_create(account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64) -> u64
```
Creates a promise that will execute a method on account with given arguments and attaches the given amount.
`amount_ptr` point to slices of bytes representing `u128`.
###### Panics
* If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
###### Returns
* Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_then(promise_idx: u64,
account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64) -> u64
```
Attaches the callback that is executed after promise pointed by `promise_idx` is complete.
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
###### Returns
* Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_and(promise_idx_ptr: u64, promise_idx_count: u64) -> u64
```
Creates a new promise which completes when time all promises passed as arguments complete. Cannot be used with registers.
`promise_idx_ptr` points to an array of `u64` elements, with `promise_idx_count` denoting the number of elements.
The array contains indices of promises that need to be waited on jointly.
###### Panics
* If `promise_ids_ptr + 8 * promise_idx_count` extend outside the guest memory with `MemoryAccessViolation`;
* If any of the promises in the array do not correspond to existing promises panics with `InvalidPromiseIndex`.
###### Returns
* Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_results_count() -> u64
```
If the current function is invoked by a callback we can access the execution results of the promises that
caused the callback. This function returns the number of complete and incomplete callbacks.
Note, we are only going to have incomplete callbacks once we have `promise_or` combinator.
###### Normal execution
* If there is only one callback `promise_results_count()` returns `1`;
* If there are multiple callbacks (e.g. created through `promise_and`) `promise_results_count()` returns their number.
* If the function was called not through the callback `promise_results_count()` returns `0`.
---
```rust
promise_result(result_idx: u64, register_id: u64) -> u64
```
If the current function is invoked by a callback we can access the execution results of the promises that
caused the callback. This function returns the result in blob format and places it into the register.
###### Normal execution
* If promise result is complete and successful copies its blob into the register;
* If promise result is complete and failed or incomplete keeps register unused;
###### Returns
* If promise result is not complete returns `0`;
* If promise result is complete and successful returns `1`;
* If promise result is complete and failed returns `2`.
###### Panics
* If `result_idx` does not correspond to an existing result panics with `InvalidResultIndex`.
* If copying the blob exhausts the memory limit it panics with `MemoryAccessViolation`.
###### Current bugs
* We currently have two separate functions to check for result completion and copy it.
---
```rust
promise_return(promise_idx: u64)
```
When promise `promise_idx` finishes executing its result is considered to be the result of the current function.
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
###### Current bugs
* The current name `return_promise` is inconsistent with the naming convention of Promise API.
## Miscellaneous API
```rust
value_return(value_len: u64, value_ptr: u64)
```
Sets the blob of data as the return value of the contract.
##### Panics
* If `value_len + value_ptr` exceeds the memory container or points to an unused register it panics with `MemoryAccessViolation`;
---
```rust
panic()
```
Terminates the execution of the program with panic `GuestPanic`.
---
```rust
log_utf8(len: u64, ptr: u64)
```
Logs the UTF-8 encoded string. See https://stackoverflow.com/a/5923961 that explains
that null termination is not defined through encoding.
###### Normal behavior
If `len == u64::MAX` then treats the string as null-terminated with character `'\0'`;
###### Panics
* If string extends outside the memory of the guest with `MemoryAccessViolation`;
---
```rust
log_utf16(len: u64, ptr: u64)
```
Logs the UTF-16 encoded string. `len` is the number of bytes in the string.
###### Normal behavior
If `len == u64::MAX` then treats the string as null-terminated with two-byte sequence of `0x00 0x00`.
###### Panics
* If string extends outside the memory of the guest with `MemoryAccessViolation`;
---
```rust
abort(msg_ptr: u32, filename_ptr: u32, line: u32, col: u32)
```
Special import kept for compatibility with AssemblyScript contracts. Not called by smart contracts directly, but instead
called by the code generated by AssemblyScript.
# Future Improvements
In the future we can have some of the registers to be on the guest.
For instance a guest can tell the host that it has some pre-allocated memory that it wants to be used for the register,
e.g.
```rust
set_guest_register(register_id: u64, register_ptr: u64, max_register_size: u64)
```
will assign `register_id` to a span of memory on the guest. Host then would also know the size of that buffer on guest
and can throw a panic if there is an attempted copying that exceeds the guest register size.
|
NEAR Q2 Protocol Roadmap Update
COMMUNITY
August 9, 2023
The Q1 protocol roadmap update was well received by the community. Pagoda committed to continuing to share quarterly roadmap updates, so here is the update for Q2 2023.
What the protocol team accomplished in Q2
Pagoda made good progress on the protocol roadmap in Q2. For the experience section, there is now a NEP on account namespaces, a key stepping stone towards account extension. Account extension would allow users to easily compose different modules such as multisig, proxy, and so on. In addition, Aurora submitted a NEP on wasm submodules, which, if implemented, would enable a limited form of synchronous execution, or allowing transactions that touch multiple contracts to settle within a single block. Both proposals are still works in progress due to the complexity of the changes.
On top of these two proposed changes, there is a NEP on shared storage for contract code which could significantly lower the cost of deploying a common contract. These proposals aspire to bring to life the account extension idea, which allows an account to install different modules to different functionalities such as multisig, recovery, proxy, and so on.
For the core section of the roadmap, Pagoda delivered a few important improvements this quarter. Flat storage with value inlining is live on mainnet and brings an 8x improvement to state reads. Work on background writes is also in progress and the protocol team’s initial experiments show that it can potentially reduce the cost of state writes by 3x. In addition, cold storage is fully live on mainnet and drastically reduces the cost of running an archival node.
Pagoda has also made good progress to revamp state sync. With the growth of mainnet state, the previous version of state sync was too inefficient and practically unusable. The new state sync, which uses flat storage to speed up state part generation, allows a node to finish syncing mainnet state within 3 hours. The team is expected to deliver the fully functional version of the new state sync in Q3.
The team has also delivered finite wasm and its integration with nearcore, which improves the security and robustness of NEAR’s contract runtime immensely.
Updates to the roadmap
The experience section of the roadmap remains mostly the same, with two changes worth highlighting. One shift is that the changes required to implement account extension are temporarily on hold as we would like to see the impact on user experience by first emulating the changes through smart contracts. Another change is that the protocol team will work on the storage refund problem to prevent potential faucet-draining attacks in the new onboarding experience.
For the core section of the roadmap, the focus in Q3 will shift to Phase 2 of sharding, which includes both resharding the current mainnet state and turning off the requirement that block producers have to track all shards. This endeavor will take more than one quarter to finish and we will post more updates as we iron out details of the design.
To stay up to date with protocol changes as they happen, or to participate in protocol governance, please join the protocol community group and follow the NEAR Enhancement Proposal (NEP) process. |
---
id: meta-transactions
title: Building a Meta Transaction Relayer
sidebar_label: Meta Transaction Relayers
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
Relayers serve to delegate gas fees to a web service, allowing users to transact on NEAR without the need to acquire the token themselves while still retaining the security of signing their own transactions. This guide will lead you through the components necessary to construct a relayer capable of handling meta transactions.
:::tip
If you're already acquainted with the technology and you just want to run your own Relayer, you can fast track to a complete [Rust Relayer server](#rust-relayer-server) open-source implementation.
:::
## How it works
A basic relayer consists of a web server housing a funded NEAR account. This account receives an encoded signed transaction, which can subsequently be decoded into a `SignedDelegate` format and transmitted on-chain.
The client can then generate a `SignedDelegateAction` (a signed message that hasn't yet been sent), encode it, and transmit it to this server, where it will be relayed onto the blockchain.
![relayer-overview-technical](/docs/assets/welcome-pages/relayer-overview-technical.png)
## Relayer (server)
<Tabs groupId="code-tabs">
<TabItem value="near-api-js">
Here's a simple express endpoint that deserializes the body, instantiates the relayer account and then sends the transaction.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay-example/blob/main/server.ts' start='16' end='27'/>
You can easily get the account object used to send the transactions from its private key using this snippet
<Github language='typescript' url='https://github.com/SurgeCode/near-relay-example/blob/main/util.ts' start='5' end='17'/>
:::info
The code in the example only works from the following versions onwards
```
"near-api-js": "3.0.4"
"@near-js/transactions": "1.1.2",
"@near-js/accounts": "1.0.4"
```
:::
</TabItem>
<TabItem value="@near-relay/server">
`@near-relay` simplifies meta transactions making it easier to get started for a beginner.
To start, call the relay method inside an endpoint to automatically deserialize the transaction and send it with the account defined in the environment variables.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay/blob/main/server/server.ts' start='8' end='12'/>
If you're interested in relaying account creation as well, it's quite straightforward. Simply create another endpoint and directly call the createAccount method with the accountId and publicKey. These parameters are automatically included in the body when using the corresponding client library.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay/blob/main/server/server.ts' start='14' end='18'/>
</TabItem>
</Tabs>
## Client
<Tabs groupId="code-tabs">
<TabItem value="near-api-js">
In this method we are creating an arbitrary smart contract call, instantiating an account and using it to sign but not send the transaction. We can then serialize it and send it to the relayer where it will be delegated via the previously created endpoint.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay-example/blob/main/client.ts' start='10' end='30'/>
</TabItem>
<TabItem value="@near-relay/client">
As mentioned in the above note in order to be able to relay on the client side it's necessary to have access to signing transactions directly on the client. Luckily leveraging the near biometric library it's possible to do so in a non custodial way.
By calling this method and passing in the URL for the account creation endpoint (mentioned in the server section) as well as the `accoundId` everything is handled under the hood to successfully create an account.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay/blob/main/example/src/app/page.tsx' start='17' end='23'/>
On the client side, you just need to create an `Action` and pass it into the `relayTransaction` method along with the URL of the relayer endpoint discussed in the server section and the id of the `receiverId`.
<Github language='typescript' url='https://github.com/SurgeCode/near-relay/blob/main/example/src/app/page.tsx' start='25' end='36'/>
</TabItem>
</Tabs>
<details>
<summary> Relaying with wallets </summary>
At the moment, wallet selector standard doesn't support signing transactions without immediately sending them. This functionality is essential for routing transactions to a relayer. Therefore, to smoothly integrate relaying on the client side, it's necessary to be able to sign transactions without relying on wallets.
Progress is being made to make this possible in the future.
</details>
### Gating the relayer
In most production applications it's expected that you want to be able to gate the relayer to only be used in certain cases.
By taking apart the `delegateAction` object inside the `SignedDelegate`on the server this can be done simply.
```typescript
export declare class DelegateAction extends Assignable {
senderId: string;
receiverId: string;
actions: Array<Action>;
nonce: BN;
maxBlockHeight: BN;
publicKey: PublicKey;
}
```
You can, for example, gate by some particular user or contract:
```typescript
const serializedTx: Buffer = req.body;
const deserializedTx: SignedDelegate = deserialize(SCHEMA.SignedDelegate, Buffer.from(serializedTx)) as SignedDelegate;
const relayerAccount: Account = await getAccount(NETWORK_ID, RELAYER_ID, RELAYER_PRIVATE_KEY);
const delegateAction = deserializedTx?.delegateAction
if(delegateAction.senderId == 'someUserId' || delegateAction.receiverId == 'someContractId' ){
const receipt = await relayerAccount.signAndSendTransaction({
actions: [actionCreators.signedDelegate(deserializedTx)],
receiverId: deserializedTx.delegateAction.senderId
});
}
```
Other examples could be looking into the actions and seeing if there is deposit or gas and limiting them, gating by particular smart contract methods or even args.
You can decode the args using:
```
JSON.parse(Buffer.from(args_base64 || "", "base64").toString())
```
---
## Rust Relayer Server
The open-source Rust [reference implementation of a Relayer server](https://github.com/near/pagoda-relayer-rs/) offers the following features:
:::info
Features can be combined as needed. Use of one feature does not preclude the use of any other feature unless specified.
:::
1. Sign and send Meta Transactions to the RPC to cover the gas costs of end users while allowing them to maintain custody of their funds and approve transactions (`/relay`, `/send_meta_tx`, `/send_meta_tx_async`, `/send_meta_tx_nopoll`)
2. Sign Meta Transactions returning a Signed Meta Transaction to be sent to the RPC later - (`/sign_meta_tx`, `/sign_meta_tx_no_filter`)
3. Only pay for users interacting with certain contracts by whitelisting contracts addresses (`whitelisted_contracts` in `config.toml`)
4. Specify gas cost allowances for all accounts (`/update_all_allowances`) or on a per-user account basis (`/create_account_atomic`, `/register_account`, `/update_allowance`) and keep track of allowances (`/get_allowance`)
5. Specify the accounts for which the relayer will cover gas fees (`whitelisted_delegate_action_receiver_ids` in `config.toml`)
6. Only allow users to register if they have a unique Oauth Token (`/create_account_atomic`, `/register_account`)
7. Relayer Key Rotation: `keys_filenames` in `config.toml`
8. Integrate with [FastAuth SDK](fastauth-sdk.md)
9. Mix and Match configuration options
:::tip
Check the [Use cases section](#use-cases) for example configuration files corresponding to different usage scenarios.
:::
### Basic Setup
You can follow these steps to set up your local Relayer server development environment:
1. [Install Rust for NEAR Development](../../sdk/rust/intro.md)
2. If you don't have a NEAR account, [create one](../../1.concepts/protocol/account-model.md)
3. With the account from step 2, create a JSON file in this directory in the format
```js
[{"account_id":"example.testnet","public_key":"ed25519:98GtfFzez3opomVpwa7i4m3nptHtc7Ha514XHMWszLtQ","private_key":"ed25519:YWuyKVQHE3rJQYRC3pRGV56o1qEtA1PnMYPDEtroc5kX4A4mWrJwF7XkzGe7JWNMABbtY4XFDBJEzgLyfPkwpzC"}]
```
using a [Full Access Key](../../1.concepts/protocol/access-keys.md#full-access-keys) from an account that has enough NEAR to cover the gas costs of transactions your server will be relaying. Usually, this will be a copy of the json file found in the `.near-credentials` directory.
4. Update values in `config.toml`
5. Open up the `port` from `config.toml` in your machine's network settings
6. Run the server using `cargo run`.
> **(OPTIONAL)** To run with logs (tracing) enabled run `RUST_LOG=tower_http=debug cargo run`
:::info Optional setup
If you're integrating with [FastAuth](fastauth-sdk.md) make sure to enable feature flags:
```
cargo build --features fastauth_features,shared_storage
```
If you're using shared storage, make sure to enable feature flags:
```
cargo build --features shared_storage
```
:::
### Redis Setup
:::tip
This is only needed if you intend to use whitelisting, allowances, and OAuth functionality.
:::
1. [Install Redis](https://redis.io/docs/latest/get-started/).
> Steps 2 & 3 assume Redis was installed on machine instead of a Docker setup. If you're connecting to a Redis instance running in GCP, follow the above steps to connect to a VM that will forward requests from your local relayer server to [Redis running in GCP](https://cloud.google.com/memorystore/docs/redis/connect-redis-instance#connecting_from_a_local_machine_with_port_forwarding)
2. Run `redis-server --bind 127.0.0.1 --port 6379` - make sure the port matches the `redis_url` in the `config.toml`.
3. Run `redis-cli -h 127.0.0.1 -p 6379`
### Advanced setup
- [Multiple Key Generation](https://github.com/near/pagoda-relayer-rs/tree/main?tab=readme-ov-file#multiple-key-generation---optional-but-recommended-for-high-throughput-to-prevent-nonce-race-conditions): this is optional, but recommended for high throughput to prevent nonce race conditions. Check
- [Docker Deployment](https://github.com/near/pagoda-relayer-rs/tree/main?tab=readme-ov-file#docker-deployment): instructions to deploy with Docker
- [Cloud Deployment](https://github.com/near/pagoda-relayer-rs/tree/main?tab=readme-ov-file#cloud-deployment): instructions to deploy on Cloud providers
### API Specifications
You can find the complete Relayer server API specification on the [GitHub repository](https://github.com/near/pagoda-relayer-rs/tree/main?tab=readme-ov-file#api-spec-).
### Use cases
The [examples folder](https://github.com/near/pagoda-relayer-rs/tree/main/examples) on the GitHub repository contains example configuration files corresponding to different use cases.
:::info
These files are for reference only and you should update the `config.toml` values before using it on your development environment.
:::
#### No filters
This is a config for a relayer that covers gas for all user transactions to all contracts with no filters. To prevent abuse, this should only be used if there's only a secure backend calling the relayer
- [`no_filters.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/no_filters.toml)
#### Basic whitelist
This is a configuration for a basic relayer that covers gas for user transactions to interact with a whitelisted set of contracts
- [`basic_whitelist.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/basic_whitelist.toml)
#### Redis
This is a configuration for a relayer that covers gas for user transactions up to a allowance specified in Redis to interact with a whitelisted set of contracts.
- Allowances are on a per-account id basis and on signup (account creation in Redis and on-chain) an OAuth token is required to help with sybil resistance
- [`redis.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/redis.toml)
#### FastAuth
This is a configuration for use if you intend to integrate with [FastAuth SDK](fastauth-sdk.md)
- It covers gas for user transactions up to a allowance specified in Redis to interact with a whitelisted set of contracts.
- Allowances are on a per-account id basis and on signup (account creation in Redis and on-chain) an OAuth token is required to help with sybil resistance
- This also makes use of a shared storage functionality on the Near Social DB contract
- and a whitelisted sender (`whitelisted_delegate_action_receiver_ids`)
- [`fastauth.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/fastauth.toml)
#### Pay with fungible tokens
This is a configuration for a relayer that ensures there's FTs sent to a burn address used to cover the equivalent amount of gas for user transactions to interact with a whitelisted set of contracts
- [`pay_with_ft.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/pay_with_ft.toml)
#### Whitelist senders
This is a config for a relayer that covers gas for a whitelisted set of users' transactions to interact with a whitelisted set of contracts
- [`whitelist_senders.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/whitelist_senders.toml) (`whitelisted_delegate_action_receiver_ids`)
#### Shared storage
This is a configuration for a relayer that covers BOTH gas AND storage fees for user transactions to interact with a whitelisted set of contracts
- be sure to include shared storage logic based on [`shared_storage.rs`](https://github.com/NearSocial/social-db/blob/master/contract/src/shared_storage.rs) in your contract that is being whitelisted
- [`shared_storage.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/shared_storage.toml)
#### Exchange withdraw
This is a configuration for a relayer where an exchange running the relayer covers user withdraw fees when they are withdrawing stablecoins on NEAR (e.g., `USDT` or `USDC`)
- [`exchange_withdraw.toml`](https://github.com/near/pagoda-relayer-rs/blob/main/examples/configs/exchange_withdraw.toml)
|
# Fungible Token
## [NEP-141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md)
Version `1.0.0`
## Summary
A standard interface for fungible tokens that allows for a normal transfer as well as a transfer and method call in a single transaction. The [storage standard](../../StorageManagement.md) addresses the needs (and security) of storage staking.
The [fungible token metadata standard](Metadata.md) provides the fields needed for ergonomics across dApps and marketplaces.
## Motivation
NEAR Protocol uses an asynchronous, sharded runtime. This means the following:
- Storage for different contracts and accounts can be located on the different shards.
- Two contracts can be executed at the same time in different shards.
While this increases the transaction throughput linearly with the number of shards, it also creates some challenges for cross-contract development. For example, if one contract wants to query some information from the state of another contract (e.g. current balance), by the time the first contract receives the balance the real balance can change. In such an async system, a contract can't rely on the state of another contract and assume it's not going to change.
Instead the contract can rely on temporary partial lock of the state with a callback to act or unlock, but it requires careful engineering to avoid deadlocks. In this standard we're trying to avoid enforcing locks. A typical approach to this problem is to include an escrow system with allowances. This approach was initially developed for [NEP-21](https://github.com/near/NEPs/pull/21) which is similar to the Ethereum ERC-20 standard. There are a few issues with using an escrow as the only avenue to pay for a service with a fungible token. This frequently requires more than one transaction for common scenarios where fungible tokens are given as payment with the expectation that a method will subsequently be called.
For example, an oracle contract might be paid in fungible tokens. A client contract that wishes to use the oracle must either increase the escrow allowance before each request to the oracle contract, or allocate a large allowance that covers multiple calls. Both have drawbacks and ultimately it would be ideal to be able to send fungible tokens and call a method in a single transaction. This concern is addressed in the `ft_transfer_call` method. The power of this comes from the receiver contract working in concert with the fungible token contract in a secure way. That is, if the receiver contract abides by the standard, a single transaction may transfer and call a method.
Note: there is no reason why an escrow system cannot be included in a fungible token's implementation, but it is simply not necessary in the core standard. Escrow logic should be moved to a separate contract to handle that functionality. One reason for this is because the [Rainbow Bridge](https://near.org/blog/eth-near-rainbow-bridge/) will be transferring fungible tokens from Ethereum to NEAR, where the token locker (a factory) will be using the fungible token core standard.
Prior art:
- [ERC-20 standard](https://eips.ethereum.org/EIPS/eip-20)
- NEP#4 NEAR NFT standard: [near/neps#4](https://github.com/near/neps/pull/4)
Learn about NEP-141:
- [Figment Learning Pathway](https://web.archive.org/web/20220621055335/https://learn.figment.io/tutorials/stake-fungible-token)
## Guide-level explanation
We should be able to do the following:
- Initialize contract once. The given total supply will be owned by the given account ID.
- Get the total supply.
- Transfer tokens to a new user.
- Transfer tokens from one user to another.
- Transfer tokens to a contract, have the receiver contract call a method and "return" any fungible tokens not used.
- Remove state for the key/value pair corresponding with a user's account, withdrawing a nominal balance of Ⓝ that was used for storage.
There are a few concepts in the scenarios above:
- **Total supply**: the total number of tokens in circulation.
- **Balance owner**: an account ID that owns some amount of tokens.
- **Balance**: an amount of tokens.
- **Transfer**: an action that moves some amount from one account to another account, either an externally owned account or a contract account.
- **Transfer and call**: an action that moves some amount from one account to a contract account where the receiver calls a method.
- **Storage amount**: the amount of storage used for an account to be "registered" in the fungible token. This amount is denominated in Ⓝ, not bytes, and represents the [storage staked](https://docs.near.org/concepts/storage/storage-staking).
Note that precision (the number of decimal places supported by a given token) is not part of this core standard, since it's not required to perform actions. The minimum value is always 1 token. See the [Fungible Token Metadata Standard](Metadata.md) to learn how to support precision/decimals in a standardized way.
Given that multiple users will use a Fungible Token contract, and their activity will result in an increased [storage staking](https://docs.near.org/concepts/storage/storage-staking) burden for the contract's account, this standard is designed to interoperate nicely with [the Account Storage standard](../../StorageManagement.md) for storage deposits and refunds.
### Example scenarios
#### Simple transfer
Alice wants to send 5 wBTC tokens to Bob.
##### Assumptions
- The wBTC token contract is `wbtc`.
- Alice's account is `alice`.
- Bob's account is `bob`.
- The precision ("decimals" in the metadata standard) on wBTC contract is `10^8`.
- The 5 tokens is `5 * 10^8` or as a number is `500000000`.
##### High-level explanation
Alice needs to issue one transaction to wBTC contract to transfer 5 tokens (multiplied by precision) to Bob.
##### Technical calls
1. `alice` calls `wbtc::ft_transfer({"receiver_id": "bob", "amount": "500000000"})`.
#### Token deposit to a contract
Alice wants to deposit 1000 DAI tokens to a compound interest contract to earn extra tokens.
##### Assumptions
- The DAI token contract is `dai`.
- Alice's account is `alice`.
- The compound interest contract is `compound`.
- The precision ("decimals" in the metadata standard) on DAI contract is `10^18`.
- The 1000 tokens is `1000 * 10^18` or as a number is `1000000000000000000000`.
- The compound contract can work with multiple token types.
<details>
<summary>For this example, you may expand this section to see how a previous fungible token standard using escrows would deal with the scenario.</summary>
##### High-level explanation (NEP-21 standard)
Alice needs to issue 2 transactions. The first one to `dai` to set an allowance for `compound` to be able to withdraw tokens from `alice`.
The second transaction is to the `compound` to start the deposit process. Compound will check that the DAI tokens are supported and will try to withdraw the desired amount of DAI from `alice`.
- If transfer succeeded, `compound` can increase local ownership for `alice` to 1000 DAI
- If transfer fails, `compound` doesn't need to do anything in current example, but maybe can notify `alice` of unsuccessful transfer.
##### Technical calls (NEP-21 standard)
1. `alice` calls `dai::set_allowance({"escrow_account_id": "compound", "allowance": "1000000000000000000000"})`.
2. `alice` calls `compound::deposit({"token_contract": "dai", "amount": "1000000000000000000000"})`. During the `deposit` call, `compound` does the following:
1. makes async call `dai::transfer_from({"owner_id": "alice", "new_owner_id": "compound", "amount": "1000000000000000000000"})`.
2. attaches a callback `compound::on_transfer({"owner_id": "alice", "token_contract": "dai", "amount": "1000000000000000000000"})`.
</details>
##### High-level explanation
Alice needs to issue 1 transaction, as opposed to 2 with a typical escrow workflow.
##### Technical calls
1. `alice` calls `dai::ft_transfer_call({"receiver_id": "compound", "amount": "1000000000000000000000", "msg": "invest"})`. During the `ft_transfer_call` call, `dai` does the following:
1. makes async call `compound::ft_on_transfer({"sender_id": "alice", "amount": "1000000000000000000000", "msg": "invest"})`.
2. attaches a callback `dai::ft_resolve_transfer({"sender_id": "alice", "receiver_id": "compound", "amount": "1000000000000000000000"})`.
3. compound finishes investing, using all attached fungible tokens `compound::invest({…})` then returns the value of the tokens that weren't used or needed. In this case, Alice asked for the tokens to be invested, so it will return 0. (In some cases a method may not need to use all the fungible tokens, and would return the remainder.)
4. the `dai::ft_resolve_transfer` function receives success/failure of the promise. If success, it will contain the unused tokens. Then the `dai` contract uses simple arithmetic (not needed in this case) and updates the balance for Alice.
#### Swapping one token for another via an Automated Market Maker (AMM) like Uniswap
Alice wants to swap 5 wrapped NEAR (wNEAR) for BNNA tokens at current market rate, with less than 2% slippage.
##### Assumptions
- The wNEAR token contract is `wnear`.
- Alice's account is `alice`.
- The AMM's contract is `amm`.
- BNNA's contract is `bnna`.
- The precision ("decimals" in the metadata standard) on wNEAR contract is `10^24`.
- The 5 tokens is `5 * 10^24` or as a number is `5000000000000000000000000`.
##### High-level explanation
Alice needs to issue one transaction to wNEAR contract to transfer 5 tokens (multiplied by precision) to `amm`, specifying her desired action (swap), her destination token (BNNA) & maximum slippage (<2%) in `msg`.
Alice will probably make this call via a UI that knows how to construct `msg` in a way the `amm` contract will understand. However, it's possible that the `amm` contract itself may provide view functions which take desired action, destination token, & slippage as input and return data ready to pass to `msg` for `ft_transfer_call`. For the sake of this example, let's say `amm` implements a view function called `ft_data_to_msg`.
Alice needs to attach one yoctoNEAR. This will result in her seeing a confirmation page in her preferred NEAR wallet. NEAR wallet implementations will (eventually) attempt to provide useful information in this confirmation page, so receiver contracts should follow a strong convention in how they format `msg`. We will update this documentation with a recommendation, as community consensus emerges.
Altogether then, Alice may take two steps, though the first may be a background detail of the app she uses.
##### Technical calls
1. View `amm::ft_data_to_msg({ action: "swap", destination_token: "bnna", max_slip: 2 })`. Using [NEAR CLI](https://docs.near.org/docs/tools/near-cli):
```sh
near view amm ft_data_to_msg '{
"action": "swap",
"destination_token": "bnna",
"max_slip": 2
}'
```
Then Alice (or the app she uses) will hold onto the result and use it in the next step. Let's say this result is `"swap:bnna,2"`.
2. Call `wnear::ft_transfer_call`. Using NEAR CLI:
```sh
near call wnear ft_transfer_call '{
"receiver_id": "amm",
"amount": "5000000000000000000000000",
"msg": "swap:bnna,2"
}' --accountId alice --depositYocto 1
```
During the `ft_transfer_call` call, `wnear` does the following:
1. Decrease the balance of `alice` and increase the balance of `amm` by 5000000000000000000000000.
2. Makes async call `amm::ft_on_transfer({"sender_id": "alice", "amount": "5000000000000000000000000", "msg": "swap:bnna,2"})`.
3. Attaches a callback `wnear::ft_resolve_transfer({"sender_id": "alice", "receiver_id": "amm", "amount": "5000000000000000000000000"})`.
4. `amm` finishes the swap, either successfully swapping all 5 wNEAR within the desired slippage, or failing.
5. The `wnear::ft_resolve_transfer` function receives success/failure of the promise. Assuming `amm` implements all-or-nothing transfers (as in, it will not transfer less-than-the-specified amount in order to fulfill the slippage requirements), `wnear` will do nothing at this point if the swap succeeded, or it will decrease the balance of `amm` and increase the balance of `alice` by 5000000000000000000000000.
## Reference-level explanation
**NOTES**:
- All amounts, balances and allowance are limited by `U128` (max value `2**128 - 1`).
- Token standard uses JSON for serialization of arguments and results.
- Amounts in arguments and results have are serialized as Base-10 strings, e.g. `"100"`. This is done to avoid JSON limitation of max integer value of `2**53`.
- The contract must track the change in storage when adding to and removing from collections. This is not included in this core fungible token standard but instead in the [Storage Standard](../../StorageManagement.md).
- To prevent the deployed contract from being modified or deleted, it should not have any access keys on its account.
**Interface**:
```javascript
/************************************/
/* CHANGE METHODS on fungible token */
/************************************/
// Simple transfer to a receiver.
//
// Requirements:
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security purposes
// * Caller must have greater than or equal to the `amount` being requested
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the fungible tokens.
// * `amount`: the number of tokens to transfer, wrapped in quotes and treated
// like a string, although the number will be stored as an unsigned integer
// with 128 bits.
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer.
function ft_transfer(
receiver_id: string,
amount: string,
memo: string|null
): void {}
// Transfer tokens and call a method on a receiver contract. A successful
// workflow will end in a success execution outcome to the callback on the same
// contract at the method `ft_resolve_transfer`.
//
// You can think of this as being similar to attaching native NEAR tokens to a
// function call. It allows you to attach any Fungible Token in a call to a
// receiver contract.
//
// Requirements:
// * Caller of the method must attach a deposit of 1 yoctoⓃ for security
// purposes
// * Caller must have greater than or equal to the `amount` being requested
// * The receiving contract must implement `ft_on_transfer` according to the
// standard. If it does not, FT contract's `ft_resolve_transfer` MUST deal
// with the resulting failed cross-contract call and roll back the transfer.
// * Contract MUST implement the behavior described in `ft_resolve_transfer`
//
// Arguments:
// * `receiver_id`: the valid NEAR account receiving the fungible tokens.
// * `amount`: the number of tokens to transfer, wrapped in quotes and treated
// like a string, although the number will be stored as an unsigned integer
// with 128 bits.
// * `memo` (optional): for use cases that may benefit from indexing or
// providing information for a transfer.
// * `msg`: specifies information needed by the receiving contract in
// order to properly handle the transfer. Can indicate both a function to
// call and the parameters to pass to that function.
function ft_transfer_call(
receiver_id: string,
amount: string,
memo: string|null,
msg: string
): Promise {}
/****************************************/
/* CHANGE METHODS on receiving contract */
/****************************************/
// This function is implemented on the receiving contract.
// As mentioned, the `msg` argument contains information necessary for the receiving contract to know how to process the request. This may include method names and/or arguments.
// Returns a value, or a promise which resolves with a value. The value is the
// number of unused tokens in string form. For instance, if `amount` is 10 but only 9 are
// needed, it will return "1".
function ft_on_transfer(
sender_id: string,
amount: string,
msg: string
): string {}
/****************/
/* VIEW METHODS */
/****************/
// Returns the total supply of fungible tokens as a string representing the value as an unsigned 128-bit integer.
function ft_total_supply(): string {}
// Returns the balance of an account in string form representing a value as an unsigned 128-bit integer. If the account doesn't exist must returns `"0"`.
function ft_balance_of(
account_id: string
): string {}
```
The following behavior is required, but contract authors may name this function something other than the conventional `ft_resolve_transfer` used here.
```ts
// Finalize an `ft_transfer_call` chain of cross-contract calls.
//
// The `ft_transfer_call` process:
//
// 1. Sender calls `ft_transfer_call` on FT contract
// 2. FT contract transfers `amount` tokens from sender to receiver
// 3. FT contract calls `ft_on_transfer` on receiver contract
// 4+. [receiver contract may make other cross-contract calls]
// N. FT contract resolves promise chain with `ft_resolve_transfer`, and may
// refund sender some or all of original `amount`
//
// Requirements:
// * Contract MUST forbid calls to this function by any account except self
// * If promise chain failed, contract MUST revert token transfer
// * If promise chain resolves with a non-zero amount given as a string,
// contract MUST return this amount of tokens to `sender_id`
//
// Arguments:
// * `sender_id`: the sender of `ft_transfer_call`
// * `receiver_id`: the `receiver_id` argument given to `ft_transfer_call`
// * `amount`: the `amount` argument given to `ft_transfer_call`
//
// Returns a string representing a string version of an unsigned 128-bit
// integer of how many total tokens were spent by sender_id. Example: if sender
// calls `ft_transfer_call({ "amount": "100" })`, but `receiver_id` only uses
// 80, `ft_on_transfer` will resolve with `"20"`, and `ft_resolve_transfer`
// will return `"80"`.
function ft_resolve_transfer(
sender_id: string,
receiver_id: string,
amount: string
): string {}
```
## Drawbacks
- The `msg` argument to `ft_transfer` and `ft_transfer_call` is freeform, which may necessitate conventions.
- The paradigm of an escrow system may be familiar to developers and end users, and education on properly handling this in another contract may be needed.
## Future possibilities
- Support for multiple token types
- Minting and burning
## History
See also the discussions:
- [Fungible token core](https://github.com/near/NEPs/discussions/146#discussioncomment-298943)
- [Fungible token metadata](https://github.com/near/NEPs/discussions/148)
- [Storage standard](https://github.com/near/NEPs/discussions/145)
|
```bash
near call tkn.near create_token '{"args":{"owner_id": "bob.near","total_supply": "1000000000","metadata":{"spec": "ft-1.0.0","name": "Test Token","symbol": "TTTEST","icon": "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","decimals": 18}},"account_id": "bob.near"}' --gas 300000000000000 --depositYocto 2234830000000000000000000 --accountId bob.near
``` |
---
id: advanced-xcc
title: Complex Cross Contract Call
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
This example presents 3 instances of complex cross-contract calls. Particularly, it shows:
1. How to batch multiple function calls to a same contract.
2. How to call multiple contracts in parallel, each returning a different type.
3. Different ways of handling the responses in the callback.
:::info Simple Cross-Contract Calls
Check the tutorial on how to use [simple cross-contract calls](xcc.md)
:::
---
## Obtaining the Cross Contract Call Example
You have two options to start the Donation Example:
1. You can use the app through `Github Codespaces`, which will open a web-based interactive environment.
2. Clone the repository locally and use it from your computer.
| Codespaces | Clone locally |
| ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/near-examples/cross-contract-calls?quickstart=1) | 🌐 `https://github.com/near-examples/cross-contract-calls` |
---
## Structure of the Example
The smart contract is available in two flavors: Rust and JavaScript
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
┌── sandbox-ts # sandbox testing
│ ├── external-contracts
│ │ ├── counter.wasm
│ │ ├── guest-book.wasm
│ │ └── hello-near.wasm
│ └── main.ava.ts
├── src # contract's code
│ ├── internal
│ │ ├── batch_actions.ts
│ │ ├── constants.ts
│ │ ├── multiple_contracts.ts
│ │ ├── similar_contracts.ts
│ │ └── utils.ts
│ └── contract.ts
├── package.json
├── README.md
└── tsconfig.json
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
┌── tests # sandbox testing
│ ├── external-contracts
│ │ ├── counter.wasm
│ │ ├── guest-book.wasm
│ │ └── hello-near.wasm
│ └── main.ava.ts
├── src # contract's code
│ ├── batch_actions.rs
│ ├── lib.rs
│ ├── multiple_contracts.rs
│ └── similar_contracts.rs
├── Cargo.toml # package manager
├── README.md
└── rust-toolchain.toml
```
</TabItem>
</Tabs>
---
## Smart Contract
### Batch Actions
You can aggregate multiple actions directed towards one same contract into a batched transaction.
Methods called this way are executed sequentially, with the added benefit that, if one fails then
they **all get reverted**.
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="37" end="40" />
<Github fname="batch_actions.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/batch_actions.ts"
start="5" end="17" />
</Language>
<Language value="rust" language="rust">
<Github fname="batch_actions.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/batch_actions.rs"
start="7" end="19" />
</Language>
</CodeTabs>
#### Getting the Last Response
In this case, the callback has access to the value returned by the **last
action** from the chain.
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="42" end="45" />
<Github fname="batch_actions.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/batch_actions.ts"
start="19" end="29" />
<Github fname="utils.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/utils.ts"
start="3" end="20" />
</Language>
<Language value="rust" language="rust">
<Github fname="batch_actions.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/batch_actions.rs"
start="21" end="34" />
</Language>
</CodeTabs>
---
### Calling Multiple Contracts
A contract can call multiple other contracts. This creates multiple transactions that execute
all in parallel. If one of them fails the rest **ARE NOT REVERTED**.
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="47" end="50" />
<Github fname="multiple_contracts.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/multiple_contracts.ts"
start="6" end="21" />
</Language>
<Language value="rust" language="rust">
<Github fname="multiple_contracts.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/multiple_contracts.rs"
start="18" end="56" />
</Language>
</CodeTabs>
#### Getting All Responses
In this case, the callback has access to an **array of responses**, which have either the
value returned by each call, or an error message.
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="52" end="55" />
<Github fname="multiple_contracts.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/multiple_contracts.ts"
start="24" end="41" />
<Github fname="utils.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/utils.ts"
start="3" end="20" />
</Language>
<Language value="rust" language="rust">
<Github fname="multiple_contracts.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/multiple_contracts.rs"
start="58" end="92" />
</Language>
</CodeTabs>
---
### Multiple Calls - Same Result Type
This example is a particular case of the previous one ([Calling Multiple Contracts](#2-calling-multiple-contracts)).
It simply showcases a different way to check the results by directly accessing the `promise_result` array.
In this case, we call multiple contracts that will return the same type:
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="57" end="60" />
<Github fname="similar_contracts.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/similar_contracts.ts"
start="6" end="35" />
</Language>
<Language value="rust" language="rust">
<Github fname="similar_contracts.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/similar_contracts.rs"
start="7" end="30" />
</Language>
</CodeTabs>
#### Getting All Responses
In this case, the callback again has access to an **array of responses**, which we can iterate checking the
results.
<CodeTabs>
<Language value="js" language="js">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/contract.ts"
start="62" end="65" />
<Github fname="similar_contracts.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/similar_contracts.ts"
start="37" end="54" />
<Github fname="utils.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-ts/src/internal/utils.ts"
start="3" end="20" />
</Language>
<Language value="rust" language="rust">
<Github fname="similar_contracts.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-advanced-rs/src/similar_contracts.rs"
start="32" end="57" />
</Language>
</CodeTabs>
---
### Testing the Contract
The contract readily includes a set of unit and sandbox testing to validate its functionality. To execute the tests, run the following commands:
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
cd contract-advanced-ts
yarn
yarn test
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
cd contract-advanced-rs
cargo test
```
</TabItem>
</Tabs>
:::tip
The `integration tests` use a sandbox to create NEAR users and simulate interactions with the contract.
:::
<hr class="subsection" />
### Deploying the Contract to the NEAR network
In order to deploy the contract you will need to create a NEAR account.
<Tabs groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
```bash
# Optional - create an account
near create-account <accountId> --useFaucet
# Deploy the contract
cd contract-advanced-ts
yarn build
near deploy <accountId> ./build/cross_contract.wasm --initFunction init --initArgs '{"hello_account":"hello.near-example.testnet","guestbook_account":"guestbook_account.near-example.testnet","counter_account":"counter_account.near-example.testnet"}'
```
</TabItem>
<TabItem value="rust" label="🦀 Rust">
```bash
# Optional - create an account
near create-account <accountId> --useFaucet
# Deploy the contract
cd contract-advanced-rs
cargo near build
# During deploying pass {"hello_account":"hello.near-example.testnet","guestbook_account":"guestbook_account.near-example.testnet","counter_account":"counter_account.near-example.testnet"} as init arguments
cargo near deploy <accountId>
```
</TabItem>
</Tabs>
<hr class="subsection" />
### CLI: Interacting with the Contract
To interact with the contract through the console, you can use the following commands:
```bash
# Execute contracts sequentially
# Replace <accountId> with your account ID
near call <accountId> batch_actions --accountId <accountId> --gas 300000000000000
# Execute contracts in parallel
# Replace <accountId> with your account ID
near call <accountId> multiple_contracts --accountId <accountId> --gas 300000000000000
# Execute multiple instances of the same contract in parallel
# Replace <accountId> with your account ID
near call <accountId> similar_contracts --accountId <accountId> --gas 300000000000000
```
:::info
If at some point you get an "Exceeded the prepaid gas" error, try to increase the gas amount used within the functions when calling other contracts
:::
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `4.0.13`
- node: `18.19.1`
- rustc: `1.77.0`
:::
|
NEAR Foundation Launches NEAR Horizon
NEAR FOUNDATION
April 26, 2023
Though there have been recent signs of crypto winter thawing, developers have continued to make the most of the current builder’s market. NEAR, in particular, has seen significant growth in new projects and increased adoption over the past year.
NEAR’s expansion is due in part to some significant upgrades and announcements from its core team. Most recently, NEAR announced its transition to a Blockchain Operating System (BOS), an industry first that further establishes NEAR as the direct entry point into Web3. With the BOS, NEAR is no longer just a Layer 1 — it’s the OS for an open web, free from the centralized platforms of Web2.
During the announcement, NEAR co-founder Illia Polosukhin signaled that the transition to the BOS was just the beginning of what’s to come for NEAR. With Consensus in full swing, and NEAR’s presence at the conference, many Web3 enthusiasts and NEAR community members anticipate more exciting announcements and were not disappointed.
At Consensus, NEAR Foundation announced NEAR Horizon, an accelerator revolutionizing how founders are supported in Web3. Made possible through partnerships with Dragonfly, Pantera, Lyric, Fabric Ventures, Decasonic, Hashed, and others, NEAR Horizon will enable founding teams to scale their projects with a wide range of support. This support will, in turn, enable the rapid growth of great products with real-world value in the NEAR ecosystem.
A revolutionary accelerator for Web3 startups
NEAR Horizon is an exciting opportunity for founder teams looking to build their startups on the BOS. Startups can interact with NEAR Horizon through a double-sided marketplace application that connects founders to each other, and to the people and organizations who are best able to accelerate their growth.
At launch, the marketplace will include over 15 service providers, 40 mentors, and over 300 backers. Founders in the NEAR ecosystem will have direct self-service access to NEAR Horizon, allowing them to make the connections and generate the resources that will help them succeed. In addition to these immediate resources, founders can apply for credits that cover service costs in critical development areas including marketing, legal, back-office finance, product, and infrastructure.
For founders looking for additional support and guidance throughout their Horizon journey, the platform will also be equipped with programs facilitated through a NEAR Foundation partner, providing mentorship, business resources, and a direct line to startup capital. These programs are available through a wide range of industry leading groups including Antler, Brinc, FabricX, CV Labs, Blockchain Founders Group, among others. Regardless of the path founders choose to take, NEAR Horizon will provide them with the support they need when they need it most to accelerate the growth of their Web3 projects built on NEAR.
As crypto winter’s thawing hopefully promises the arrival of a crypto spring, NEAR is continuing to build momentum with both founders and investors in the Web3 community. With higher transaction speeds than Ethereum, a strong commitment to its ecosystem, and an industry-first Blockchain Operating System, NEAR has created a direct path toward success for founders.
Interested in getting involved? Over the next couple of months, the NEAR Foundation will be onboarding projects and founders to NEAR Horizon. If you don’t want to miss the introductions, advice, capital, or hires that come from the marketplace, reach out and get involved today:
|
NEAR Integrates Wormhole to Launch ZK-Enabled Cross-Chain Communication with Ethereum
NEAR FOUNDATION
May 16, 2023
Driving the evolution of Web3 through innovation and interoperability, bridging technology has become a critical factor in user adoption and functionality. NEAR Foundation has chosen to bolster its multi-chain interoperability by integrating with Wormhole, harnessing the power of cutting-edge Zero-Knowledge (ZK) light clients.
This strategic move revolutionizes secure Web3 application communication, unlocking vast potential across diverse sectors including DeFi, NFTs, and governance. The integration represents a tangible stride towards a less abstract and more interconnected, trustless Web3. By incorporating Wormhole’s technology, NEAR Foundation envisions a practical shift where cross-chain transactions become efficient, secure, and user-friendly.
NEAR’s unique position as a developer-friendly platform amplifies the impact of this integration, driving the adoption of Zero-Knowledge technology to a wider audience. The NEAR Foundation is not just creating a world of possibility but is actively building it, bringing advanced blockchain solutions to the mainstream.
Signaling a new era of trustless cross-chain communication, this NEAR-Wormhole integration will be explored through the NEAR <> ETH corridor and the promise of Zero-Knowledge bridging.
Wormhole: the key to NEAR’s vision of a multi-chain Web3
Wormhole is forging its place in crypto as the industry-standard cross-chain messaging protocol, reliably facilitating transfers exceeding $35 billion dollars via countless cross-chain messages. In this integration, Wormhole’s role is vital, employing its advanced technology to connect the NEAR ecosystem with over 20 other high-value blockchain networks.
The integration enables synergy of Wormhole Connect’s technology with NEAR’s Blockchain Operating System (BOS) to enhance developer access to multiple chains and diverse liquidity. It will also serve to break down barriers for casual users, blending complex blockchain tech with a user-friendly experience.
Moreover, Wormhole’s integration with NEAR’s BOS presents a significant opportunity for businesses using NEAR. This collaboration simplifies multi-chain interaction and introduces Zero-Knowledge proofs, making it easier for businesses to fully utilize blockchain technology in a straightforward and accessible manner.
Wormhole’s NEAR <> ETH corridor opens opportunities
Born from this integration is the trustless NEAR <> ETH corridor, an innovation powered by Wormhole and secured by Zero-Knowledge (ZK) Proofs. This marks a shift from NEAR’s traditional Rainbow Bridge, introducing seamless integration of NEAR assets with Wormhole-linked chains.
The NEAR <> ETH corridor represents a new class of zk-enabled bridges, offering heightened interconnectedness between the NEAR ecosystem and a multitude of Wormhole-facilitated applications. This trustless corridor is poised to catalyze more efficient and secure transactions, symbolizing a substantial stride toward a fully interoperable Web3 ecosystem.
Making tomorrow’s crypto-verse trustless and ZK-based
The NEAR and Wormhole integration isn’t just a stride toward the future — it’s a giant leap toward a new era powered by ZK Proofs. As part of the integration work, developers are building the first ZK light clients, which will play a crucial role in supporting the trustless NEAR <> ETH corridor.
ZK light clients promise to revolutionize the bridging experience, discarding the need for trust assumptions and external validation. By offloading most of the computational load to an off-chain entity, these clients optimize storage and compute resources, paving the way for a streamlined and efficient bridging process. This innovation is set to redefine the standards of security and reliability in the blockchain sector.
The integration between NEAR and Wormhole is a decisive step towards a future where cross-chain communication is seamless, secure, and trustless. It’s a future that opens up new horizons for developers and users alike, offering improved interoperability and accessibility.
With Wormhole, NEAR citizens can engage and interact with other chains in a blink of an eye.
|
NEAR Foundation Backs Hydra Ventures to Create Web3’s First ‘Fund of Funds’ Investment DAO
NEAR FOUNDATION
March 29, 2023
NEAR Foundation is excited to announce that it has joined Hydra Ventures, a “fund of funds” investment DAO. A first in the Web3 space, Hydra Ventures is designed to help other investment DAOs get off the ground.
By partnering with NEAR Foundation, Hydra Ventures will open the doors to the eventual launch of the first investment DAO in the Near ecosystem.
“The combined expertise of the leaders that have created this fund offers a winning formula that will help provide critical funding to purpose-driven, socially impactful web3 startups,” said Marieke Flament, CEO of NEAR Foundation. “We are delighted to be playing a part in launching this DAO and look forward to seeing the role it will play in developing our ecosystem.”
Decentralizing Web3 investment with DAOs
To power the “fund of funds” investment DAO, Hydra Ventures has raised $10M in capital from NEAR Foundation, MetaCartel Ventures, ConsenSys, 1kx Ventures, Collab + Currency, Nonagon Ventures, CMT Digital, among others. Hydra Ventures aims to take a hands-on approach to support investment DAOs, from community coordination and investment practices to organizational design, incentive design, and back office/operations.
“While the first legally wrapped investment DAOs showed us what was possible, many of them have had major operating flaws which have been exposed over the years,” said Peter Pan, co-summoner of MetaCartel and Partner at 1kx Ventures. “Hydra looks to address many of these problems and ultimately emerge with a fundamentally better model for how investment DAOs should be operated. We are thrilled to have NEAR Foundation’s support in this venture.”
Hydra Ventures is incubated by Thing3 and MetaCartel Ventures (the first and one of the most successful investment DAOs created), and backed by leading founders and thinkers in Web3. MetaCartel has incubated and made investments in several category-leading projects like Sky Mavis, Axie Infinity, Arweave, Open Zeppelin, DAOhaus, Zapper Finance, and Rarible, and were also one of the first investors in Mintbase, an NFT marketplace built on Near. MetaCartel members include Ameen Soleimani (founder, Moloch DAO), Stani Kulechov (founder, AAVE), Roneil Rumburg (founder, Audius), Bobby Ong (founder, Coingecko), RAC (Grammy award winner), Peter Pan (Partner, 1kx Ventures), amongst others.
|
NEAR & Social Good: A Deep Dive Into Open Forest Protocol
COMMUNITY
July 25, 2022
Humans are waking up to the ecological and psychological benefits of forests. And if civilization is to tackle climate change, then protecting and regenerating forests is one incredibly important tactic.
But slow and complicated processes dominate the forestation industry, as do high costs and little transparency. This is particularly true in the carbon credit industry, where companies offset their fossil fuel consumption by buying and trading credits derived from forest projects.
Enter regenerative finance, or “ReFi”, in Web3 parlance. ReFi projects like Open Forest Protocol are using smart contracts to transform how we understand the value of forests. They are bringing much needed transparency, high quality data, and funding opportunities to small and medium sized forest projects and securities.
With increasing calls to mitigate the effects of climate change, ReFi couldn’t have arrived at a better time. Built on NEAR, OFP is one of a growing number of ReFi projects illuminating a path for how decentralized communities can have positive, real world impact on the environment.
To get a better sense of how Web3 is tackling ecological issues, let’s take a look at Open Forest Protocol.
Forest projects before the blockchain
Before crypto, there was much to like about reforestation and forest conservation efforts, says Frederic Fournier, CEO and Co-founder of Open Forest Protocol. He notes that the industry created a common understanding around methodologies used for measuring, reporting and verifying (MRV) tree planting and carbon credits.
“[But] there is very little to no digital transformation in the industry,” says Fournier, who previously worked in the environmental consulting sector, and managed an NGO that supported sustainable reforestation projects. “Meaning the processes are slow, complicated, expensive and not transparent.”
Olga Dyka, OFP’s Chief Operating Officer, notes that while MRV methodologies are well-developed, none are comprehensive. And although these methodologies can work in Web3, there is rarely room for future developments or improvements.
“There is also a lack of financing for small or medium-sized projects to ‘get off’ the ground,” she says. “The lack of transparency is that forestation still follows a ‘carbon-sequestered-on paper’ approach in carbon credits generation, offsets, and trade.”
Inside OFP’s smart forest contracts
With Web3, forestration projects can streamline their work in a multiple stakeholder environment. In just a few clicks, anyone can access verified, high quality, and immutable data.
“It will bring transparency and trust in a system that is today opaque,” says Fournier. “Everyone will have access to the best MRV tools.”
As Dyka notes, these MRV tools will be free. Reforesting and conserving forests with Web3 technology will, according to Fournier, create a community-based approach. Ideally, it will upend the industry’s siloed and centralized status quo.
“It will give power to communities and people to value their restoration work,” he says. “And another mindset about how to scale in an open and transparent way.”
With standardized, accessible MRV tools, OFP can open doors for offsetting and carbon credits trading on its protocol. While OFP is still developing these features, the team can easily implement with NEAR smart contracts.
“It also creates the possibility for many decentralized apps to be built on top of OFP protocol to benefit forestation beyond MRV,” says Dyka.
To give users access to MRV data, OFP’s smart contracts primarily manage the protocol’s cyclical data upload and validation processes. When a forest project leader uses OFP to measure their trees’ biomass and report on the forest’s health, they interact with the protocol’s front-end interfaces. Project managers can upload certain data points about their trees, such as measurements and photos of individual trees.
After being compiled in IPFS, these data points are sent at regular intervals to OFP’s distributed group of data validators. Think of these validators as data auditors. They evaluate the legitimacy of the reported data, then assign a binary affirm/deny judgment to each data upload.
“This judgment is recorded in the project’s data and saved on NEAR’s blockchain,” says Luke Schubert, OFP’s Product Development Lead. “The entire cycle begins again with the forest project manager collecting more data. We have additional smart contracts in development that will enable nature-based asset generation and results-based financing.”
All OFP users must first create a NEAR account, where forest data is stored as utility NFTs representing individual forest projects. OFP’s dashboard automatically update this forest data over time.
“We were surprised by how easy it was to integrate the necessary functions of OFP into the larger NEAR infrastructure,” says Schubert. “And the standardized token contracts enabled reliable NFT creation and management.
Beyond OFP’s front-end and smart contracts, the platform developed and released a mobile app called “Forester” that can collect tree data from the field.
“The mobile app works offline, enables geo-fenced data collected, and provides a single-directional feed of information from forests to the NEAR blockchain,” says Schubert. “This app is the first of many tools we will provide for forest project managers to report on what is happening within their forests.”
Social good on Open Forest Protocol
While it’s one thing to disrupt the forestation industry, the community-based approach that OFP pursues will also elevate social good.
For Fournier, one particular social good would be an onboarding process that is easy and open for all. Making OFP’s tools free to use, while allowing generating incentives to profit for the planet and its people, are also game changers.
“OFP creates opportunities for communities to directly participate in combating the climate crisis along with other stakeholders (‘one person effort also matters’),” says Dyka. “The platform also creates equal opportunities for forestation companies in gaining access to forestation financing which overall results in scaling forestation worldwide.”
The OFP team also sees the protocol empowering both the crypto and climate communities. OFP is an application with real world impact through people and their environment. It can be a model for other Web3 projects working to integrate with traditional industries and the real, physical world.
“It’s a concrete project that these communities can understand and get involved in,” Fournier says. “They can see a concrete application of blockchain. It’s a way to create interest in Web3 and its potential applications.”
But OFP will also have an impact beyond giving small to medium-sized projects, says Rim Berjack, OFP’s Community Development Officer. The protocol will also benefit local communities and indigenous peoples who depend on forests for their way of life.
“We want to provide a viable alternative to local forest communities and indigenous peoples who depend on their forests, who have been exploited by people using their resources,” says Berjack. “We want to put the MRV and financing tools in their hands. I think more than anything this is a form of social good we are the most excited about. Autonomy and empowerment, which brought many of us to blockchain in the first place.”
Investing in smaller forest projects
OFP can also impact communities, farmers and land stewards by proposing an answer to their restoration efforts. With OFP’s help, the people can support and scale their forest and land use efforts.
As Dyka points out, small and medium-sized projects in developing communities are getting MRV tools through the OFP dashboard. They now have the ability to run a project in a transparent way. This gives projects more credibility in getting access to potential investors and financial donors. In turn, this will lead to more workplaces and better living conditions in specific regions.
“Basically, we’re making financial access happen for people who maybe didn’t have it,” says Dyka. “To me it’s about creating equal opportunities wherever people are.”
“My background is in law, and, as lawyers, we’re always in a fight with somebody for something, being in a constant pursuit of truth, equality and fairness for everyone,” she says. “And for me, building OFP is about fighting for truthfulness in the current state of forestation by bringing metrics on public immutable blockchain, which, in turns, unlocks financing for forestation, available everywhere and for everyone.”
“We are revolutionizing the forestation industry, and we are bringing transparency on-chain—that’s important,” she adds.
Aside from Web3 technology, Fournier believes long-term vision and an entrepreneurial spirit is necessary for new players. Project leaders must envision these efforts over 10 to 20-year timeframes and beyond, if they’re serious about reforestation and forest conservation.
Going it alone as a forestation startup is most likely impossible. New projects usually seek out the help of non-governmental organizations (NGOs). Fournier says this is common in Kenya, where there are many social and environmental NGOs.
With OFP, there is now another path.
“If you provide projects with adequate tools and pre-financing that will come in the second stage with OFP, they could very well start a very small project—a few hectares of restoration—from scratch because it’s completely possible,” says Fournier. “And if they do a good job at that, then they can scale from there and get bigger and bigger.”
The future of OFP and ReFi
Unlike the traditional forestation industry, OFP has plans to keep building and evolving. Over time, more exciting products will build atop OFP’s existing MRV stack. Imagine, for instance, an OFP starter that could be a finance mechanism for projects.
“There will also be integration with other projects in the Web3 space. Especially integration with carbon credits providers, executing partnerships with other like minded initiatives, and so on,” Fournier says. “The economic downturn turns out to be an opportunity for OFP. It gives us the space to focus on building and communicating about the project’s long term positioning.”
Schubert envisions OFP’s smart contracts evolving in many ways. In the coming months, the team will be open sourcing the OFP codebase.
“This will enable really cool natural asset financing tools and novel nature-based climate solutions to be built on top of OFP and use the validation oracle we have created,” Schubert explains. “So, while our core smart contracts that manage the cyclical data upload and validation processes might not fundamentally change in the future, new solutions can be developed and plugged into the existing OFP ecosystem.”
Ultimately, OFP plans to create the biggest global ground platform for any and all forestation companies across the globe.
“They will be able to run a project with us and to create a strong community of various stakeholders, who will ensure transparency,” she says. “The world can go through an economic downturn, there may be conflicts, wars, profit or deficits or other force-majeurs, but nobody canceled the next decade’s 1.5C degree temperature rise and the fact that we all somehow are going to live with that. So, we have to keep moving and OFP has stable financing to run the project to reach the planned goals.” |
---
title: DAO Legal Discussion
description: Guidance to setting up a DAO without running into any legal issues
---
# DAO Legal Discussion
Guidance to setting up a DAO without running into any legal issues
:::info on this page
* A Decentralized Autonomous Organization (DAO) is not a recognized legal entity type in any jurisdiction yet and is subject to different interpretations by judges, courts, and regulators.
* A DAO should be truly decentralized or have a legal entity/"wrapper" associated with it and perform any necessary KYC relevant to its actions to provide actual functionality and legal protection.
* "DAOs" which are actually just a shared account do not provide any legal protections and should simply be considered an account of whatever group or organization controls it. DAOs need to consider taxes and employment law like any other legally recognized organization.
:::
:::note
_The information provided here does not constitute legal advice. All information and content are for general informational purposes only. You should consult your own lawyer to obtain advice with respect to any particular legal matter in the relevant jurisdiction. Only your individual lawyer can make sure that the information contained here and your interpretation of it, is applicable or appropriate to your particular situation. Please note that all existing ideas around DAO issues are not yet court-verified and could potentially fail. However, there is value in starting a discussion of how to make DAOs become legally viable solutions and add value to society._
:::
## **TLDR Summary**
* If your DAO is not truly decentralised and does not have a legal form (or "wrapper") around it, it should be considered "at risk", meaning its members are bearing significant liability.
* Simply using a smart contract that creates a multisig structure and/or spinning up a Discord channel for people to direct those funds and calling it a "DAO" doesn't change that. Members are legally responsible for what happens with funds and actions. "DAOs" which are actually just a shared account do not provide any legal protections and should simply be considered an account of whatever group or organisation controls it.
* To provide actual functionality and legal protection for a DAO, it should be truly decentralised (no single entity or person has control) or have a legal entity/"wrapper" associated with it (like a US LLC or Swiss Association) and perform any necessary KYC relevant to its actions.
* DAOs need to consider taxes and employment law like any other legally recognised organisation.
## Introduction
The Decentralised Autonomous Organisation ([DAO](https://en.wikipedia.org/wiki/Decentralized\_autonomous\_organization)) is a fantastic blockchain technology application in the context of social coordination. Implemented and applied well, the DAO can provide an attractive alternative to traditional collaboration frameworks (legal entities, 1 to 1 agreements) in certain contexts. As DAOs haven’t been addressed much by lawmakers yet, there is uncertainty concerning their legal treatment in most jurisdictions. This post is discussing a few non-binding thoughts on applying DAOs with some ideas on how to potentially solve legal challenges.
## Your Intentions
While it is understood that this post is non-binding, there is one particular piece of advice that one can give whole-heartedly. Please do not set up a DAO with the target to circumvent any law or regulation, as this attitude will likely put you on a path of conflict and failure. Instead, initiate a DAO with the best of your intentions to provide a solution to challenges of your ecosystem while keeping an eye on mitigating any negative externalities.
## What is a DAO?
A DAO is a number of people coming together to complete a mission together in an organised manner by using a set of smart contracts that provide governance functionality (voting, multi-signature execution, interface). The smart contracts themselves do not constitute a DAO yet. It is rather the collective actions of the participants through the smart contracts that inhale life into the DAO. There isn’t a specific number of participants defined that constitute the decentralisation of a DAO, but it should be many. Also there shouldn’t be any single party controlling the DAO. Otherwise, it isn’t autonomous. DAOs are essentially a cooperative of people sharing a pool of assets. A DAO isn’t a recognised legal entity type in any jurisdiction yet. Its implementation results in legal uncertainty, as it is subject to different interpretations by judges, courts, and regulators.
## Responsibility
Everyone is responsible for their own actions. This is one of the key underlying assumptions of every legal framework. There is an exception. Legal entities allow shifting certain responsibilities from the individual to a legal construct: a company, a foundation, an association and so on. However certain responsibilities always remain with the individuals. For example, individuals remain subject to criminal law. As DAOs are not legal entities by themselves, most jurisdictions assume that individuals remain responsible for their actions with the DAOs and treat it as a general partnership.If DAOs are truly decentralised then no individual person can be identified to have taken any specific action. If DAOs are not well decentralised, introducing a legal wrapper (for example a Swiss Association ("Verein")) for the DAO might make sense to protect the DAO participants from certain liabilities. If a DAO is not specifically organised with a legal wrapper around it, the following uncertainties arise:
* DAOs are currently **not recognised** legal actors **in any jurisdiction**, and thus become subject to unexpected interpretations by various stakeholders.
* By lack of legal recognition, DAOs can be considered a mental concept shared among its participants only. Thus, DAOs generally are typically **unable to interact** with third parties or governmental actors in their own capacity. This means they can't execute contracts.
* DAOs are at risk of being considered general partnerships. **EACH DAO partner** would then be held jointly and severally **responsible for all liabilities of the DAO’s actions**, and all personal assets of each partner may be subject to seizure to meet the liabilities of the DAO (unlimited liability of each DAO participant).
## Safety for the DAO <a href="#safety-for-the-dao" id="safety-for-the-dao"></a>
There are several things you can do to reduce risk of running into any issues when setting up a DAO and limiting liability.
### Technical Development of the DAO
As the developer of DAO smart contract system, your liability is expected to remain limited or be none as long as you don’t retain any control over the smart contracts. This is similar to how software developers of banking systems are not actually responsible for their ultimate use. Nevertheless, expect that regulators knock on your door for a discussion about your creations if they can’t find any other “responsible person” to talk to. There might be good reasons why Satoshi preferred to remain anonymous.
### Setting up the DAO
When you set up a DAO, introduce many participants who can only exercise control through collective action. Have the DAO operate in areas considered legal and avoid regulated business activities (acting as a bank, exchange, investment vehicle, financial intermediary, gambling, or any illicit activities). Establish a vision statement and a [DAO Constitution](https://blog.kleros.io/how-to-write-your-dao-constitution-and-become-a-founding-father/) that help align the participants on the good cause and fosters an ongoing discussion about how to avoid negative externalities of the DAO to the general public.
### Funding the DAO
Before funding a DAO, try to identify the participants of the DAO, to obtain a view of their good standing. Check the past and proposed activities of the DAO for any activities that could reflect poorly on yourself or the organisation you might be representing. Before you transfer the funds, obtain proper documentation on the purpose of the transfer. Try to obtain an invoice (e.g. from the legal wrapper of the DAO) that describes the purpose of the contribution to the DAO. If you cannot obtain an invoice, do your own write-up including a justification for the contribution, e.g. by extracting information in the form of PDFs from the forum posts that led up to your contribution. Check what documentation is required in your jurisdiction as a legal proof e.g. for any tax audit. Do not retain any rights in funds after you transfer them to the DAO. Do not seek to retain any control over the DAO, as control introduces responsibility.
### Operating the DAO
Decisions should be taken by the broader collective of the DAO. If any decisions can be accrued to any single individuals, these people are responsible for their decisions and derived actions. Responsibility is desired as long as the decision, the derived actions, and outcomes don’t cause any issues. Don’t try to control the DAO. If anyone controls the DAO, it isn’t a DAO anymore. It is just someone operating through a set of smart contracts. Promote a healthy discourse on the actions of the DAO. Make improvement proposals to address any negative externalities and issues emerging over the lifetime of the DAO. Engage in a dialogue with all stakeholders including politicians, lawmakers, and regulators.
### Using the DAO Tools for Other Purposes
Of course, you can also deploy and use the DAO smart contract toolset without forming a true DAO and use the tools more or less like a regular multisig, e.g. to simplify operations of your organisation. In that case, make sure to put in place all the compliance measures that are standard to operating in a traditional business environment.
## **Legal Wrapping of a DAO**
A “Legal wrapper” in whatever jurisdiction it’s set up, can provide the required legal basis to interface with the authorities. Moreover, the legal entity put in place helps shielding liabilities from the participants of the DAO. The draw back is that the legal wrapper requires compliance with the laws of the applicable jurisdictions which can restrict the DAO to meet its full purpose and results in an administrative overhead.
### Switzerland as an Attractive Jurisdiction for Legal Wrapping
Switzerland has earned itself the reputation of providing a crypto-friendly jurisdiction. The collaboration with authorities is excellent, allowing legit crypto projects to realise their visions on a path in compliance with regulations. Local advisors have accumulated extensive crypto expertise and support a quick and efficient setup. The Swiss Association ("Verein") has become a popular model for legal wapping of DAOs that are not meant to be a profit-seeking organisation.
The Swiss Association is governed by the articles 60 et seq. of the Swiss Civil Code. An association does not require approval from any authorities in order to setup in Switzerland and thus does not require registration in the corporate registry if it does not pursue a business purpose (target to generate recurring income). However under certain circumstances, it must fill a tax declarations. The statutes of the association can establish that members have no individual responsibility and liability. The creation of an association does not entail any 3rd party cost. [Here](https://www.cagi.ch/en/practical-infos/creating-an-association/) you can find basic information on the Association setup requirements.
We advise to consult your lawyer to choose the right structure that will meet the goals of your organisation which is different from project to project. [Matthias Kuert of CMS](https://cms.law/en/che/people/matthias-kuert), [Thomas Linder of MME](https://www.mme.ch/de/team/thomas\_linder/), and [Raphael Baumann of PST](https://www.pst-legalconsulting.ch/raphael-baumann-de) are crypto-experienced legal experts for structuring and setting up legal entities in Switzerland. MME and [Silvan Amberg of SwissTaxExpert](https://www.swisstaxexpert.com/about-me/) can help with any tax topic arising. [Roger Rohner and Mario Erni of Retax](https://retax.ch) will also be at your disposition for Swiss VAT and Swiss personal tax topics. Accounting can be taken care of by the accounting firm [Cleverkin](https://www.cleverkin.one/team) that fully specialises in servicing crypto projects. Financial audit services, if necessary, are provided by [Copartner](https://www.copartner.ch) and [Wadsack](https://www.wadsack.ch).
An alternative to Switzerland for legal wrapping can be found in Vermont, i.e. the hybrid entity model called “Blockchain based LLC” [here](https://github.com/dOrgTech/LL-DAO/blob/master/guidelines/bbllc.md), including the Operating agreement as a template of BBLLC [here](https://github.com/dOrgTech/LL-DAO/blob/master/templates/dOrg-BBLLC-Operating-Agreement.md).
Wyoming’s state senate passed a bill called the Decentralised Autonomous Organisations Supplement (DAO Supplement), with the target to clarify the legal status of the decentralised autonomous organisation (DAO). You can proceed with registration [here](https://app.wyomingllcattorney.com/intake?\_ga=2.195102063.292922569.1636708712-614970791.1636708712).
|
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
const tokenData = Near.view("nft.primitives.near", "nft_token", {
token_id: "1",
});
```
<details>
<summary> Example response </summary>
```json
{
"token_id": "1",
"owner_id": "bob.near",
"metadata": {
"title": "string", // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055"
"description": "string", // free-form description
"media": "string", // URL to associated media, preferably to decentralized, content-addressed storage
"media_hash": "string", // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included.
"copies": 1, // number of copies of this set of metadata in existence when token was minted.
"issued_at": 1642053411068358156, // When token was issued or minted, Unix epoch in milliseconds
"expires_at": 1642053411168358156, // When token expires, Unix epoch in milliseconds
"starts_at": 1642053411068358156, // When token starts being valid, Unix epoch in milliseconds
"updated_at": 1642053411068358156, // When token was last updated, Unix epoch in milliseconds
"extra": "string", // anything extra the NFT wants to store on-chain. Can be stringified JSON.
"reference": "string", // URL to an off-chain JSON file with more info.
"reference_hash": "string" // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included.
}
}
```
</details>
</TabItem>
<TabItem value="Paras" label="Paras">
```js
const tokenData = fetch("https://api-v2-mainnet.paras.id/token?token_id=84686:1154");
```
<details>
<summary> Example response </summary>
```json
{
"status": 1,
"data": {
"results": [
{
"_id": "61dfbf27284abc1cc0b87c9d",
"contract_id": "x.paras.near",
"token_id": "84686:1154",
"owner_id": "bob.near",
"token_series_id": "84686",
"edition_id": "1154",
"metadata": {
"title": "Tokenfox Silver Coin #1154",
"description": "Holding this silver coin in your wallet will bring you health and happiness \uD83D\uDE0A",
"media": "bafkreihpapfu7rzsmejjgl2twllge6pbrfmqaahj2wkz6nq55c6trhhtrq",
"media_hash": null,
"copies": 4063,
"issued_at": null,
"expires_at": null,
"starts_at": null,
"updated_at": null,
"extra": null,
"reference": "bafkreib6uj5kxbadfvf6qes5flema7jx6u5dj5zyqcneaoyqqzlm6kpu5a",
"reference_hash": null,
"collection": "Tokenfox Collection Cards",
"collection_id": "tokenfox-collection-cards-by-tokenfoxnear",
"creator_id": "tokenfox.near",
"blurhash": "U7F~gc00_3D%00~q4n%M_39F-;RjM{xuWBRj",
"score": 0,
"mime_type": "image/png"
},
"royalty": {
"tokenfox.near": 1000
},
"price": null,
"approval_id": null,
"ft_token_id": null,
"has_price": null,
"is_creator": true,
"total_likes": 8,
"likes": null,
"categories": [],
"view": 4
}
],
"count": 1,
"skip": 0,
"limit": 10
}
}
```
</details>
:::info
See the [Paras API documentation](https://parashq.github.io/) for the full list of methods.
:::
:::note
Paras API methods returns data from all NFT contracts in NEAR. You might want to pass more parameters like `contract_id` or `owner_id` to make the response more accurate.
:::
</TabItem>
<TabItem value="Mintbase" label="Mintbase">
```js
const tokenData = fetch("https://graph.mintbase.xyz", {
method: "POST",
headers: {
"mb-api-key": "anon",
"Content-Type": "application/json",
"x-hasura-role": "anonymous",
},
body: JSON.stringify({
query: `
query getToken{
tokens: nft_tokens(
where: {
token_id: { _eq: "84686:1154" }
}
) {
tokenId: token_id
ownerId: owner
contractId: nft_contract_id
reference
issuedAt: issued_at
copies
metadataId: metadata_id
}
}
`,
}),
});
```
<details>
<summary> Example response </summary>
```json
{
"ok": true,
"status": 200,
"contentType": "application/json",
"body": {
"data": {
"tokens": [
{
"tokenId": "84686:1154",
"ownerId": "bob.near",
"contractId": "x.paras.near",
"reference": "bafkreib6uj5kxbadfvf6qes5flema7jx6u5dj5zyqcneaoyqqzlm6kpu5a",
"issuedAt": "2022-01-13T05:56:51.068358",
"copies": 4063,
"metadataId": "x.paras.near:5210047642790498956c9669d6a37b98"
}
]
}
}
}
```
</details>
:::note
In the future, users may be required to register using an api key. For now, simply passing the value `anon` for `mb-api-key` will work.
:::
</TabItem>
</Tabs>
|
---
description: Secure way to lock NEAR tokens for a period of time
title: Token Launch Considerations
---
# Launching a Token: Key Considerations:
Launching a token for the first time is a make it or break-it moment for your project. Failing to prepare for a token launch can ruin years of product and business development work. Successfully launching your token can expedite visibility and engagement with your project, and also provide an easier pathway to fundraising and treasury management in the future.
#### Below is a suggested ‘order of operations’ for successful launching and listing a token:
* **The Launching Entity: A (Swiss or Offshore) Foundation.** Whenever we discuss ‘crypto-economics’ we need to make sure we are in the regulatory clear to promote a token. Having this done from a foundation is an essential first step in doing anything public with your crypto-economy and by extension your token launch and listing strategy.
* **Public Information About The Crypto-Economy:** To have anyone take your token seriously, you need to give them the details pertaining to your crypto-economy. This has to do with supply, distribution, emissions over time, function of token, and so forth. A good example of this is what NEAR did in preparation for their token launch: [https://near.org/blog/near-token-supply-and-distribution/](https://near.org/blog/near-token-supply-and-distribution/).
* **Get Listed on Coinmarketcap and Coingecko:** Once you have publicly available information about your crypto-economy, we can start moving to get your token visible to the general public: Exchanges, token listing platforms, marketmakers, and retail of course. To do this you want to list your token on Coinmarketcap and Coingecko. Simply fill out the form to get the process started - and make sure you have accounted for all of the relevant information they ask for!
* **Engage with Different Launch Pads:** If you are planning on doing a public token sale, you will want to collect a list of launch pads depending on the focus of your project and where you would like to eventually list your project. Many projects launch on exchange launchpads, and then subsequently list on those exchanges. Other launchpads are ecosystem specific: Ethereum, Binance Smart Chain and so forth, and harvest large investments from whales within their ecosystems. If you are deploying your token on NEAR you will also want to consider the logistics of making sure that token can be bridged back and forth should you choose to launch in another ecosystem.
* **Preparing Token Listing by Contacting Exchanges:** A list of both [exchanges ](https://coinmarketcap.com/rankings/exchanges/)and [DEXs ](https://coinmarketcap.com/rankings/exchanges/dex/)is available on coinmarketcap. Depending on your location and regulatory requirements (usually you cannot list in the USA for the first year), you will want to begin outreach to relevant exchanges for listing your token once it has launched. This can be done in parallel to the launch pad discussion, as oftentimes there is significant overlap between the two (An exchange will also have their own launchpad). Work with your investors, the NEAR Foundation, and other ecosystem partners to set up telegram groups or email threads that can get the relevant information in place for a successful listing plan.
* **Aligning Market Makers:** In order to ensure that there is liquidity for your token to trade with, you want to make sure that you have signed market makers for when your token launches. Top market makers include GSR, Wintermute and Amber, however many exist. Be sure to ask for recommendations from your investors and to double check any agreements as to the conditions for how they hold and manage your token over time.
* **Market Making Accountability Mechanisms:** A new up-and-coming service in crypto is accountability tools and mechanisms for market makers. Services such as **_[Glassmarkets ](https://glassmarkets.io/)_** can guarantee that there is transparency in how a market maker handles your tokens.
* **Token Listing Strategy:** Once you have aligned market makers and potential listing partners (be it DEX or CEX), you want to strategically decide where to list first - keep in mind that listing on too many platforms too quickly may limit liquidity and trading potential.
* **Cycle Timing:** Crypto is still young enough that the macro cycle of bull and bear market has a significant impact on the performance of a token; its volume, price action, and volatility. Timing out when you launch your token is essential to guaranteeing that it has room to grow and will not inadvertently be dumped by an impending bear market. Check what stage of the crypto market is in, and get insight from investors on how they see the market evolving in the coming months - specifically as it pertains to liquidity in-flows, and significant events (like the Bitcoin Halving). |
Mantle Ecosystem Gateway Launches on the NEAR Blockchain Operating System (B.O.S)
NEAR FOUNDATION
September 20, 2023
An ecosystem gateway for Mantle, the layer-2 scaling solution built on Ethereum, has launched on the NEAR Blockchain Operating System (B.O.S) to offer a unified point of entry into the Mantle ecosystem.
Hosted by popular Mantle dApp FusionX, the gateway, built in collaboration with the NEAR community, streamlines the discovery of Mantle applications and helps aggregate components of top dApps including the Mantle Bridge, Agni, Ammos, iZiSwap, FusionX, Gamma, Lendle, and soon Pendle, in one place.
The gateway offers greater accessibility for developers and users, easier discoverability for the apps they build, and powerful composability. This was all made possible thanks to the B.O.S.
“Mantle has seen some great traction since their launch and we’re very excited to have a Mantle gateway built on B.O.S. Ethereum and DeFi users interested in discovering new projects can now find lots of Mantle apps in one place, with bridging already solved so they can get started right away,” says Illia Polosukhin, co-founder of NEAR Protocol. “The Mantle gateway demonstrates the value of B.O.S gateways for other L2s and EVM projects looking to increase discoverability.”
Unlocking the Web3 ecosystem
Mantle’s development on NEAR is a testament to the protocol’s commitment to creating the foundations for the open web. “We are delighted to ally with NEAR in bringing leading Mantle dApps to a wider community through the Mantle Ecosystem Gateway on B.O.S,” says Arjun Kalsy, head of ecosystem of Mantle. “Through this effort, we look to provide even more support to our dev community, and allow for more cross-pollination in our respective Web3 communities.”
The Mantle gateway joins a growing list of projects that have partnered with the B.O.S to help unlock the full potential of Web3. A zkEVM B.O.S gateway for the Polygon ecosystem launched on NEAR to help increase accessibility and discoverability for developers, while also improving the user experience for end users exploring L2 ecosystems.
While the B.O.S is built on NEAR, it offers many benefits to founders and builders from EVM projects and across the whole Web3 ecosystem. The Blockchain Operating System speeds up the process of building multi-chain experiences, empowering builders from any ecosystem––including EVM projects such as Ethereum layer 2s––to focus on creating great products for users rather than on managing infrastructure.
Developers can quickly build composable apps for the open web from thousands of flexible components, as well as seamlessly onboard users and increase discoverability across Web3 since every application utilising B.O.S is visible on a common interface. This collaboration brings new capabilities to developers and lets them build apps that can quickly reach more users.
|
---
id: events
title: Events
sidebar_label: Events
---
import {Github} from "@site/src/components/codetabs"
In this tutorial, you'll learn about the [events standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Event) and how to implement it in your smart contract.
## Introduction
To get started, either switch to the `6.royalty` branch from our [GitHub repository](https://github.com/near-examples/nft-tutorial/), or continue your work from the previous tutorials.
```bash
git checkout 6.royalty
```
:::tip
If you wish to see the finished code for this _Events_ tutorial, you can find it on the `7.events` branch.
:::
## Understanding the use case {#understanding-the-use-case}
Have you ever wondered how the wallet knows which NFTs you own and how it can display them in the [collectibles tab](https://testnet.mynearwallet.com//?tab=collectibles)? Originally, an [indexer](/tools/indexer-for-explorer) was used and it listened for any functions starting with `nft_` on your account. These contracts were then flagged on your account as likely NFT contracts.
When you navigated to your collectibles tab, the wallet would then query all those contracts for the list of NFTs you owned using the `nft_tokens_for_owner` function you saw in the [enumeration tutorial](/tutorials/nfts/js/enumeration).
### The problem {#the-problem}
This method of flagging contracts was not reliable as each NFT-driven application might have its own way of minting or transferring NFTs. In addition, it's common for apps to transfer or mint many tokens at a time using batch functions.
### The solution {#the-solution}
A standard was introduced so that smart contracts could emit an event anytime NFTs were transferred, minted, or burnt. This event was in the form of a log. No matter how a contract implemented the functionality, an indexer could now listen for those standardized logs.
As per the standard, you need to implement a logging functionality that gets fired when NFTs are transferred or minted. In this case, the contract doesn't support burning so you don't need to worry about that for now.
It's important to note the standard dictates that the log should begin with `"EVENT_JSON:"`. The structure of your log should, however, always contain the 3 following things:
- **standard**: the current name of the standard (e.g. nep171)
- **version**: the version of the standard you're using (e.g. 1.0.0)
- **event**: a list of events you're emitting.
The event interface differs based on whether you're recording transfers or mints. The interface for both events is outlined below.
**Transfer events**:
- *Optional* - **authorized_id**: the account approved to transfer on behalf of the owner.
- **old_owner_id**: the old owner of the NFT.
- **new_owner_id**: the new owner that the NFT is being transferred to.
- **token_ids**: a list of NFTs being transferred.
- *Optional* - **memo**: an optional message to include with the event.
**Minting events**:
- **owner_id**: the owner that the NFT is being minted to.
- **token_ids**: a list of NFTs being transferred.
- *Optional* - **memo**: an optional message to include with the event.
### Examples {#examples}
In order to solidify your understanding of the standard, let's walk through three scenarios and see what the logs should look like.
#### Scenario A - simple mint
In this scenario, Benji wants to mint an NFT to Mike with a token ID `"team-token"` and he doesn't include a message. The log should look as follows.
```js
EVENT_JSON:{
"standard": "nep171",
"version": "1.0.0",
"event": "nft_mint",
"data": [
{"owner_id": "mike.testnet", "token_ids": ["team-token"]}
]
}
```
#### Scenario B - batch mint
In this scenario, Benji wants to perform a batch mint. He will mint an NFT to Mike, Damian, Josh, and Dorian. Dorian, however, will get two NFTs. Each token ID will be `"team-token"` followed by an incrementing number. The log is as follows.
```js
EVENT_JSON:{
"standard": "nep171",
"version": "1.0.0",
"event": "nft_mint",
"data": [
{"owner_id": "mike.testnet", "token_ids": ["team-token0"]},
{"owner_id": "damian.testnet", "token_ids": ["team-token1"]},
{"owner_id": "josh.testnet", "token_ids": ["team-token2"]}
{"owner_id": "dorian.testnet", "token_ids": ["team-token3", "team-token4"]},
]
}
```
#### Scenario C - transfer NFTs
In this scenario, Mike is transferring both his team tokens to Josh. The log should look as follows.
```js
EVENT_JSON:{
"standard": "nep171",
"version": "1.0.0",
"event": "nft_transfer",
"data": [
{"old_owner_id": "mike.testnet", "new_owner_id": "josh.testnet", "token_ids": ["team-token", "team-token0"], "memo": "Go Team!"}
]
}
```
## Modifications to the contract {#modifications-to-the-contract}
At this point, you should have a good understanding of what the end goal should be so let's get to work!
### Logging minted tokens {#logging-minted-tokens}
Since the contract will only be minting tokens in one place, it's trivial where you should place the log. Open the `nft-contract/src/mint.ts` file and navigate to the bottom of the file. This is where you'll construct the log for minting. Anytime someone successfully mints an NFT, it will now correctly emit a log.
```js
// Construct the mint log as per the events standard.
let nftMintLog = {
// Standard name ("nep171").
standard: NFT_STANDARD_NAME,
// Version of the standard ("nft-1.0.0").
version: NFT_METADATA_SPEC,
// The data related with the event stored in a vector.
event: "nft_mint",
data: [
{
// Owner of the token.
owner_id: token.owner_id,
// Vector of token IDs that were minted.
token_ids: [tokenId],
}
]
}
// Log the json.
near.log(`EVENT_JSON:${JSON.stringify(nftMintLog)}`);
```
<Github language="js" start="7" end="85" url="https://github.com/near-examples/nft-tutorial-js/blob/7.events/src/nft-contract/mint.ts" />
### Logging transfers {#logging-transfers}
Let's open the `nft-contract/src/internal.ts` file and navigate to the `internalTransfer` function. This is the location where you'll build your transfer logs. Whenever an NFT is transferred, this function is called and so you'll correctly be logging the transfers.
```js
// Construct the transfer log as per the events standard.
let nftTransferLog = {
// Standard name ("nep171").
standard: NFT_STANDARD_NAME,
// Version of the standard ("nft-1.0.0").
version: NFT_METADATA_SPEC,
// The data related with the event stored in a vector.
event: "nft_transfer",
data: [
{
// The optional authorized account ID to transfer the token on behalf of the old owner.
authorized_id: authorizedId,
// The old owner's account ID.
old_owner_id: token.owner_id,
// The account ID of the new owner of the token.
new_owner_id: receiverId,
// A vector containing the token IDs as strings.
token_ids: [tokenId],
// An optional memo to include.
memo,
}
]
}
// Log the serialized json.
near.log(`EVENT_JSON:${JSON.stringify(nftTransferLog)}`);
```
<Github language="js" start="113" end="205" url="https://github.com/near-examples/nft-tutorial-js/blob/7.events/src/nft-contract/internal.ts" />
This solution, unfortunately, has an edge case which will break things. If an NFT is transferred via the `nft_transfer_call` function, there's a chance that the transfer will be reverted if the `nft_on_transfer` function returns `true`. Taking a look at the logic for `nft_transfer_call`, you can see why this is a problem.
When `nft_transfer_call` is invoked, it will:
- Call `internalTransfer` to perform the actual transfer logic.
- Initiate a cross-contract call and invoke the `nft_on_transfer` function.
- Resolve the promise and perform logic in `internalResolveTransfer`.
- This will either return true meaning the transfer went fine or it will revert the transfer and return false.
If you only place the log in the `internalTransfer` function, the log will be emitted and the indexer will think that the NFT was transferred. If the transfer is reverted during `internalResolveTransfer`, however, that event should **also** be emitted. Anywhere that an NFT **could** be transferred, we should add logs. Replace the `internalResolveTransfer` with the following code.
<Github language="js" start="138" end="242" url="https://github.com/near-examples/nft-tutorial-js/blob/7.events/src/nft-contract/nft_core.ts" />
With that finished, you've successfully implemented the events standard and it's time to start testing.
## Deploying the contract {#redeploying-contract}
For the purpose of readability and ease of development, instead of redeploying the contract to the same account, let's create a sub-account and deploy to that instead. You could have deployed to the same account as none of the changes you implemented in this tutorial would have caused errors.
### Creating a sub-account
Run the following command to create a sub-account `events` of your main account with an initial balance of 25 NEAR which will be transferred from the original to your new account.
```bash
near create-account events.$NFT_CONTRACT_ID --masterAccount $NFT_CONTRACT_ID --initialBalance 25
```
Next, you'll want to export an environment variable for ease of development:
```bash
export EVENTS_NFT_CONTRACT_ID=events.$NFT_CONTRACT_ID
```
Using the build script, build the deploy the contract as you did in the previous tutorials:
```bash
yarn build && near deploy --wasmFile build/nft.wasm --accountId $EVENTS_NFT_CONTRACT_ID
```
### Initialization and minting {#initialization-and-minting}
Since this is a new contract, you'll need to initialize and mint a token. Use the following command to initialize the contract:
```bash
near call $EVENTS_NFT_CONTRACT_ID init '{"owner_id": "'$EVENTS_NFT_CONTRACT_ID'"}' --accountId $EVENTS_NFT_CONTRACT_ID
```
Next, you'll need to mint a token. By running this command, you'll mint a token with a token ID `"events-token"` and the receiver will be your new account. In addition, you're passing in a map with two accounts that will get perpetual royalties whenever your token is sold.
```bash
near call $EVENTS_NFT_CONTRACT_ID nft_mint '{"token_id": "events-token", "metadata": {"title": "Events Token", "description": "testing out the new events extension of the standard", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$EVENTS_NFT_CONTRACT_ID'"}' --accountId $EVENTS_NFT_CONTRACT_ID --amount 0.1
```
You can check to see if everything went through properly by looking at the output in your CLI:
```bash
Doing account.functionCall()
Receipts: F4oxNfv54cqwUwLUJ7h74H1iE66Y3H7QDfZMmGENwSxd, BJxKNFRuLDdbhbGeLA3UBSbL8UicU7oqHsWGink5WX7S
Log [events.goteam.examples.testnet]: EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_mint","data":[{"owner_id":"events.goteam.examples.testnet","token_ids":["events-token"]}]}
Transaction Id 4Wy2KQVTuAWQHw5jXcRAbrz7bNyZBoiPEvLcGougciyk
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/4Wy2KQVTuAWQHw5jXcRAbrz7bNyZBoiPEvLcGougciyk
''
```
You can see that the event was properly logged!
### Transferring {#transferring}
You can now test if your transfer log works as expected by sending `benjiman.testnet` your NFT.
```bash
near call $EVENTS_NFT_CONTRACT_ID nft_transfer '{"receiver_id": "benjiman.testnet", "token_id": "events-token", "memo": "Go Team :)", "approval_id": 0}' --accountId $EVENTS_NFT_CONTRACT_ID --depositYocto 1
```
This should return an output similar to the following:
```bash
Doing account.functionCall()
Receipts: EoqBxrpv9Dgb8KqK4FdeREawVVLWepEUR15KPNuZ4fGD, HZ4xQpbgc8EfU3PiV72LvfXb2f3dVC1n9aVTbQds9zfR
Log [events.goteam.examples.testnet]: Memo: Go Team :)
Log [events.goteam.examples.testnet]: EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_transfer","data":[{"authorized_id":"events.goteam.examples.testnet","old_owner_id":"events.goteam.examples.testnet","new_owner_id":"benjiman.testnet","token_ids":["events-token"],"memo":"Go Team :)"}]}
Transaction Id 4S1VrepKzA6HxvPj3cK12vaT7Dt4vxJRWESA1ym1xdvH
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/4S1VrepKzA6HxvPj3cK12vaT7Dt4vxJRWESA1ym1xdvH
''
```
Hurray! At this point, your NFT contract is fully complete and the events standard has been implemented.
## Conclusion
Today you went through the [events standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Event) and implemented the necessary logic in your smart contract. You created events for [minting](#logging-minted-tokens) and [transferring](#logging-transfers) NFTs. You then deployed and [tested](#initialization-and-minting) your changes by minting and transferring NFTs.
In the next tutorial, you'll look at the basics of a marketplace contract and how it was built.
:::note Versioning for this article
At the time of this writing, this example works with the following versions:
- near-cli: `3.0.0`
- NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0`
- Events standard: [NEP297 extension](https://nomicon.io/Standards/Tokens/NonFungibleToken/Event), version `1.0.0`
:::
|
# Architecture
### BOS Component Loading
BOS Components are loaded in BOS Web Engine by way of a client-side pipeline, responsible for BOS Component source
fetching, TSX transpilation, and Component composition. A web worker services requests from the outer application to
load new Components, caching the Component source and transpiled wrapper function. The worker responds with the wrapped
source code, which is used to initialize containers with iframes.
![source-compile-container](/img/source-compile-container.png)
_High-level overview of the flow from BOS Component source to Component container._
### Component Containers
Containers are abstractions around sandboxed iframes, responsible for managing the lifecycle of a single root Component.
The outer application renders a container for each root Component, rendering the container's hidden iframe and executing
the container code in the iframe's `srcDoc` field.
Containers rely on Preact for Component lifecycle management. When a Component has updated, options hooks set in Preact
serialize the rendered node and send it to the outer application. The initial render request is explicitly triggered upon
container initialization. This Preact integration enables the use of React hooks within BOS Components.
Interactions between containers are facilitated by the iframe parent's _window_ object, e.g. `window.parent.postMessage()`.
The outer application and individual containers register event handlers on this _window_ object to facilitate bidirectional
message passing to communicate renders and broker inter-Component callbacks. As a consequence of this, all inter-Component
communication is inherently asynchronous.
![Container to Outer Window Application](/img/container-owa.png)
_Component containers manage root Components, which may be under another Component in the DOM tree despite being sandboxed._
### Trust
Component Trust ensures that BOS Components retain control over composability with other Components. When rendering a BOS
Component in Web Engine, the **trust mode** determines how to load the Component:
- **trusted** loads the Component inside the same container
- **sandboxed** loads the Component as a root Component in a new container
Trust mode does not impact the rendered output in the outer application, but has implications for performance and security.
In particular:
- Trusted Components invoke methods directly within the same context. Sandboxed Components are subject to performance overhead
inherent in proxying callbacks through the outer application.
- Sandboxed Components are loaded dynamically, and their paths do not need to be known at build time. Trusted Components
incur a loading penalty upfront when fetching and parsing source for multiple Components, and must use statically-analyzable
paths to guarantee all Components are known at build time.
- Sandboxed Components run in their own sandboxed iframe container and may only communicate with other containers using a
well-defined message passing interface. Trusted Component trees run in the same context, with access to the same references.
Component Trust is best employed to create logical trust boundaries in a BOS application, for instance between Components
from different accounts. By default, BOS Components are loaded as **sandboxed**; loading a Component as **trusted** requires
explicit configuration.
![trusted-source-compile-container](/img/source-container-trusted.png)
_Trusted Components are included in the same container context as their parent Component._
### Component Callbacks
Callbacks between Components (e.g. functions passed via `props`) are supported in BOS Web Engine, though the exact behavior is
dependent on whether the Components are within the same container. Callbacks between two Components _in the same container_
work without constraints, but there are caveats for callbacks _between containers_ as the caller and callee exist in completely
independent contexts. Under the hood, these inter-container callbacks must be invoked (and return data) using the message passing interface
provided by `window.postMessage`, and are subject to some constraints accordingly:
- Arguments may only use types compatible with the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
While functions cannot be provided as arguments directly, references to callbacks in other containers may be passed, allowing
BOS Components to invoke functions on `props` with function arguments.
- Inter-container callbacks are inherently asynchronous, for which a Promise-based interface is provided to abstract away
the underlying event-based communication.
|