Moralis 與Node.js連接

2022-05-13 11:22 更新

安裝 Moralis SDK

運行以下命令安裝 Moralis SDK,您可以使用?npm?或者?yarn?

npm install moralis
yarn add moralis

SDK 初始化

您需要在 node.js 中使用以下語法初始化 Moralis SDK:

創(chuàng)建文件 ?index.ts? 并添加以下代碼:

/* import moralis */
const Moralis = require("moralis/node");

/* Moralis init code */
const serverUrl = "YOUR-SERVER-URL";
const appId = "YOUR-APP-ID";
const masterKey = "YOUR-MASTER-KEY";

await Moralis.start({ serverUrl, appId, masterKey });

使用 ?masterKey?,您可以直接訪問 Moralis 儀表板,無需進行身份驗證。

使用主密鑰,您可以直接從后端使用 SDK 使用您 Moralis 帳戶的 ?API?、?RPC ?節(jié)點和其他功能。

請記住永遠不要泄露您的主密鑰,因為一旦有人獲得您的主密鑰,他們就可以完全訪問您的 Moralis 帳戶。

數(shù)據(jù)庫查詢

保存數(shù)據(jù)

要使用數(shù)據(jù)復(fù)制粘貼以下代碼來保存對象:

創(chuàng)建一個文件 ?SaveData.ts? 并添加以下代碼:

const SaveData = async () => {
  await Moralis.start({ serverUrl, appId, masterKey });

  const Monster = Moralis.Object.extend("Monster");
  const monster = new Monster();

  monster.set("strength", 1024);
  monster.set("ownerName", "Aegon");
  monster.set("canFly", true);

  await monster.save();
};

SaveData();

在終端中運行以下命令:

ts-node SaveData.ts

轉(zhuǎn)到您的 Moralis 儀表板,您將看到保存在數(shù)據(jù)庫中的數(shù)據(jù):

spaces_-MVStbACGLCycg7J5WQ2_uploads_git-blob-c452479d573523fbf0f25ba33e45160b77abb115_node1

Query

創(chuàng)建一個文件 ?FindQuery.ts? 并添加以下代碼:

const FindQuery = async () => {
  const Monster = Moralis.Object.extend("Monster");
  const query = new Moralis.Query("Monster");

  const results = await query.find();
  console.log(results);
};

運行:

ts-node FindQuery.ts

在您的控制臺中,您將看到:

[
  ParseObjectSubclass {
    className: 'Monster',
    _objCount: 0,
    id: 'I3tbPplP8T531e0vgBrFVj5O'
  }
]

Live Query

訂閱查詢以在查詢結(jié)果集中的數(shù)據(jù)發(fā)生更改時獲取實時警報。

創(chuàng)建文件 ?LiveQuery.ts? 在文件中添加以下代碼:

const LiveQuery = async () => {
  const Monster = Moralis.Object.extend("Monster");
  const query = new Moralis.Query(Monster);

  let subscription = await query.subscribe();
  console.lIog(subscription);
};

LiveQuery();

運行:

ts-node LiveQuery.ts

在您的控制臺中,您將看到:

Subscription {
  _events: [Object: null prototype] { error: [Function (anonymous)] },
  _eventsCount: 1,
  _maxListeners: undefined,
  id: 1,
  query: ParseQuery {
    className: 'Monster',
    _where: {},
    _include: [],
    _exclude: [],
    _select: undefined,
    _limit: -1,
    _skip: 0,
    _count: false,
    _order: undefined,
    _readPreference: null,
    _includeReadPreference: null,
    _subqueryReadPreference: null,
    _queriesLocalDatastore: false,
    _localDatastorePinName: null,
    _extraOptions: {},
    _hint: undefined,
    _explain: undefined,
    _xhrRequest: { task: null, onchange: [Function: onchange] }
  },
  sessionToken: undefined,
  subscribePromise: Promise {
    undefined,
    resolve: [Function (anonymous)],
    reject: [Function (anonymous)]
  },
  subscribed: true,
  [Symbol(kCapture)]: false
}

使用Web3API

創(chuàng)建文件 ?Web3API.ts? 并添加以下代碼:

const serverUrl = "YOUR-SERVER-URL";
const appId = "YOUR-APP-ID";
const moralisSecret = "YOUR MORALIS SECRET";

