Moralis Web3 Provider

2022-05-13 10:36 更新

讓我們談?wù)?nbsp;Web3 集成!

Moralis 附帶了一組插件,可幫助您專(zhuān)注于應(yīng)用程序的開(kāi)發(fā),剩下的交給我們。

類(lèi)似于 ?window.ethereum.enable()? 但返回一個(gè)從 Ethers.js 解析為 ?web3Provider ?實(shí)例的promise。 當(dāng)您需要一個(gè)功能齊全的 ?web3Provider ?實(shí)例時(shí)使用它,例如進(jìn)行合約調(diào)用。

注意:確保安裝了 v1.0.0 或更高版本的 SDK。 否則 ?Moralis.enableWeb3()? 將返回 web3.js 的實(shí)例而不是 ethers.js

例如:

// Get a (ethers.js) web3Provider
const web3Provider = await Moralis.enableWeb3();

有關(guān)如何使用 Ethers.js 的更多信息,請(qǐng)參閱 Ethers.js 文檔

Web3.js

您可能想要使用另一個(gè)庫(kù),例如 Web3.js。 為此,您需要將此庫(kù)包含到您的代碼中。

當(dāng)您通過(guò) html 導(dǎo)入 javascript 腳本時(shí):

<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js" rel="external nofollow" ></script>

或者當(dāng)您使用包管理器時(shí):

npm install web3

然后在您的代碼中,使用 ?Moralis.provider? 來(lái)初始化 web3.js 庫(kù)。 ?Moralis.provider? 只會(huì)在調(diào)用 ?Moralis.authenticate? 或 ?Moralis.enableWeb3? 后設(shè)置。

import Web3 from "web3"; // Only when using npm/yarn

// Enable web3 and get the initialized web3 instance from Web3.js
await Moralis.enableWeb3();
const web3Js = new Web3(Moralis.provider);

有關(guān)如何使用 web3.js 的更多信息,請(qǐng)參閱 Web3.js 文檔

注意:Ethers.js 包含在 Moralis SDK 中。 因此 ?Moralis.executeFunction? 和 ?Moralis.transfer? 的函數(shù)響應(yīng)將始終由 Ethers.js 格式化(更多信息見(jiàn)下文)

獲取 EthersJs 庫(kù)

您可以訪問(wèn) Moralis 正在使用的 Ethers.js 庫(kù):

const ethers = Moralis.web3Library;

有了這個(gè)實(shí)例,你可以使用 Ethers.js 中的任何方法,例如:

const ethers = Moralis.web3Library;

const daiAddress = "dai.tokens.ethers.eth";
const daiAbi = [
  "function name() view returns (string)",
  "function symbol() view returns (string)",
  "function balanceOf(address) view returns (uint)",
  "function transfer(address to, uint amount)",
  "event Transfer(address indexed from, address indexed to, uint amount)",
];
const daiContract = new ethers.Contract(daiAddress, daiAbi, provider);

const name = await daiContract.name();
console.log(name);
// 'Dai Stablecoin'

有關(guān)如何使用 Ethers.js 的更多信息,請(qǐng)參閱 Ethers.js 文檔

連接器

您可以使用任何連接器(例如 ?WalletConnect?、?Metamask?、?Network ?等)啟用 web3,與使用 ?Moralis.authenticate? 的方式相同),使用 ?provider ?選項(xiàng):

const web3 = await Moralis.enableWeb3({ provider: "walletconnect" });

NodeJs環(huán)境

在 nodejs 環(huán)境中使用moralis 時(shí),您可以選擇使用私鑰選項(xiàng)來(lái)簽署交易:

const web3 = await Moralis.enableWeb3({ privateKey: "your_private_key" });

在云函數(shù)中

也可以在云函數(shù)中獲取 Web3 實(shí)例,但語(yǔ)法有點(diǎn)不同。 

這個(gè)實(shí)例是一個(gè) Web3.js 實(shí)例

執(zhí)行函數(shù)

通過(guò) ?executeFunction?,您可以執(zhí)行只讀(查看)函數(shù)和編寫(xiě)方法。 他們都給出了略有不同的回應(yīng)。 所以我們?cè)谙旅娣謩e處理它們。

選項(xiàng):

  • ?contractAddress?(必填):智能合約地址
  • ?abi?(必填):合約或函數(shù) ABI(應(yīng)作為數(shù)組提供)
  • ?functionName?(必需):函數(shù)名稱(chēng)
  • ?params?(必需):您的特定功能所需的參數(shù)
  • ?msgValue?(可選):數(shù)字|字符串|BN|BigNumber。 wei為交易轉(zhuǎn)移的價(jià)值

只讀函數(shù)

對(duì)于只讀函數(shù),您需要等待執(zhí)行完成。 然后你直接得到結(jié)果。

const ABI = [
  {
    inputs: [],
    name: "message",
    outputs: [
      {
        internalType: "string",
        name: "",
        type: "string",
      },
    ],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [
      {
        internalType: "string",
        name: "_newMessage",
        type: "string",
      },
    ],
    name: "setMessage",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function",
  },
];

const readOptions = {
  contractAddress: "0xe...56",
  functionName: "message",
  abi: ABI,
};

const message = await Moralis.executeFunction(readOptions);
console.log(message);
// -> "Hello World"

需要啟用的 web3 提供程序。 在執(zhí)行該功能之前,請(qǐng)確保在您的錢(qián)包中選擇了正確的網(wǎng)絡(luò)。

您可以使用我們的 Web3API 在沒(méi)有活躍的 web3 提供者的情況下接收此信息: ?Moralis.Web3API.token.getAllowance()?

調(diào)用寫(xiě)合約方法的示例

通過(guò) ?setMessage ?函數(shù)調(diào)用設(shè)置消息的示例。

const ABI = [
  {
    inputs: [],
    name: "message",
    outputs: [
      {
        internalType: "string",
        name: "",
        type: "string",
      },
    ],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [
      {
        internalType: "string",
        name: "_newMessage",
        type: "string",
      },
    ],
    name: "setMessage",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function",
  },
];

const sendOptions = {
  contractAddress: "0xe...56",
  functionName: "setMessage",
  abi: ABI,
  params: {
    _newMessage: "Hello Moralis",
  },
};

const transaction = await Moralis.executeFunction(sendOptions);
console.log(transaction.hash);
// --> "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c"

// Wait until the transaction is confirmed
await transaction.wait();

// Read new value
const message = await Moralis.executeFunction(readOptions);
console.log(message);
// --> "Hello Moralis"

您將從 Ethers.js 獲得交易響應(yīng),其中包括哈希和其他信息。

交易響應(yīng)示例

{
    "hash": "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c",
    "type": 2,
    "accessList": null,
    "blockHash": null,
    "blockNumber": null,
    "transactionIndex": null,
    "confirmations": 0,
    "from": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
    "gasPrice": {
        "type": "BigNumber",
        "hex": "0x04cf1ef09a"
    },
    "maxPriorityFeePerGas": {
        "type": "BigNumber",
        "hex": "0x908a9040"
    },
    "maxFeePerGas": {
        "type": "BigNumber",
        "hex": "0x04cf1ef09a"
    },
    "gasLimit": {
        "type": "BigNumber",
        "hex": "0x75c0"
    },
    "to": "0x73bceb1cd57c711feac4224d062b0f6ff338501e",
    "value": {
        "type": "BigNumber",
        "hex": "0x00"
    },
    "nonce": 13,
    "data": "0x368b877200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004486f6c6100000000000000000000000000000000000000000000000000000000",
    "r": "0x8b00442b141406a1b5d701c7ac6ab3b6adec13010fdc1218a42f8f9aa8e57718",
    "s": "0x1abc60ae4de7af8bcba4d1b44e470f40a04c3c632fd4a75f87a553820a43ddef",
    "v": 1,
    "creates": null,
    "chainId": 0
}

如果你想等到交易被鏈確認(rèn),那么你可以調(diào)用transaction.wait()。 這將解析為交易收據(jù)。 此收據(jù)還將包括交易中已觸發(fā)的所有事件的日志。 例如,我們?cè)谶@里等待 3 個(gè)確認(rèn):

const receipt = await transaction.wait(3);

收據(jù)示例

{
    "to": "0x73bceb1cd57c711feac4224d062b0f6ff338501e",
    "from": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
    "contractAddress": null,
    "transactionIndex": 72,
    "gasUsed": {
        "type": "BigNumber",
        "hex": "0x75b2"
    },
    "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
    "blockHash": "0x746d7d42e8022f560577dfdc0150e1e8b009e59c537a9053a82e9ad6d20f6d06",
    "transactionHash": "0x39af55979f5b690fdce14eb23f91dfb0357cb1a27f387656e197636e597b5b7c",
    "logs": [],
    "blockNumber": 11847564,
    "confirmations": 2,
    "cumulativeGasUsed": {
        "type": "BigNumber",
        "hex": "0x6743ab"
    },
    "effectiveGasPrice": {
        "type": "BigNumber",
        "hex": "0x04623af60c"
    },
    "status": 1,
    "type": 2,
    "byzantium": true,
    "events": []
}

在合約方法示例中傳輸本機(jī)加密

例如,您想調(diào)用一個(gè)智能合約方法,將本機(jī)加密貨幣換成代幣。 這種情況與您使用 ?ERC20? 代幣并指定要用作方法參數(shù)的代幣數(shù)量的通常情況不同。 在智能合約中使用原生加密貨幣的操作假定您將隨交易一起轉(zhuǎn)移一些價(jià)值。 在solidity中,您可以將其稱(chēng)為 ?msg.value?

const options = {
  contractAddress: "0xe...56",
  functionName: "swapNativeForTokens",
  abi: ABI,
  msgValue: Moralis.Units.ETH("0.1"),
};

const transaction = await Moralis.executeFunction(options);
const receipt = await transaction.wait();
console.log(receipt);

創(chuàng)建可重用選項(xiàng)的示例

您可以使用此構(gòu)造來(lái)創(chuàng)建可重用的選項(xiàng)來(lái)調(diào)用多個(gè)合約方法。

const options = {
  contractAddress: "0xe...56",
  abi: ABI,
};

const symbol = await Moralis.executeFunction({
  functionName: "symbol",
  ...options,
});
const decimals = await Moralis.executeFunction({
  functionName: "decimals",
  ...options,
});
const name = await Moralis.executeFunction({
  functionName: "name",
  ...options,
});

解析交易結(jié)果

?Moralis.executeFunction()? 返回:

  • 如果函數(shù)是只讀的,則返回值
  • 如果函數(shù)在鏈上寫(xiě)入,則為交易響應(yīng)。

您可以通過(guò)等待交易得到確認(rèn),將交易響應(yīng)解析為收據(jù)。 例如,要等待 3 次確認(rèn):

const options = {
  contractAddress: "0xe...56",
  functionName: "swapNativeForTokens",
  abi: ABI,
  msgValue: Moralis.Units.ETH("0.1"),
};
const transaction = await Moralis.executeFunction(options);
const result = await transaction.wait();

事件

您可以在 Moralis 上監(jiān)聽(tīng)?zhēng)讉€(gè)事件,以檢查用戶(hù)的 web3 連接:

  • onWeb3Enabled
  • onWeb3Deactivated
  • onChainChanged
  • onAccountChanged
  • onConnect (fired from the EIP1193 provider)
  • onDisconnect (fired from the EIP1193 provider)

Moralis.onWeb3Enabled()

當(dāng)用戶(hù)連接到鏈時(shí)監(jiān)聽(tīng)事件(通過(guò) ?Moralis.authenticate()? / ?Moralis.enableWeb3()?):

// Subscribe to onWeb3Enabled events
const unsubscribe = Moralis.onWeb3Enabled((result) => {
  console.log(result);
});

