BytesIO
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- id: near-web3-provider title: NEAR Web3 provider sidebar_label: Web3 Provider --- The [near-web3-provider](https://github.com/near/near-web3-provider) 是一个自定义提供程序,可以在Web3环境中使用。 Web3提供程序有两种典型的用例: 1. [前端](#front-end) — 通过Web上的用户界面与智能合约进行交互。 2. [后端](#back-end) — 通常测试和部署基于EVM的合约或使用NEAR CLI。没有网站前端与智能合约进行交互的任何事物。 ## 前端 [NPM package](https://npmjs.com/package/near-web3-provider) 可以用以下命令安装到一个NodeJs项目: npm install near-web3-provider --save 或者,要遵循以下代码片段,您可能想要使用: npm install near-web3-provider web3-eth-contract --save 在前端JavaScript中,可以使用其构造函数实例化提供程序。`NearProvider`类有两种模式: 1. 只读模式 — 只能访问对NEAR EVM的`view`(view只可以向区块链查询不可写入数据)调用. 2. 已签名模式-可以访问NEAR帐户,并且可以与`view`和`call`方法进行交互。 **Note**: in Ethereum, executing a read-only method is referred to as `call`, while a state-changing method is referred to as `send`. In NEAR, it's `view` and `call` and this terminology will be used widely in the documentation. **注意**:在以太坊中,执行只读方法称为`调用`,而将状态更改方法称为`发送`。在NEAR中,它是`视图`和`调用`,并且此术语将在文档中广泛使用。 ### 实例化只读 ```js const { NearProvider } = require('near-web3-provider'); // … const nearProvider = new NearProvider({ networkId: this.nearNetwork, keyStore: new nearAPI.keyStores.BrowserLocalStorageKeyStore(), isReadOnly: true }); ``` ### 实例化签名 对于已签名的实例,这假定浏览器具有本地存储,其中包含指向指定帐户的密钥。 对于不熟悉NEAR钱包的人们,简要回顾一下,因为NEAR中的工作流程与浏览器扩展或通过扫描QR码不同。假设用户想要使用NEAR betanet帐户与EVM进行交互。第一步是使用钱包创建帐户。 (非主网网络允许免费创建初始余额为Ⓝ的帐户。) NEAR Betanet钱包: https://wallet.betanet.near.org 网站的本地存储包含此帐户的密钥。当您想使用您的帐户与前端进行交互时,通常会将前端重定向到钱包,请求创建一个特殊的功能调用访问密钥。允许创建后,浏览器将使用包含此新密钥的本地存储重定向到dApp前端。 ```js const { NearProvider } = require('near-web3-provider'); // … const nearProvider = new NearProvider({ networkId: this.nearNetwork, masterAccountId: 'yourname.betanet', // NEAR account with key that exists in local storage keyStore: new nearAPI.keyStores.BrowserLocalStorageKeyStore(), }); ``` ### 合约实例,设置提供者 Web3开发人员能够使用熟悉的库进行合同实例化。例如,在“宠物店”示例中,使用NPM包实例化了一个`Contract`对象。 [`web3-eth-contract`](https://www.npmjs.com/package/web3-eth-contract). 然后一个`Contract` 对象可以使用诸如 [`发送`](https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-send) and [`调用`](https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-call). ```js const Contract = require('web3-eth-contract'); const { NearProvider, utils } = require('near-web3-provider'); const path = require('path'); const credentialsPath = path.join(os.homedir(), '.near-credentials'); const yourBetanetAccount = 'yourname.betanet'; // NEAR account with key that exists in local storage const nearProvider = new NearProvider({ networkId: this.nearNetwork, masterAccountId: yourBetanetAccount, keyStore: new nearAPI.keyStores.UnencryptedFileSystemKeyStore(credentialsPath), }); const myContractArtifact = require('path/to/build/contracts/MyContract.json'); const networkId = nearProvider.version; const myContractAddress = myContractArtifact.networks[networkId].address; const myContract = new Contract(myContractArtifact.abi, myContractAddress, { from: myContractAddress }); myContract.setProvider(nearProvider); // view-only const viewResult = myContract.methods.myViewMethod().call(); // signed const yourBetanetAccountAsEthAddress = utils.nearAccountToEvmAddress(yourBetanetAccount); const signedResult = myContract.methods.mutateStateMethod().send({from: yourBetanetAccountAsEthAddress}); ``` 这涵盖了前端`near-web3-provider` 的基本用法,允许您的以太坊智能合约与网站进行交互。 ## 后端 ### 简单以太坊虚拟机交互 以下代码摘自[此示例代码仓库](https://github.com/near-examples/evm-simple)。该项目将包含运行此演示所需的私钥。 在第42行,我们将会在NEAR EVM(NEAR虚拟机)上与合约进行交互: ```js const Contract = require('web3-eth-contract'); const { NearProvider, utils, nearAPI } = require('near-web3-provider'); Demo = { start: async function() { await this.callEvm('mike.betanet'); console.log('-------------------') await this.callEvm('josh.betanet'); }, callEvm: async function(betanetAccount) { console.log(`Interacting with ${betanetAccount}`); const nearProvider = new NearProvider({ networkId: 'betanet', masterAccountId: betanetAccount, // See list of near-api-js keystores here: https://near.github.io/near-api-js/classes/_key_stores_keystore_.keystore.html keyStore: new nearAPI.keyStores.UnencryptedFileSystemKeyStore('./private-keys'), }); // See the NEAR Pet Shop example at: https://github.com/near-examples/near-pet-shop const myContractArtifact = require('./build/contracts/Adoption.json'); const networkId = nearProvider.version; console.log('aloha networkId', networkId); const myContractAddress = myContractArtifact.networks[networkId].address; const myContract = new Contract(myContractArtifact.abi, myContractAddress, { from: myContractAddress }); myContract.setProvider(nearProvider); // signed const betanetAccountAsEthAddress = utils.nearAccountToEvmAddress(betanetAccount); // could also get the account with web3.eth.getAccounts console.log(`The NEAR account ${betanetAccount} is ${betanetAccountAsEthAddress} on the EVM`); console.log('Setting first item to the EVM account…') // We're setting the first entry in the array to be the accounts EVM address const signedResult = await myContract.methods.adopt(0).send({from: betanetAccountAsEthAddress}); let transactionHash = signedResult.transactionHash.split(':')[0]; console.log(`View transaction in NEAR Explorer: https://explorer.betanet.near.org/transactions/${transactionHash}`); // view-only console.log('Retrieving state…') const viewResult = await myContract.methods.getAdopters().call(); console.log('viewResult', viewResult); } } Demo.start(); ``` Note that we can use common libraries from the Ethereum ecosystem like `web3-eth-contract` as we have here. Once the keys and contract object is set up, you may interact with: 注意,我们可以使用以太坊生态系统中的通用库,例如`web3-eth-contract` 。设置密钥和合约对象后,您可以与以下对象进行交互: `view` ```js const readOnlyResult = await myContract.methods.readOnlyMethodName().call(); ``` `call` ```js const transactionResult = await myContract.methods.changeStateMethodName(argValue).send({from: accountAsEthAddress}); ``` ### 编译和部署Solidity合同 The [NEAR Pet Shop example](https://github.com/near-examples/near-pet-shop) also demonstrates both front-end and back-end with regards to building and deploying using Truffle's `migrate` command. Please see the NEAR documentation [Truffle page](/docs/develop/evm/truffle) for details on this. [NEAR Pet Shop示例](https://github.com/near-examples/near-pet-shop) 还演示了使用Truffle的`migrate`命令进行构建和部署的前端和后端。有关详细信息,请参阅NEAR文档[Truffle页面](/docs/develop/evm/truffle)。 ### NEAR CLI 您可以使用命令行界面工具NEAR CLI与EVM智能合约进行交互。对于NodeJS 12+版本,您可以通过以下方式在全局范围内安装: npm install -g near-cli 有关更多信息,请参见[NEAR CLI documentation](/docs/tools/near-cli). 确保使用先前的说明通过钱包创建Betanet NEAR帐户。使用以下命令以在本地创建完全访问密钥文件: env NEAR_ENV=betanet near login 密钥文件将位于 `~/.near-credentials/betanet/yourname.betanet.json`. 现在,我们准备使用NEAR CLI与NEAR EVM上的智能合约进行交互。假设我们已经按照[本指南中的详细说明](/docs/develop/evm/truffle#build-and-deploy)使用Truffle构建和部署了智能合约,并且**合约地址**输出为` 0xAdf11a39283CEB00DEB90a5cE9220F89c6C27E67`。在这种情况下,合约是前面提到的NEAR Pet Shop示例。有一个只读方法`getAdopters`和一个更改状态的方法称为`adopt`。 查看使用 `evm-view`: NEAR_ENV=betanet near evm-view evm 0xAdf11a39283CEB00DEB90a5cE9220F89c6C27E67 getAdopters '[]' --abi ~/path/to/near-pet-shop/build/contracts/Adoption.json --accountId yourname.betanet The `evm-view` command returns an array of addresses, each corresponding to the index of a dog. Dogs open for adoption have the value of the zero address (`0x0000000000000000000000000000000000000000`) and dogs already adopted contain the address of the account that's adopted them. `evm-view` 命令返回一个地址数组,每个地址对应于一条狗的索引。开放供领养的狗的地址为零地址('0x0000000000000000000000000000000000000000000000'),而已被领养的狗包含领养它们的帐户的地址。 在撰写本文时,先前的CLI命令返回: ```shell script [ '0x0000000000000000000000000000000000000000', ⟵ we will be adopting this dog '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C' ⟵ josh.betanet ] ``` 如上所示,索引0处的“狗”(数组中的第一个)地址为零(即零地址),因此可供收养。 调用和更改状态 `evm-call`: NEAR_ENV=betanet near evm-call evm 0xAdf11a39283CEB00DEB90a5cE9220F89c6C27E67 adopt '["0"]' --abi ~/path/to/near-pet-shop/build/contracts/Adoption.json --accountId yourname.betanet CLI命令行将会输出: ```shell script 在EVM中调用call: 0xAdf11a39283CEB00DEB90a5cE9220F89c6C27E67.adopt() with args [ '0' ] ``` 我们再次可以使用`evm-view` 命令来查看新的结果: ```shell script [ '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ newly adopted dog '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0xb948c53cBA274D77e54109061068512e92d1249d', ⟵ mike.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C', ⟵ josh.betanet '0x5d60a489B2f457cB351b0faaBf5f9746d6bd4A8C' ⟵ josh.betanet ] ```

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully