New answers tagged

0

Enums in Solidity are just stored as unsigned integers. For instance, if there are 256 values or less, it will be a uint8. So if you want to check that a value passed into a method is a valid enum, you can just check the range: enum Series { ONE, TWO, THREE, FOUR, FIVE } function testSeriesEnum( Series _series ) external returns (...


1

You can enter them in the field next to the Deploy button, separated by commas. Or you can expand this field and you get individual fields for each parameter.


0

In KittenRegistry contract first set address of KittyShelter contract. Then in the method, which you are calling from KittyShelter contract verify caller like: require(msg.sender == KittyShelter)


0

You need to call approve from the original contract, then use the transferFrom function and upon the transfer of whatever the balance is, add that to a user balance and work from there contract side. interface tokenToTransfer { function transferFrom(address from, address to, uint256 value) external; } //Contract B, below calls Contract A's interface ...


0

Yes. You create a bool. address public isPaused; You create a modifier modifier onlyIfRunning { require(!isPaused); _; } You decide which functions should freeze in the paused state (not necessarily everything). You add the modifier. function deposit() public payable onlyIfRunning ... You create a function to set the flag: function ...


0

While there are many proposals, e.g. ERC223, generally the two-step process is the most basic approach to start with. Have the user approve the contract to transferFrom, and then have the contract do it. A UI can choreograph that for the user so it looks like one move. EIP-1102 smooths out permissions from a user perspective so they aren't constantly ...


1

In your code you are making the division first. My guess is that _totalSupply is larger than any balance so solidity will truncate the result to 0. uint256 _SavedDividend = _balances[address(this)].mul( (_balances[msg.sender]).div(_totalSupply) ); You have to multiply first and then divide. uint256 _SavedDividend = ( _balances[address(this)].mul(...


1

It is trying to compile migrations scripts as solidity code. That will not work. Move migrations scripts to the directory migrations and rename them with the .js extension. Your project should look like this migrations\ 1_Migrations.js 2_Migrations.js contracts\ Token.sol


0

You don't have to use push with an array. You can add a new element modifying its length. Candidate[] public candidates; function addCandidate(string memory _name) public { uint idx = candidates.length; candidates.length += 1; candidates[idx].name = _name; } Another option is to use a mapping. You will need to keep the length separately. mapping (...


0

If you are somehow sure that the amount you want to burn is available in contract then just use .transfer() to transfer the ether to any other account. address(0).transfer(_amount); By the way this ether will be lost forever. If you send it to a known address, then at least it can be reused at later point. pragma solidity ^0.5.12; contract SillyContract { ...


0

1st impossible thing: You can't make sure to burn exact amount of ether when calling a function. Solidity smart contracts use gas not ether/gwei to execute operations and transaction sender specifies the gas price. So a function that requires 200 gas to execute may cost one user 200 wei and another user 600 wei. 2nd impossible thing: You can't just burn ...


1

The contract should try to send its funds but it will need to have some to begin with. You will have to send 1000000000 wei, or more when you deploy the deploy the contract. Any surplus will remain in the contract. I can't think of any good reason to do this so I'll refrain from suggesting improvements. Hope it helps. UPDATED WARN: I don't think anyone ...


0

Inside Purchase smart contract define counters for the total number of buyers and the total earnings like this: contract Purchase { uint public totalBuyers = 0; uint public totalEarnings = 0; ... } Then, when purchase is confirmed, increase these counters appropriately: function confrimReceived() public condition(msg.value == price) payable { ...


0

You can use a try catch block to call the contract function. If call fails then you can interact with revert message in catch block. try { var inOwner = await simpleCI.methods.isOwner().call({ from: accounts[1] }); } catch (err) { console.log(err); } and this is a sample err object: { name: 'o', results: { '...


1

Fibonacci is perfect example to illustrate the recursion(tail): Mathematically, the Fibonacci sequence is a recursive function that adds the previous elements to obtain the next element, Like below: Fn = Fn-1 + Fn-2 function fib(uint n) public view returns(uint) { if (n <= 1) { return n; } else { return this.fib(n - 1) + this.fib(...


0

I solved the problem , contract need ether to work function2(in my case) , so ...this is the "Invaild opcode" solution.


2

It is possible to use recursive functions in Solidity. The following is a simple recursive function in solidity pragma solidity ^0.5.12; contract Test { uint x; function set(uint y) public { x = y; } function factorial(uint y) internal pure returns(uint){ if (y == 1){ return y; } else { ...


0

Make Sure that you are calling function getTokenBalanceOf() after the call setToken() function. hope this will help you.


0

Smart contract cannot access anything out of the contract ,but you can access smart contract functions through java's web3j library


1

Yes, you do need to change function Contract (... to constructor(... because this is the new way to indicate the constructor. There is nothing else you need to do in the Factory to invoke the constructor. The constructor always runs one time on deployment, regardless of how the contract is deployed. It cannot be prevented/avoided even if you want to. In ...


0

Recursion is possible indirectly: struct BTree { uint x; BTree[] children; bool nil; } You can also use a mapping instead of the array.


0

For most IoT project incorporating Smart Contracts, one will make use of an external oracle to input data into the Smart Contract. Try http://www.oraclize.it/ Hope this helps


2

Here is my answer, to my own questions after testing in Remix: A.foo() does not work: TypeError Member "foo" not found or not visible after argument-dependent lookup in type(contract A) same for super.foo() except it says ... lookup in contract super B Both 1) and 2) could be expected from the docs that only list this.f() as a way to call external functions ...


1

I found that OpenZeppelin seems to silence such compiler warnings about state mutability in this way: function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } This snippet is from there Context.sol ...


1

You probably need to build you own code on the top of these two libraries: https://github.com/hamdiallam/Solidity-RLP and https://github.com/commitground/solidity-patricia-tree The former library allows decoding RLP encoded data structure. The second allows checking that certain data is stored in Merkle-Patricia tree. Ethereum stores state of all ...


0

For anyone coming to this, I found the below - it is unproven though and has some limitations: https://github.com/figs999/Ethereum/blob/master/EventStorage.sol


2

You cannot assign it to a variable directly, you has to do it in a function or constructor Corrected Code: I had moved assignment operation to constructor pragma solidity ^0.5.1; contract MyContract{ struct student{ int RollNo; string Name; } student public s1=student({RollNo:1, Name:"Test Bunny"}); int public disint; ...


2

There is only one EVM (Ethereum Virtual Machine) and it's not physically located in any single place. It's distributed to each node. The EVM is a rather abstract construct. If a function in contract A calls a function in contract B all the execution happens within the same transaction. A transaction either succeeds fully or fails fully (in which case all ...


0

As everything is public in the Ethereum blockchain you can't prevent someone from copying your contract. So anyone can deploy the same token contract and make a crowdsale for it. The difference is that your token and the fake token will have different addresses and they won't have anything to do with each other. The same applies to the crowdsale contract. ...


0

that error is because you pass account= '' .(in the from:) i think is your web3 version(can you check the version in console with "web3.version") and with web3 1.x.x can you try : web3.currentProvider.selectedAddress to get the address.


1

I'm a little unsure of what you want, but assuming _id is unrelated to an item's position in the list and you require a way to enumerate the Users in the system, you probably need both an array and a mapping, i.e.: import "./User.sol"; contract Main is Ownable { User[] private _users; mapping(uint256 => bool) userExists; function ...


0

Use a mapping instead of an array: mapping (uint256 => User) private users; uint256 private numOfUsers; function createUser(uint256 _id) onlyOwner external { require(users[_id] == User(0), "User already exists"); users[_id] = new User(_id); emit UserCreated(users[_id], ++numOfUsers); }


2

Actually, transferFrom is payable in EIP 721. From https://eips.ethereum.org/EIPS/eip-721: function transferFrom(address _from, address _to, uint256 _tokenId) external payable; So it's not a modification at all. It's already part of the interface. If the code you're using doesn't have payable there, you can simply add it.


0

From the Solidity documentation: Fixed point numbers are not fully supported by Solidity yet. They can be declared, but cannot be assigned to or from. The only possible fix at this point is to not use fixed point numbers.


0

How many arguments does the vote method take? In web3.js the smart contract method's arguments are interpreted first, and the last argument is expected to be transaction options such as: { from, gas, gasPrice } If you are supplying a different number of arguments than is expected, web3.js will try to find the from field from an argument where it's not ...


1

This is a very broad question and I almost voted to close this as 'too broad'. The answer also depends quite much on what other assumptions we make about the business case. So something like the following might be required as well: 1) Do you want to implement your business case with a blockchain at all? If yes, is Ethereum the right choice? Private or ...


1

In short: yes it's bad. If you wish your contract to be recognized (and used) as an ERC721 contract you have to implement the correct interface (correctly). If your contract is not ERC721 standard compliant exchanges will most likely not accept it as it would require extra coding from their part just to get your token to work. The point of standards is ...


1

Assuming order doesn't matter (implied by "set"), the combination of a mapping and an array can handle set operations in constant time. The trick is to keep track of where in the array each element is and swap elements to the end for deletion. I wrote a blog post about this pattern: https://programtheblockchain.com/posts/2018/06/03/storage-patterns-set/. ...


1

I believe that all of this can be solved with a single keyword - interface. For example: pragma solidity 0.4.26; interface IBaseContract { function func(uint _x) external view returns (bool); } contract BaseContract is IBaseContract { function func(uint _x) external view returns (bool) { return _x == 1; } } contract DerivedContract ...


0

Here MaintainableUpgradeabilityProxy is name of contract so what is it returning a contract address? Yes. The difference between doing this and returning an address is that if another contract calls this method, then it will receive that contract instance. It's equivalent to returning the address of the contract and then doing ...


0

Do you need these non-predictable numbers committed to the blockchain (e.g. because they determine a payment transaction), or synchronized between multiple users? If no, then the answer given above will work. Randomness is generated from contract state using view function, which means you may as well off-load it to Javascript code calling on the client's ...


0

It isn't possible to generate non-predictable numbers in a single transaction in Solidity. Any data that would be used to generate the random number would be available to an attacker immediately before the transaction, and therefore the outcome could be known before the attacker chooses to act.


0

You can use this pattern: pragma solidity 0.4.26; contract Test { uint256[] public globalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; function getPartialArray() public view returns (uint256[] memory) { uint256[] memory localArray = clone(globalArray, globalArray.length); for (uint256 i = 0; i < localArray.length;...


0

function balanceOf(address _owner) constant returns (uint256 balance); is the problem I think you must use as follows: function balanceOf(address _owner) public view returns (uint256);


2

Just a guess because the link seems to be dead, but maybe you're using libraries? From https://solidity.readthedocs.io/en/v0.5.11/using-the-compiler.html: If your contracts use libraries, you will notice that the bytecode contains substrings of the form __$53aea86b7d70b31448b230b20ae141a537$__. These are placeholders for the actual library addresses. The ...


3

Gas costs are often dominated by storage. In this case, your first contract writes an address to storage, which costs 20,000 gas. The second contract doesn't do that.


1

Typically the one who signs a transaction also pays for the transaction. However, this doesn't have to be the case. What you are looking for is something called meta transactions. A user signs a transaction he wishes to send to the blockchain and then hands the transaction to a third party which actually sends the transaction for the user (and pays for the ...


0

Within the Ethereum Virtual Machine, there isn't a way to get the current time, other than the block time. To get current block time stamp we can directly use block.timestamp in solidity. Its returns a time in unix timestamp. Ethereum provides Time unites to facility date computation to a particular level, refer the following document. https://solidity....


1

This isn't a simpler scheme than what you propose, but some of the details hashed out. One thing you can use is a commit-reveal scheme in a two-step process (we can improve this later with state channels or batching zero-knowledge proofs, as you suggested). You can't use the IPFS hash modulo the sender's address as the commitment, b/c the front-runner will ...


Top 50 recent answers are included