// Unsubscribe to onWeb3Enabled events
unsubscribe();

結(jié)果對(duì)象

{
  account: '0x1a2b3c4d....',
  chain: '0x1',
  connector: {} // the connector instance
  web3: {} // the Ethers.js web3 instance
  provider: {} // the EIP1193-provider, used to connect
}

Moralis.onWeb3Deactivated()

當(dāng)用戶(hù)斷開(kāi)連接時(shí)監(jiān)聽(tīng)事件(通過(guò) Moralis.deactivateWeb3()):

// Subscribe to onWeb3Deactivated events
const unsubscribe = Moralis.onWeb3Deactivated((result) => {
  console.log(result);
});

// Unsubscribe to onWeb3Deactivated events
unsubscribe();

結(jié)果對(duì)象

{
  connector: {
  } // the connector instance
  provider: {
  } // the EIP1193-provider, used to connect
}

Moralis.onChainChanged()

在啟用 web3 后,當(dāng)用戶(hù)更改鏈時(shí)監(jiān)聽(tīng)事件。

// Subscribe to onChainChanged events
const unsubscribe = Moralis.onChainChanged((chain) => {
  console.log(chain);
  // returns the new chain --> ex. "0x1"
});

// Unsubscribe to onChainChanged events
unsubscribe();

Moralis.onAccountChanged()

在啟用 web3 后,在用戶(hù)更改帳戶(hù)時(shí)監(jiān)聽(tīng)事件。

// Subscribe to onAccountChanged events
const unsubscribe = Moralis.onAccountChanged((chain) => {
  console.log(chain);
  // returns the new account --> ex. "0x1a2b3c4d..."
});

// Unsubscribe to onAccountChanged events
unsubscribe();

Moralis.onConnect()

您可能想改用 ?Moralis.onWeb3Activated?,因?yàn)樗恢?,并且?nbsp;Moralis 處理,而不是 EIP-1193 提供程序

當(dāng)提供者觸發(fā)連接事件時(shí)監(jiān)聽(tīng)事件。

規(guī)范

Provider 在以下情況下發(fā)出連接:
  • 初始化后首先連接到一個(gè)鏈。
  • 在發(fā)出斷開(kāi)事件后,首先連接到鏈。
// Subscribe to onConnect events
const unsubscribe = Moralis.onConnect((provider) => {
  console.log(provider);
  // returns the EIP-1193 provider
});

// Unsubscribe to onConnect events
unsubscribe();

Moralis.onDisconnect()

您可能想改用 ?Moralis.onWeb3Deactivated?,因?yàn)樗恢?,并且?nbsp;Moralis 處理,而不是 EIP-1193 提供程序

當(dāng)提供者觸發(fā)斷開(kāi)事件時(shí)監(jiān)聽(tīng)事件。

規(guī)范

Provider 在與所有鏈斷開(kāi)連接時(shí)發(fā)出斷開(kāi)連接

// Subscribe to onDisconnect events
const unsubscribe = Moralis.onDisconnect((error) => {
  console.log(error);
  // returns a ProviderRpcError
});

// Unsubscribe to onDisconnect events
unsubscribe();

要監(jiān)聽(tīng)這些事件,您只需調(diào)用 ?Moralis.onXXX?。 例如:

const unsubscribe = Moralis.onAccountChanged(function (account) {
  console.log(account);
});
// "0x1a2b3c4d..."

Metamask(和其他錢(qián)包)事件

如果您想在連接用戶(hù)之前(在元掩碼上)偵聽(tīng)事件,那么您可能希望直接從元掩碼偵聽(tīng)事件

https://docs.metamask.io/guide/ethereum-provider.html#events

例如

window.ethereum.on('accountsChanged' (accounts) => {
  console.log(accounts)
  // --> [0x1a2b3c4d...]
})

其他錢(qián)包也有類(lèi)似的實(shí)現(xiàn),請(qǐng)查看各自錢(qián)包的文檔。

鏈接

