提问人:pirqqs 提问时间:10/7/2023 最后编辑:pirqqs 更新时间:10/9/2023 访问量:31
Remix 中的智能合约函数返回 true,但在 VS code 中返回 false
Smart Contract Function in Remix returns true but in VS code returns false
问:
当我在 Remix 中编译并调用 and 函数时,它们都返回 true 。现在,在我的 Js 文件中,我只想在这两个智能合约函数返回 true 时进行一些计算,当我创建智能合约的实例并调用这两个函数时,返回 false 而不是 true。我不明白为什么?
我将提供我的智能合约代码,我的compile.js以及我的Js文件来做一些计算(Signataire.js)
Solidity智能合约:check_If_Address_Already_Signed()
check_Database_Verified_Address()
check_Database_Verified_Address()
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "./DataBase_Add_Verifies.sol";
// import "./Identification_C_EA.sol";
// Deno was installed successfully to /Users/pierre/.deno/bin/deno
// Manually add the directory to your $HOME/.zshrc (or similar)
// export DENO_INSTALL="/Users/pierre/.deno"
// export PATH="$DENO_INSTALL/bin:$PATH"
// Run '/Users/pierre/.deno/bin/deno --help' to get starte
contract Signataire is DataBaseAddresses {
mapping(address => bool) already_Signed_Addresses;
// Event pour dire que le signataire peut signer le Jeton
// Function pour check avec Database addresse verifie
function check_Database_Verified_Address() public view returns (bool) {
for (uint256 i = 0; i < verified_Addresses.length; i++) {
if (verified_Addresses[i] == msg.sender) {
return true;
}
}
return false;
}
//Function pour check si Addresse a deja signe un jeton
function check_If_Address_Already_Signed() public view returns (bool) {
if (already_Signed_Addresses[msg.sender] == false) {
return true;
}
}
//Function qui ajout msg.sender a l'aray
function Ajout_Add_Array() internal {
if (
check_Database_Verified_Address() &&
check_If_Address_Already_Signed() == true
) {
already_Signed_Addresses[msg.sender] = true;
}
}
}
这是我的编译文件:
const path = require("path");
const fs = require("fs-extra");
const solc = require("solc");
const Web3 = require("web3");
// Loading the contract ABI and Bytecode
// (the results of a previous compilation step)
const ethers = require("ethers");
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const sourceFolderPath = path.resolve(
__dirname,
"/Users/pierre/Authentification_TM/Smart-Contracts"
);
const buildFolderPath = path.resolve(__dirname, "build");
const getContractSource = (contractFileName) => {
const contractPath = path.resolve(
__dirname,
"Signataire.sol",
contractFileName
);
return fs.readFileSync(contractPath, "utf8");
};
let sources = {};
var walk = function (dir) {
var results = [];
var list = fs.readdirSync(dir);
list.forEach(function (file) {
file = dir + "/" + file;
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(walk(file));
} else {
if (file.substr(file.length - 4, file.length) === ".sol") {
sources = {
...sources,
[file]: {
content: getContractSource(file),
},
};
}
results.push(file);
}
});
return results;
};
walk(sourceFolderPath);
const input = {
language: "Solidity",
sources,
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
console.log("\nCompiling contracts...");
const output = JSON.parse(solc.compile(JSON.stringify(input)));
console.log("Done");
let shouldBuild = true;
if (output.errors) {
console.error(output.errors);
// throw '\nError in compilation please check the contract\n';
for (error of output.errors) {
if (error.severity === "error") {
shouldBuild = false;
throw "Error found";
break;
}
}
}
if (shouldBuild) {
console.log("\nBuilding please wait...");
fs.removeSync(buildFolderPath);
fs.ensureDirSync(buildFolderPath);
for (let contractFile in output.contracts) {
for (let key in output.contracts[contractFile]) {
fs.outputJsonSync(
path.resolve(buildFolderPath, `${key}.json`),
{
abi: output.contracts[contractFile][key]["abi"],
bytecode:
output.contracts[contractFile][key]["evm"]["bytecode"]["object"],
},
{
spaces: 2,
EOL: "\n",
}
);
}
}
console.log("Build finished successfully!\n");
} else {
console.log("\nBuild failed\n");
}
这是我的 Signataire.js 文件:
/*
Le signataire ne doit signer le message transmis que si les deux
already_Signed_Addresses() et check_If_Address_Already_Signed()
sont vrais.
Import le smart contract, call les deux fonctions, si elles sont just => ecrire code pour signer avec
la private key d une addresse (Signgataire), si c est faux alors revert
Ecrire une transaction du signataire au Citoyen (msg.sender), Avec comme data son Jeton signé
*/
const crypto = require("crypto");
const ethers = require("ethers");
const web3 = require("web3");
require("dotenv").config();
const { abi, bytecode } = require("./build/Signataire.json");
function getRandomJeton(Choix_Vote, N_V) {
// Avoir deux nombre completement aleatoire
let randomAnonymeNumber1 = crypto.getRandomValues(new Uint32Array(1))[0];
let randomAnonymeNumber2 = crypto.getRandomValues(new Uint32Array(1))[0];
// Avoir un nombre unique a chaque citoyen
let uniqueNumber = "12345678910";
// Mettre ensemble le nombre aleatoire et unique pour cree un nombre 100% aleatoire et unique
let uniqueRandomValue = `${uniqueNumber}${randomAnonymeNumber2}${randomAnonymeNumber1}`;
// Mettre ensemble les donne necessaire pour avoir le jeton
let unhashedJeton = `${Choix_Vote}${uniqueRandomValue}${N_V}`;
const Jeton = crypto.createHash("sha256").update(unhashedJeton).digest("hex");
return Jeton;
}
const Jeton = getRandomJeton(1, 2);
console.log(Jeton);
//Function pour aveugle le jeton
const provider = new ethers.providers.WebSocketProvider(
`wss://polygon-mumbai.g.alchemy.com/v2/${process.env.ALCHEMY_PRIVATE_KEY}`
);
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const ABI = abi;
// console.log(ABI);
const contractAddress = "0xF0168BC0DBb989bf3163f2353DdA4D3A09b073fa";
// Replace with your contract's ABI
const contract = new ethers.Contract(contractAddress, ABI, provider);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
// console.log(wallet);
async function sign_jeton() {
try {
console.log(await contract.get_Array());
const databaseVerified = await contract.check_Database_Verified_Address();
const addressAlreadySigned =
await contract.check_If_Address_Already_Signed();
console.log(databaseVerified);
console.log(addressAlreadySigned);
if (addressAlreadySigned && databaseVerified == true) {
// If both conditions are met, sign the Jeton
const signature_Jeton = web3.eth.accounts.sign(Jeton, PRIVATE_KEY);
console.log("Signature:", signature_Jeton);
process.exit();
} else {
console.log("Conditions not met. Cannot sign Jeton.");
process.exit();
}
} catch (error) {
console.error("Error:", error);
process.exit();
}
}
sign_jeton();
// process.exit();
我已经看到,当我尝试从我的 JS 文件中的合约中获取时,我得到 js 文件无法从智能合约中读取数组,因此它无法返回 true,因为不匹配。导入此数组不是程序,因为我尝试在同一个智能合约中声明它,但它仍然不起作用,我也尝试在构造函数中声明它,但没有工作。我试图声明一个不同的数组,如 uint8 myArray[] = [1,2,3],我用保留完全相同逻辑的 myArray 替换了verified_Adresses,它确实有效。所以我不明白问题出在哪里,是不是地址数组不能在合约之外访问?我还看到另一个人用一个关于块的音印的函数问同样的问题,但没有帮助,这是问题的链接: Solidity 函数在混音中返回 true,但在 web3 函数调用中返回 false 任何帮助都会得到赞赏,console.log(verfied_Adresses)
0x000...
check_Database_Verified_Address()
0x000...
msg.sender
非常感谢您抽出宝贵时间:)
答:
阅读文档后,我发现了问题所在。对于遇到相同问题的人,您需要将 solidity 代码中的 msg.sender 替换为变量。这意味着我们声明地址不是 msg.sender 用户 = msg.sender ,通常它会起作用。谢谢
评论