简体   繁体   English

在服务器端(NodeJS)使用其他人签名者与以太坊智能合约集成

[英]Integrate with Ethereum smart contract using other person Signer on server-side (NodeJS)

I'm building a website for selling NFTs.我正在建立一个销售 NFT 的网站。 The way I saw to let visitors pay for a NFT item is by integrating with the smart contract on client side in order to get Signer from their wallet (eg Metamask).我看到让访问者为 NFT 项目付款的方式是与客户端的智能合约集成,以便从他们的钱包(例如 Metamask)中获取 Signer。

My client code:我的客户代码:

export async function createItemToken(itemPrice: number): Promise<string> {
  const web3Modal = new Web3Modal();
  const connection = await web3Modal.connect();
  const provider = new ethers.providers.Web3Provider(connection);
  const signer = provider.getSigner();

  const contract = new ethers.Contract(
    contractAddress,
    MyNFTContract.abi,
    signer,
  );

  const formatedItemPrice = ethers.utils.parseUnits(String(itemPrice), 'ether');
  const transaction = await contract.transferToken(
    {value: itemPrice},
  );

  const tx = await transaction.wait();
  return tx.transactionHash;
}

I understand the access to visitor's wallet is only on the client side but it doesn't make sense to let the client side do the call to the smart contract.我了解访问者钱包的访问权限仅在客户端,但让客户端调用智能合约是没有意义的。 For example, the visitor can enter different price for the item.例如,访问者可以为商品输入不同的价格。

How to avoid it?如何避免? is there a way to do this integration on the server side (NodeJS)?有没有办法在服务器端(NodeJS)进行这种集成?

I couldn't find a way to get visitor's signer on the server so maybe my all flow is not correct...thanks for the help!我找不到在服务器上获取访问者签名者的方法,所以也许我的所有流程都不正确......感谢您的帮助!

the visitor can enter different price for the item访问者可以为商品输入不同的价格

Sure they can.他们当然可以。 But the smart contract should also validate whether the value is an expected price.但智能合约还应验证该value是否为预期价格。 If it's not, it should revert the transaction.如果不是,它应该恢复交易。

Based on the provided code and questions, I'm assuming the price for token creation is only stored off-chain.根据提供的代码和问题,我假设创建代币的价格仅存储在链下。 You should use the contract as the source of truth for the price and validate it on-chain as well.您应该使用合约作为价格的真实来源,并在链上进行验证。

pragma solidity ^0.8;

contract MyNFTContract {
    function transferToken() external payable {
        require(msg.value == this.getPrice(), "Incorrect value");
        // ... 
    }

    function getPrice() external pure returns (uint256) {
        // can by also dynamic based on the token ID or any other on-chain param
        return 0.5 ether;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM