I found SelfDestruct problem in geth
I didn't call SelfDestruct on my smart contract
but, after restart my server PC which implements geth, my contract suddenly selfdestruct.
I have no sense about this kind of problem.
is there any condition of selfdestruct which I didn't know?
pragma solidity^0.4.19;
contract Dan_v1_1 {
struct DanInfo {
string file_path;
string kor_name;
string personal_key;
string eng_name;
uint8 gradeOfpoomDan;
string danCertificate;
uint[] regDateHistory;
bool flag;
}
mapping (string => DanInfo) danInfo;
mapping (uint => string) indexOfDanInfo;
uint private danInfoCount = 0;
address contractOwner;
function Dan_v1_1() public{
contractOwner = msg.sender;
}
function setInitDanInfo (string file_path,string kor_name, string personal_key,string eng_name,
uint8 gradeOfpoomDan,string danCertificate, uint []regDateHistory, bool flag)
public{
require (keccak256(danInfo[personal_key].personal_key) != keccak256(personal_key));
danInfo[personal_key] = DanInfo(file_path,kor_name, personal_key,eng_name,gradeOfpoomDan,danCertificate,regDateHistory,flag);
indexOfDanInfo[danInfoCount++] = personal_key;
}
function getDanInfoCount () public constant returns(uint) {
return danInfoCount;
}
function getDanInfo (string personal_key) public constant returns(string,string, string, string, uint8, string, uint[], bool) {
DanInfo memory temp = danInfo[personal_key];
return(temp.file_path,temp.kor_name, temp.personal_key, temp.eng_name, temp.gradeOfpoomDan, temp.danCertificate, temp.regDateHistory, temp.flag);
}
function killContract() public{
if(contractOwner == msg.sender) {
selfdestruct(contractOwner);
}
}
}
Related
i make simple code, but have error "TypeError: Explicit type conversion not allowed from "uint256" to "address"." Can you help me? I even asked the gpt bot about this error, but it confused me even more)))
in the beginning there was a simple idea - 10k nft, 30 of them immediately after the deposit, the minimum price is indicated and everyone can buy without restriction
`pragma solidity ^0.8.4;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract Sptzrawef is ERC721 {
// Define the token name, symbol, and maximum supply
uint256 public totalSupply = 10000;
string public tokenURI;
// Define the owner of the contract
address public owner;
// Define the minimum price of the token
uint256 public minPrice;
// Define the mapping for the token ownership
mapping(address => mapping(uint256 => bool)) public tokenOwnership;
// The constructor function
constructor() ERC721("Sptzrawef", "SP") {
tokenURI = "https://nftstorage.link/ipfs/ba.................q3oq/";
owner = msg.sender;
minPrice = 0.025 ether;
totalSupply = 10000;
// Mint 30 tokens immediately upon deployment
for (uint256 i = 1; i <= 30; i++) {
tokenOwnership[msg.sender][i] = true;
}
}
// Function to mint new tokens
function mint(address _to, uint256 _tokenId) public {
require(msg.sender == owner);
require(_tokenId <= totalSupply);
require(tokenOwnership[_to][_tokenId] == false);
tokenOwnership[_to][_tokenId] = true;
totalSupply++;
}
// Function to buy the token
function buy(uint256 _tokenId) public payable {
require(msg.value >= minPrice);
require(tokenOwnership[msg.sender][_tokenId] == false);
require(_tokenId <= totalSupply);
tokenOwnership[msg.sender][_tokenId] = true;
}
function balanceOf() public view returns (uint256) {
return totalSupply;
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
uint256 count = 0;
for (uint256 i = 1; i <= totalSupply; i++) {
if (tokenOwnership[_owner][i]) {
if (count == _index) {
return i;
}
count++;
}
}
return 0;
}
function ownerOf(uint256 _tokenId) public view override returns (address) {
require(_tokenId <= totalSupply);
for (uint256 i = 0; i < totalSupply; i++) {
address wallet = address(i); - error at this line
if (tokenOwnership[wallet][_tokenId]) {
return wallet;
}
}
return address(0);
}
}`
I think you are using ownerOf function in the wrong way.
try to create a new "getWalletAddress" function, for example, and use it in this way:
function getWalletAddress(uint256 _tokenId) public view returns (address) {
require(_tokenId <= totalSupply);
for (uint256 i = 0; i < totalSupply; i++) {
address wallet = ownerOf(i);
if (tokenOwnership[wallet][_tokenId]) {
return wallet;
}
}
return address(0);
}
}
Or if you want to override the "ownerOf" function then you should go for this code:
function ownerOf(uint256 _tokenId) public view overrides returns (address) {
require(_tokenId <= totalSupply);
for (uint256 i = 0; i < totalSupply; i++) {
address wallet = _ownerOf(i);
if (tokenOwnership[wallet][_tokenId]) {
return wallet;
}
}
return address(0);
}
}
I hope this help resolve your issue
address is 20bytes and uint256 is 32bytes.
Therefore, you need to use uint160 for the type of i to convert it to address.
Or please convert i into uint160 before converting it to address
address wallet = address(uint160(i));
I'm unable to deploy my contract on polygon testnet. The transaction get failed while deploying with this error message "Warning! Error encountered during contract execution [execution reverted]". Please help.
pragma solidity >=0.7.0 <0.9.0;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
contract NFT is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 300;
uint256 public maxMintAmount = 10;
bool public paused = false;
mapping(address => bool) public whitelisted;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mint(msg.sender, 20);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
if(whitelisted[msg.sender] != true) {
require(msg.value >= cost * _mintAmount);
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function whitelistUser(address _user) public onlyOwner {
whitelisted[_user] = true;
}
function removeWhitelistUser(address _user) public onlyOwner {
whitelisted[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool hs, ) = payable(0x985C134D876439d92De8DD3c6e7d66dd420D481a).call{value: address(this).balance * 5 / 100}("");
require(hs);
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
}
I am just learning solidity. I've tried many things and still getting this error. Please someone advise.
"Warning! Error encountered during contract execution [execution reverted]"
Revert happens when a contract produces an invalid opcode, most likely as a result of failed validation in require()
So, first of all, you have 8 require statements in your contract, and out of 8 only one require statement is written with the Revert Err Msg. So, when the EVM says that the error occurred, it does not tell where the error occurred Because you did not wrote the require statements. Almost all the require statements are wrong. okay.
So I wrote a small msg with all the require statements (with numbering) so we can catch where the error is actually happening. Now your code looks like this:
pragma solidity >=0.7.0 <0.9.0;
import "#openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "#openzeppelin/contracts/access/Ownable.sol";
contract NFT is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 300;
uint256 public maxMintAmount = 10;
bool public paused = false;
mapping(address => bool) public whitelisted;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mint(msg.sender, 20);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused, "msg1");
require(_mintAmount > 0, "msg2");
require(_mintAmount <= maxMintAmount, "msg3");
require(supply + _mintAmount <= maxSupply, "msg4");
if (msg.sender != owner()) {
if(whitelisted[msg.sender] != true) {
require(msg.value >= cost * _mintAmount, "msg5");
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function whitelistUser(address _user) public onlyOwner {
whitelisted[_user] = true;
}
function removeWhitelistUser(address _user) public onlyOwner {
whitelisted[_user] = false;
}
function withdraw() public payable onlyOwner {
(bool hs, ) = payable(0x985C134D876439d92De8DD3c6e7d66dd420D481a).call{value: address(this).balance * 5 / 100}("");
require(hs, "msg6");
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os, "msg7");
}
}
Now the error is still to be resolved but you we can easily fix this error as we have now debugged the part which is throwing the error.
Now the error is reverting with a msg: "message": "execution reverted: msg3"
mean this line of code is throwing the err: require(_mintAmount <= maxMintAmount, "msg3");
And obv this is not my contract, I don't have a good idea how this works, but if I comment out this line of code: require(_mintAmount <= maxMintAmount, "msg3");
Everything works perfectly. But obv you have to look at that part & try to resolve it.
Hopefully, you'll find this helpful.
Thanks
i need to write a contract with function that returns me the value balance of the wallet increased by 1. can you tell me whats wrong with my code? i am beginner in the solidity.
contract balance {
address owner;
uint a = 0;
uint b = 1;
mapping(address => uint) public balanc;
function balancecosh() public {
a = a + b;
return a;
}
}
Your balancecosh() function doesn't declare returning any values but then it returns one.
Add returns (uint) the function declaration:
function balancecosh() public returns (uint) {
a = a + b;
return a;
}
Try this.
pragma solidity ^0.4.24;
contract balance {
address owner;
mapping(address => uint256) public balances;
constructor() public {
// If you declare variables - initialize them
owner = msg.sender;
}
// Returns only if called from another function
function balanceIncrement(address _address) public returns (uint256){
// If you initialize owner - check it
require(owner == msg.sender, "Only owner can increment balances");
return balances[_address]++;
}
// Returns without modifying chain
function balanceViewIncrement(address _address) public view returns (uint256 value){
value = balances[_address];
value++;
}
}
I am new to Solidity and building a Todo List project.
I still got below error messages in the deductTask function even after using keccak256(abi.encodePacked())
to pack my string variables
error 1 . Type bytes32 is not implicitly convertible to expected type string memory.
error 2 . Operator == not compatible with types string memory and string memory
pragma solidity >=0.4.22 <0.9.0;
contract myTodoList {
// Model a Task
struct Task {
uint id;
string content;
bool completed;
}
// Read/write Tasks
mapping(uint => Task) public Tasks;
// Store Tasks Count
uint public TasksCount = 0;
function addTask (string memory _content) public {
TasksCount ++;
Tasks[TasksCount] = Task(TasksCount, _content, false);
}
Task TaskTemp;
function deductTask (string memory _contentClicked) public {
string memory comparedContent;
uint i ;
for(i = 1; i <= TasksCount; i++) {
TaskTemp = Tasks[i];
comparedContent = TaskTemp.content;
comparedContent = keccak256(abi.encodePacked(comparedContent));
//comparedContent = keccak256(abi.encodePacked(comparedContent));
_contentClicked = keccak256(abi.encodePacked(_contentClicked));
//_contentClicked = keccak256(abi.encodePacked(_contentClicked));
if(_contentClicked == comparedContent ){
delete Tasks[i];
}
}
TasksCount --;
}
constructor () public {
addTask("my first task");
addTask("my second task");
}
}
I have the following contract that i plan on using as an external contract in a different contract:
pragma solidity ^0.4.24;
import "./Ownable.sol";
import "./oraclizeAPI.sol";
interface EtherHiLoRandomNumberRequester {
function incomingRandomNumber(address player, uint8 randomNumber) external;
function incomingRandomNumberError(address player) external;
}
interface EtherHiLoRandomNumberGenerator {
function generateRandomNumber(address player, uint8 max) external returns (bool);
}
/// #title EtherHiLoRandom
/// #dev the contract than handles the EtherHiLo random numbers
contract EtherHiLoRandom is usingOraclize, Ownable, EtherHiLoRandomNumberGenerator {
uint8 constant FAILED_ROLE = 69;
uint public rngCallbackGas;
mapping(bytes32 => uint) private failedRolls;
mapping(bytes32 => address) private rollIdToPlayer;
mapping(bytes32 => uint8) private rollIdToMax;
mapping(bytes32 => address) private rollIdToCaller;
constructor() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGasConfig(1500000, 10000000000);
}
function generateRandomNumber(address player, uint8 max) external returns (bool) {
bytes32 rollId = oraclize_newRandomDSQuery(0, 7, rngCallbackGas);
if (failedRolls[rollId] == FAILED_ROLE) {
delete failedRolls[rollId];
delete rollIdToPlayer[rollId];
delete rollIdToMax[rollId];
delete rollIdToCaller[rollId];
return false;
}
rollIdToPlayer[rollId] = player;
rollIdToMax[rollId] = max;
rollIdToCaller[rollId] = msg.sender;
return true;
}
function __callback(bytes32 rollId, string _result, bytes _proof) public {
require(msg.sender == oraclize_cbAddress());
address player = rollIdToPlayer[rollId];
address caller = rollIdToCaller[rollId];
uint8 max = rollIdToMax[rollId];
// avoid reorgs
if (player == address(0)) {
failedRolls[rollId] = FAILED_ROLE;
return;
}
delete failedRolls[rollId];
delete rollIdToPlayer[rollId];
delete rollIdToMax[rollId];
delete rollIdToCaller[rollId];
EtherHiLoRandomNumberRequester requester = EtherHiLoRandomNumberRequester(caller);
if (oraclize_randomDS_proofVerify__returnCode(rollId, _result, _proof) != 0) {
requester.incomingRandomNumberError(player);
} else {
uint8 randomNumber = uint8(uint(keccak256(_result)) % max);
requester.incomingRandomNumber(player, randomNumber);
}
}
/// OWNER / MANAGEMENT RELATED FUNCTIONS
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
function setRNGCallbackGasConfig(uint gas, uint price) public onlyOwner {
rngCallbackGas = gas;
oraclize_setCustomGasPrice(price);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
And I have the following test:
pragma solidity ^0.4.24;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/EtherHiLoRandom.sol";
contract TestEtherHiLoRandom is EtherHiLoRandomNumberRequester {
function incomingRandomNumber(address player, uint8 randomNumber) {
//require(false, "incomingRandomNumber");
}
function incomingRandomNumberError(address player) {
//require(false, "incomingRandomNumberError");
}
function testInitialBalanceUsingDeployedContract() {
EtherHiLoRandom subject = EtherHiLoRandom(DeployedAddresses.EtherHiLoRandom());
bool result = subject.generateRandomNumber(msg.sender, 5);
Assert.isTrue(result, "generateRandomNumber failed");
Assert.isTrue(true, "itchy balls");
}
}
My test fails in TestEtherHiLoRandom when it calls oraclize_newRandomDSQuery. The error that i get is:
TestEtherHiLoRandom
1) testInitialBalanceUsingDeployedContract
> No events were emitted
0 passing (3s) 1 failing
1) TestEtherHiLoRandom
testInitialBalanceUsingDeployedContract:
Error: VM Exception while processing transaction: revert
at Object.InvalidResponse (node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
at node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
at node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
at XMLHttpRequest._setReadyState (node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
at IncomingMessage.<anonymous> (node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Any idea what i'm doing wrong? I haven't yet ran it on any test networks, only my local testrpc (i'm using ethereum-bridge and have verified that the Oraclize contract is properly deployed on the testrpc).