owned this note
owned this note
Published
Linked with GitHub
---
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
]
```