BlockChain區塊鏈
  • 本書簡介
  • 區塊鏈運作原理
  • Bitcoin介紹
    • 簡介
    • Bitcoin其他知識
  • Bitcoin原理與實作
  • BitcoinJS
    • BTC 地址格式種類
    • 從 Mnemonic 轉為地址
  • Serverless 架構實作
  • Docker常用指令
  • ethereum初探
    • ethereum歷史
    • EVM
  • ethereum PoS 節點架設
  • ethereum(Docker)
  • ethereum(Geth)
    • Parity
  • ethereum(智能合約)
    • 合約測試 Unit Test
    • DAO
    • 可升級合約
    • 使用合約進行 multiswap
    • 合約安全
    • 開發工具
    • Hardhat 教學
      • Hardhat 寫測試
    • ERC-721 範例
      • 白名單機制
    • OpenZeppelin 合約 library
    • Truffle
    • 合約部屬
    • solidity 教學
  • ethereum(Dapp)
    • 相關 SDK
    • Multicall
    • Ethers.js 使用
    • Remix IDE
    • web3.js 使用
    • 在網頁上使用 web3 並操作區塊鏈
      • solidity筆記
  • Hyperledger Fabric
  • blockchainDB
  • 挖礦程式使用教學
    • 門羅幣/Monero (XMR)
  • Bitfinex API 使用
  • FTX API
  • CCXT 通用交易所 API
  • Solana 教學
  • Ethereum BigQuery
  • The Graph
    • yaml 定義
    • mapping 語法
    • Schema 定義
    • Query 範例
    • Unit test
  • DeFi 筆記
    • MEV 相關
    • Dex 聚合
    • Yearn
    • Curve
    • Uniswap
      • Swap 互動
    • AAVE、Compound
      • Compound 原理
      • AAVE 合約開發
Powered by GitBook
On this page
  • 單位 Ether 轉 Wei
  • 單位 Wei 轉 Ether
  • 讀取地址餘額:
  • 執行合約
  • 讀取合約:
  • 前端使用 sendTransaction 與 signMessage
  • 從後端呼叫 function
  • Call static
  • JSON 內有 Bigint 結構轉換

Was this helpful?

  1. ethereum(Dapp)

Ethers.js 使用

單位 Ether 轉 Wei

return bigint (e.g. 12000000n)

ethers.utils.parseUnits("0.11", "ether")

單位 Wei 轉 Ether

return string (ether string)

ethers.utils.formatEther(balance);

讀取地址餘額:

const { ethers } = require("ethers");

let provider = new ethers.providers.InfuraProvider('rinkeby');

 let address = "0x00....";

 provider.getBalance(address).then((balance) => {
     let etherString = ethers.utils.formatEther(balance);
     console.log("Balance: " + etherString);
 });

執行合約

const { Contract, providers, utils: Utils, Wallet, ethers } = require("ethers");

const {
  abi,
} = require("./artifacts/contracts/<contract>.sol/<contract>.json");

async function createMarket(
  privateKey,
  title
) {
  const provider = new ethers.JsonRpcProvider(url);

  // Create a wallet using the private key
  const wallet = new ethers.Wallet(privateKey, provider);

  // Connect the wallet to the contract
  const contract = new ethers.Contract(contractAddress, abi, wallet);
  return new Promise(async (resolve, reject) => {
    try {
      // Sign and send the transaction using the wallet
      const tx = await wallet.sendTransaction({
        to: contractAddress,
        data: contract.interface.encodeFunctionData("createMarket", [
          title
          ]),
      });

      // Wait for the transaction to be mined
      await tx.wait();
      resolve(tx);
      console.log("Market created successfully!");
    } catch (error) {
      reject();
      console.error("Error creating market:", error);
    }
  });
}

讀取合約:

const { ethers } = require("ethers");
const { abi } = require("./abi/...");

let provider = new ethers.providers.InfuraProvider('rinkeby');

let contractAddress = "0x...";
let contract = new ethers.Contract(contractAddress, abi, provider);

(async () => {
  let currentValue = await contract.symbol();
  console.log(currentValue);
})()

前端使用 sendTransaction 與 signMessage

const provider = new ethers.providers.Web3Provider(web3.currentProvider);
const signer = provider.getSigner();

const tx = await signer.sendTransaction(tx);
const signature = await signer.signMessage("Hello world");

從後端呼叫 function

後端所以需要直接填入私鑰

const { ethers } = require("ethers");
const { abi } = require("./abi/...");

let provider = new ethers.providers.InfuraProvider('rinkeby');

let contractAddress = "0x...";

let contract = new ethers.Contract(contractAddress, abi, provider);

 let privateKey = '...';
 let wallet = new ethers.Wallet(privateKey, provider);

 let contractWithSigner = contract.connect(wallet);

(async () => {
  let currentValue = await contractWithSigner.getUserRefundList();
  console.log(currentValue);
})()

Call static

通常會用在於獲取執行 function 的回傳值

JSON 內有 Bigint 結構轉換

例如出現:TypeError: Do not know how to serialize a BigInt

可以使用以下方式

const toObject = (obj) => {
  return JSON.parse(JSON.stringify(obj, (key, value) =>
      typeof value === 'bigint'
          ? value.toString()
          : value // return everything else unchanged
  ));
}
PreviousMulticallNextRemix IDE

Last updated 1 year ago

Was this helpful?

I see no way to obtain the return value of a non-view function (ethers.js)Ethereum Stack Exchange
Logo