如何使用以太坊加密将签名从 React 应用程序发送到 Node JS 服务器

How to send a signature from a React App to a Node JS Server with ethereum-cryptography

提问人:Matias Salimbene 提问时间:11/14/2023 最后编辑:YilmazMatias Salimbene 更新时间:11/14/2023 访问量:30

问:

我正在做一个来自 Alchemy 的练习,我需要在将交易发送到服务器之前对其进行签名。然后在服务器端验证事务。我正在使用一个脚本,在该脚本中输入私钥和消息以生成签名,如下所示:

注意:我需要将signMessage转换为字符串,否则由于“BigInt”而收到TypeError


  async function transfer(evt) {
    evt.preventDefault();
    const signMessage = {
      r: 36691152806955910003274360488470766136656266395316605280087404244279825225745n,
      s: 25775843654993118241418850103739194190473898130155752009759534141754021856163n,
      recovery: 0,
    };

    try {
      const {
        data: { balance },
      } = await server.post(`send`, {
        signature: signMessage.toString(),
      });
    } catch (ex) {
      console.log(ex);
      alert(ex.response.data.message);
    }
  }

然后我在服务器端使用此代码,但它不起作用,由于错误“SyntaxError:无法将 [object Object] 转换为 BigIn”,我无法将字符串转换回 bigint

app.post("/send", (req, res) => {
  // TODO: get a signature from the client-side app
  // recover the public address from the signature

  const { signature } = req.body;

  // Convert the strings back to BigInt and Buffer
  const signatureBigInt = BigInt(signature);
  console.log({ signatureBigInt });

  res.send("testing");
  
});

我尝试了不同的东西和转换类型,但我认为我遗漏了一些东西,或者我对我正在做的事情从根本上是错误的。

JavaScript ReactJS Node.js 加密 以太坊

评论


答:

0赞 Yilmaz 11/14/2023 #1

来自 mdn doc:

使用 BigInt() 函数将值转换为 BigInt 时, value 将首先转换为基元。然后,如果它不是一个 的 BigInt、字符串、数字和布尔值,则会引发错误。

看起来只能转换类型。BigInt, string, number, and boolean

不应字符串化整个对象,而应字符串化要传递的对象键的值