Contract-Invocation
如何在 nodejs 中使用這個合約?謝謝
我得到了這個似乎滿足我需要的契約,但我不知道如何從 nodejs 撥打電話,你能幫我嗎?謝謝
// SPDX-License-Identifier: MIT pragma solidity ^0.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Rewards is Ownable { IERC20 public rewardsToken; mapping(address => uint) public rewards; constructor(address _rewardsToken) { rewardsToken = IERC20(_rewardsToken); } function setReward(address account,uint256 amount) public onlyOwner { rewards[account] = amount; } function claimReward() public{ uint256 reward = rewards[msg.sender]; rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward*10**18); } }
您將使用諸如web3js或ethers之類的庫與它們進行互動。
正如鍊接一樣,這兩個都提供了一些很好的入門步驟,但您也可以在網上找到很多教程:
編輯:
範例
ethers
:import { ethers } from "ethers"; // See https://docs.ethers.io/v5/api/providers/ const jsonRpc = "some json rpc (e.g. infura)" const provider = new new ethers.providers.JsonRpcProvider(jsonRpc) // See https://docs.ethers.io/v5/api/signer/#Wallet const privateKey = "some private key" const wallet = new ethers.Wallet(privateKey, provider) // Manually define abi for the simplicity of the exmaple // Solidity also creates a abi definition when compiling the contract that can be used. const rewardsAbi = [ "function setReward(address account,uint256 amount) public", "function claimReward() public", ] const rewardsAddress = "0x<some_address>" // Use signer here as we want to change the state // See https://docs.ethers.io/v5/getting-started/#getting-started--writing const rewardsContract = new ethers.Contract(rewardsAddress, rewardsAbi, wallet); const tx = await rewardsContract.claimReward() // Wait for the tx to be mined const receipt = await tx.wait()