通过脚本在本地机器上使用SAME钱包密钥将数据处理到以太坊上的智能合约



我计划接受不了解"公钥/私钥和以太坊"的人的数据,我想将这些数据交易到以太坊区块链上我已经部署的智能合约中。

我不能使用web3,因为用户没有任何以太坊钱包。这个条件是我的要求。

如何在合同中输入数据:示例场景:具有get((和set((的Greeter合约。

我只想在每次将一些数据发布到我的服务器时自动运行一个脚本,以便将这些数据处理到set((中的Greeter合约。总是使用相同的公钥/私钥对。

任何建议或伪脚本都会有所帮助。

开始:

const express = require("express");
const ethers = require("ethers");
const fs = require("fs");
const app = express();
const port = 3000;
// The contract ABI
let abi = [
{
constant: true,
inputs: [],
name: "get",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: false,
inputs: [{ internalType: "uint256", name: "x", type: "uint256" }],
name: "set",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
}
];
// Connect to contract
// https://goerli.etherscan.io/address/0x00530Aae5fDFa2C4cFe21Df5Fbe1B2213fe8f551#code
let provider = ethers.getDefaultProvider("goerli");
let contractAddress = "0x00530Aae5fDFa2C4cFe21Df5Fbe1B2213fe8f551";
let contract = new ethers.Contract(contractAddress, abi, provider);
app.get("/:message", async (req, res) => {
try {
userInput = req.params.message;
console.log("User input:", userInput); // if it prints 'favicon.ico', that's normal
userNumber = parseInt(userInput);
// Make sure user input is a number
if (isNaN(userNumber)) {
return res.send("Please only send number").end();
}
// Do not store private key in code
let privateKey = fs
.readFileSync("private-key.txt")
.toString()
.trim();
let wallet = new ethers.Wallet(privateKey, provider);
let contractWithSigner = contract.connect(wallet);
let tx = await contractWithSigner.set(userNumber);
res.send(
`Tx with number '${userNumber}' has been sent to contract.nHash: ${tx.hash}.`
);
// When the tx has been mined, you can verify it here:
// https://goerli.etherscan.io/address/0x00530aae5fdfa2c4cfe21df5fbe1b2213fe8f551#readContract
} catch (error) {
return next(error);
}
});
app.listen(port, () => console.log(`App is listening on port ${port}!`));

有关完整的源代码,请参阅此存储库。合同可以在这里找到。

最新更新