ethereum - 我可以在交易记录中附加一段文字吗?

标签 ethereum smartcontracts web3js

根据 web3.eth.sendTransaction 的文档和 eth_sendTransaction 的文档:

交易对象可以包含一个可选的data参数,它应该是一个String,包含:

要么是包含合约函数调用数据的 ABI 字节字符串,要么是合约创建交易的初始化代码。

我想为data分配一个字符串,并将该字符串与交易记录一起存储在区 block 链上,这样我就可以在检索该交易记录时检索该字符串稍后。

const [testAccount] = await window.ethereum.request({ method: "eth_requestAccounts" })
    
const web3 = new Web3(window.ethereum)

if (!testAccount) {
  return
}

let transactionHash = await web3.eth.sendTransaction({
  from: testAccount,
  to: testAccount,
  value:  web3.utils.toWei('0.0003'), 
  data: web3.utils.utf8ToHex(JSON.stringify({ a: 1, b: 2 }))
})

let transaction = await web3.eth.getTransaction(transactionHash)
let data = JSON.parse(web3.utils.hexToUtf8(transaction.data))
console.log(data.a) // should log 1

当我执行 sendTransaction(使用 Metamask,同时连接到 Ropsten 网络)时,我收到以下错误:

Error:  Error: TxGasUtil - Trying to call a function on a non-contract address
{
  "originalError": {
    "errorKey": "transactionErrorNoContract",
    "getCodeResponse": "0x"
  }
}

显然,您不能将任何字符串分配给 data 并期望该字符串被合并到区 block 链上的交易记录中,开箱即用,只需将一个值分配给它。 这是正确的吗?

问题:我是否需要编写自定义智能合约才能实现此目的?

最佳答案

这是 MetaMask 特有的功能/限制。可能是为了保护想要与智能合约交互但连接到未部署合约的不同网络的用户。

但是,技术上可以将具有非空 data 字段的有效交易发送到非合约地址。您只需要使用不同的节点提供商来广播交易。不幸的是,MetaMask 中的节点提供者是硬编码的,因此无法使用此钱包。

示例:This transactionRopsten testnet 到具有 USDT0xdac1... 地址部署在主网上的 token 合约,但在测试网上是一个非合约地址。这是一个有效的交易,成功地从发件人地址购买了 gas 以支付交易费用,在一个区 block 中开采,只是没有执行任何智能合约代码(因为收件人地址上没有智能合约)。

关于ethereum - 我可以在交易记录中附加一段文字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72521460/

相关文章:

ethereum - Solidity 中 require(send()) 的安全问题

blockchain - assert 和 require 的区别

javascript - MetaMask 不注入(inject) window.ethereum : Uncaught (in promise) TypeError: Cannot read property 'request' of undefined

database - 区 block 链的物理位置是什么?

ethereum - 是否可以从 Ledger Nano S 以太坊钱包导出 Xpub Key

ethereum - Solidity 中数组后面定义的变量存储在哪些槽中?

c# - 获取 Azure 区 block 链项目的不记名 token

node.js - 我们可以在 NodeJS 中使用 Solidity 吗?

javascript - 如何使用 web3js 创建公钥和私钥?

ethereum - Web3.js API 调用有限制吗?