const web3API = async () => {
  await Moralis.start({ serverUrl, appId, moralisSecret });

  const price = await Moralis.Web3API.token.getTokenPrice({
    address: "0xe9e7cea3dedca5984780bafc599bd69add087d56",
    chain: "bsc",
  });
  console.log(price);
};

web3API();

使用?moralisSecret?,所有API 調(diào)用都直接轉(zhuǎn)到API,而不是通過Moralis 服務(wù)器。

要獲得?moralisSecret?,您需要進入帳戶設(shè)置,如下圖所示

spaces_-MVStbACGLCycg7J5WQ2_uploads_git-blob-cc694e959a8b1bc5336e50639ecee97e116bb881_moralisSecret1

然后轉(zhuǎn)到API并復(fù)制你的?moralisSecret?密鑰

spaces_-MVStbACGLCycg7J5WQ2_uploads_git-blob-2e88d7d2f8bb0a0acf1f4b5853aaeb2eeccc3f87_moralisSecret2

運行:

ts-node Web3API.ts

您將看到以下結(jié)果:

{
  nativePrice: {
    value: '2492486316397403',
    decimals: 18,
    name: 'Binance Coin',
    symbol: 'BNB'
  },
  usdPrice: 1.000879782388469,
  exchangeAddress: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
  exchangeName: 'PancakeSwap v2'
}

使用私鑰啟用 Moralis

Moralis.Transfer

我們可以在后端使用私鑰傳輸任何“native”| 'erc20' | 'erc721' | 'erc1155' tokens。

創(chuàng)建一個文件 ?tranx.ts? 并添加以下代碼:

const tranx = async () => {
  await Moralis.start({ serverUrl, appId, moralisSecret });

  // Enable web3
  await Moralis.enableWeb3({
    //BSC mainnet
    chainId: 0x38,
    privateKey: "YOUR-PRIVATE KEY",
  });

  // sending 0.5 DAI tokens with 18 decimals on BSC mainnet
  const options: Moralis.TransferOptions = {
    type: "erc20",
    amount: Moralis.Units.Token("0.5", 18),
    receiver: "0x93905fd3f9b8732015f2b3Ca6c16Cbcb60ECf895",
    contractAddress: "0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3",
  };
  await Moralis.transfer(options).then((result) => {
    console.log(result);
  });
};

tranx();

使用?moralisSecret?,所有?API調(diào)用都直接轉(zhuǎn)到?API?,而不是通過Moralis 服務(wù)器。

私鑰不應(yīng)暴露給前端或瀏覽器或云端,否則將導(dǎo)致資金損失

運行:

ts-node tranx.ts

您將在終端中看到結(jié)果:

{
  nonce: 9,
  gasPrice: BigNumber { _hex: '0x012a05f200', _isBigNumber: true },
  gasLimit: BigNumber { _hex: '0x8d07', _isBigNumber: true },
  to: '0x1AF3F329e8BE154074D8769D1FFa4eE058B1DBc3',
  value: BigNumber { _hex: '0x00', _isBigNumber: true },
  data: '0xa9059cbb00000000000000000000000093905fd3f9b8732015f2b3ca6c16cbcb60ecf89500000000000000000000000000000000000000000000000006f05b59d3b20000',
  chainId: 56,
  v: 147,
  r: '0x2715e0d05fdf82f7e129c1d0608de4629d15fffa557d43339d78489d80f78a0f',
  s: '0x12ab674095e18b1e81525e30826b55ebcc24cddfceed855c26819aafdd4f78d3',
  from: '0x7094F8B1a2a1EeA360D79Be99bAeF18175aa30Ca',
  hash: '0xc53417f3f584680ad81046195c64edf59f8a2eb6826793765676ebe304f74760',
  type: null,
  confirmations: 0,
  wait: [Function (anonymous)]
}

Moralis.executeFunction

創(chuàng)建一個文件 ?execute.ts? 并添加以下代碼:

