日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Moralis教程:Moralis與Node.js連接

安裝 Moralis SDK

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

創(chuàng)新互聯(lián)主要從事網(wǎng)站制作、成都網(wǎng)站制作、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)永濟(jì),10余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):18980820575

npm install moralis
yarn add moralis

SDK 初始化

您需要在 node.js 中使用以下語(yǔ)法初始化 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?,您可以直接訪問(wèn) Moralis 儀表板,無(wú)需進(jìn)行身份驗(yàn)證。

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

請(qǐng)記住永遠(yuǎn)不要泄露您的主密鑰,因?yàn)橐坏┯腥双@得您的主密鑰,他們就可以完全訪問(wèn)您的 Moralis 帳戶。

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

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

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

創(chuàng)建一個(gè)文件 ?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();

在終端中運(yùn)行以下命令:

ts-node SaveData.ts

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

Query

創(chuàng)建一個(gè)文件 ?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);
};

運(yùn)行:

ts-node FindQuery.ts

在您的控制臺(tái)中,您將看到:

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

Live Query

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

創(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();

運(yùn)行:

ts-node LiveQuery.ts

在您的控制臺(tái)中,您將看到:

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,而不是通過(guò)Moralis 服務(wù)器。

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

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

運(yùn)行:

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)建一個(gè)文件 ?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?,而不是通過(guò)Moralis 服務(wù)器。

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

運(yùn)行:

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)建一個(gè)文件 ?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?,而不是通過(guò)Moralis 服務(wù)器。

運(yùn)行:

ts-node execute.ts

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

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

從代碼添加新地址同步

Sync and Watch Address? 插件在底層調(diào)用了一個(gè)名為 ?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();

運(yùn)行:

ts-node watchAddr.ts

在終端中,您將看到:

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

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

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

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

從代碼添加新的事件同步

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

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

創(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();

運(yùn)行:

ts-node watchEvent.ts

在終端中,您將看到:

{ success: true }

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


新聞標(biāo)題:創(chuàng)新互聯(lián)Moralis教程:Moralis與Node.js連接
標(biāo)題鏈接:http://www.dlmjj.cn/article/cceojoh.html