將地址鏈接(取消鏈接)到當(dāng)前用戶(hù)。

  • link(address)
  • unlink(address)

用戶(hù)可能有多個(gè)他們希望與他們的個(gè)人資料相關(guān)聯(lián)的地址。 這可以在用戶(hù)通過(guò)身份驗(yàn)證后使用鏈接功能完成。

Moralis.onAccountChanged(async function (account) {
  const confirmed = confirm("Link this address to your account?");
  if (confirmed) {
    await Moralis.link(account);
    alert("Address added!");
  }
});

取消鏈接功能從用戶(hù)的個(gè)人資料中刪除給定的地址。

await Moralis.unlink(address);

更改鏈接消息

可以通過(guò)提供?signingMessage ?選項(xiàng)來(lái)更改用戶(hù)在將地址鏈接到當(dāng)前用戶(hù)時(shí)看到的消息:

await Moralis.link(accounts[0], { signingMessage: "Custom Linking Message" });

ensureWeb3IsInstalled

檢測(cè)是否激活了 web3 提供程序。

返回: True or False

const isWeb3Active = Moralis.ensureWeb3IsInstalled();

if (isWeb3Active) {
  console.log("Activated");
} else {
  await Moralis.enable();
}

停用 Web3

停用當(dāng)前的 web3 連接

      await Moralis.enableWeb3();
      console.log("ENABLED", Moralis.isWeb3Enabled());
      await Moralis.deactivateWeb3();
      console.log("DISABLED", Moralis.isWeb3Enabled());

連接器/連接器類(lèi)型

返回連接器或連接器類(lèi)型的詳細(xì)信息,用于驗(yàn)證或啟用 web3:

const connectorType = Moralis.Web3.connectorType;
if (connectorType === "injected") {
  console.log("Metamask or an injected provider is used");
}

const connector = Moralis.Web3.connector;
console.log(connector);

鏈 ID

返回用于連接 web3 的當(dāng)前鏈 ID

const chainId = await Moralis.chainId;
console.log(chainId); // 56

帳戶(hù)

返回用于連接到 web3 的當(dāng)前帳戶(hù)

更改網(wǎng)絡(luò)

改變當(dāng)前網(wǎng)絡(luò)的功能

注意:此方法只能在 Metamask 用作連接器時(shí)使用

選項(xiàng):

  • ?chain?(必填):要切換到的鏈 id。 接受數(shù)字或十六進(jìn)制字符串中的值。 有效值列在交易和余額部分的介紹頁(yè)面上。 示例:56、“0x38”

const chainId = "0x1"; //Ethereum Mainnet
const chainIdHex = await Moralis.switchNetwork(chainId);

您只能切換到錢(qián)包中的網(wǎng)絡(luò)。 如何添加新網(wǎng)絡(luò),您可以在下面找到。

添加網(wǎng)絡(luò)

注意:此方法只能在 Metamask 用作連接器時(shí)使用

將新網(wǎng)絡(luò)添加到錢(qián)包的功能。 您可以在他們的文檔站點(diǎn)中找到每個(gè)鏈的網(wǎng)絡(luò)配置。

選項(xiàng):

  • ?chainid?(必填):網(wǎng)絡(luò)鏈 ID
  • ?chainName?(必填):網(wǎng)絡(luò)名稱(chēng)
  • ?currencyName?(必填):本幣名稱(chēng)
  • ?currencySymbol?(必填):貨幣符號(hào)
  • ?rpcUrl?(必填):新的 RPC URL
  • ?blockExplorerUrl?(必填):塊瀏覽器 URL

const chainId = 43114;
const chainName = "Avalanche Mainnet";
const currencyName = "AVAX";
const currencySymbol = "AVAX";
const rpcUrl = "https://api.avax.network/ext/bc/C/rpc";
const blockExplorerUrl = "https://cchain.explorer.avax.network/";

await Moralis.addNetwork(
  chainId,
  chainName,
  currencyName,
  currencySymbol,
  rpcUrl,
  blockExplorerUrl
);


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)