texts: How does the system enforce correct execution of smart contracts?

texts:
If I understand correctly, the smart contracts are run by the miners. What incentive do the miners have to execute the smart contracts correctly? What stops a malicious miner from changing the result, or a simply lazy miner from doing a simpler computation?

In bitcoin, the proof-of-work is hard to calculate but easy to verify. I don't expect this to be true of all contracts.


texts: Retrieve public key of an address to verify off-chain signatures

texts:
I have a question regarding use of keys in Ethereum for signing requests/data OUTSIDE of Ethereum.
Let's say I have a regular Ethereum EOA with an address and keypair. I now want to have a piece of information transferred to a third party (off-chain) and allow this third party to verify that this information came from me, i.e. the owner of the EOA in question. Approach: digitally sign the information with my private key associated with my EOA.
Now the question is, how the third party is verifying the signature. What he has is the signature, the data, and (lets assume we specified this) the address of my EOA.
For allowing him to verify the signature, he will need the public key of my EOA. To get this to him, I see two options:

GIVE him the public key directly, e.g. by using a ERC1056 registry where I store the public key for each address. Now, I'd be required to verify on-chain (i.e. in Solidity) that the public key set as an attribute is matching the address (i.e. that the first 20 bytes of the hash of the public key are the same). Seems pretty cost-intensive Gas-wise to me.
Anyhow First question: How to compute the address from a public key (string) in Solidity for such a check?
Derive the public key off-chain (on the receiver's side) from the signature. I read this would be possible, I'm just unsure how exactly to do this. The recipient would then compute the public key, verify the signature, and verify that the signature was actually created by the EOA (address) it claims to be from. Hence, my second question: How to do this in Java? Is there a lib for that?

Is there a third, even better option?


texts: Communication between nodes of two private blockchains

texts: How can the nodes on one Ethereum private blockchain send/receive transactions from the nodes operating on another private blockchain?


texts: How can I run scripted geth commands with specified command line parameters?

texts:
I have a contract running on the testnet, and every time I need to call a function, after opening Geth I have to type (or paste):

primary = eth.accounts[0];
personal.unlockAccount(primary, 'mypassword');
var source = "contract FooContract {...}";
var compiled = web3.eth.compile.solidity(source);
var contract = web3.eth.contract(compiled.FooContract.info.abiDefinition);
var fooContract = contract.at("0xf00");

Is there a way to make geth remember that after I close it?


texts: How to replicate the state of a deployed contract in development environment

texts:
I'm trying to debug a contract that has been deployed, and I'd like to have a debug version that has a contract state as close as possible to the version in production (variable values).

The first thing that I noticed is that I don't know how to find the value of this data on https://etherscan.io is there another place to find them?

The second thing is how to I replicate this to my debug environment (let's say truffle/ganache-cli)?

For now I'm importing the JSON of the Etherscan API  and replaying transactions using a truffle script with some way to map test accounts with real accounts, but I'm not sure it's putting me to the correct state.

Any better option?


texts: Can hd wallets have different withdrawal permission levels?

texts: Specifically, is it possible for a wallet to have a key which can spend an ERC721 collectible, but its child keys not?


texts: Is there any API available to get transaction history from rinkeby test network?

texts:
I want to show this transaction history on my website? Is there any API available for this?
Contract URL: https://rinkeby.etherscan.io/address/0x104a1fc33d88a3ee8beaf3a61309758174e82b93


texts:
I have a simple smart contract as below. Using go-ethereum-1.8.6 , when i execute contract.sha.call() it returns the correct hash value. However, contract.getSha256.call() it returns 0x, did I do something wrong?

pragma solidity ^0.4.23;

/* Online compiler https://remix.ethereum.org */

contract test{

    address public owner;

    constructor() public {
        owner = msg.sender;
    }

    function getOwner() external view returns (address) {
        return owner;
    }

    function getSha256() external pure returns (bytes32) {

        bytes32 hash = sha256("12345678");

        return (hash);
    }

    function sha() external pure returns (bytes32) {

        bytes32 hash = sha3("12345678");

        return (hash);
    }

}


texts: Getting an error when (attempting to) using Web3js

texts:
I'm trying to connect a smart contract to a very simply front end that has html/css/js.  I keep getting an error when trying to use web3 to connect - I have the code below but the terminal is giving me an error of "web3.min.js:1 Uncaught TypeError: e.toLowerCase is not a function
    at Object.h [as inputAddressFormatter] (web3.min.js:1)
    at Object.set [as address] (web3.min.js:1)
    at o.e (web3.min.js:1)
    at new o (web3.min.js:1)
    at index.html:87"
Here's the index.html:

<title>dApp Example</title>

<link rel="stylesheet" type="text/css" href="main.css">

        Athletic Club Member?

    Member name
    <input id="name" class="text">

    Member age
    <input id="name" class="text">

    <button id="button">Update Instructor</button>

** Line 87 is:    new web3.eth.Contract(contractAbi,[contractAddress]);


texts: Is there any ETH wallet without transaction fees?

texts:
I have 2 questions to ask here:
First is there any ETH wallet that doesnt charge transaction fees?
Second, currently I using Jaxx wallet, I have 1 ETH in my account. If i want to send 1 ETH out, is it possible? Or do I need to purchase more ETH to cover the transaction fees?

Thank you.


texts:
Is it possible to attach with geth to ganache-cli?

I start ganache-cli like this:

ganache-cli --db ~/ganache -i 15

Then I try to attach to the chain like this:

geth --datadir ~/ganache/ --networkid 15 attach

This is the error I get:

Fatal: Unable to attach to remote geth: dial unix /root/ganache/geth.ipc: connect: no such file or directory

If I start a private chain using geth directly, I can attach to it without any problems.

geth --datadir ~/mychain --rpc --rpcapi eth,net,web3 --nodiscover --networkid 15 --bootnodes {URI}
geth --datadir ~/mychain --networkid 15 attach


texts: How is account managed in Ethereum blockchain?

texts:
What is the process for creating account? (I know I can geth account new, but what is the internal process actually being done?)
Where does the entropy for randomness come from when creating an account? (What would be the seed?)
Where is the newly created account(or balance) stored in Ethereum blockchain?
Why does it seem to be free(of charge)(you can easily create one through MetaMask or MyEtherWallet) to create an account while it's intuitively deemed to cost gas just like deploying smart contract since it's writing something onto the blockchain?

Think it should be me misunderstanding something. Any hints would be appreciated.


texts: sendRawTransaction is not being sent to the network

texts:
I'm using web3 to transfer tokens between two wallets. I'm successfully generating and signing the transaction, a hash is being created, but is never updated to the network. I am using the Rinkeby test network. GETH is showing the transactions being created. I've waited several hours for the transactions, one of which I've waited over 24 hours so far.

Here's the raw transaction data before signing it and converting it to a hex string:

{
    from: '0x1A9c7...',
    to: '0xaed2df...',
    nonce: '0x10',
    gasPrice: '0x5208',
    gasLimit: '0x670aac',
    value: '0x00',
    data: '0xa9059cbb0000000000...',
    chainId: 4
}

Here's the code I'm using to generate the transaction, please note that web3legacy is 0.20.x and web3 is 1.0.0-beta20

let sendTransaction = async () => {
        const senderAddress = "0x1A9c7c...";
        const destinationAddress = "0x2aABeb...";
        const transferAmount = 100;
        const nonce = web3legacy.eth.getTransactionCount(senderAddress);

        const rawTransaction = {
            from: senderAddress,
            to: contractAddress,
            nonce: web3legacy.toHex(nonce),
            gasPrice: web3legacy.toHex(web3legacy.eth.estimateGas({from: senderAddress, to: destinationAddress, amount: web3legacy.toWei(0, "ether")})),
            gasLimit: web3legacy.toHex((await web3.eth.getBlock("latest")).gasLimit),
            value: "0x00",
            data: contract.transfer.getData(destinationAddress, transferAmount, { from: senderAddress }),
            chainId: 4
        };

        // senderAddress private_key
        const privateKeySnapshot = await walletsRef.child(senderAddress).once('value');
        const rawPrivateKey = privateKeySnapshot.val();
        const privateKey = new Buffer(rawPrivateKey, "hex");
        const transaction = new Transaction(rawTransaction);
        transaction.sign(privateKey);

        console.log("Validation:", transaction.validate());
        const serializedTransaction = transaction.serialize();

        web3legacy.eth.sendRawTransaction('0x' + serializedTransaction.toString("hex"), (err, hash) => {
            if(err) console.error("ERROR:", err);
            else {
                console.log("HASH:", hash);
            }
        });
    };

The validation from transaction.validate() is successful.

The hash is created from the sendRawTransaction method but it never appears on the rinkeby network, and my wallet/tokens are never affected.  I get the common error message "Sorry, we are unable to locate that Transaction Hash" from rinkeby etherscan.

For anyone curious, sendSignedTransaction in 1.0.0 is currently bugged and doesn't work per issue #1102 which is why I brought in 0.20.0 to send a raw transaction


texts:
I installed geth on a 64-bit Ubuntu 16.04 by building from source (as described here), and I can run the program as follows:

~$ 'path_to/go-ethereum/build/bin/geth' ...

However, I want to run it with just the command geth. I tried to set an alias in ./bashrc:

alias geth='path_to/go-ethereum/build/bin/geth'

Now it works when I type geth in the terminal, however, -I think- it fails when a script calls the command. In my case, the command populus deploy Greeter --chain local_test yields an error as follows:

  ...
  File "/usr/local/lib/python2.7/dist-packages/geth/accounts.py", line 133, in ensure_account_exists
    accounts = get_accounts(data_dir, **geth_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/geth/accounts.py", line 31, in get_accounts
    stderrdata,
ValueError: Error trying to list accounts
Command    : nice -n 20 geth --rpc --rpcaddr 127.0.0.1 --rpcport 8545 --rpcapi admin,debug,eth,miner,net,personal,shh,txpool,web3,ws --ws --wsaddr 127.0.0.1 --wsport 8546 --wsapi admin,debug,eth,miner,net,personal,shh,txpool,web3,ws --datadir /home/me/populus/chains/local_test --maxpeers 0 --networkid 1234 --port 30303 --ipcpath /home/me/populus/chains/local_test/geth.ipc --ipcapi admin,debug,eth,miner,net,personal,shh,txpool,web3,ws --verbosity 5 --unlock 0 --password /usr/local/lib/python2.7/dist-packages/geth/default_blockchain_password --nodiscover --mine --minerthreads 1 account list
Return Code: 127
stdout: N/A
stderr:
`nice: ‘geth’: No such file or directory
`

Finally, I tried to install geth with npm, but after a series of -probably badly ordered- package installations, when I call sudo apt-get install ethereum, I get this error:

The following packages have unmet dependencies:
 ethereum : Depends: geth but it is not going to be installed
            Depends: bootnode but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

When I try to install geth beforehand with sudo apt-get install geth, I get the following error:

The following packages have unmet dependencies:
 geth : Depends: ttf-ancient-fonts but it is not installable

The issue is already discussed here but the solution proposed (sudo apt-get update && sudo apt-get upgrade before installation) did not work for me, so I'm stuck at this point.

Should I try to clean things and install with npm, or is there a way to make it work with this build? Any help would be appreciated.

Thanks,


texts: Transaction runs out of gas with MetaMask on a simple function

texts:
MetaMask calculated automatically the gas needed for every transaction, but for one in particular, it always returns the error "out of gas" if I use the default amount.

The function is really simple so I don't get how it can run out of gas:

mapping (uint => xyz) public xyzs;

function setXyzParameters(uint id, uint newPrice, bool _isForSale) public {
    require(msg.sender == xyzs[id].creator);
    xyzs[id].price = newPrice;
    xyzs[id].isForSale = _isForSale;
}

On my private node, MetaMask sets by default a gas limit of 27043 and it fails if I leave it at that, 30000 still fails but it works 40000.

What am I doing wrong?

Additional info: Turns out the amount of gas is different if the boolean is true or false. I guess when it's false some part of the Tx data is 00000000 while it's more info if it's true, so maybe that's why the estimated gas is different.

(To give context, I'm working on something based on the Truffle tutorial)


texts: If the price of ether coin goes up, does it mean less likely people are going to build application on the ethereum network?

texts: If I am not mistaking, application developers need to pay using ether coins to have their application hosted on the ethereum network. So if the price of ether keeps going up like it is now, doesn't it mean the cost of hosting an app on the network goes up? Where is the break point for people not even thinking about hosting their application on the ethereum network? By the way, are there any real applications on ethereum network as of now?


texts: How to write a contract that can only accept a payment of fixed amount?

texts:
I'm a beginner contract writer. How can I ensure that a payment (in a payable function) is only done with a fixed amount?

My first attempt (which doesn't work) looks like this:

  function getIn() public payable returns (uint256)  {

    uint256 _amount = 30000000000000000;
    require( msg.sender.balance >= _amount);
    balanceOf[ msg.sender ] -= _amount;
    ...

Is the only way to do this to create a payable function that then returns the diff? Something like this:

  function getIn() public payable returns (uint256)  {

    uint256 _amount = 30000000000000000;
    require( msg.value >= _amount);
    require( msg.sender.balance >= _amount);

    balanceOf[ msg.sender ] -= _amount;
    msg.sender.transfer( msg.value - _amount);


texts: How does PassHasBeenSet honeypot contract work?

texts:
I've been trying to pick this honeypot contract apart, but I haven't figured out exactly how it works.

overview

The premise is pretty simple, the contract is set up to look like a "new year's gift" where the ETH is retrievable if someone (probably the gift receipient) puts in the correct password.

However the contract author has made a fatal "flaw". If a certain field named passHasBeenSet is false, anyone can send the contract >1 ETH and become the contract's owner! Once you're the owner, you can call the revoce function to pull out all of the funds in the contract.

What's the problem? I found this contract suspect because it was 1) created by the creator of another honeypot contract described on reddit and 2) generally strange - why post the source to Etherscan? Why allow someone else to become the owner if they pay more into the contract? The contract is designed with if statements/doesn't throw errors and looks like it was written by a beginner.

However, I couldn't initially spot anything wrong with the contract. Additionally, it seemed like it only had two transactions, a contract creation and a call to setPass. This should still leave passHasBeenSet set to false.

pen testing

I figured I might as well see if the contract was a Honeypot or not. I knew I could design the "attack" contract so I couldn't lose, but I was still curious.

I put together a contract that would call setPass and then revoce. If the contract's balance decreased, it would revert. This construction meant I couldn't lose any money.

The honeypot contract (& attacking contract) worked as expected on Ropsten. Any balance in the contract was extracted and could then be withdrawn from then attacking contract. However, the attacking contract failed on the mainnet. The balance was successfully sent to the target contract, but the revoce failed so the contract's revert failsafe was triggered. Debugging the transaction showed that passHasBeenSet was true.

So, how did the "vulnerable" contract manage to set passHasBeenSet? I must be missing something pretty obvious.


texts: Which graphics card is currently the best for mining?

texts:
Which graphics card is currently the best for mining (mhs-watt-ratio)?
I'm using the R9 280x which generates about 13 mhs.

Thanks for your answers!


texts: Why is the units of gasUsed in the transaction receipt 10^11 Wei?

texts:
I'm checking the balance of an account after a payable transaction in a Truffle test. Below is my code:

// amount is the value supplied to the txn
assert.equal(Number(String(currentBalance)),
             Number(String(previousBalance)) + amount - (gasUsed * 100000000000),
            'Account balance for ' + String(acct) + ' incorrect after txn.');
// previous account bal: 99965457999999999000
// current account bal: 99954881999999998000
// gasUsed: 105760
// amount: 1000

As you can see, I have to multiply the gasUsed value by 10^11 or my test will fail... I don't really understand why it's 10^11? GWEI (10^9) makes a lot more sense. At least a multiple of 3 right? This isn't in the web3 documentation at all.

EDIT: to clarify I'm trying to figure out what gasUsed is and if web3 or Truffle are overwriting the default gas price. The gas price according to my Ganache interface is 20000000000, which doesn't work with my calculations. That's why I was lead to believe gasUsed is the total txn fee in wei.


texts: what will be the auction end time value?

texts: what should be the auction end time value like I entered bidding time value? I had never entered anything over there if manually I have to do then how should I do it?


texts: SOLIDITY: How to get a bytes32 keccak256 hash of an address and 2 uint256 variables

texts:
I would like to know how to get a bytes32 keccak256 hash of an address and 2 uint256 variables.

I want something that will look like this. But from the remix IDE errors, I need to make the the 3 variables into bytes32 and then hash that?

/* here are the variable names and types (Apart from msg.sender which is address */

uint256 _unixTimestamp;
uint256 _timeExpired;

/* This is what I have got so far, what do I need to do to fix the error? */
bytes32 output = keccak256(msg.sender, _unixTimestamp, _timeExpired);

Here is the warning message from the remix IDE

  Warning: This function only accepts a single "bytes" argument. Please use "abi.encodePacked(...)" or a similar function to encode the data.

  bytes32 output = keccak256(msg.sender, _unixTimestamp, _timeExpired);

  . . . . . . . . . . . . . .^----------------------------------------------------------------------- ^


texts: Error: Send transaction failed: Invalid address. if you use injected provider, please check it is properly unlocked

texts:
I have written my first sample contract. It compiled successfully but when I am trying to run this, it is giving me an error as:

  Send transaction failed: Invalid address. if you use injected
  provider, please check it is properly unlocked.

Code is as follows:

pragma solidity ^0.4.22;

contract Myfirstcontract
{
    string private name;
    uint private age;

    function setName (string newName)
    {
        name = newName;
    }

    function getName () returns (string)
    {
        return name;
    }

    function setAge (uint newAge)
    {
        age = newAge;
    }

    function getAge () returns (uint)
    {
        return age;
    }

}

Please suggest.


texts: Pricing when creating a contract from another contract

texts:
Say, I am creating a contract from another contract's function.
AND I want to transfer certain amount (1 ether) to be added to contract's balance after it is created.
Will this 1 ether and gas price be independent? I mean, if I run out of gas, I want that 1 ether to remain untouched, and if a contract is created successfully, I want it to get 1 ether, and not 1 ether - gas fee.
Will it work as I described?


texts: Erigon (former Turbo-Geth) IPC endpoint location

texts:
I used to run a local Geth node and connect to it using web3.py but I've recently discovered and switched to Erigon (former Turbo-Geth).
I cannot seem to find the IPC endpoint of the Erigon client though, which in the case of Geth it used to be under ~/.ethereum/geth.ipc.
Any ideas?


texts: Need to prove quantity/date of Ether Pre-Sale purchase for tax reasons

texts:
Lucky me - I bought 10000 Ether for 5BTC in the pre-sale and forgot about them until just recently. Yahoo! However, now that I've sold some at a profit I'm going to need to prove the date and quantity of purchase for the tax authorities and I'm not sure they'll just accept an email dated 2014. Even if they do the confirmation email doesn't state the quantity purchased. Idiot me updated all my BTC wallets since then without taking screenshots so the list of transactions no longer includes the transfer to the bitcoin address I used to purchase the Ether. Didn't realize that an update would wipe the transaction history to date but there you go.

Does the Ethereum Foundation provide any kind of proof-of-purchase for people who bought in the pre-sale? If I could only find proof of the quantity purchased then I would at least have a continuous 'chain' of proof [Press release stating quantity of Ether per BTC - purchase confirmation email - price of BTC on that date - ... quantity purchased...].

This is important as in Germany if I can prove I've held them longer than 1 year I won't have to pay tax. I would really appreciate some help!


texts: what is use of body less '_beforeTokenTransfer internal virtual ' function

texts: Inside _transfer function there is a call goes to _beforeTokenTransfer(sender, recipient, amount); and that function is written as function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } with no body parts, then is is not useless ? or if it is useful what is purpose of calling a body less inter virtual function ?


texts: I'm creating an erc20 contract and deploying with metamask. I only have 3 dollars in ether, so I could only afford 5 gwei for gas. It's been 3 hours, how long will it take? It looks like 40 gwei would cost something like 30 dollars, and I don't want to spend that much. Thanks!


texts: How blocks in a blockchain are identified that store concerned policy?

texts:
I am working on blockchain. My project is to store Role based access control policies(user-role assignment and role-permission assignment) in blockchain. Policies are written in 2 dimensional array (user name and his respective role are stored in array format, role and its respective permission are also stored in array format). I compiled and deployed this smart contract on Remix IDE(and also using geth). Through func1(), I gave 2D array(users-roles) as input and function successfully executed. Now, through another func2(), I gave 2D array(roles-permissions) as input and function successfully executed.

On executing func1() in Remix, block number(block 1) is displayed along with the transaction hash. On executing func2() in Remix, block number(block 2) is displayed along with the transaction hash.

My doubt is, does data given through different functions(func1() and func2()) are stored in same blocks of blockchain with transaction hash in different blocks and how this block is identified? If data is stored in the different blocks of blockchain, later when I cal func3() which takes username as input and gives roles that user possess, how does this function knows the block number in which user-role assignment(2D array stored using func1()) is stored??

Reply really helps a lot.
Thank you.


texts:
a quick beginner's question... is it possible to sign a message twice with web3?  For example Alice creates a message and signs it. Then it is sent to Bob. Can Bob sign the message before he executes the transaction to make sure that the message was accepted by both of them?

Thanks a lot!


texts: Unable to attach to remote geth: Invalid pipe address '/.rinkeby/geth.ipc'

texts:
I'm on Windows and trying to connect to Ethereum Testnet via rinkeby.

I downloaded geth 1.8.2 and Ethereum Wallet 0.9.3

I gave 1st command as:

  geth --rinkeby --fast --cache=1024

NOTE: after above command, I get the url on cmd as:

  url=\\\\.\\pipe\\geth.ipc

And 2nd command in another command prompt as:

  geth --datadir=./rinkeby attach

The same commands were working earlier.

I uninstalled both geth and Ethereum wallet and installed latest versions. I tried the commands on the earlier versions also where they were working but now they are not.

I also tried connecting to Private net just now, but got the error message on 2nd command prompt as:

  Unable to attach to remote geth: no known transport for URL scheme "c"

Thanks in advance!


texts: I am trying to connect my Website with Remix Ethereum IDE and getting one issue { setInstructor} function is not responding.help me with set function

texts:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="main.css">

Faculty Instructor

        Instructor Name
        <input id="name" type="text">

        Instructor Age
        <input id="age" type="text">

        <button id="button">Update Instructor</button>


texts: Why is GETH excessively and unnecessarily writing to my drive C?

texts:
I am only using ropsten
d:\Shared\Geth> geth --ropsten --datadir data console --syncmode "fast"

Below are the info shown when GETH starts.
INFO [08-30|08:30:00.514] Disk storage enabled for ethash caches   dir=D:\Shared\Geth\data\geth\ethash count=3
INFO [08-30|08:30:00.521] Disk storage enabled for ethash DAGs     dir=C:\Users\USER\AppData\Local\Ethash count=2

I am aware the Ethash folder is still in drive C. But it shouldn't cause too much trouble since it either doesn't exist or only using a small amount of disk space and never growth exponentially
However, from time to time I will notice this happened to my PC for a very long time.

It is going to kill my SSD. And I have checked in task manager, GETH is the only application that accessing my drive during that time

Stop and restart GETH, and everything goes back to normal. It is writing to drive D: now


texts: Solidity Contract - Store and access address payable of holder of the contract

texts:
I am working on one smart contract with solidity.
using Address for address;

mapping (address => uint256) private _address;

I am using a mapping like usual here. I think with this mapping, I can only access to the balance of each address/holder. Now I would also like to access to one address of this mapping so I can send some tokens to it. I think it is not possible.
If not, is it possible to create a list of address payable and add the address used by the new holder to the list when someone create a transaction with my contract ?
In summary, I want to have the address payable of all the holders, and send token to one of them for exemple.
Thank you for your help !


texts: Using the same chain folder for both Parity and Mist/Ethereum Wallet

texts:
I have been having some issues with the Ethereum Wallet and after days of on/off syncing I decided to use parity, which works like a charm so far. However, I would like to use the Mist browser to play with solidity and I don't want to have to download the chain for both mist and parity.

Is there anyway I could specify to the Ethereum Wallet where the chain is and point it at parity's chain?


texts:
I get this error when I try to paste the democracy contract code in solidity:

Unused local variable
        Member m = members[id];


texts: Call contract's mint function from Truffle console

texts:
I'm trying to call my contract's mint function from the Truffle console, but I keep getting an error.
The code looks like this:
  function mint(uint256 _optionId, address _toAddress, uint256 _amount, bytes calldata _data) external nonReentrant() {
    return _mint(Option(_optionId), _toAddress, _amount, _data);
  }

/**
   * @dev Main minting logic implemented here!
   */
  function _mint(
    Option _option,
    address _toAddress,
    uint256 _amount,
    bytes memory _data
  ) internal {
    require(_canMint(msg.sender, _option, _amount), "MyFactory#_mint: CANNOT_MINT_MORE");
    uint256 optionId = uint256(_option);
    MyCollectible nftContract = MyCollectible(nftAddress);
    uint256 id = optionToTokenID[optionId];
    if (id == 0) {
      id = nftContract.create(_toAddress, _amount, "", _data);
      optionToTokenID[optionId] = id;
    } else {
      nftContract.mint(_toAddress, id, _amount, _data);
    }
  }

From the Truffle console, I'm calling it like this:
MyLootBox.at("0xB4e6e1DAB3148187Eb220dbB1268CAB9F0aA4F15").then(contract => contract.mint(0, accounts[0], 1, web3.utils.toHex("")))

The above command is returning this error:
Thrown:
{ Error: Transaction: 0xfbc4e7ae429fcb7d7393e463c32f6f4248637bace256551ff2677dbba18e4093 exited with an error (status 0).     at PromiEvent (/Users/me/Code/crypto/cryptojanky/node_modules/truffle/build/webpack:/packages/contract/lib/promievent.js:9:1)
    at TruffleContract.mint (/Users/me/Code/crypto/cryptojanky/node_modules/truffle/build/webpack:/packages/contract/lib/execute.js:169:1)
    at MyLootBox.at.then.contract (evalmachine.<anonymous>:0:86)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  message:
   'Transaction: 0xfbc4e7ae429fcb7d7393e463c32f6f4248637bace256551ff2677dbba18e4093 exited with an error (status 0). \n     Please check that the transaction:\n     - satisfies all conditions set by Solidity `require` statements.\n     - does not trigger a Solidity `revert` statement.\n',

For some more context, I'm working off of OpenSea's example contracts.
Would really appreciate some help! Thanks in advance.


texts: Did I get this right that with delegatecall the msg.sender is the last entity that calls delegatecall (example below)?

texts:
In other words:

If contract B is called by contract A:

B:

function externalcall() public
{
//msg.sender is contract A...
msg.sender.call.value(0);

}

Then assuming msg.sender.call above calls back contract A:

function () //we use fallback to catch anything here, say a call from B
{
address e = contract A
e.delegatecall... //here we call any function back in B, say 'setowner'
}

back to B:

function setowner(address _owner) public onlycontractoronlyowner
{
//check to see if the sender is the owner or the contract itself - as with dsauth, the famous library which uses both contract/owner...
}

So who will be the msg.sender at the very end? Will this be the user who started it all(A) or will this be the "innocent" contract B?

Also can this be done just with flow as described: using call.value or even better/worse: send/transfer? Thanks!


texts: Sending Ether between two separate ethereum blockchain

texts:
is there any possible way to send ether (preferably other cryptos too) between two separate ethereum (also any other blockchains) blockchains ?
also is HTLC support is needed for this to be achieved?... because it does kind of resembles an atomic swap process.

Thank you for your answers in advance :D

Edit: would the Ethereum cross-chain swap work between a private Net and the ethereum mainnet giving that we have here two different genesis block configs (for example: the private has 0 mining rewards )


texts: Solidity Smart Contract using BigChainDB

texts:
I recently read about BigChainDB and plan to use in some PoC project like KYC or Land/Asset Registry using Solidity. If someone has created any solidity smart contract(s) using BigChainDB, can they please share document/blog/links/GitHub repository.
On the BigChainDB site, I could not find many resources which talk about smart contract implementation using BigChainDB.

Thanks in advance!

Regards


texts: Alternatives to get LINK tokens in Ropsten, for RNG

texts:
Sorry if this question sounds like very newbie (and maybe it is.
I'm developing a Smart Contract which needs a random number generation, and after researching some time it seems that ChainLink VRF function is the best option now, because of the problems of RNG on chain.
To execute VRF Smart Contract you need to fund the Smart Contract, in order to get random numbers.
The problem is that I want to test with faucet LINK tokens, and Chainlink has a website working as a faucet for Ropsten.
When I ask to test tokens, a green message is displayed with confirmation and transaction hash.
But when I try to see the transaction in Etherscan, that transaction does not exist.
Is there any other option to get test LINK tokens? Or another production acceptable RNG method?


texts: "Nonce too low" using contract.methods.myFunction().send()

texts:
Using web3 to build a contract from the ABI:

contract = new web3.eth.Contract(JSON.parse(abi), '0x17c91A5a6f5e3E4BEaFC478D18C4A44D88833277', { from: '0x0Ad2b5CCe78D677fD000698a7E4Cde866DE189C6', gas: 100000})

contract.methods.myFunction('constructorVariable1', 'constructorVariable2').send()

First send completes successfully. Second+ send returns the error: nonce too low

Truffle v5.1.13 (core: 5.1.13)
Web3.js v1.2.1
Ropsten testnet
Infura as HDWalletProvider node

I can't find any documentation on manually increasing the nonce using the send() method. I would have also thought nonces would be increased automatically?

I should add that there were no pending transactions during these sends.

Update:

Disconnecting and reconnecting from truffle console resolved the issue.


texts:
I have deployed  and tested my custom token contract using Openzeppelin contracts successfully. I need to design a dapp using metamask. I want to sell my tokens in exchange for Tether Token. In order to transfer token to buyer Is there any way to transfer token to buyer without need to pay the gas fee? I mean using a mechanism to make buyer does transaction.
thanks


texts: Why does this throw a stack underflow error?

texts:
Simple contract, one function.

function getSha256(uint32 nonce) returns (bytes32 hash) {
    return sha256(nonce);
}

> contractInstance.getSha256.call(1);
Error: Error: VM Exception while executing eth_call: stack underflow


texts: Error when connecting to web3 and metamask

texts:
I use this code to connect ui with smart contract

  window.addEventListener('load', () => {
     // Wait for loading completion to avoid race conditions with web3 injection timing.
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          currentAddress = web3js.eth.accounts[0]
          // Acccounts now exposed
          return web3;
        } catch (error) {
          console.error(error);
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log('Injected web3 detected.');
        return web3;
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/abikeygoeshere');
        const web3 = new Web3(provider);
        console.log('No web3 instance injected, using Local web3.');
        return web3;
      }
    });

but in my console i get this error

exchange.js:41 Uncaught SyntaxError: await is only valid in async function

this is in line 41

await window.ethereum.enable();

how can i fix this?


texts: Whats the important specifications for a GPU

texts:
Which specifications are important for a GPU to get a high Hashrate.

Frequency
GPU Clock Speed
Graphics Ram Type
Memory Bus Width
Memory Speed?

or another important thing?


texts: `evm_increaseTime` does not increase timestamp

texts:
How can I fix this?

See:

$ truffle console
truffle(development)> web3.eth.getBlock("latest").timestamp
> 1506694386
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_increaseTime", params: [500000], id: 123})
{ id: 123, jsonrpc: '2.0', result: 500000 }
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_increaseTime", params: [500000], id: 123})
{ id: 123, jsonrpc: '2.0', result: 1000000 }

When using evm_increaseTime, the result returns a value that appends to 0, instead of adding onto the block time.

The expected result value should be 1506694386 + 500000, but instead, it returns 0 + 500000.

Your Environment

Version used: v4.1.3
Operating System and version: Mac OSX

EDIT: On the suggestion of force-mining:

If I mine a block before (or even after) performing evm_increaseTime, it does not make a difference:

$ truffle console
truffle(development)> web3.eth.getBlock("latest").timestamp
1506739091
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_mine", params: [], id: 0})
{ id: 0, jsonrpc: '2.0', result: [] }
truffle(development)> web3.eth.getBlock("latest").timestamp
1506739124
truffle(development)> web3.eth.getBlock("latest").timestamp
1506739124
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_increaseTime", params: [500000], id: 123})
{ id: 123, jsonrpc: '2.0', result: 500000 }
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_mine", params: [], id: 0})
{ id: 0, jsonrpc: '2.0', result: [] }
truffle(development)> web3.currentProvider.send({jsonrpc: "2.0", method: "evm_increaseTime", params: [500000], id: 123})
{ id: 123, jsonrpc: '2.0', result: 1000000 }


texts: Does the Wallet Griefing Attack still Exists?

texts:
I read about Wallet Griefing attack at the following link:
[Ethereum Griefing Wallets][1]

'send' is checked but contract uses throw. The code is given below:
for (uint i=0; i<investors.length; i++) {
  if (investors[i].invested == min_investment) {
    // Refund, and check for failure.
    // This code looks benign but will lock the entire contract
    // if attacked by a griefing wallet.

    if (!(investors[i].address.send(investors[i].dividendAmount)))
      {
        throw;
      }
    investors[i] = newInvestor;
  }
}

Can this attack still occur by replacing throw with revert?
Somebody please guide me?
Zulfi.


texts:
I have cloned the cpp-ethereum in Linux (centOS) from git as follows as suggested in cpp-ethereum-develop cmake error

git clone https://github.com/ethereum/cpp-ethereum

cd cpp-ethereum

git checkout 5669c209f4f8dbb7dc3f744e8e2a9c92f1104ca3

git checkout -b develop

git submodule update --init --recursive

mkdir -p build
cd build

git clone https://github.com/cinemast/libjson-rpc-cpp

cmake ..

When building, I get:

-- Could NOT find jsoncpp (missing:  JSONCPP_LIBRARY JSONCPP_INCLUDE_DIR)

-- JsonCpp headers: JSONCPP_INCLUDE_DIR-NOTFOUND

-- JsonCpp lib   : JSONCPP_LIBRARY-NOTFOUND

CMake Error at cmake/UseJsoncpp.cmake:8 (message):

  Jsoncpp library not found
Call Stack (most recent call first):

  cmake/EthDependencies.cmake:203 (eth_apply)

  cmake/UseJsonRpc.cmake:3 (eth_use)

  cmake/EthDependencies.cmake:203 (eth_apply)

  eth/CMakeLists.txt:7 (eth_use)

Is the above problem from path setting or some thing else?


texts: what is the use of the payload field in the ethereum transaction reciept?

texts:
as seen in the following transaction reciept: https://www.etherchain.org/tx/0xf6769d28b35ac24e2e89b6cebc835c16c4e616bd6e2f96d0eea337c7bd02605f

what is the payload field and what is the use?
how to put/get data in it?
is there web3 function to manipulate that?


texts: Myether wallet.com balance zero but I had a balance and it shows on the blockchain too

texts:
Please help as I have sent an email to my provider myetherwallet.com but so far no response sadly. My knowledge is very basic.

I opened an account added funds which showed several months ago but  today my balance says zero. Concerned I checked my address on the block chain for ethereum and it matches my balance that I originally held with this provider. Is this to do with the hrd fork? How do I get access to my funds. Sorry if this seems a dumb question but of course its concerning to have lost access and control of my funds.

Really appreciate your help guys.


texts: Timeout w/ Mocha on deploying a contract

texts:
Starting to build the following test suite for a contract. It deploys fine on Remix.

I get the following error message.

1) "before each" hook for "deploys a contract":
     Error: Timeout of 20000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

I haven't had much of an issue doing this on other contracts with this setup. Not sure what's going on here. Am I missing something basic?

const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());

const json = require('../build/contracts/Contract.json');
let accounts, contract;

const NULL_ADDRESS = "0x0000000000000000000000000000000000000000";

beforeEach( async () => {
  // Get a list of all accounts;
  accounts = await web3.eth.getAccounts();
  console.log('accounts', accounts);
  const interface = json["abi"];
  contract = await new web3.eth.Contract(interface)
  .deploy({ data: json["bytecode"] })
  .send({ from: accounts[0], gas: '3000000' })

  console.log('contract', contract);
});

describe("Contract", () => {

  describe("Smoke test", () => {
    it("deploys a contract", async () => {
      await assert.ok(contract.options.address);
    });
  })

});


texts: What IDE or text editor can I use for solidity in ethereum?

texts: I need to know how to use solidity (What IDE to use) and is there any other languages that is used in the Ethereum blockchain.


texts:
I'm using the embark framework to deploy some smart contracts to a private Ethereum network. The problem is, the network behaves differently on separate machines, even though they're similarly spec'd - for instance, on one machine it mines instantly, but on another it can take up to 30 minutes between committing a block and actually mining it. I'd like to figure out why!

Embark calls geth this way:

geth --datadir=".embark/development/datadir" --networkid 12301 --password config/development/password --port 30303 --rpc --rpcport 8545 --rpcaddr localhost --rpccorsdomain="*" --nodiscover --mine --shh --rpcapi "eth,web3,shh" --unlock=74ce832e8e34a554d6d77f1350f8d76e261d9f7a js .embark/development/js/mine.js

It uses a genesis.json that looks like this:

{
  "nonce": "0x0000000000000042",
  "difficulty": "0x0",
  "alloc": {
    "0x3333333333333333333333333333333333333333": {"balance": "15000000000000000000"}
},
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x3333333333333333333333333333333333333333",
  "timestamp": "0x00",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "0x",
  "gasLimit": "0x4c4b40"
}

The other 'variable', I think, is mine.js, which is basically doing this:

var start_transaction_mining = function (config, miner_obj) {
  web3.eth.filter("pending").watch(function () {
    if (miner_obj.hashrate > 0) return;
    miner_obj.start();
  });

  web3.eth.filter("latest").watch(function () {
    if (!pendingTransactions()) {
      miner_obj.stop();
    }
  });
};

Where pendingTransactions does this:

var pendingTransactions = function() {
  if (web3.eth.pendingTransactions === undefined || web3.eth.pendingTransactions === null) {
    return txpool.status.pending || txpool.status.queued;
  }
  else if (typeof web3.eth.pendingTransactions === "function")  {
    return web3.eth.pendingTransactions().length > 0;
  }
  else {
    return web3.eth.pendingTransactions.length > 0 || web3.eth.getBlock('pending').transactions.length > 0;
  }
};

Any ideas as to where I might look in order to solve the performance disparity between different machines?


texts: How to add superscript in the code and what data type to use?

texts:
I stated in my solidity code
 _name = 'UZAIR™';

which gives this error
'ParserError: Invalid character in string.
    _name = 'AUREALS™';
            ^-------^'

Please tell how to fix it


texts: The Unicorn Mystery - Solidity fails to decode valid UTF-8 encoded bytes

texts:
The Ethereum Foundation has the Unicorn token to encourage donations, and the unicorn emoji is represented by three bytes. How in the world did they do that?

I know that Solidity supports unicode escapes, so something like \u2934 in a string is displayed in Mist as ⤴ . But what about something like the puppy emoji ?

One would think the escape sequence would be \u1F436, but instead Mist just shows a character that isn't what I want, presumably whatever emoji has the encoding \u1F43.

So then I tried with two unicode points: \uD83D\uDC36. Mist didn't show anything.

The following commit makes me think this is impossible, because it seems to me like the for loop has i iterating through four characters, or two bytes for each escape sequence:
https://github.com/ethereum/solidity/pull/666/commits/aa4593cab3d60468e5ea4318012c5252ebbc7d13
And as noted, unicode points don't seem to work, or at least aren't displayed in Mist (yet Mist shows the Unicorn emoji).

How in the world do I support an emoji consisting of 3+ bytes?

EDIT:

0xcaff found a bug in the way that Solidity decodes UTF-8 encoded bytes.

I've filed the issue on GitHub: https://github.com/ethereum/solidity/issues/2383
If someone has a fix, the bounty is theirs. Otherwise it will go to 0xcaff.

EDIT II:

The issue has been closed, UTF-8 validation has been fixed (or at least improved) and changes have been merged: https://github.com/ethereum/solidity/pull/2386

Now you can use emojis in Solidity with something like:

string public constant working = hex"F09F90B6";

Using the UTF-8 encoded bytes that can be generated from sites like https://mothereff.in/utf-8.

Woohoo!


texts: What are explicit steps to deploy dapp to mainnet?

texts:
There doesn't seem to be much documentation on how to transition your truffle DApp from working locally to being migrated to the mainnet. Below are some steps I generally would think are necessary:

Develop Smart Contract
Compile and migrate contract into testrpc
Test Smart Contract w/ testrpc, test scripts, etc.
Build front end of DApp
Test Dapp locally with testrpc on
Compile and Migrate contract on mainnet

Step 7 is where my questions start:

Which IP address do we use in the truffle.js file of the Dapp?
What steps do we take to migrate the contract to mainnet AND make sure that the Dapp still works with live instance of the contract? I assume that we'll need to record the contract's live address and change some code around in the Dapp.

Lastly, some more theoretical questions related to migrating contract code onto various networks:

How do test networks know which address is the contract owner, given that you don't need to deploy from a static account on test networks like you would on mainnet?

Thanks in advance!


texts: The D in the DApp? Decentralised vs Distributed

texts:
Understand that the D in the DApp is decentralised. I saw some whitepapers put the D as distributed such as the flight chain whitepaper.

What is the precise difference between decentralised and distributed?

To me the term distributed still has the element of centralised control. I.e., distributed computing. Anything other differences between distributed and decentralised?


texts: Use msg.value more than once vs assign a variable?

texts:
Imagine that I have an Smart Contract which is using the uint value of msg.value to add it to other "not monetary" variable, only to record the received money. I'm a bit worried specially for security concerns, I don't want to have a breach that could lead to money loss.
My biggest doubt is if msg.value is more than a uint, and could have potential issues if you use it directly for anything apart of value transfers.
struct Item {
    uint _postId;
    address payable _author;
    uint _value;
}

uint numPosts;

mapping(uint => Item) items;
uint[] public itemValues;
mapping(uint => address payable) itemAuthors;

Is this valid?
    function supportAuthor(uint _itemId) payable public  {
       //Monetary transfer here
       address payable author_ = itemAuthors[_itemId];
       require(author_ == address(author_),"Invalid address");
       author_.transfer(msg.value);

       //adding the received money to the struct
       items[_itemId]._value = items[_itemId]._value + msg.value;

       //adding the received money to the list of items.
       //Array position is the ID.
       itemValues[_itemId] = itemValues[_itemId] + msg.value;
    }

Or is better in this way? - Assigning msg.value to uint variable
    function supportAuthor(uint _itemId) payable public  {
       uint value = msg.value;
       //Monetary transfer here
       address payable author_ = itemAuthors[_itemId];
       require(author_ == address(author_),"Invalid address");
       author_.transfer(msg.value);

       //adding the received money to the struct
       items[_itemId]._value = items[_itemId]._value + value;

       //adding the received money to the list of items.
       //Array position is the ID.
       itemValues[_itemId] = itemValues[_itemId] + value;
    }


texts:
In the patricia merkle tree, each shortnode represent a key-value mapping which saved in DB.

Key = Hash(Value)

Value = rlp.encode(node)

There is question that if a node been updated and the node's value changed. When the node saved to DB, the key of the node change! But i didn't find any reorgnization tree code.

How does patricia merkle tree work during the node updating?


texts:
Want to provide an interface on my page to show filter based event data.

Haven't come across a proper working example to fetch event data by providing a date span. So it will be helpful if one could give few examples of querying on old event data.


texts: Ocasional connection refused initializing web3

texts:
I have an ethereum web application using web3js 1.0.0-beta.34 on a private network. Most of the times everything works fine. Sometimes the connection to the node through a websocket provider fails with the error:

web3.min.js:1 WebSocket connection to 'wss://myserver.com/quorum/node4/ws' failed:
Error during WebSocket handshake: Unexpected response code: 400

I cannot replicate the error consistently, and my guess is that is related to the network conditions. Something like I start using the web3 library before is connected. This is how it's initilialized:

const provider = new Web3.providers.WebsocketProvider("wss://myserver.com/quorum/node4/ws");
const web3 = new Web3(provider);
const contract = new web3.eth.Contract(contractAbi, contractAddress, { gasPrice: 0, gas: 4500000 });

Is there a better way to initialize web3 so I can ensure the connection has been stablished?

Thanks


texts: Can you attack/ddos/spam a single contract?

texts:
Can you make a denial of service attack against a Contract? By blocking a single contract (or ethereum-object) instance so it can't be executed? For example spamming it in some way, like repeadetly calling a method of a single contract that modifies the internal values of the contract?

Is it possible to be able to find a way to spam the contract first because it's easier/cheaper to spam it and block it individually instead of spamming the whole network? How much do you need to roughly spend in ethers?

An example attack I have in mind would be to call a specific transactional method (sendTransaction to a method that stores data into a contract) in an Ethereum contract repeadetly, to see if you can block a normal user from executing the contract, because of increased gas cost or for other reasons.

How much Ethereum is resistant to attacks like that? Are there any other attacks that can render a contract completely blocked or unusable instead, is it much cheaper/easier to run such an attack instead of a broad spam of the whole network, is the potential cost different/cheaper?


texts:
I am failing to use the push method against a dynamic array declared as a state variable. How can I do this?
I declare a dynamic array of addresses as a state variable like below:
contract Sample {
  address[] public path;
}

Then, inside a function of this contract, I push two addresses into the dynamic array:
path.push(address1, address2);

And I get this compile error:
CompileError: Sample.sol:91:9: TypeError: Member "push" not found or not visible after argument-dependent lookup in address[] storage ref.
        path.push(address1, address2);
        ^-------^


texts:
I'm quite new to Ethereum and might have lost my 0.046 ETH. Granted, not the biggest loss, however I'm trying to find out where I went wrong.
I downloaded the Aragon wallet, and got to a screen that told me, my balance was 0.

In order to continue:
Get testnet ether for your address (needed to transact), we are sending some but if it doesn't appear in your account in one minute, try here

It didn't appear, however my address did appear, so I went and bought some and sent a test amount. The transaction was a success (See Etherscan) but when I check the balance of the address (see Etherscan) it's empty?


texts: restricting sensitive information accessible from / linked to the blockchain?

texts:
I'm currently researching the practicalities of implementing a blockchain ledger whereby the company I work for, our competitors, our clients, our clients users (who we service indirectly) and an industry regulator would all need access to some of the information contained in the chain.

The crucial piece of information would be an asset which changes hands multiple times over it's short lifecycle.  Publicly the asset would list the owner and would also detail other users who would be listed as having a legitimate interest in the details of the asset. The Owner of the asset would be able to make predefined changes to the asset depending on their role, e.g. client issues asset to user, regulator would approve asset, after regulator verification we (or our competitor) perform an action and would terminate the useful life of the asset in the blockchain.

Would you need to set up a private side chain that interacts with the public ethereum chain to store sensitive information? And would it be possible to restrict access to the information depending on which parties are listed as having permission to view asset details.

My initial thoughts on a design would be to create a distributed database such as the BigchainDB or to use the Openchain project which would store sensitive info and then these would interact with the Ethereum blockchain which lists an asset owner and interested parties. My boss is drawn to the Openchain project but I think a completely private system would lose the benefit of the networks power, which helps prevents fraudulent activity and helps to prevent the existence of there being a single-point-of-failure in the system.

Sorry if this is too broad a question, and I will be doing a lot more reading to try and make my vision a reality that I can implement, but if I'm missing something crucial or am suggesting something that just isn't possible I'd like to know in advance! :/

Thanks in advance to anyone who can help guide me!


texts: Is the EVM operand stack size (at any instruction) independent of the execution path?

texts:
I'm trying to analyze some EVM bytecode, comparing it with Java bytecode.

The Java specification states the following in the JVM specification §4.9.2. Structural Constraints:

  If an instruction can be executed along several different execution paths, the operand stack must have the same depth (§2.6.2) prior to the execution of the instruction, regardless of the path taken.

So for any given instruction the operand stack has a well-defined size.

Now I wonder whether the same is true for EVM bytecode?


texts: Chaining smart contract deployments through instantiation in constructors

texts:
As the title suggests, I'm not sure what is considered to be good practice when it comes to deploying smart contracts that interact with each-other.
My example:
migrate contract A.
Contract A creates new instance of Contract B in constructor.
Contract B creates new instance of contract C in constructor.
Contract C created new instance of contract D in constructor.
This chained relationship is important for my contracts as they rely on the ownership structure to execute my design pattern.
When attempting to migrate contract A over in truffle I am getting:
"ran out of gas (using a value you set in your network config or deployment parameters.)

Block limit:  6721975 (0x6691b7)
Gas sent:     6721975 (0x6691b7)"

I guess my question is, is this pattern madness?
The block limit in the error scares me as I'm not sure if I will encounter this when migrating to mainnet?
Is this chaining of contracts adding to my gas costs in an exponential manner that could otherwise be avoided by using a different pattern?


texts: How to interact with Geth mobile from react-native

texts:
I'm working on a react-native dapp to get some experience, but I'm struggling to interact with geth from the javascript side. I'm currently only focused on Android. The Geth client is succesfully executed on the start of the application following this guide: Geth mobile introduction. Since the new mobile packages of Geth don't run a rpc anymore, web3 alone won't do the trick.

I have already tried to wrap Geth inside a native module, but it cannot access the Geth running on the main thread as far as I know.

Status is doing a similar thing, but I couldn't wrap my head around how they do it from looking at their code.

Has anyone figured out how to do this already?


texts: How connect non-authority node to the PoA


texts: It is known that Ethereum follows State transition model. How is the balance of each account known at any given time ? From my understanding, the yellow paper states that the balance is not stored on blockchain, where is it stored and how is it modified?


texts: function gas calculator and function gas padding

texts:
not sure if this is possible, but I was wondering if one function can calculate the gas cost of another function?

Also can a function run a series of computations to match the gas cost of the function?

function checkGasCostToRunFunctionX() public view returns(uint) {
  return uint(gasCostOfRunningFunctionX())
}

function functionX() public {
 10000000000000000000000 + 10000000000000000000000;
}

function cloneFunctionXGasCost() public {
// small computation
1 + 1;
someKindOfPaddingComputationToMakeThisFunctionCostTheSameAsFunctionX;
}

function checkCloneFunctionCostsSameAsFunctionX() public view returns(uint) {
 if (gasCostOfFunctionX == gasCostOfCloneFunction) {
    return = true;
}


texts: Help understanding and translating my private network genesis file parameters with config.go variables

texts:
I am modifying the file config.go in the geth project for a private blockchain.

Here are the config.go variables

// MainnetChainConfig is the chain parameters to run a node on the main network.
MainnetChainConfig = &ChainConfig{
    ChainId:        big.NewInt(1),
    HomesteadBlock: big.NewInt(1150000),
    DAOForkBlock:   big.NewInt(1920000),
    DAOForkSupport: true,
    EIP150Block:    big.NewInt(2463000),
    EIP150Hash:     common.HexToHash("0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"),
    EIP155Block:    big.NewInt(2675000),
    EIP158Block:    big.NewInt(2675000),
    ByzantiumBlock: big.NewInt(math.MaxInt64), // Don't enable yet

    Ethash: new(EthashConfig),
}

If I give an example of my test network

{
"config": {
    "chainId": 87079082075,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
},
"nonce": "0x0000087079082075",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x00",
"gasLimit": "0x8000000",
"difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333"

Some parameters / variables are straight forward to map.

Here is my attempt

ChainId big.NewInt(87079082075),
HomesteadBlock: big.NewInt(0),
DAOForkBlock:   big.NewInt(0),
DAOForkSupport: true,
EIP150Block:    big.NewInt(0),
EIP150Hash:     common.HexToHash("NotSureWhereToGetThisValue"),
EIP155Block:    big.NewInt(0),
EIP158Block:    big.NewInt(0),
ByzantiumBlock: big.NewInt(math.MaxInt64)

I then get confused with the values in util.go and will it overwrite these values in config.go.

I also do not see in config.go the values associated with the other genesis file parameters like difficulty and gaslimit.  I think they are updated in protocol_params.go can someone confirm I am observing the code correctly and on the right track.


texts: Contract 'throw' - ether sent by the contract also reverted?

texts:
If a contract throws a exception (using 'throw') is any ether sent by the contract to other contracts or external accounts also reverted?

I understand that any contract callers have the ether value returned (refunded) but I am unsure what happens to the contract ether balance when sending ether to other contracts or accounts.


texts: Sorry just a little confused. If the geth rpc node needs to be running on the live server (say you deploy your dapp to the world), does that mean everyone has access (via the web) to modify the accounts authorized by that node? How would you allow people to access their own accounts instead of the servers geth authorized accounts?


texts: Is there any way to create an ethereum account from RSA key?

texts:
I have my very private RSA key:

-----BEGIN PRIVATE KEY-----
MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQDI0vCkxjyJQ7b7
MVJKKXVTFSH3yN5xWozV1pZ8grTTr6dL90bmeCHIw9PnsZRJWsAhstnSnLm1v7KE
kkNqFi2s+sBf1BSBDZ5onoWE0dtb3R2dG25AsYRj54Sd6rtX9U/2aF ... uNjei
sMA0VQ2av7J60ulAz2AYMHoMrEOznhUpgOM7Op7hR3WE0XFkmL4wmcovboCXTtp8
tMK8EN5Hp4YasJp4Hw9Rc50EluiXMsCuc9Uwr41FZhQQJGtWPGImxoiPU6jJfZUP
yja709eeToSrwU6xoYArh7RnN3Qx
-----END PRIVATE KEY-----

I use keythereum to generate an ethereum wallet:

const privateKey = fs.readFileSync('my_private_key_file', 'utf8')
const password = 'myVerySecretPassword'

function generateWallet(privateKey, password){

    const dk = {
        privateKey: Buffer.from(privateKey, 'utf8'),
        salt: crypto.randomBytes(32),
        iv: crypto.randomBytes(16)
    }

    const options = {
        kdf: "pbkdf2",
        cipher: "aes-128-ctr",
        kdfparams: {
            c: 262144,
            dklen: 32,
            prf: "hmac-sha256"
        }
    }

    return keythereum.dump(
        password,
        dk.privateKey,
        dk.salt,
        dk.iv,
        options
    )
}

That's what I get back:

{
    address: 'c1cfd69deab90015dd456164d058f73abe3b80f4',
    crypto: {...},
    id: 'd94389ec-1e8a-4e95-a386-0a3be0900e13',
    version: 3
}

Now I want to start transacting from the address 0xc1cfd69deab90015dd456164d058f73abe3b80f4. How can I unlock it and set as a desired coinbase? The JSON RPC method parity_newAccountFromSecret accepts only hex, no more than 64-character long.


texts: How do I send ETH from a simple wallet contract via MyEtherWallet?

texts:
I used Ethereum Wallet to make a single wallet contract and sent it some ETH. When I load the keystore in MyEtherWallet, I can see the balance on the main account, however, I cannot see the balance on the wallet contract.

How do I see the the balance on the wallet contract, and send from this contract using MyEtherWallet (not Ethereum Wallet)?


texts: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead

texts:
The warning is from running sample code from Mastering Ethereum, I get the above error and it says

  Use "constructor(...) { ... }" instead.
    function Migrations() public {


texts: How can I test mining ethereum using my MacBook Pro's CPU with a remote pool?

texts:
This may seem like a stupid question, and maybe it is - I'm fairly new to all this.

My use-case is that a friend has deployed a pool and wants others to try it, just to test it for setup issues etc.

I don't have good enough hardware to try GPU mining, so have spent over a week trying to find a decent way to mine using the CPU on my MacBook Pro.

Lots of answers here just say 'Oh, if you want to test using CPU mining, just use Geth'. But they generally assume you're using it locally, with a private pool which is also running a Geth node on the same machine.

So, could I use Geth to test mining in my friend's pool? How do I set that up to point to his pool server?

And lastly, are there any better solutions? I've looked into the various forks of cpp-ethereum to see if I can get ethminer to work on my Mac, but so far all of the ones I've tried have dropped support for CPU mining altogether, which I find really weird.

Thanks all for any help you can provide.


texts: Basically i want to have a smart contract that can allow users to exit early under specific conditions. Does anyone have any resources for this or know whether its possible?


texts:
In Etherscan, it is easy to find a contract. For example here is an example:

https://etherscan.io/address/0x80fB784B7eD66730e8b1DBd9820aFD29931aab03#code

The web page says that the contract address is 0x80fB784B7eD66730e8b1DBd9820aFD29931aab03. I guess that the address is where the contract is created and is installed.

In the middle of the same web page, there is a Contract source code. But in the source code, there are several Contract declarations. Does it mean that more than one contract have been created and installed? Who has the Contract address in the top of the web page if there are more than one Contract?


texts: web3.js why is there dots when calling addresses

texts:
I'm trying to use web3.js to use the "transfer" function of an ERC20 token.

I've found this example here : How to send ERC20 token using Web3 API? which seems good (but kind of old)

But I notice they almost always put "..." after an address like so :

var contractAddress = "0x8...";

or

"data": contract.transfer.getData("0xCb...", 10, {from: "0x26..."}),

Why is that ?


texts:
I know that in Ethereum, same addresses works across the network(mainnet and all testnets).

But I am looking to know if there are any chances to find out the network on which a contract is deployed by using its contract address because only relevant network will be having the data of contract stored.

Also how much reliable this approach can be?


texts: Warning: Use of the "var" keyword is deprecated

texts:
I am trying to fix the following var warning that the use of var is deprecated. I can't work out what to change it to, any advice would be appreciated. Any help would be greatly appreciated.

function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) {
    require(_to != address(0));

    var _allowance = allowed[_from][msg.sender];

    balances[_from] = balances[_from].sub(_value);
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = _allowance.sub(_value);
    emit Transfer(_from, _to, _value);
    if(transferIns[_from].length > 0) delete transferIns[_from];
    uint64 _now = uint64(now);
    transferIns[_from].push(transferInStruct(uint256(balances[_from]),_now));
    transferIns[_to].push(transferInStruct(uint256(_value),_now));
    return true;
}


texts: Is it possible to do in a smart contract that a particular node can approve certain actions like checking if the sender's address is authenticated by that specific node and that it will confirm it by its signature?


texts: How to sign anything with my ethereum private key and verify with public key?

texts: How can I use the private key of my eth.accounts[0] to sign a file from outside Ethereum, so people can verify that the file belongs to that account with the public key?


texts:
I wrote a smart contract in solidity to swap ERC20 tokens on different exchanges, however I'm still stuck on how to get my transaction to go from one dex to another without having to use my smart contract as a middleman.
Any help would be much appreciated.


texts: Specifically, How does erc725, erc735 deter identity fraud?


texts: How many Ethereum-based tokens are there?

texts:
(Possibly a little off-topic, but along the lines of previous questions like "How many nodes are supporting Ethereum Classic?" and "How many pre-sale addresses are there?", perhaps... )

The question "Naming conventions for ERC-20 instancies" got me wondering:

How many Ethereum-based tokens are there, and how does this compare to the number of tokens on other platforms?

Clarifications:

Public, main (ETH) network only;
I'm not counting ETH as a token itself, though strictly you could argue it is;
ERC-20/ERC-223 or otherwise;
By "other platforms" I mean other, non-interoperable, blockchains;
I'm loosely defining "tokens" on other platforms, be they backed by smart contracts or otherwise. (...Which now has me questioning: "What is a token...?")


texts: Is there a version of the Casper Proof of Stake engine either CBC or FFG that is available for testing on a private network?  If so is there a guide on how I would utilize it?


texts: Distribute tokens to multiple addresses from wallet

texts:
How can i Distribute tokens from my new wallet "not contract" once?

AND

How select who token to send it


texts: How does the "block parameter" work with RPC calls? Do light nodes have access to historical data?

texts:
I'm looking at the RPC spec. Many calls (eth_getBalance, eth_getStorageAt) allow for a custom "block parameter" where I can pass in any block number.

How does this work? Does each node maintain a copy of the state for each block (I assume not). Do nodes synced via --fast have access to blocks before they were fast synced?

Cheers
-Aakil


texts: Smart contract - require token balance in constructor

texts:
I want to build a smart contract which can only be constructed, if there's an amount x of a specific ERC20 token available to spend for this contract.
So either the contract has to be allowed to spend this amount in the name of the creator of the contract or it already has the desired balance itself. I don't think there's really a difference between these 2 options from conceptual perspective but in some way the contract must be able to spend amount x and if amount x is not available for spending than the contract should not be deployed at all. And just for clarification, the amount x would also be passed with the constructor.

Actually i just want to have something like the following which is obviously not really possible:

constructor(uint x, ...) public {
    require(
        token.transferFrom(msg.sender, this, x)
        //...
    );
    //...
}

Is it possible to achieve this?
It's not really an option to transfer tokens to the address of the contract before it's even deployed i think. Theoretically it could be done this way this since contract addresses are deterministically computed from what i know but i'm really looking for a more handy solution.

Oh, and this ERC20 token is also issued by myself. If it would bring any benfits to extend the token's smart contract, i could do this for sure.

In the end i want to have a contract which can promise to pay out certain participants and i want to have a guarantee from the beginning that this is possible. These certain participants are predetermined as well so imo it would only make sense to have the promised amount x of tokens ready at contract construction.


texts: Why people use public function that just calls an internal function?

texts:
After user for a long time codes from Open zeppelin I found comething weird. Usually, they use public functions which only use is to call an internal function with the same name but with _ in front.

function transferOwnership(address _newOwner) public onlyOwner {
    _transferOwnership(_newOwner);
}

function _transferOwnership(address _newOwner) internal {
    require(_newOwner != address(0), "Adress can't be 0x0000...");
    emit OwnershipTransferred(owner, _newOwner);
    owner = _newOwner;
}

This repeats in a lot of contracts. Why do they do that? Is it a security thing or am I missing something. For me right now, the only thing that this gives me is more gas cost.


texts: Gas not enough and not able to run functions

texts:
I am a new comer to the Ethereum and I am writing a piece of smart contract for my project. I used Win 10 and Mist 0.8.8 with the testnet that started with "R".

The contract code has the functions of  changing the state and some modifier, however, after I launched the contract, I am not able to run any functions of it. The following errors show up. Thank you so much!!!

The contract code is show below: Thank you so much!

pragma solidity ^0.4.6;
contract FairTrade {

    /* Variables */
    address public creater;
    address public trader;
    address public framer;
    address public preieumHandler;

    /* State handling */
    enum State { Paying, Transporting, Received, Completed }
    State public state;

    /* Contructor */
    function FairTrade(address _trader, address _framer, address _preieumHandler,
      uint _price, uint _quantity) {
        creater = msg.sender;
        trader = _trader;
        framer = _framer;
        preieumHandler = _preieumHandler;

    }

    /* Modifiers */
    modifier onlyFramer {
        if (msg.sender != framer) throw ; else _;
    }

    modifier onlyTrader {
        if (msg.sender != trader) throw; else _;
    }

    modifier inState(State s) {
        if (state != s) throw; else _;
    }

    modifier notInState(State s) {
        if (state == s) throw; else _;
    }

    /* Functions */
    function completedPaid() onlyTrader {
        state = State.Transporting;
    }

    function receivedGood() inState(State.Transporting) onlyFramer {
        state = State.Received;
    }

    function paid() inState(State.Received) {
        state = State.Completed;
    }
}


texts: What’s the transaction ordering inside a block?

texts:
The game
I found a game where each gambler needs to pay 0.02 ᴇᴛʜ to register a secret before the game before the games switch to status==reveal each day.
Then, during the status==reveal period no secret can be registered but each gambler who is revealing the secret behind the hash they registered is increasing a ++revealedcount counter. The person making revealedcount==5 is awarded the daily price (revealedcount is reset each day).
Currently, very few peoples are playing the game or at least, nobody seems to be playing it automatically.
How I’m thinking about winning each time
One way I’m thinking about is to pay 5 times 0.02 ᴇᴛʜ for 5 differents commitments and when status becomes reveal, then, post the reveal transactions in batch with a high fee and using an increasing gas price between each of them in order make sure I’ll get the transaction making revealedcount==5 (the price would offset the loss of the other 4 lost reveal tickets).
The problem
Nobody seems to be doing this currently and I think there’s might be a reason : The 5 transactions I will post may have the highest fee, but they will be far to fill the BLOCKGAS limit. This means there will be plenty of room for other transactions in the same block which will also include transactions from competitors on the same game.
While this the transactions paying the highest fee which are included inside a block first, is it the same inside a block ? I mean, does the transactions paying the highest fee are processed first inside the same block ?
Or rather what’s the behavior of the top mining pools ? Are transactions from the same Ethereum address grouped together regardless of their fees ?


texts: How can I get involved in the ethereum community?

texts:
I am looking to become involved in the crypto-currency ecosystem in a way that best uses my talents. My background is in finance and in the past I’ve worked for one of the largest technology-focused hedge funds in the world as well as one of the most successful investment banks. I also have a background in computer science and can code, though im not as talented as many of those already in the community. I don’t want to quit my current job yet, but I wanted to get involved in the ecosystem in a way that uses my skills.

What do you all recommend that I do?

One thing I’ve wanted to do is to join a DAO that does angel investing but I haven’t found any that exist yet. For now, I am just reading white papers and trying to learn by asking questions online, but I’d like to do more.


texts: Dropped & replaced Uniswap, trust wallet

texts:
I invested to a new coin through uniswap with my trustwallet, it was pending, but ended up showing "Dropped & Replaced". Lost all hope for this transaction since i have no knowledge on how to get it back or try and push through the investment somehow.
Does anybody have the powerful knowledge to help me out? :)
Really appreciated for any type of help. Thanks


texts: Is it possible to create an expiring/ephemeral ERC-20 token?

texts:
There are certain tokenizable assets (e.g. tokenized frequent flier reward points or product discounts) that might be well served by the concept of "expiration." Ideally, these assets (pre-expiry) could be listed and traded on exchanges, with the addition of expiration metadata.

Is it possible to build a token on the Ethereum blockchain that "expires" after a preset amount of time? Is anyone known to be working on this? I'm familiar with Freicoin which uses demurrage to disincentivize HODLing, but true expiration is a different concept.

Alternatively, is there a different way to functionally enable token expiration to serve the use cases mentioned above on the Ethereum blockchain, short of creating a new blockchain?


texts: What happens if you call a non-existent function of another contract that has no fallback function in Solidity?

texts:
Let's say you call a function at another contract in Solidity:

contractB.doFunction()

It would then match it using the function signature to run the function in contractB. If there's not match, it would run the fallback function.

But if neither exists? What happens? Does it throw an error, or would you just expend the cost of the CALL?


texts: web3.py createFilter: filter => SyntaxError: positional argument follows keyword argument

texts:
Web3.py version 4.2.1
geth version: 1.8.0-unstable

I have followed web3.py guide for filtering.

  Through the contract instance api:

event_filter = mycontract.events.myEvent.createFilter(fromBlock='latest', {'filter':{'arg1':10}})

But I get an error for this line:

myContract.events.LogJob.createFilter(fromBlock='latest', {'filter': {'arg1':10}})

My main goal is the filter events based on their arguments.

Error I am having:

myContract.events.LogJob.createFilter(fromBlock='latest', {'filter': {'arg1':10}})
                                                                 ^
SyntaxError: positional argument follows keyword argument

[Q] How could I fix this error?

Update: I have followed @Mikko Ohtamaa 's answer. Now I do not get any error, but filter returns [] even I provide correct event's keyword (dictionary of argument name and its value).

Please see an example:

blockReadFrom = 1899201;
myFilter = eBlocBroker.events.LogJob.createFilter(fromBlock=blockReadFrom)
print(myFilter.get_all_entries())

Returns, here you can see that there is emitted event with 'storageID': 0 under AttributeDict:

[AttributeDict({'address': '0x128c9F368F12C24Cc2a4f88dCDCf3daA13C9667e', 'transactionHash': HexBytes('0x8f7c50fe276057ea90985be6d14dc7abb79ee0430c66bd161861b582b7db0c97'), 'args': AttributeDict({'desc': 'Science', 'jobKey': 'QmRsaBEGcqxQcJbBxCi1LN9iz5bDAGDWR6Hx7ZvWqgqmdR', 'index': 21, 'storageID': 0, 'clusterAddress': '0x75A4c787c5c18C587B284a904165Ff06a269B48C'}), 'transactionIndex': 0, 'event': 'LogJob', 'blockHash': HexBytes('0x9782cb281aa72defe54e0f84055a03a0b1bf6c6f21bd3d276a1252098f83c15f'), 'logIndex': 0, 'blockNumber': 1899201})]

blockReadFrom = 1899201;
myFilter = eBlocBroker.events.LogJob.createFilter(fromBlock=blockReadFrom, argument_filters={'storageID':0})
print(myFilter.get_all_entries())

Returns:

[]

And interesting point that following line returns a valid output even though {'arg1': 999 or  'arg111': 999 etc.} does not exists.

myFilter = eBlocBroker.events.LogJob.createFilter(fromBlock=blockReadFrom, argument_filters={'arg1': 999})

Note:

For more information please follow this closed issue: https://github.com/ethereum/web3.py/issues/943#event-1723643072


texts: Serious BUG in the example DAO contract on the official Ethereum.org website?

texts:
when I look through the DAO (The Blockchain Congress) example from the official Ethereum website here

https://www.ethereum.org/dao

I noticed something strange, specifically for the addMember and removeMember functions :

/**
 * Add member
 *
 * Make `targetMember` a member named `memberName`
 *
 * @param targetMember ethereum address to be added
 * @param memberName public name for that member
 */
function addMember(address targetMember, string memberName) onlyOwner public {
    uint id = memberId[targetMember];
    if (id == 0) {
        memberId[targetMember] = members.length;
        id = members.length++;
    }

    members[id] = Member({member: targetMember, memberSince: now, name: memberName});
    emit MembershipChanged(targetMember, true);
}

/**
 * Remove member
 *
 * @notice Remove membership from `targetMember`
 *
 * @param targetMember ethereum address to be removed
 */
function removeMember(address targetMember) onlyOwner public {
    require(memberId[targetMember] != 0);

    for (uint i = memberId[targetMember]; i<members.length-1; i++){
        members[i] = members[i+1];
    }
    delete members[members.length-1];
    members.length--;
}

for addMember, it adds a mapping of memberId from address to uint, but when deleting a member, it just basically removes the member from the members array but not changing the memberId mapping, doesn't that mean the whole thing may get messed up after multiple member adding and removing operations?

I mean, if I add address 0x1, 0x2 and 0x3 as the first three members, since there are 2 default members (0x0 and owner), so now I have five members with memberId mapped 0 to 4 like

memberId[0x0] = 0
memberId[owner] = 1
memberId[0x1] = 2
memberId[0x2] = 3
memberId[0x3] => 4

and the members array basically have addresses like

members[0]={member: 0}
members[1]={member: owner}
members[2]={member: 0x1}
members[3]={member: 0x2}
members[4]={member: 0x3}

Now I remove member 0x2, and the member array ends up with length 4 like

members[0]={member: 0}
members[1]={member: owner}
members[2]={member: 0x1}
members[3]={member: 0x3}

however since the memberId are not updated, it is still

memberId[0x0] = 0
memberId[owner] = 1
memberId[0x1] = 2
memberId[0x2] = 3
memberId[0x3] = 4

and it seems all hell will break loose if you do further member adding or removing operations. For example if you add another member 0x4, then it will end up with the same memberId 0x3, resulting in something like

members[0]={member: 0}
members[1]={member: owner}
members[2]={member: 0x1}
members[3]={member: 0x3}
members[4]={member: 0x4}

memberId[0x0] = 0
memberId[owner] = 1
memberId[0x1] = 2
memberId[0x2] = 3
memberId[0x3] = 4
memberId[0x4] = 4

and that's actually the least problematic scenario. Worse is if you decide to call remove 0x2 again, 0x3 will actually be removed, ending up with something like

members[0]={member: 0}
members[1]={member: owner}
members[2]={member: 0x1}

memberId[0x0] = 0
memberId[owner] = 1
memberId[0x1] = 2
memberId[0x2] = 3
memberId[0x3] = 4

Or if I call add member with 0x2 again, it will actually REPLACE 0x3 instead of adding a new member

members[0]={member: 0}
members[1]={member: owner}
members[2]={member: 0x1}
members[3]={member: 0x2}

memberId[0x0] = 0
memberId[owner] = 1
memberId[0x1] = 2
memberId[0x2] = 3
memberId[0x3] = 4

Considering the code on the official website should be written by Ethereum experts and code gurus, I'm really not sure what is happening here. Is this really such a serious bug that somehow got past all the code reviewers, or is it intended as a buggy code example? Or have I missed something so that not updating the memberId mapping in the removeMember function is actually okay?


texts: Where to report scammer Ether wallet addresses?

texts: Bitcoinabuse.com is where we can report scammer addresses for Bitcoin wallets. What is the equivalent for Ether scammer addresses?


texts: Why are elements in a byte array padded to 32 bytes?

texts: On readthedocs.io, it says that byte[] or bytes1[] elements are padded to 32 bytes.  I thought at first it was for even distribution, but distribution would still be even if each element had exactly one byte of space.  So, what is the purpose of this padding?  Also, is this padding also added to bytes2 - bytes31?


texts: How do you get the UTXOs a transaction is spending using web3.js?

texts:
I'm unsure how to get the UTXOs that a transaction is spending.

Here's what I have so far. I get transaction details from txhash

web3.eth.getTransaction("0x97df3cd87f87bb6f04e643b66f495e993e9c128632549c539c76caf1ca8d1e2a").then(function(receipt){
  console.log(receipt);
});

It provides

blockHash:"0x13c008fbe05e6a181cdecdc434d1a0dd089918cd71861650131e00a69997dbe9"
blockNumber:6810576
from:"0xF092966e7bcc2b5646e0F0c20A715584DB37cd4B"
gas:600000
gasPrice:"20000000000"
hash:"0x97df3cd87f87bb6f04e643b66f495e993e9c128632549c539c76caf1ca8d1e2a"
input:"0x"
nonce:1135
r:"0x47397afae235efb00910e69da29ff30177ecf227619c09cdb50af880d24c20ea"
s:"0x7df404ca4bec847e45ec3934e5b8047136a9a5207d9801795d5d05673105a7c6"
to:"0xb60fdD0914b966b38EcFeFB9cb98C86F920EC7f6"
transactionIndex:4
v:"0x1c"
value:"3000000000000000"

This has the from address and the value, but what are the UTXOs that the value is coming from?


texts: Staking algorithms: are there any common grounds or each one develops per to it's own understanding?

texts:
Staking algorithms and rewards scheme
If it needs to be developed,
is there any common source of truth on how to implement this or everyone making their own one?
If governance contract needs some tokens to be locked to make a vote and
this amount is supposed to be taking part in staking and getting rewards for the time being in the lock
Does it mean that this amount should be locked in the state of Staking contracts or transferred
from Token user balance to the Staking contract user balance?


texts: Parse uint256 parameters to a function call from web3.js

texts:
I was trying to invoke some function which takes two uint256 numbers as inputs. Something likes this (solidity code)

function doSomething(uint256 input1,
                     uint256 input2)

I have tried several combinations but still doesn't find a correct way to parse the uint256 parameters to invoke doSomething correctly. For example, the below approach does not work (I tried it in Mix).

input1 = '0xfc9e0eefe9f3a5101b7c025b217c03c95dbf9bb4f2d1d46db238e305af104103';
input2 = '0xabcbcbcbcbbc';
contracts['Sample'].contract.doSomething(input1, input2)

Mix shows input1 as some negative value. The same log if I use the number in decimal format. I wonder whats the correct way of parsing uint256 parameters to a function call from web3.js?


texts: Solidity error when encoding arguments to query public mapping

texts:
While developing a Smart Contract with Solidity on Remix , after creating the contract I'm trying to query a public mapping:

mapping (address => uint256) public balanceOf;

but when I call balanceOf for address 0x9b9731b07b9b5f982289bab87097eade6a4bc25d it throws the following error:

  Error encoding arguments: SyntaxError: Unexpected token x in JSON at position 2

Any idea how can I properly call balanceOf?


texts:
Raspberry Pi 3B (arm7) with Raspbian (which /etc/debian_version shows as 9.1)
I'm logged in as the user pi.
I'm following instructions from http://raspnode.com/diyEthereumGeth.html.

After installing go under $HOME/bin/go, I'm doing these commands:

cd go-ethereum
my path now includes /home/pi/bin/go/bin
make geth

I also tried sudo make geth and got the same error. Oddly enough, sudo didn't ask me for my password like on other linux machines I work on. At the make command I get these errors:

pi@rpi3b-cr:~/bin/go-ethereum $ make geth
build/env.sh go run build/ci.go install ./cmd/geth
internal/build/azure.go:23:2: cannot find package "github.com/Azure/azure-storage-go" in any of:
/home/pi/bin/go/src/github.com/Azure/azure-storage-go (from $GOROOT)
/home/pi/bin/go-ethereum/build/_workspace/src/github.com/Azure/azure-storage-go (from $GOPATH)
internal/build/pgp.go:27:2: cannot find package "golang.org/x/crypto/openpgp" in any of:
/home/pi/bin/go/src/golang.org/x/crypto/openpgp (from $GOROOT)
/home/pi/bin/go-ethereum/build/_workspace/src/golang.org/x/crypto/openpgp (from $GOPATH)
Makefile:15: recipe for target 'geth' failed
make: *** [geth] Error 1

I also tried:

sudo apt-get install eth and sudo apt-get install ethereum and neither could be found in the package repo.
The error was "unable to locate package geth" or similar.

How do I install geth? Or even Parity? I have not been able to find instructions that work yet.

Thank you! I'm a noob when it comes  to installing a node, and to Rpi, although I know a little linux.


texts: Is it safe to use web3 with electron/angular?

texts:
I am building an electron or angular (not sure yet) application integrated with web3. I will be using a parity node and infura as a fallback node to communicate with the blockchain. I will be generating/importing keystore files. With keythereum and electron I can load these files and extract the private key with a password to sign transactions that I can send to the nodes.

The private key is exposed while signing the transaction. Is there a security issue?


texts: Different return value Truffle & online compiler

texts:
Using the online solidity compiler startGame() returns false, but using truffle this function returns a long hex string: 0xf697bd4ff4f5574f3cf73cd46a18087a5a0cf1aa1580fd4992ab20f574a808fe

function startGame() critical returns (bool) {
    Player player = players[msg.sender];
    if (player.ready) {
        if (player.balance < minimumwager) { throw; }
            waiting.push(player);
            numWaiting++;
            if (numWaiting > 1) {
                var thismatchup =  makeMatchup();
                player.playing = true;
                matchupMade(thismatchup);
                return true;
            }
            else {
                player.playing = true;
                playerWaiting(player.ethaddress);
                return false;
            }
        }
    }
}


texts:
I have a smart contract which generates a random number and compares it with the user's input to check if both are equals, and based on that it updates a mapping. But anyhow the same transaction is getting mined twice. Not able to understand what is going wrong.

//function to store the guess in the mapping when a guess is made.
function guessIt(uint _guess) public returns (bool) {
  //Need to check if the guess number is less than or equal tp range
  require(_guess <= range);
  uint random = generateRandomNumber(range);
  // uint random = 10;
  if (random == _guess) {
    Guess storage correctGuess = guesses[msg.sender];

    correctGuess.lastGuess = _guess;
    correctGuess.lastCorrectGuess = _guess;
    correctGuess.correctGuessCount = correctGuess.correctGuessCount + 1;
    correctGuess.lastGuessAt = now;
    totalNoOfGuesses = totalNoOfGuesses + 1;

    Guessed(msg.sender,random, _guess);

    return true;

   } else {
     Guess storage wrongGuess = guesses[msg.sender];

     wrongGuess.lastGuess = _guess;
     wrongGuess.wrongGuessCount = wrongGuess.wrongGuessCount + 1;
     wrongGuess.lastGuessAt = now;
     totalNoOfGuesses = totalNoOfGuesses + 1;

     Guessed(msg.sender,random, _guess);
   }
   return false;
}

This is how I am calling the function in my aap.js file.

checkMyGuess: function() {
    var guessInstance;
    var guessedNumber = parseInt($('#myGuess').val());
    console.log($('#myGuess').val());
    console.log($('#myGuess').val());
    var account = web3.eth.coinbase;
    App.contracts.GuessNumber.deployed().then(function(instance){
      guessInstance = instance;
      return guessInstance.guessIt(guessedNumber, {from: account});
    }).then(function(receipt){
      var guessResult;
      if (receipt.logs.length == 1) {
      guessResult = receipt.logs[0].args._randomNumber.toNumber() === receipt.logs[0].args._guess.toNumber() ? "Congrats!! You Guessed it correct"
                      : "Sorry!! I thought it was " + receipt.logs[0].args._randomNumber.toNumber() + ".<br/> Better luck next time.";
      }
      $("#guessResult").html(guessResult);
    });
  }


texts: Why is Proof of Work, Proof of Stake associated with Consensus Mechanisms/Algorithms?

texts:
Many often associate Proof of Work, Proof of Stake, etc with blockchain consensus algorithm/mechanisms.

I find that association to be inaccurate. Yes, proof of work / proof of stake are mechanisms by which leaders are elected to validate transactions. It is a crucial part in building consensus but not the only thing. For example, in bitcoin blockchain, the longest chain wins -- this to me is also considered as a crucial part in building consensus across the nodes.

As a blockchain nazi, to me, it only makes sense to call the distributed consensus algorithms such as Paxos, Raft, PBFT, etc as consensus algorithm/mechanisms because of its theoretical/mathematical underpinnings.

Why then is Proof of Work, Proof of Stake used interchangeably with Consensus Mechanisms/Algorithms?


texts: Solidity event not showing up from Web3.js

texts:
I'm trying to set up an event in Solidity and listen to it from Web3 but I keep getting a null response. Here's my code:

The relevant part of the contract:

event NewUser(string userid);

function createNewUser(string memory _userId) public {
    // creating the user and setting it to a mapping
    emit NewUser(_userId);
}

The Javascript, from Ethereum's reference:

async function watchEvents(contract) {
    contract.events.allEvents({
       fromBlock: 0
    },function(error, event){ console.log('all events?'); console.log(event); })
  .on('data', function(event){
     console.log(event); // same results as the optional callback above
  })
  .on('changed', function(event){
     // remove event from local database
  })
  .on('error', console.error);
}

Using another javascript function I can see that new users are being created, and the transactions are listed as successful on Ganache. But the watchEvents method keeps printing null.

What am I missing?


texts:
I have the following code:
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract Collectioning is ERC721 {
...
address ownerAddress = ownerOf(_tokenId);
address payable pSender = payable(msg.sender);
transferFrom(ownerAddress, pSender, _tokenId);
address payable ownerAddressPayable = _make_payable(ownerAddress);
ownerAddressPayable.transfer(itemCost);
if(msg.value > starCost) {
  pSender.transfer(msg.value - itemCost);
}

transferFrom includes also the approval by the owner, but I keep getting this:
ERC721: transfer caller is not owner nor approved.
I cannot debug to the console (don't know how), so the only clue I have is that the error comes from somwewhere in this block of code, triggered buy one of the transfers.


texts: Uniswap V2 smart contract integration reverts attempt at swapping ETH for tokens

texts:
I'm trying to integrate Uniswap V2 into my contract but my attempts at making a trade (ETH to Token) always gets reverted.

Here is my solidity code:

pragma solidity ^0.6.0;

// Included the interface found here: https://uniswap.org/docs/v2/smart-contracts/router/#interface
interface IUniswapV2Router01 {
...
}

contract MyContract {
  address internal constant UNISWAP_ROUTER_ADDRESS = 0xcDbE04934d89e97a24BCc07c3562DC8CF17d8167; // Rinkeby

  IUniswapV2Router01 public uniswapRouter;

  constructor() public {
    uniswapRouter = IUniswapV2Router01(UNISWAP_ROUTER_ADDRESS);
  }

  function swapEthForTokenWithUniswap(uint ethAmount, address tokenAddress) public onlyOwner {
    // Verify we have enough funds
    require(ethAmount <= address(this).balance, "Not enough Eth in contract to perform swap.");

    // Build arguments for uniswap router call
    address[] memory path = new address[](2);
    path[0] = uniswapRouter.WETH();
    path[1] = tokenAddress;

    // Make the call and give it 15 seconds
    // Set amountOutMin to 0 but no success with larger amounts either
    uniswapRouter.swapExactETHForTokens.value(ethAmount)(0, path, address(this), now + 15);
  }

  function depositEth() external payable {
    // Nothing to do
  }
}

Before calling swapEthForTokenWithUniswap I deposit 1 ETH by calling depositEth.
I'm testing this on Rinkeby with the BAT token (0xda5b056cfb861282b4b59d29c9b395bcc238d29b). Unfortunately I don't have much information in terms of logs (still new to Solidity dev so may not know where to look).

Here's a link to a failed transaction I tried making:
https://rinkeby.etherscan.io/tx/0x465b095ee53ceff57850f7f1d6a1c0256f7bfc948563907d189d6bc4f9ad64c2


texts: Accesing state variables in an other contract

texts:
I as trying to add methods in a contract, but it got so big that i couldn't deploy it with truffle. Now i need to create an otehr contract that will be called instead of the original contract to process data stored in the original contract as state variable.

The variable i am going to process is a mapping.

I am trying to do somehting like this :

contract Original {

mapping(bytes32 => Person) private Persons;

 /* many structs and methods here */
}

contract SecondContract {
   function processdata(){
     /* here i want to process the data stored in the mapping in the first contract */
   }
}

how do i get the link between the two contracts and be able to process that data ?