const execute = async () => {
  await Moralis.start({ serverUrl, appId, moralisSecret });

  // Enable web3
  await Moralis.enableWeb3({
    chainId: 0x1,
    privateKey:
      "afcf6a8d1a2b9e20bd322850afb28085693f436427fe8da3d0e40954cfb2d0dc",
  });

  const options = {
    // CAPSULE contract
    contractAddress: "0xfcb1315c4273954f74cb16d5b663dbf479eec62e",
    // calling tokenURI function
    functionName: "tokenURI",
    // contract ABI
    abi: [
      {
        inputs: [{ internalType: "uint256", name: "tokenId", type: "uint256" }],
        name: "tokenURI",
        outputs: [{ internalType: "string", name: "", type: "string" }],
        stateMutability: "view",
        type: "function",
      },
    ],
    // token URI of token ID 700
    params: { tokenId: 700 },
  };
  await Moralis.executeFunction(options).then((result) => {
    console.log(result);
  });
};

execute();

使用?moralisSecret?,所有?API?調(diào)用都直接轉(zhuǎn)到?API?,而不是通過Moralis 服務(wù)器。

運行:

ts-node execute.ts

您將在終端中看到結(jié)果:

https://hatch.capsulehouse.io/api/metadata/700

從代碼添加新地址同步

Sync and Watch Address? 插件在底層調(diào)用了一個名為 ?watchXxxAddress ?的云函數(shù),其中“?Xxx?”是下表的鏈名。 這些云函數(shù)也可以直接從自己的代碼中調(diào)用!

 Chain  Prefix
 Ethereum Mainnet, Ropsten, Georli, Kovan, Local Devchain  ?Eth?
 Binance Smart Chain Mainnet, Testnet  ?Bsc?
 Polygon (Matic) Mainnet, Mumbai Testnet  ?Matic?
 Elrond  ?Erd?

創(chuàng)建文件watchAddr.ts??并添加以下代碼:

const watchAddr = async () => {
  await Moralis.start({ serverUrl, appId, masterKey });

  await Moralis.Cloud.run(
    "watchBscAddress",
    { address: "0x..." },
    { useMasterKey: true }
  ).then((result) => {
    console.log(result);
  });
};

watchAddr();

運行:

ts-node watchAddr.ts

在終端中,您將看到:

{ status: 200, data: { success: true, result: true } }

交易數(shù)據(jù)存儲在 Moralis Dashboard 中:

spaces_-MVStbACGLCycg7J5WQ2_uploads_git-blob-d950dd0c327d216ae2bde44b3927878dfe482e9b_db1

默認情況下,只有使用此云功能被監(jiān)視的地址所做的新交易才會被添加到數(shù)據(jù)庫中。 如果您還想為要觀看的地址添加歷史數(shù)據(jù),可以添加 ?sync_historical:true ?

注意:監(jiān)視地址函數(shù)在開始作業(yè)時不返回任何值。 它們?nèi)匀皇钱惒降模?nbsp;一旦 ?promise ?返回同步的事務(wù),它們應(yīng)該在相應(yīng)鏈的 ?XxxTransactions ?表中。

從代碼添加新的事件同步

Moralis Server 有一個特殊的云功能,稱為 ?watchContractEvent(options)?。 您可以使用主密鑰調(diào)用它。

注意:目前通過代碼創(chuàng)建的事件不會在管理 UI 中看到,您只能在數(shù)據(jù)庫中看到它們。

創(chuàng)建文件 ?watchEvent.ts? 并添加以下代碼:

const watchEvent = async () => {
  await Moralis.start({ serverUrl, appId, masterKey });
  // code example of creating a sync event from cloud code
  let options = {
    chainId: "42",
    // UniswapV2Factory contract
    address: "0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f",
    topic: "PairCreated(address, address, address, uint256)",
    abi: {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "token0",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "token1",
          type: "address",
        },
        {
          indexed: false,
          internalType: "address",
          name: "pair",
          type: "address",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "test",
          type: "uint256",
        },
      ],
      name: "PairCreated",
      type: "event",
    },
    limit: 500000,
    tableName: "UniPairCreated",
    sync_historical: false,
  };

  Moralis.Cloud.run("watchContractEvent", options, { useMasterKey: true }).then(
    (result) => {
      console.log(result);
    }
  );
};

watchEvent();

運行:

ts-node watchEvent.ts

在終端中,您將看到:

{ success: true }

事件數(shù)據(jù)成功存儲在 Moralis Dashboard 中

spaces_-MVStbACGLCycg7J5WQ2_uploads_git-blob-5b24e27c37f04687cd0c804c93226da35d5d5f1d_db2


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號