texts: loop to find the highest value in an array

texts:
I have made a struct which has an address called playersAddress and a uint called numbers.

I then have a fixed sized array which has in it the playersAddress and the numbers.

When someone calls the function pickWinner, the highest number in the numbers variable compared with the other numbers will transfer a certain amount of ether to the address in the playersAddress.

Also the numbers in the numbers variable are always changing value. I would like to know in this situation would the only way to find the highest number in an array would be to use a loop?  I have tried to write out a for loop in the pickWinner function, but it keeps coming up with an error.

function getPickWinner() public {

    var test = numbers;
    var largest = 0;
    var i;

    for (i = 0; i < test.length; i++) {
        if (test[i] > largest) {
            largest = test[i];
    }
}

The error comes up in the var i; part and it says assignment necessary for type detection.

I would like to know what this means and how I could fix it? At the moment I am not worrying about gas or anything I just want to experiment a bit first. If gas is a really big issue would it be possible in this scenario to do the loop offchain but keep everything else the way it is ? How could I possibly go about doing it offchain? thank you


texts:
Currently I'm trying to find a solution for this problem TypeError: Member "toTimestamp" is not available in contract DateTime outside of storage , and I decided to take another approach. I've inherited the DateTime contract and rewritten the method to be as follows:

function _incrementMonths(uint16 _months, uint _timestamp) internal returns (uint){
    uint16 year = getYear(_timestamp);
    uint16 month = getMonth(_timestamp);

    uint16 newMonth = month + _months;
    while(newMonth > 12){
        newMonth -= 12;
        year++;
    }

    // get new timestamp
    uint time = toTimestamp(
        year,
        newMonth,
        getDay(_timestamp),
        getHour(_timestamp),
        getMinute(_timestamp),
        getSecond(_timestamp)
    );
}

However now the compiler gives me this new error:

browser/Payroll.sol:326:21: TypeError: No matching declaration found after argument-dependent lookup.
        uint time = toTimestamp(
                    ^---------^

Again, the contract I'm referencing is found here: https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol . The method I'm calling is found here https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol#L165

I've been trying to debug this, but I don't see what is causing this error. What could be the cause?

Edit:

Please see the code in the IDE I've been working with https://ethereum.github.io/browser-solidity/#version=soljson-v0.4.17+commit.bdeb9e52.js&gist=03e5543f137d3ec464462cc190104de3


texts: Deploying contract with web3 returning all zeros transaction hash

texts:
I am running the following code in web3 the backend is a node running parity --testnet -j -w --jsonrpc-interface all.

My web3 code

  // data.contracts.TestContract is the results of
  // solc test-contract.sol --json-combine abi,asm, etc...
  var abi = data.contracts.TestContract.abi;
  var TestContract = eth.contract(JSON.parse(abi));
  var myTest = TestContract.new({
    data: "0x" + data.contracts.TestContract.bin, // binary data for contract
    gas: 300000,
    from: someAddressWithEther,
  }, function (err, myContract) {
    // from offical docs at https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethcontract
    if(!err) {
      // e.g. check tx hash on the first call (transaction send)
      if(!myContract.address) {
        console.info("transactionHash", myContract.transactionHash) // The hash of the transaction, which deploys the contract
        // check address on the second call (contract deployed)
      } else {
        console.info("theAddress", myContract.address) // the contract address
      }
    }
  }

The results

The console.info with the transaction hash returns

transactionHash 0x0000000000000000000000000000000000000000000000000000000000000000

Which doesn't seem like a valid transactionHash. The theAddress line never seems to run.

My questions

I am not sure why I would get the 0x0...0 hash? Is there some error in this code that i am not seeing? How long should i wait for the address?

Also wouldn't mind comment pointing to a full description, ideally with full source examples on how to properly deploy from the web3?


texts: How to know the current block reward in Ethereum

texts: How to know the block reward value for a Particular block . Like the block reward has decreased from 5 to 3 to 2 ether now. So if i an given a block number what is the formula to calculate the block reward


texts: When I use this web3.personal.importRawKey(pkey, passPhrase); Where does it store the private key I import? And How can I manually delete it?


texts: Send token only to non-zero ETH addresses

texts:
Pretty straight forward: is there any way for a contract to send tokens only to addresses with non-zero (or with a minimum required amount) ETH addresses?

I have this function to send tokens to multiple addresses:

function distributeToken(address[] addresses, uint256 _value) onlyOwner {
     for (uint i = 0; i < addresses.length; i++) {
         balances[owner] -= _value;
         balances[addresses[i]] += _value;
         Transfer(owner, addresses[i], _value);
     }
}

but I'm trying to add a require for non-zero balance. I changed it this way, so it should check if the receiver got at least 0.01 ETH:

function getEthBalance(address _addr, uint userBalance) constant returns(uint) {
return _addr.balance;
userBalance = _addr.balance;
}

function distributeToken(address[] addresses, uint256 _value, uint userBalance) onlyOwner {
 require(userBalance >= 10000000000000000);
     for (uint i = 0; i < addresses.length; i++) {
         balances[owner] -= _value;
         balances[addresses[i]] += _value;
         Transfer(owner, addresses[i], _value);
     }
}

but it doesn't work properly.
Sorry but I'm new to solidity and I'm still learning it. Thank you for you helping and patience.


texts: How to call nameless function from contract, say "fallback" function(){}

texts: I mean I am using myetherwallet and there I paste the ABI, yet the ABI has all functions described except the function (){}, so should I make up some name and just call it, would this ever work or? thanks!


texts: Can someone download and run a local version of my contract?

texts: Say I have a smart contract the preforms a specific function and is used in a decryption process off-chain. Would it be possible for Molly to download the entire contract and run it on their own local node, thereby brute-forcing the decryption element of the smart contract. She would do this as she is not limited by the slower block times of the public chain.


texts: Compile error with trivial assertion in Truffle test

texts:
Before I did anything serious I just wanted to check the toolchain is working. I wrote a test like this:

pragma solidity ^0.4.2;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";

contract TestMyContract {
  function testOneEqualsOne() {
    Assert.equal(1, 1, "The world as we know it has ended!");
  }
}

But it produces an error:

TestMyContract.sol:10:5: : Member "equal" not unique after argument-dependent lookup in type(library Assert)
    Assert.equal(1, 1, "The world as we know it has ended!");
    ^----------^

What's going on?

The sample test, which are created via truffle init all work perfectly:

uint expected = 10000;
Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");

And even with the arguments reversed:

Assert.equal(expected, meta.getBalance(tx.origin), "Owner should have 10000 MetaCoin initially");


texts: Aleth. Create unsigned transacion from json

texts:
I am trying to create unsigned transaction with aleth. I am trying to use ./rlp create command for this which accepts transaction in json format. Does anybody know this json format looks like?
What should I write if i want send 1 eth from address1 to address2? I mean which fields and order of fields are correct for aleth transaction?


texts:
One issue I've come across frequently lately is in functions which have several return types, for example:

function show() onlyOwner returns(string _name, uint _age) {
        return name;
        return age;
    }

Clearly there are two return parameters defined in the function and return is used twice. Yet I'm getting an error:

  Different number of arguments in return statement than in return declaration.

This has also happened in more complex return declarations with up to 10 separate statements, but both matched. What is the problem?


texts: Retrieve the return value from a non-constant function

texts:
Recently, I was reading a paper in which the writers stated that

"In the Ethereum smart contract, the return value of the nonconstant function can only be obtained through logs event."

However, I think that you can retrieve a value from a non-constant function by using myContract.func.call().
What is your opinion? Thanks!
(Btw, a similar question has been asked here; Truffle: 'func.call()' retrieves the return-value of a non-constant function but it is not answered).


texts: Is it possible to subscribe to the same event, but in multiple contracts at the same time?

texts:
Let's say we have 1000 contracts with the same type of event 'Event'. I can subscribe to each one of them individually using contract.listen('Event'), but I cannot use this if I want to create a single handshake that sends me every 'Event' happening in each of them. For that I would need to create 1000 contracts and then call .listen('Event') a 1000 times.
Is there a way to do something like w3.listen([contracts],'Event')? Or some feasible way to subscribe to so many contracts at the same time?
Thanks


texts: What is faster the main network or Ropsten?

texts:
Ropsten sometimes works VERY slowly.

What's about the main network? What is usually faster the main network or Ropsten?

I do not yet have Ether to try to deploy something on main network and I want to ask in advance.

I want to deploy a testing contract and make sure my web3.js code works with my contract in a right way.

Right now my Ethereum Wallet is stuck "Looking for peers..." (in Ropsten) and so far found zero peers. It is stalled on this stage about 40 minutes or so.


texts:
I am looking a way to create signed transaction using c++ libs from aleth. I have this transaction:
{
  from: "0025defd0f341b7f673f84b81c8416d58df29045",
  to: "0078fca08eacba4f0313e43366e6c3ecb21fb8eb",
  gasLimit: "21000",
  gasPrice: "200",
  nonce: "0",
  value: "10000000000",
}

As I understand i can sign it using 'aleth-key sign', but it requires hex representation of transaction. How can i get it? Can I use for this purposes sha3 and rpl? Which steps I have to do for getting hex representation?


texts: Why do wallets consistently underestimate gas for our smart contract?

texts:
We made a smart contract where you send it ETH, it checks the current price of ETH/USD using a chainlink oracle and then sends back our token at 12 cents a token until March 1, then 15 cents etc.
All people do is send ETH to the contract, and then the payable function gets triggered and executes all this other stuff. Somehow, the main wallets all consistently UNDERESTIMATE how much gas is supposed to be used. Does this have something to do with the fact that the person is sending ETH so they think there should be a ceiling to how expensive that transaction can be, versus a call to some method directly, even though the payable hook consumes quite a bit?
The largest gas cost honestly is checking the chainlink oracle. I am not sure why! Isn’t it just looking up a value?
Here is my main question ... can’t wallets see the whole blockchain and simulate the execution of the ENTIRE CALL, and sum up the current gas price it would take? Where are the unpredictable spots for them to underestimate the cost so wildly?
What can we do to fix it?


texts: How do i get to return value form one smart contract function into another smart contract on private ethereum network?

texts:
Here it is my called function.

pragma solidity ^0.4.19;

contract Called{

    string public name;

    function set(string _var) {
        name = _var;
    }

    function   get() view returns (string){
        return name;
    }

    function A () payable {

    }

}

Here it is my Caller function.

pragma solidity ^0.4.19;

interface Called{

    function set(string);

    function get() view returns (string);
}

contract Caller {

    string public new_name;

    Called public called_address;

    function set_address(address _addy) {
        called_address = Called(_addy);
    }

    function caller_set(string _var) {

        called_address.set(_var);
    }
    function caller_get() {
        new_name= called_address.get();

    }

    function B () payable {

    }

}

Here is my genesis file

{
  "config": {
        "chainId": 8888,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0xffffffffffffffff",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

I am here interacting with called contract using caller contract. It works fine with  in remix browser(without connected to ethereum network). When i connect remix browser to my private ethereum network caller_set function of caller contract works fine but when i called caller_get function it gives the error "gas required exceeds allowance or always failing transaction". I have given more and more gas but it always failed. somebody please help.


texts: I want to build stablecoin for my college project. I am thinking of developing ERC20 token pegged with fiat currency. Can someone please suggest me best tutorials/guides to build stablecoin on ERC20?


texts: How to properly test bytes32 in Javascript testing

texts:
How do i address the bytes32 testing issue below?  From the code below:

coinState = await NewCoin.at(newCoinAddress).getAuthorization(web3.fromAscii("1A2B3C4D5E6F7G8H9I0J"));
console.log(coinState);
console.log("A+" + web3.toAscii(coinState[1]).toString().trim() + "+");
console.log("B+" + "1A2B3C4D5E6F7G8H9I0J" + "+");
console.log("C+" + coinState[1] + "+");
console.log("D+" + web3.fromAscii("1A2B3C4D5E6F7G8H9I0J") + "+");
assert.equal(web3.toAscii(coinState[1]).trim(), "1A2B3C4D5E6F7G8H9I0J", "authGUID not correct.")

generates the output:


texts: Is there an API that can find all the ERC20 token icons?

texts: I'm trying to find icons for all ERC20 tokens, does any API provide that information ?.


texts: Can we not allow to read/write contract from ethereum explorer?

texts:
Is there any way to not allow reading and writing contract from ethereum blockchain explorer?
One can view contract code, ABI, and every other information once the owner verifies contracts. Is this correct or not?


texts:
In 2016 I did exactly the sentence below. Not ETH account was ever sent to me. Now I have almost 10 ETH sitting on the DAO that I can’t access. I tried customer support for both ShapeShift and myethwallet:

“If you don’t already have an ETH account, you can have daohub.org
create you one right on the website, select the ShapeShift option,
choose that you don’t have an account and it will generate you one on
the fly using myetherwallet. Then you can insert that account address
and and use the shifty button popup to send to the DAO!”

I can see ShapeShift taking in my BTC from my Circle Wallet but then they withdraw to some ETH account that then took the DAO token. See below is my transaction.
Order Summary:

Order Number: 35dc095a7b
You Deposited: 0.3 BTC
You Received: 9.64040070 ETH
The exchange took 16 seconds
Deposit Address: 1BjnVzWLqC4hq5ph9CkCnkHWVEnwVs9AyN
Withdraw Address: 0x0e257ca1ff6457c5c3d39a27f0adeb1fbb1b9350
Transaction Hash: 0x620ff746ac662dfefcb116ae1a64f3b36fb6a709e4fd95bbd7a3548c4da1e0b1

I NEVER RECEIVED ANY INFORMATION OTHER THEN THIS. My money is in the DAO now. I see it on the 0x0e257ca1ff6457c5c3d39a27f0adeb1fbb1b9350 address but I have no idea what the username and password for the Ethernet wallet they created!
Please help.


texts:
I have setup my Geth node and started it with 200.000 maximum pending tx and 5000 max queued tx.
Now it reached 190k pending Tx although other nodes are showing a total of 150k (etherscan) or 155k (Infura). SOmetimes the Geth node is deleting some of the pending Tx but I do belive I am over 40k pending tx up when comparing with other full nodes.
How can I solve this for my node to reflect the actual pending tx?

txpool.status
{
pending: 190364,
queued: 499
}


texts: Kovan contract creation gas limit behavior

texts:
I have a fairly large contract that I must create on Kovan network for testing. There is fairly weird behavior occurring when I am trying to create the said contract.

Behavior being: whenever transaction consumed limit goes over 6`000`000 gas the transaction fails with out of gas error (in spite of 10`000`000 gas limit specified (which was the block gas limit).

Now my contact theoretical size is around 6.8-7 million limit when created.

Here is some sample transactions:
This one succeeded when I stripped away some functions from the code (unrelated to initialization):
https://kovan.etherscan.io/tx/0x0d903408120c352876879d833ecfec01f7f4b8b3a17967b6f4920b4d30c9253b

This one fails (raw transaction size 58`236/2 bytes), meaning around 5.8236 million limit + some EVM specified gas costs (contract creation etc.) Which in result goes over 6 millions:
https://kovan.etherscan.io/tx/0xc8a1a2d4c3c010801cd769b0325c4bf1c8dcb2bc47f76505f91dface7cb62050

Questions:

As you can see in both cases here where plenty of room left in the block for new transaction, is there some sort of limit that I am not
aware of?
Any tips on how to solve this issue?
Is this behavior chain/node specific?

Haven't actually tested this on any other chains.

I know that this is a large contract by all standards, but splitting it into more subcontracts would increase the operational cost for each transaction + increase logical complexity (ensuring only allowed actors are accessing specific public methods). On top of that it already is one part of a series of interconnected contracts.


texts: How to Query the state of a smart contract using web3j in Android?

texts:
I found this documentationQuerying the state of a smart contract.
but i can't get resault,this is my code.

                Web3j web3j = Web3jFactory.build(new HttpService(url));
                List<Type> inputParameters = new ArrayList<>();
                List<TypeReference<?>> outputParameters = new ArrayList<>();
                Function function = new Function("getManufacturer",
                        inputParameters,
                        outputParameters);
                String functionEncoder = FunctionEncoder.encode(function);
                EthCall response = web3j.ethCall(
                        Transaction.createEthCallTransaction(contractAddress,
                        DefaultBlockParameterName.LATEST
                ).sendAsync().get();
                List<Type> someType = FunctionReturnDecoder.decode(response.getValue(),function.getOutputParameters());
                Iterator<Type> it = someType.iterator();
                Type resault = someType.get(0);
                String a = resault.toString();
                Log.d("MainActitity", a + "111");

someone know how to fix it.:)


texts:
I want to implement some features as precompiled contracts in Ethereum. I read some articles and the contract code, but I still don't know how to do this.

Is there's a tutorial from scratch?


texts: I had been using the npm package solidity-coverage and while reading the coverage reports I came up with this E symbol. I am not sure what it means and there is no explanation in the documentation as well. Does anyone know what this means?


texts:
I'm newbie in the blockchain and ethereum technologies.

I have an account created in Ethereum Wallet inside the Test-NET network, my problem is the syncronitzaction with the peers.

In my personal computer work fine with my house network connection, but in other connection doesn't work fine some days works and connect and syncronise and others doesn't works, with other's computers doesn't connect just work with my personal computer, where is the problem with this network?

I've tried this:

Open the ports.
Change the antivirus and firewall of the computers.
Test on the networks.
Uninstall and install again the program.
I tried the same with Mist.

PD: In the others computers just work well the main network of Ethereum and the Test-NEt doesn't work.


texts: Can we assume that Ethereum Events (aka Logs) are in-sequence

texts:
Lets consider a simple Contract that is to track a variable. A client App needs to access this variable's history to show a graph.

I can create an Array inside the Contract, and push() the value anytime, like the following (untested code):

contract Price {
    uint[] public priceHistory;
    function logPrice(uint price) public {
        priceHistory.push(price);
    }
}

Perhaps a cheaper and better option is to emit Events, similar to the following:

contract Price {
    event PriceChanged(uint price);
    function logPrice(uint price) public {
       emit PriceChanged(price);
    }
}

As per (3) a cheaper form of storage, the second approach is low cost. My question is, can we assume, reliably, that the logs will be written in time order (so that we can reconstruct a history from them).

The next question is, if this Contract calls other Contracts, which follow the same design pattern (all storage is in logs), how can we weave together a history with proper time-ordering? ie, establishing ClientApp -> ContractA - ContractB -> ContractC from reading Event logs for all the three Contracts.

One thought could be to pass-on transaction-hash from the first user -> contract call, and pass it all the way to subsequent contract -> contract calls.

If this were a monolithic system, timestamp could have helped. But since its a distributed system, I wonder how do we establish the notion of a sequence here?


texts:
In here it's said we need to run below command line to let Metamask connect to geth:

 geth --rpc --rpccorsdomain="chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn"

I'm running a private blockchain and when I run the above command line it tries to synchronise and it takes a very long time. It looks like it is connecting to a real blockchain network which I don't need right now.

Obviously, I need Metamask, as I want to write my own user interface that can interact with my private blockchain (or smart contract).

Question: Do I need to run the above (or any other) command line to let Metamask connect to geth when I'm using a private blockchain?


texts: I transferred eth to my parity account and then to my parity wallet. I accidentally erased the account, and it also erased my wallet. I got them back, but now my wallet is stuck in my addressbook. I can't make any transfers out, but I can transfer eth into the wallet. I've tried to add my wallet to the account tab, and it shows that it accepts it...but still doesn't show up on my accounts page. Any help would be appreciated!


texts:
Two of the functions of web3
 -  web3.eth.accounts.wallet.load
 -  web3.eth.accounts.wallet.save

Mentioned in the Doc of web3, these are browser only functions. Already tried to test these function by using IPC as well as RPC calls but both failed saying "load is not a function/save is not a function"
How and where i can run these functions to check their functionality and what does "browser only" means?


texts: How to determine whether block is orphaned?

texts:
I've been working on a high stakes contract, which is deployed using the web3 v1.0 library. An important condition for robustness is ensuring the contract has been confirmed 12 blocks prior (at the very least).

This is easily done with the new confirmation 'PromiEvent' convenience feature, but a lingering question remains. What happens if the chain my contract is on gets abandoned? How does one check that (with web3 v1)? I doubt the confirmation event itself changes any data in the receipt. Does it stop firing perhaps? Here's some sample code:

        newContract = await BigContractParent
              .deploy({ data: BigContractCompiled, arguments: [100, accounts[0], accounts[1]] })
              .send({ from: accounts[0], gas: '2000000', value: web3.utils.toWei(JSON.stringify(req.body.val), "ether") })
              .on('transactionHash', function (transactionHash) { console.log("Txn hash is: " + transactionHash) })
              .on('receipt', function (receipt) {
                console.log(receipt);
                console.log("Contract mined! Address: " + receipt.contractAddress + "  Contract blocknumber: " + receipt.blockNumber)
              })
              .on('confirmation', function (confirmationNumber, receipt) {
              if (confirmationNumber > 12)
                 console.log("Congratulations! You are safe! ", confirmationNumber, receipt) });

        //send response with newContract, wait for 12th confirmation...


texts: Say I have deposited to the y-pool at curve.fi and staked the corresponding crv tokens at the gauge. Is it possible to transfer that "loan" to another wallet without unstaking?


texts: Is it possible to create a trigger when a state variable contract is i.e. 10?

texts:
Let's supose this is my contract:

Contract MyContract{
   uint a = 0;

   function myFunction(){
      a = 0;
   }
}

I want "myFunction" to fire up when "a" value is 10. Thanks.


texts: Can Ethereum blockchain and Bitcoin blockchain integrate with each other thus creating some sort of intermesh of networks?

texts:
Can Ethereum blockchain and Bitcoin blockchain integrate/interoperate with each other thus creating some sort of intermesh of blockchain networks thus increasing reliability? (Chain of Chains, Blockchains of Blockchains, etc).

If the answer is yes, what is the best way to integrate/intermesh both blockchains together? Atomic APIs?

Blockchain 1.0 - Bitcoin
Blockchain 2.0 - Smart Contracts
Blockchain 3.0 - DApps
Blockchain 4.0 - Chains of Chains? Blockchains of Blockchains?


texts: IP address and system details of msg.sender

texts: Is it possible to log the IP address and various system details (meta data etc.) about a msg.sender who is sending a transaction to your smart contract?


texts:
I am quite new to flash loan and I don't fully understand it. I've been reading on flash loan attacks lately and notice often times it involves a huge dump on Uniswap to skew the price of a coin. I am wondering if I can take out a flash loan, say 10000 ETH from AAVE, and dump all that in Uniwap to exchange BTC. Is this going to increase the price of BTC for a short time (a few seconds)? If yes, then what I can do is I immediately sell some of my own BTC on Uniswap after I skewed the price of BTC with the flash loan and buy it back when the price corrects itself. I don't even need to pay back the flash loan since all I need is to skew the price for a short moment (a few seconds) and do arbitrage with my own holdings. Pretty sure I'm missing something here but I don't know which part is wrong.
My second part of the question is say during a flash loan attack I manipulated a price of some coin. If a user queries the price of that coin in the middle of my flash loan attack, is that user seeing the manipulated price or the normal price?


texts:
Mist (0.7.2) freezes on Linux Ubuntu 15.10

Mist (0.7.2) freezes and just displays a white rectangular box especially when I stop it and restart it. This is white screen before the Mist browser even launches. Initially I could see the downloading blockchain splash screen so it might not be related to a video or graphics issue. Not sure.

Even if I kill the processes and restart Mist it remains frozen.

If I log out of Ubuntu and back in the problem remains.

The only thing that seems to fix it is restarting the computer.

Any advice?


texts:
I have very basic contract like this:

pragma solidity ^0.4.15;

contract Test {
    function() public payable {
    }

    function pay(uint _amount) public returns (uint) {
        require(this.balance >= _amount);
        msg.sender.transfer(_amount);
    }
}

Once started on Remix with JavascriptVM it works as expected - payable function receives ethers and pay pay it to any address. But when I connect Remix to the locally running testrpc or to Rinkeby network this contract fails on line with transfer call with error transact to Test.pay errored: VM Exception while processing transaction: out of gas.

I tried to replace transfer with send without any luck.

Of course I and trying to pay less then current contract balance (sent 10 ETH, trying to pay out 5 ETH).

UPD:

It is damn strange, but almost same contract works:

contract Test {

    event Event(string _msg, address _address, uint _amount);

    function() public payable {
    }

    function pay(uint _amount) public returns (uint256) {
        require(this.balance >= _amount);

        _pay(msg.sender, _amount);
    }

    function _pay(address _to, uint _amount) private {
        _to.transfer(_amount);
        Event("Outcome", _to, _amount);
    }
}

BUT! If I remove mentions of Event - it stops works with the same error!

UPD2: It becomess stranger and stranger. If in contract that works I remove returns (uint256) it stop working too. I am totally confues - why return value affects contract work? Why separated logic works and merged into one function - no?


texts: Can't deploy ConsenSys MultiSig wallet using Mist

texts:
I'm trying to deploy the MultiSig wallet provided by ConsenSys here using Mist 0.8.10.

No matter how much I'm willing to pay in fees, it doesn't work. The contract compiles fine but when I press deploy I can see the following warnings:

It seems this transaction will fail. If you submit it, it may consume
all the gas you provide.
The contract won't allow this transaction to be executed

If I click 'Send transaction' it fails every time with 'intrinsic gas too low'.

Obviously, I'm doing something wrong, though Mist is terribly bad at communicating what.

How can I find out what the problem is?


texts: web3.eth.getCode doesn't return the data shown on etherscan

texts:
For example, let's take contract address 0xdac17f958d2ee523a2206206994597c13d831ec7.

Does anybody have an idea why the following two are totally different:

The string returned from await web3.eth.getCode(0xdac17f958d2ee523a2206206994597c13d831ec7)
The string under Contract Creation Code at
https://etherscan.io/address/0xdac17f958d2ee523a2206206994597c13d831ec7#code

I am using Web3.js v1.2.1.

Thank you!


texts: What's wrong with generating private keys in this way?

texts:
Mostly out of curiosity, but if you wanted to generate your own ethereum private/public key pair, and NOTE use anyone else's code, is there anything that's wrong with doing it like this:

const validChars = ["a", "b", "c", "d", "e", "f", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let key = ""

for (var i = 0; i < 64; i++) {
    let rand = validChars[Math.floor(Math.random() * validChars.length)];
    key += rand
}

//key is now a random string of 64 valid ETH characters
console.log(key)


texts: Search blockchain without having own node running?

texts:
I have a simple python program that I can run to get all the tx's from a block using the web3api.  This requires me to run geth and have my node running/listening.

I understand there websites out there that offer API access but they are typically limited.

My question is if I can search through the blocks/data that have already been downloaded to my machine without having to have geth running.


texts: JVM waits for some timeout every time when I load a Smart Contract using Web3j In Java

texts:
Initially I had a problem with the Web3j object, but after explicitly calling its shutdown method everything works fine (JVM quits immediately, so my application closes). The problem occurs when I call load(...) method of any Smart Contract. For some reason, if I quit the application, JVM hangs for 40-50 seconds until it quits. This is the thread dump:

Here is the code used to load the contract:


texts:
As the Ethereum platform relies on the Keccak256 hash algorithm, I'd like to get a better understanding of it.
My rough understanding is something like this:

a function accepting a finite set of bits into a giant imaginary rubik's cube which is then shunted about in a specific way. A subset of 256 bits are then returned. The function has the property that a change to a single input bit causes the output to change in an unpredictable way.

Is the above approximately true? You might see where I got the rubik's cube idea from if you look at Figure 1 here (I think this is the right spec).
There's also this, which I've read through, but it has not really soaked in.
How does the Keccak256 hash function work?


texts: How to get values returned by non constant transaction functions?

texts: As per my understanding when I invoke a constant function without a transaction in a contract and if the function returns some result I am able to get it in EthereumJ or Go-Ethereum, But when a transaction is performed on a function it is returning a hex value. Please suggest how to get a return value from a function on which a transaction has been performed.


texts:
What is the default license for solidity code released to the blockchain?
Is there such a thing?

I'm just wondering because i thought the idea of smart contracts is to release the source code, so people can make informed decisions whether to use said contract or not.
Even if the source code is not revealed, it seems to me that it is in the best interest of a lot of people to try and decompile it.
One way or another most smart contract's code will be available somewhere somehow and now the question: what license applies to this code?


texts:
in my contract I need to do some calculations to convert some ERC20 tokens value to WEI and I need to do something like:

tokenValueWei(uint) = tokenValue(uint) * multiplier(ufixed)

eg. 100000012 (some token fractions) * 0.0013233 (multiplier) = 132330 (WEI rounded)

while the multiplier is being supplied to the contract by the contract manager.
Any way to achieve this?


texts: Private ethereum network geth admin.addPeer not working

texts:
I am trying to make a private ethereum network the only problem I am facing now is when I make multiple nodes on same pc they discover each other but when I tried to connect other pc on different network that pc was not able to connect to mine and it keep on logging "Looking for peers peercount=0"
I have tried
1:- Generating boot.key from bootnode and also passed my ip and port correctly in enode string
2:- adding the other pc enode string from admin.addPeer with the correct ip and port of that pc
I have tried all the solution listed on google but nothing seems to work, Iam only able to make nodes locally and connect them but with other pc on different network nodes are not connecting to each other
I have used the external Ip that we get from the google by typing "what is my ip"
Please Help!!


texts: Blockchain.info Wallet Restoration Using Xprv Key

texts:
I have a partial backup of my wallet.json from blockchain.info - it contains my xprv key, which gives me my Bitcoin wallet fine
However,
When I try and restore my Ethereum addresses from this key using hd-wallet-derive (https://github.com/dan-da/hd-wallet-derive), it gives the incorrect addresses. The path I'm using is m/44'/60'/0'/0
Is anyone familiar with how Blockchain.com derives Ethereum wallets from the xprv key?


texts: Calling schemas of various mobile wallets on iOS and Android

texts:
I realize that I can call web3 methods and browser extensions like MetaMask will leap into action, allowing me to set up any kind of transaction
The question, can I do this on iOS and Android, with wallet apps? I know that WalletConnect allows doing things like adding a token, and sending some ETH somewhere. But can I set up more complex transactions - perhaps arbitrarily complex - similar to the linked API? My app or website would set the gas price, then it switches to the wallet app, and the user can sign the transaction in the wallet and post it to the blockchain?
What I really want is a list of schemas and URLs for handleOpenURL of these wallet apps. Is there something standard? The closest I can think of is possibly giving them a url querystring parameter, to open a dapp with buttons that can then use web3. But maybe it can be done with one click?


texts:
So I've made a simple tx to transfer. And it has been broadcasted.

But I did not calculate the gas price properly so the tx is in still pending status.

That seems takes long time.

What if I make same tx and same nonce with more high enough gas price.

Will it rewrite or revert the previous pending TX?
Will the mempool revert my previous tx...


texts: How to create a secure, production ready private chain?

texts:
I'm looking for more information or resources on how to run a private chain with ethereum with multiple nodes that would work in production and would only be accessible to my users/network.

I know all about the dev private network but as stated it's "for testing purposes only".

The question is somewhat vague but important as i have no clue what would be needed and would require many different questions ( how many nodes?miners?hardware?software? security ? ).

Any help is appreciated.


texts: Im experimenting with the erc20 token. When trying to write contract on etherscan the Web3 connection just don't work, and I don't know why. But then I thought that perhaps Ethersweep could do something similar and hopefully good also, but no, that site is promising something Awesome! That is a good thing of course but is there any similar service or site that offers some sort or Erc20 swapping also?


texts: When and if ETH converts to PoS who will receive the staking rewards?

texts: For ETH stored on online exchanges will the exchanges receive all staking rewards or will they be passed along to their users that actually own the ETH?


texts: Theoretically, how fast can a Proof-of-Authority chain process transactions?

texts: How fast can Proof-of-Authority chains like Kovan process transactions? What's the upper bound?


texts: Pending transactions from Nano X Ledger Live

texts: I have three pending transactions (I think) - only 1 is showing up on Latest Operations on my Nano X Ledger Live - the most recent one.  It's been four days.  I don't think I have the skills to pursue cancel or replace on myetherwallet.  When I go to Etherscan, they don't show up as Pending for some reason - my last transaction listed is months ago - confirmed.  Should I just keep waiting?  If so, for how long?  Will they at least FAIL or be REJECTED?  I'm afraid they will stay this way forever, then what?  Then I won't ever be able to transfer my crypto from Ledger Live, correct?  Thanks in advance for your help. Tom


texts:
I don't understand what should input into bid() function. Whatever I do, it shows the same error:
"Error encoding arguments: Error: invalid arrayify value (argument="value", value="1 true secret", code=INVALID_ARGUMENT, version=bytes/5.0.5)
"

What am I missing?
Below is the code for the bid() function.
function bid(bytes32 _blindedBid)
        public
        payable
        onlyBefore(biddingEnd)
    {
        bids[msg.sender].push(Bid({
            blindedBid: _blindedBid,
            deposit: msg.value
        }));
    }


texts: Can't even create a smart contract: Sender doesn't have enough funds to send tx

texts:
I wrote and deployed a basic smart contract on Remix Javascript VM Environment. It worked fine.

Then I installed and started TestRPC (now ganachi-cli). Then, upon changing the environment to Web3 Provider the Account box got emptied, so I had to create a new account by clicking on the plus sign next to Account. Then I tried to deploy the contract again and I got the following error:

  Error: sender doesn't have enough funds to send tx. The upfront cost
  is: 278786 and the sender's account only has: 0

I've been looking in several blogs (like this one) for a workaround either by decreasing the cost of the creation of the contract to zero or increasing the sender's account balance, but I can't find any solution. I'm stuck, please help me.


texts: When uploading an ERC20 token for an ICO, how does one program the ICO token sale? Is it done in the same contract? It seems to be judging by existing sales that you send ether to a contract address, but what function does this trigger?


texts: Why is the Eternal Storage approach still used if it hugely increases gas usage compared to storing data in structs?

texts:
I was wondering why is the eternal storage approach (first code snippet) still used? I know it's meant to make contracts upgradable but it seems too expensive to me.

contract Storage {

   mapping(bytes32 => uint256)    private uIntStorage;
   mapping(bytes32 => string)     private stringStorage;
   mapping(bytes32 => address)    private addressStorage;
   mapping(bytes32 => bytes)      private bytesStorage;
   mapping(bytes32 => bool)       private boolStorage;
   mapping(bytes32 => int256)     private intStorage;

   function getAddress(bytes32 _key) public view returns (address) {
       return addressStorage[_key];
   }

   function getUint(bytes32 _key) public view returns (uint) {
       return uIntStorage[_key];
   }

   function getString(bytes32 _key) public view returns (string) {
       return stringStorage[_key];
   }

   function getBytes(bytes32 _key) public view returns (bytes) {
       return bytesStorage[_key];
   }

   function getBool(bytes32 _key) public view returns (bool) {
       return boolStorage[_key];
   }

   function getInt(bytes32 _key) public view returns (int) {
       return intStorage[_key];
   }

   function setAddress(bytes32 _key, address _value) public {
       addressStorage[_key] = _value;
   }

   function setUint(bytes32 _key, uint _value) public {
       uIntStorage[_key] = _value;
   }

   function setString(bytes32 _key, string _value) public {
       stringStorage[_key] = _value;
   }

   function setBytes(bytes32 _key, bytes _value) public {
       bytesStorage[_key] = _value;
   }

   function setBool(bytes32 _key, bool _value) public {
       boolStorage[_key] = _value;
   }

   function setInt(bytes32 _key, int _value) public {
       intStorage[_key] = _value;
   }
 }

Consider this struct.

 struct Test {
   address user;
   uint96 amount;
   uint48 timestamp;
   uint48 expiry;
 }

Saving one struct element to a mapping would need 3 storage slots:
1 for the mapping key
1 for user and amount
1 for timestamp and expiry

Now consider saving the same struct in the eternal storage shown before.
We would need 4 slots for the mapping keys and 4 slots for the actual values.

So 3 slots vs 8 slots.

Keeping in mind the a SSTORE operations costs 20000 gas, the struct method costs 60k gas vs 160k gas of the eternal storage.

Supposing my calculations are correct, this seems too much of a difference to me, especially from a customer perspective. So why is this method still used?

EDIT: As Jesse clarified below, mapping keys do not cost any SSTORE operation. Even deleting them from the calculation, we would still have double costs for the eternal storage, 4 slots, compared to the struct, 2 slots. The difference would be even bigger for more complex structs.


texts: What is the point of Zeppelin's SafeMath.sol?

texts:
I see many ICOs using SafeMath.sol. An example function in this contract is:

function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
  uint256 z = x + y;
  assert((z >= x) && (z >= y));
  return z;
}

What is the reason for this function at all? Why not just add the two values? What additional functionality does this safeAdd function provide?

http://zeppelin-solidity.readthedocs.io/en/latest/safemath.html


texts:
Need your help/suggestion for below question
Question: Smart contract size limit
My application size for Smart (contracts folder with .sol file) is around 140 KB
It is structured as below, with each module folders will have their specific .sol file
e.g., Module 1 till Module 5
Module 1 (Folder): below is the content inside
interfaces1.sol - 2 KB
implementation1.sol - 26 KB
library1.sol - 4 KB
proxy1.sol - 1 KB
Module 2 (Folder): below is the content inside
interfaces2.sol - 3 KB
implementation2.sol - 28 KB
library2.sol - 5 KB
proxy2.sol - 1 KB
When I will compile & deploy the Smart Contract of whole application
which is spread across folders i.e., Module 1 till Module 5
How the Smart Contract size will be calculated

It is calculated for .sol file or the generated bytecode file?
It is calculated per/individual each .sol file (e.g., implementation1.sol) spread across folders or?
It is calculated the overall size i.e., Module 1 till Module 5?
What is the Smart Contract size limit for deploying to Main network
What is the Smart Contract size limit for deploying to Test network (Kovan, Rinkeby, Ropsten)
What will happen if I go ahead with existing size of 140 KB and deploy the Smart Contract to Test network, Main Network, will it allow?
Any solution to solve/reduce the current Smart Contract size (e.g., splitting implementation1.sol & implementation2.sol to multiple .sol file)?
If I split single (implementation2.sol) file to multiple (implementation2_1.sol & implementation2_2.sol) file, and some state variables & mapping I declare in implementation2_1.sol file, how can I access/use them in implementation2_2.sol file, what will happen to storage in this case ?

Your quick response will really help as I am stuck with this problem & need to resolve it soon
Thanks in advance


texts: Is it possible to get info via JSON RPC about --no-ancient-blocks flag for an openethereum node?

texts:
It's possible to run an openethereum node with --no-ancient-blocks flag.
How can I check that a node was started with this flag via JSON RPC call?


texts: Using Web3j to load a smart contract, how do i specify my credentials?

texts:
I am using the Web3j library to generate a Java wrapper for my solidity contract, i have already deployed the contract to the blockchain and it has been mined, i now want to load the contract in java using the java wrapper.

The java wrapper is SimpleStorage, Web3j has generated the following method signatures for loading the contract;

    public static SimpleStorage load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

public static SimpleStorage load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

How do i supply the Credentials object? I have the public key, private key and address of the node from which i deployed the contract on the blockchain but the Credentials object takes a ECKeyPair which expects the Private Key and Public Key to be a BigInteger however my keys are just an arbitrary string of characters.

Is there something i am missing?

To be a little more clear i have the following;

String publicKey
String privateKey
String address

and i want

Credentials creds

to pass in to the load method but Credentials only takes

    public static Credentials create(String privateKey, String publicKey) {
    return create(new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey)));
}

Where this is failing for my public and private keys because they can't be converted to BigInt


texts: Ethereum mining but not receiving rewards

texts:
I have been mining using NiceHash for a while now and decided I want to mine ethereum into my own wallet so I dont need to wait for the payout threshold. I copied the claymore miner out of nicehash 3rdparty folder. I then enetered my own settings into the start.bat file

EthDcrMiner64.exe -epool eth-eu.dwarfpool.com:8008 -ewal 0xcC261261d920ad5aa37CDFDeDBE4B076D22cA2c1 -epsw x

I launch it and it appears to work fine. I left it on for 12 hours to check my wallet which I created on MyEtherWallet.com to see that I had no balance.

Am I doing something wrong? Any suggestions are appreciated.


texts: How to store each new transaction in multiple/different blocks

texts: How can I connect to Ganache so each time I add to the blockchain the transaction is stored in the next block. I have an issue that each time I add to the blockchain it gets added to the same block address. I am using React to add the date to the blockchain. However, I have init web3 with ABI and Address(which all the transactions are stored in).


texts: Error while testing a smart contract functionality with Mocha

texts:
I wanted to test my code functionality with the Mocha Framework, but every time it responded me with an error, not an assertion.
The specific error was:

Error:cannot find module "ganache-cli"
require stack:...

This is my contract.test.js:
const assert = require("assert");
const ganache = require("ganache-cli");
const Web3 = require("web3");
const web3 = new Web3(provider());

const { interface, bytecode } = require("../compile");

let lottery;
let accounts;

beforeEach(async () => {
  accounts = await web3.eth.getAccounts();

  lottery = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({ data: bytecode })
    .send({ from: accounts[0], gas: "1000000" })
});

describe("Lottery contract", () => {
  it("deploys a contrcat", () => {
    assert.ok(lottery.options.address);
  })
})


texts: Error trying to synchronize geth clique client after shutdown

texts:
I'm working with a private network using geth clique clients. Each time a node shut downs, (after a power cut, or just killing the geth process), if a try to put it to work again, the node can't synchronize, shooting a runtime error:

ERROR[02-01|17:31:27.234] Impossible reorg, please file an issue   oldnum=11495 oldhash=415d9b…c9aa7c newnum=11495 newhash=415d9b…c9aa7c
TRACE[02-01|17:31:27.236] Findnode failed                          id=b1a7659b8a9da1db failcount=1280  err="RPC timeout"
...
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x51163e]

goroutine 305 [running]:
math/big.(*Int).Cmp(0xc44e55ff40, 0x0, 0xbe6c1acfbb42a6ab)
    /usr/lib/go-1.10/src/math/big/int.go:319 +0x2e
github.com/ethereum/go-ethereum/core.(*BlockChain).insertSidechain(0xc430d16000, 0xc44fdef650, 0xc420069400, 0xc420069401, 0x1, 0x1, 0xc44fb119cf, 0x1, 0x1, 0xc44d001320, ...)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/core/blockchain.go:1333 +0x1165
github.com/ethereum/go-ethereum/core.(*BlockChain).insertChain(0xc430d16000, 0xc44ebebd50, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/core/blockchain.go:1139 +0x2ee3
github.com/ethereum/go-ethereum/core.(*BlockChain).InsertChain(0xc430d16000, 0xc44ebebd50, 0x1, 0x1, 0x0, 0x0, 0x0)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/core/blockchain.go:1088 +0xc46
github.com/ethereum/go-ethereum/eth/downloader.(*Downloader).importBlockResults(0xc4200a2ea0, 0xc44ebebd48, 0x1, 0x1, 0x1, 0x19)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/eth/downloader/downloader.go:1490 +0x434
github.com/ethereum/go-ethereum/eth/downloader.(*Downloader).processFullSyncContent(0xc4200a2ea0, 0x0, 0xc431a27f98)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/eth/downloader/downloader.go:1464 +0x79
github.com/ethereum/go-ethereum/eth/downloader.(*Downloader).(github.com/ethereum/go-ethereum/eth/downloader.processFullSyncContent)-fm(0xc400000008, 0x1013570)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/eth/downloader/downloader.go:479 +0x2a
github.com/ethereum/go-ethereum/eth/downloader.(*Downloader).spawnSync.func1(0xc4200a2ea0, 0xc44f7e6900, 0xc44f5c8280)
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/eth/downloader/downloader.go:491 +0x59
created by github.com/ethereum/go-ethereum/eth/downloader.(*Downloader).spawnSync
    /build/ethereum-BgsY40/ethereum-1.8.21+bionic/build/_workspace/src/github.com/ethereum/go-ethereum/eth/downloader/downloader.go:491 +0xaf

the only way I found for the node to keep running is to delete the database and have it downloaded again, which obviously is not the best option.

Anyone having the same problem? How do you deal with this?


texts: Solidity compilation issue on Linux Mint

texts:
I have a smart contract which I am invoking through webjs. Everything works well untill I am on Windows.
Recently i had to move to Linux Mint. Now when i compile the contract. I get stdin in the compiled code.
Becuase of this, I am not able to access the value of code.
I verified the issue by running a simple smart contract on the command line, as follows-

>eth.getCompilers()
["Solidity"]
> var testSource='contract Test {  function double(int a) constant returns(int) { return 2*a; } }';
undefined
> var testCompiled = web3.eth.compile.solidity(testSource);
undefined
> testCompiled
{
  <stdin>:Test: {
    code: "0x60606040523415600b57fe5b5b60788061001a6000396000f300606060405263ffffffff60e060020a6000350416636ffa1caa81146020575bfe5b3415602757fe5b60306004356042565b60408051918252519081900360200190f35b600281025b9190505600a165627a7a72305820bf2f987fd5895006a3af08154264d6de5a6d35b25eb3f85572f8264ab26db1b70029",
    info: {
      abiDefinition: [{...}],
      compilerOptions: "--combined-json bin,abi,userdoc,devdoc --add-std --optimize",
      compilerVersion: "0.4.9",
      developerDoc: {
        methods: {}
      },
      language: "Solidity",
      languageVersion: "0.4.9",
      source: "contract Test {  function double(int a) constant returns(int) { return 2*a; } }",
      userDoc: {
        methods: {}
      }
    }
  }
}

Note I have tried compiling this with both with stable solc version for Linux and latest dev version of Solc with same results.


texts: During deploying contract in go ethereum how other contract gets to know where other one is when they are inherited?

texts: when we deploy two contracts in go ethereum and one is inherited by the other ,when we deploy contracts differently how other contracts gets to know where the other contract is and it is able to access the functions of the parent contract ?


texts: How can I invoke an approve() function call from the user and not the contract?

texts: I am working on a basic staking platform for practice. I understand that the user of the platform has to call the approve() function and pass the contract into it in order for the contract to use the transferFrom(). However, as a beginner I don't know how to call that function from the perspective of the "user," in this case, my test accounts. How can I increase the allowance of a token that is already on the network?


texts: How do I verify a contract that has imports on etherscan?

texts:
There is an answer from 2017 here saying that it's not possible but it's been 3 years since then so hopefully there is progress.
My Vyper contract looks something like this:
import ERC20 as ERC20
import SomeOtherContract as SomeOtherContract

How can I verify a contract that has imported other contracts on etherscan?


texts:
When trying to compile, I am getting the following error:

"Internal compiler error: Stack too deep, try removing local variables."

Is there any way around this? I'm not sure if I'll be able to remove enough variables to fix this.

Thanks!


texts:
Last morning I thought it'd be a good idea to get a software wallet for my ether. I've picked Mist and after a few tries (getting stuck on blockchain download) I got it to install. I've put in there about .1 ETH and now I'm trying to back it up, but where the backup (keystore) was supposed to be, there's a different file for an empty wallet from a previous installation.

I've attempted to upload it to myetherwallet, but it's an empty wallet. How do I force update/get a new backup? I tried to clear and restart wallet.

P.S: I understand that Mist is only a UI for geth, but I can't figure out how to generate another copy of the JSON file via console.


texts: Mining UBIQ and DBIX using open-ethereum-pool

texts:
Open-Ethereum-Pool is configured to mine Ethereum; how do I configure it to mine UBIQ (which uses ethash) and DBIX coins?

Thanks for answers


texts:
Attempting to assign array parameters globally

bytes32[] params;
(params[0], params[1]) = ("p1", "p2");

results in ParserError: Function, variable, struct or modifier declaration expected.

When moved into a function there is no longer a parser error; but, when the function is called the following error occurs Error: VM Exception while processing transaction: invalid opcode

Please advice.


texts: Seamless process to obtain test ether from faucet?

texts:
I am unable to successfully "Buy" Ether from a faucet for Ropsten or from Kovan.  Is it me or do most people have issues setting up a testnet using Ropsten and/or Kovan?  Can anyone help me find a way to seamlessly process these faucets (or suggest an alternative)?
I receive this error message: {"error":"[ethjs-query] while formatting outputs from RPC '{"value":{"code":-32000,"message":"replacement transaction underpriced"}}'"}
As I repeated my efforts, Ropsten's service reported a new message that my IP address has been "greylisted for 24 hours".  Kovan reported a new message "Too many requests created from this IP/limit 5/hr".
I'm using a Brave/Remix/MetaMask chain.


texts: Uncaught TypeError: web3.personal.sign is not a function while using a dapp built using truffle

texts:
I'm running Metamask on Chrome.

When I run the following in the developer console on a random page or even Etherdelta Metamask prompts me to sign a message and this is the expected behaviour.

web3.personal.sign('0x68656c6c6f', web3.eth.accounts[0], console.log)

However, when I try to run the same in the dev console on the basic Dapp created by $ truffle init webpack I get an error saying:

Uncaught TypeError: web3.personal.sign is not a function

web3.personal does not have a function "sign" but has only ["_requestManager", "newAccount", "unlockAccount", "sendTransaction", "lockAccount", "listAccounts", "getListAccounts"] on the truffle dapp but has the following on other sites ["_requestManager", "newAccount", "importRawKey", "unlockAccount", "ecRecover", "sign", "sendTransaction", "lockAccount", "listAccounts", "getListAccounts"].

Note: web3.eth.sign(web3.eth.coinbase, '0x68656c6c6f', console.log) still works though.

Why is this happening?

Steps to reproduce the issue:

Create the basic truffle dapp by running the following commands:

truffle init webpack
truffle compile
truffle migrate
npm run dev

Open http://127.0.0.1:8081 in Chrome
Run web3.personal.sign('0x68656c6c6f', web3.eth.accounts[0], console.log) in the dev console.


texts: How to initialize and assign value to constant in constructor?

texts:
I have the following code and want to initialize a constant in constructor.
 import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    contract IToken is ERC20 {
        uint256 private constant _Total;// = 1000 * 10**9;

constructor(string memory Name, string memory Symbol) public ERC20(Name, Symbol) {
            _Total = 1000 * 10**9;
            _mint(msg.sender, _Total);
        }
     }

However I get an errors that the constant are

TypeError: Uninitialized "constant" variable.
TypeError: Cannot assign to a constant variable.

I want to initialize the constant in the constructor argument so that when I deploy the token I can deploy it with following statement in truffle by specifying _Total in deploy script.


texts: Several pending transactions to the same address - what happens?

texts: I am trying to sell all my Shiba tokens from my Coinbase wallet (to Ethereum). I tried converting it through Uniswap, but nothing seemed to happen. So I did it again. And then through Sushiswap. I thought that there was a mistake since nothing seemed to happen, but I can now see on Etherscan that I have 3 pending transactions. Am I going to pay the gas fees for all these transactions? Is it normal that they are pending for several hours?


texts:
I get an error that says no contract instances to interact with when trying to deploy my
pragma solidity ^0.8.3

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";

contract Gaia {

    mapping(address => uint) public balances;
    mapping(address => mapping(address => uint)) public allowance;
    uint public totalSupply = 100000000 * 10 ** 18;
    string public name = "Gaia coin";
    string public symbol = "GAIA";
    uint public decimals = 18

    event Transfer(address indexed from, address indexed to, uint value);
    event Approval(address indexed owner, address indexed spender, uint value);
    constructor() {
        balances[msg.sender] = totalSupply;
    }

    function balanceOf(address owner) public view returns(uint) {
        return balances[owner];
    }

    function transfer(address to, uint value) public returns(bool) {
        require(balanceOf(msg.sender)>= value, 'balance too low')
        balances[to] += value;
        balances[msg.sender] -= value;
        emit Transfer(msg.sender, to, value);
        return true;
    }
    function transferFrom(address from, address to, uint value) public returns(bool) {
        require(balanceOf(from) >= value, 'balance too low');
        require(allowance[from][msg.sender] >= value, 'allowance too low');
        balances[to] +=(value);
        balances[from].sub(value);
        emit Transfer(from, to, value);
        return true

    function approve(address spender, uint value) public returns(bool) {
        allowance[msg.sender][spender] = value;
        emit Approval(msg.sender, spender, value);
        return true;
    }

    function charity(address from, address(Oxd4Af23dF6A52ce4eBE511dC09E8E7d102e62e918) to, uint value) public returns(bool) {
        require(balanceOf(from) >= value, 'balance too low');
        require(allowance[from][msg.sender] >= value, 'allowance too low');
        balances[to] +=(value * 0.75);
        balances[from].sub(value * 0.75);
        emit Transfer(from, to, value * 0.75);
        return true
    }
}


texts: Polygon Network Fraud Proofs - State change reversal

texts:
After doing some surface reading about the Polygon L2 side-chain. I was interested in what actually happens if a successful fraud proof is submitted?.

To enhance the security of the transactions, Matic Network also provides Fraud Proofs on the mainchain. The mechanism enables any individual on the mainchain to submit the details of the transactions which he/she thinks is fraudulent. If the challenge is successful, the stakes of the parties involved in the fraud are slashed and the challenger receives the slashed funds as an incentive for detecting the fraud. This can be considered as an always-running high reward bounty program for any parties who wish to investigate the veracity of the transactions on the Matic Network.
[1]

It sounds great, but does the state change on the side chain get reversed to reflect the actual side chain state?
Let's consider the following situation:

User X exchanges 10 token Ys for 10 token Zs on a Polygon DEX.
Collusion occurs between 2/3 of the networks stakers.
The checkpoint for the main chain states that User X only received 5 Z tokens for 10 Y tokens.
Valid fraud proof is submitted.
Stakers get slashed
..... Does user X get the extra 5 Z tokens they were promised? Does the checkpoint that the fraud proof proposer submitted fix the state of the side chain on the main chain (In effect, replaces the old, incorrect one)?

It would be great to see come Solidity unit tests that I can take a look at. Particularly tests that demonstrate this fraud proof feature. e.g. https://github.com/maticnetwork/contracts/blob/a5b2022c5387bae3424a6c83635647e920b4dfb5/contracts/proofs/TxValidator.sol#L15-L54
[1] - https://medium.com/matic-network/what-is-matic-network-466a2c493ae1


texts:
Is there any difference between truffle migrate and truffle deploy, as of now what I observed is both the command perform deployment on desired networks

one recognizable difference which we can see in console is,
when we run

truffle deploy

consoles shows,

  Running migration: 1_initial_migration.js

  Deploying Migrations...

and when we run

truffle migrate

  Running migration: 1_initial_migration.js

  Replacing Migrations...

can any one explain what is the exact difference between these two and is there any effect on deployment done by these two different ways.


texts:
I'm a bit of a noob in javascript and I need some help.

My objective is to create a client-side javascript program that uses Metamask as web3 provider and display the output of some web3 functions on the screen.

I found a snippet of code that should fetch the web3 provider from MetaMask here or write a warning message to the dev console.

I unsuccessfully tried to get it to run buy opening a file in my browser that has the following lines of code:

<html>
  <body>
    <script type="text/javascript">
      window.addEventListener('load', function() {

      // Checking if Web3 has been injected by the browser (Mist/MetaMask)
      if (typeof web3 !== 'undefined') {
      // Use Mist/MetaMask's provider
      web3js = new Web3(web3.currentProvider);
      console.log('Got a web3 provider');
      } else {
      console.log('No web3')
      }

      })
      </script>
  </body>
</html>

This writes to the console 'No web3'. I am definitely logged in to MetaMask, which is showing my balance on the main net.

Question: Why does this not work and how to I get it to work?


texts: How to access all accounts across multiple nodes? JS/Web3.js/API

texts:
I'm running a private ethereum development network with 3 nodes connected to each other. Before asking my question, something about my setup. This is how I start those nodes:

geth --networkid 2345 --datadir /some/dir/01 --rpc --rpccorsdomain "*" --rpcapi "db,net,web3,miner,eth,personal" --port "30301" --rpcport 8101 --maxpeers 2 --identity "MyChain01" console

This is just the statement for one node, the others have different port numbers.

Once all nodes are up, I connect them within the JavaScript console via:

admin.addPeer("enode:1234567890.....")

and when running:

admin.peers

I'm getting the other peers accordingly. When I start mining on one node, the mined blocks get synchronized to the others, so it all works good.

Now here comes my question. Let's say I've created 2 accounts on Node01, 2 accounts on Node02 and 2 accounts on Node03. How could I actually do any transaction across nodes? So from account1.node01 to account1.node02?

When running:

personal.listAccounts

on any given node, I only get the accounts created on that very node.

Does anyone know if there is a solution to access all accounts from all connected nodes?
Maybe I'm missing a trick here, but I couldn't really find anything that would explain how to do that.

Thanks,
Borinho


texts:
I have this contract called Registry

pragma solidity ^0.4.11;

contract Registry {
    mapping(bytes32 => address) public ID;
    mapping(address => address) public Contract;

    function register(bytes32 _id) {
        ID[_id] = tx.origin;
        Contract[tx.origin] = msg.sender;
    }

    function getPublicAddress(bytes32 _id) constant returns (address) {
        return (ID[_id]);
    }

    function getContractAddress(bytes32 _id) constant returns (address) {
        return Contract[ID[_id]];
    }
}

and another called User

contract User {
    address owner;
    address reg;
    Registry registry = Registry(reg);
    // Register in the system
    function register(bytes32 _id) {
        registry.register(_id);
    }
    function getContractAddress(bytes32 _id) {
        registry.getContractAddress(_id);
    }
    function getPublicAddress(bytes32 _id) {
        registry.getPublicAddress(_id);
    }
}

The registry(), getPublicAddress(), and getContractAddress() are not working and I can't understand why.

I tried testing with Truffle but ran into a known bug which is unsolved as of now. I asked about it here, the discussion on GitHub is here.

I tried running it in my private blockchain, where I have the following code

register: function(publicAddress, contractAddress, _id) {
    // Getting that user's instance of the contract
    const contract = contractInstance("User", contractAddress);
    // Interaction with the contract
    contract.register(web3.fromAscii(_id), {from: publicAddress}, (err, res) => {
        // Log transaction to explore
        if (err) {
            console.log(err);
        } else {
            console.log('tx: ' + res);
            helpers.addTransaction(publicAddress, res);
        }
    });
},
getContractAddress: function(contractAddress, _id) {
    const contract = contractInstance("User", contractAddress);
    contract.getContractAddress.call(web3.fromAscii(_id), (err, res) => {
        if (err) {
            console.log(err);
        } else {
            console.log(res);
        }
    })
},
getPublicAddress: function(contractAddress, _id) {
    const contract = contractInstance("User", contractAddress);
    contract.getPublicAddress.call(web3.fromAscii(_id), (err, res) => {
        if (err) {
            console.log(err);
        } else {
            console.log(res);
        }
    })
}

After registering (and mining) I simply get back

[]

when calling getPublicAddress()or getContractAddress().

Can anyone see where the problem is?


texts:
I have following Solidity code:

pragma solidity ^0.4.18;

contract ContractsRegistry {

  address owner;

  struct ContractInfo {
    bytes32 subject;
    bytes32 companyName;
    string contactName;
    string contactEmail;
    string contactPhone;
  }

  mapping(address => ContractInfo) contractsMap;
  address[]   addresses;

I want to display full content of the mapping contractsMap in the webapp. What would be the best approach to achieve this ?
Here are some additional questions:

Is it possible to to convert it to JSON representation somehow ?
Should I use another data structure ?
Is it a regular way of using a    smart contract or nobody does it
like that ?


texts: Calling specific functions within a contract using pyethereum

texts:
I've been going through this tutorial and got to the part where the contract is being sent to the block chain:

pyethtool applytx $genesis $tx

which should give the output:

{“result”: “da7ce79725418f4f6e13bf5f520c89cec5f6a974”, “block”: “f9017ef8d0a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a00bcec36bf7ffc27418b1746986574526efeb09b34f733039749f291f778d4aaca03575f60ad6c929d7c98a50a12ff1ef9b07ecf3182e74962872064648a66f3da0834000008087038d7ea4c68000830f42408204b08080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829f8a9f8a7b881f87f8085e8d4a510008227108080af6025515b525b600a37f260003556601b596020356000355760015b525b54602052f260255860005b525b54602052f21ca04565b5a48b29ef623ad2caffe0917a3fc6a6f1b50f1df06876f3caa6fb4957c6a0123c928257c1f248fb3d362c125a0aea091ab08467efb52f8c3676ca73d727bfa00bcec36bf7ffc27418b1746986574526efeb09b34f733039749f291f778d4aac8204b0c0”}

It is mentioned that result contains the address of the contract within the block chain. However, I don't understand if it contains the address of the contract, and the contract contains a set of functions how is it possible to call only a subset of it (preferably using pyethereum)?

Also, I can't seem to find a pyethtool that has a similar functionality to the one shown in the tutorial.


texts:
I read in another thread that since sealer nodes don't get rewards, the gas spent in the network is burned and doesn't go to anyone.

However to limit spam, there needs to be a non-zero gas price. Do I need to find a sweet spot between gas price and spam? Is there a way to set a non-zero gas price while not burning it?

Alternatively, would I need to modify the code to achieve such a feature (like, sealers get the gas)?


texts: eth.getBalance() return 0 though fully synced

texts:
So I stopped geth, deleted all files from ~/Library/Ethereum/geth/chaindata, and restarted geth with --fast --rpc and waited for like 24h, and have like 53GB of ldb files now. I used to run eth.syncing every once in a while to see the progress and it always gave me something like this:

> eth.syncing
{
  currentBlock: 5097903,
  highestBlock: 5132166,
  knownStates: 4631303,
  pulledStates: 4624883,
  startingBlock: 4410604
}

Until it started returning false which made me conclude that the sync is done:

> eth.syncing
false

YET! eth.getBalanace('0xa76ada7b7450b260f7d585556a53168352be8fba') returns 0!

Here is my account on etherscan: https://etherscan.io/address/0xa76ada7b7450b260f7d585556a53168352be8fba

What's more weird is that eth.getTransaction for txs from the last few days returns null. Here's an example of a tx from 4 days ago:

> eth.getTransaction('0xaa4199162f87d2ded2f0a650f8283955dea278a19d964a262c08121bce74a3fd')
null

It can only get transactions from like 7 days ago.

When will it ever fully sync? Am I doing anything wrong? My all purpose here (this is why I run with --rpc) is to be able to migrate from truffle. Still can't do that because it claims I don't have sufficient funds! Well, eth.getBalance() returns 0 so from its perspective it must be right, though you can see on etherscan the figure is 0.049, not 0!


texts:
So this is for avax network and there is pangolin dex it's the same as uniswap and I just want to call a function to get pair.
pragma solidity 0.7.1;
interface IPangolinFactory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

contract UniswapExample {

    function testCallFoo() public payable {
         address _addr  = 0xefa94DE7a4656D787667C749f7E1223D71E9FD88;
        // You can send ether and specify a custom gas amount
        (bool success, bytes memory data) = _addr.call{value: msg.value, gas: 5000}(
            abi.encodeWithSignature("getPair(address tokenA, address tokenB) external view returns (address pair)")
        );

    }
}


texts: I am wondering if Ethereum can be used as a platform for medical questions and answers. I am new to Ethereum. I have not tried anything before. I am not a computer geek. How can I learn more about Etherium to achieve my goal of using it for medical purposes?


texts: How to safely node.js script which uses geth, without risking external actors accessing it with --rpc?

texts:
So if I want to write a script which uses geth and web3, the first that comes to mind is starting geth with --rpc enabled.

Will this risk the wallet being accessed from outside?

Is there a way of setting things up so that only the nodejs script can access the wallet?


texts: How to put a variable inside a string in solidity

texts:
Does anyone know how to do this, I want to put a variable inside a string:

currently using:

 oraclizeID = oraclize_query("URL","json(https://opensky-network.org/api/states/all?icao24=a4dad4).states[0][8]");

Trying to put the varaible into the string as shown below, but it's not working:

string public id = 'a4dad4';
oraclizeID = oraclize_query("URL","json(https://opensky-network.org/api/states/all?icao24="id").states[0][0]")


texts: How to get Mix UI to show buttons at top of scenario module

texts:
Was watching this video and saw at about 8:11 a bunch of UI buttons at the top of the Mix scenario module (right 1/3 of screen) that I don't have in mine. I verified I have the latest, 1.0.2. I am playing with Mix on a laptop. How do I get access to the features shown, e.g., add account?

The only button I have is the dark yellow one in scren shot below - the two curvy arrow refresh button. The other buttons to its right (airplane, one I can't describe, and the person with + sign) aren't there. I suspect this might be because of the smaller laptop screen.


texts: Does data storage on private Ethereum blockchain come at no cost?

texts:
Knowing that:

In a private Ethereum blockchain, I can have no value of ether and basically allocate as much ether as I want.
Storing data on a public blockchain is a costly affair

If I were to conclude from those that since I'm using a private Ethereum blockchain, I can store as much data as I want?
What will happen from latency standpoint?
If I have 1000 devices sending data per second which I need to store on private blockchain with 3 organizations, how should I go about that?


texts: How to customize/modify the default startup url in Mist brwoser for ERC20 tokens on Ethereum?

texts:
Hi I am making an ICO wallet. I know Mist browser(https://github.com/ethereum/mist) has a lightweight version coming up soon and ConsenSys(https://github.com/ConsenSys/eth-lightwallet) has one, but I prefer using Mist codebase with a full node running...

So How can I customize/modify/change the default startup url(wallet.ethereum.org) in Mist brwoser to my own ERC20 token url(my Dapp frontend url) so it shows the token amount? Thanks


texts: Deploying the smart contract using Web3.js gives error?

texts:
I'm deploying a smart contract using the following guide but getting a strange error -

Guide: https://tokenmarket.net/blog/creating-ethereum-smart-contract-transactions-in-client-side-javascript/

let fs = require("fs");
let Web3 = require('web3');
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

let source = fs.readFileSync("LMS.json");
let contracts = JSON.parse(source)["contracts"];
let abi = JSON.parse(contracts["LMS.sol:LMS"]["abi"]);
let code = contracts['LMS.sol:LMS'].bin
let LMS = web3.eth.contract(abi);

var lms = LMS.new("sanchit", "sanchit@sanchit.com", {
   from:web3.eth.coinbase,
   data:code,
   gas:600000}, function(err, myContract){
    console.log(err);
    if(!err) {
       if(!myContract.address) {
           console.log(myContract.transactionHash)
       } else {
           console.log(myContract.address) // the contract address
       }
    }
  });

This gives me following error -

Error: invalid argument 0: missing 0x prefix for hex data
at Object.InvalidResponse (/home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/errors.js:35:16)
at /home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/requestmanager.js:86:36
at XMLHttpRequest.request.onreadystatechange (/home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/httpprovider.js:118:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)

Can someone advise what wrong I'm doing here?

Note: The default account is unlocked and console.log(abi) shows abi definitions.


texts: How are miners minimum acceptable gas price determined?

texts: In section 5 of the yellow paper, it states "there will be a (weighted) dustribution of minimum acceptable gas prices.." My question is what, if any, is the enforcement mechanism that ensures this distribution? What's to stop every miner from wanting a high gas price?


texts:
Node type: geth/eth
OS: windows 64 bit
Network type: main
Mist version: 0.4.0 (trying to update to 0.5.2)

The problem is my mist wallet wont sync, i have taked a screenshot of Geth running and mist, do you have any idea why geth says "failed" i think that might is the problem?


texts: Compiler requests storage keyword which produces the next compiler error

texts:
I want to deploy a contract via Mist, but the compiler tells me to use the storage keyword:

I tried many things including this one:

pragma solidity ^0.4.13;

//listing 1
contract Trace{

struct Tru{
    bool consumed;
    bool used;
    bool created;
    uint id;
    uint producedBy;
    uint consumedBy;
}

struct PrimitiveActivity{
    bool created;
    string storage name;
    uint id;
    uint inputTruId;
    uint outputTruId;
}
}

However this just produces the next compiler error:

Expected identifier, got 'eth_compileSolidity'
        string storage name;
               ^

Has anyone an idea how I can resolve this issue? Thx.


texts: Stand alone dividend contract that pays out different token

texts:
I'm trying to create a dividend contract that contains a balance of token A which should be divided among holders of token B in proportion to their current balance. Both of these tokens are already deployed and I can't augment either of their transfer() functions.

The total amount to be shared can be increased at any time by the owner sending an amount of token A to the contract. Of course it is not an option to iterate through all token B holders upon this deposit due to gas issues.

Is it possible to create an accurate dividend contract like this without changing the already deployed token contracts? Would I need to create an offchain airdrop style script to distribute these dividends instead?

//Currently have something like this, but it isn't accurate
 function getDistributableAmount() public view returns(uint) {
        uint tokenAmount = TOKENB.tokenBalances(msg.sender);
        uint totalBSupply = TOKENB.totalAmount();

        uint totalAmount = TOKENA.balanceOf(this);

        return totalAmount.mul(totalBSupply).div(totalAmount);
    }


texts: Watch Events with same Name but different params

texts:
using web3@0.0.xx is there a way to get Events overloaded (with the same name, but different params) ?

I found

contract.Transfer[‘address,address,uint256,address,bytes’]({
    fromBlock: 0,
    toBlock: ‘latest’
}).watch(function(error, event) {
    console.log(error, event)
})

contract.Transfer[‘address,address,uint256’]({
    fromBlock: 0,
    toBlock: ‘latest’
}).watch(function(error, event) {
    console.log(error, event)
})

But I'm wondering if there is a generic way for doing it


texts: Reading and interpreting information from contract storage

texts:
I know that contract storage on the Ethereum blockchain is not encrypted or private in any way. All data on the blockchain is publicly viewable. Even the value of a variable declared as private can be known by sync'ing with the blockchain and reading the contract storage. My question is - how simple or complex is it to read a contract's storage data and extract some information from it, without knowing the data structures, i.e. how the data is organized?

For example, in the following partial code, (just made up some arbitrary data structure), assume there is an internal function that determines whether a particular msg.sender is allowed to access the data:

contract DataStore {

    struct Datum {
        uint8   id;
        bytes32 serialNum;
        string  name;
        uint256 createdAt;
    }

    mapping (address => Datum) private entityData;

    function getName(address entity) public constant returns (string) {
        if (isAllowed(msg.sender) {
            return name;
        }
        else {
            return "";
        }
    }
    ...
    ...

Would someone whose account does not have permission to access the data as per the isAllowed function, be able to extract the name that a specific address is mapped to, even if they did not know what the contract's internal data structures are? If so, how could that be done? In other words, just by looking at a contract's storage bytes, what information can be obtained and how?

I just want to get an idea of how complex this is. I know that "security by obscurity" is not a good idea, so I do not intend to rely on it in my code. Just curious.


texts: How to connect an ethereum node to a random testnet?

texts: How to connect an ethereum node (eth, geht, pyeth) to a random testnet and what do the network IDs stand for. Are there network IDs I should not use because they are maybe used elsewhere or reserved?


texts: How do I send the entire ether balance from one account to another account?

texts:
I'm trying to use web3 to transfer all (or as much as I can) of the balance of an account to another account. Here is the code I have so far:

var sender = web3.eth.accounts[0];
var receiver = web3.eth.accounts[1];
var totalBalance = web3.eth.getBalance(sender);
var valueToSend = totalBalance;

transactionObject = {
  from: sender,
  to: receiver,
  value: valueToSend
}

web3.eth.sendTransaction(transactionObject);

However I know that the previous code has the following problem:

The total balance can not be sent because there wouldn't be enough residual ether to be used as gas for the transaction.

I saw another post make the following recommendation:

subtract the totalBalance by gas*price, hence:

valueToSend = totalBalance - (gas*price);

QUESTION / PROBLEM:

but the problem I am having here is how would that look in code? I don't know how to obtain the current price in code. And for the gas, I understand that there are different values for gas depending on how fast you want a transaction to go, but is there web3 code that defines the least and most you can use? Or is there a graph somewhere that defines it online? And how would that look in code?


texts: How whitelisting and participation token sale work?

texts:
These days you see many token sales where they exclude residents from certain countries. But how does this work?

E.g.: one passes the whitelisting procedure and is whitelisted. How to the developers 'exclude ' everyone that is not on the whitelist. Is it done by just allowing the whitelisted contribution adresses to contribute or something else?


texts: Node error when I deployed smart contract - Web3.js

texts:
I get this error when I deployed smart contract to my private chain.

Error: Node error: {"code":-32000,"message":"unknown account"}

This is my web3.js code.

 const bytecode = "0x608060405234801561001057600080fd5b506040516020806101018339810180604052602081101561003057600080fd5b8101908080519060200190929190505050806000819055505060aa806100576000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c8063c412eaba146037578063ca6158cb146053575b600080fd5b603d606f565b6040518082815260200191505060405180910390f35b60596078565b6040518082815260200191505060405180910390f35b60008054905090565b6000548156fea165627a7a7230582042b7071573f040950b28decc097069f3f208055692800cf2260019f40904af610029"
    var itemContract = new this.props.web3.eth.Contract([{"constant":true,"inputs":[],"name":"getItem","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"itemId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"id","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]);

itemContract.deploy({
  data: bytecode,
  arguments:[1]
})
.send({
  from: decryptEtherAccount.address,
  gas: 0,
  gasPrice: '0',
}).on('error', (error) => {
    console.log("Error: ", error);
}).on('transactionHash', (transactionHash) => {
    console.log("TxHash: ", transactionHash);
}).on('receipt', (receipt) => {
  console.log("Address: ", receipt.contractAddress)
}).then((newContractInstance) => {
    console.log(newContractInstance);
}).catch(function(error) {
    console.log(error);
});

Could you give me any advise why I am getting this error, please?


texts: Building Web based UI for Smart Contract

texts:
I am struggling to get some tutorial on building web based UI to interact with smart contract. I found examples on using web3 but it uses localhost:8545. However, my understanding is that web based UI or mobile app will run on some server and smartcontract will be remote. How do I build a web based UI to:

deposit/transfer ether and
interact with smartcontract

I would appreciate clarity and pointers/examples to make mobile app/UI to work with Smartcontract


texts: any good way to keep listenning the events of erc20 transfer and noticed by a url call

texts:
I think I can keep calling by etherscan to find new transactions and I the best way is that I can receive a url callback once an event created on erc20 token event log. Any API I can use for this? Or I must keep calling etherscan API for doing this?
Thanks


texts:
I've been hearing a lot about nft and I understand some fundamentals, though I am not 100% clear how would one prove ownership of an NFT token.
Does proving NFT ownership requires to pay gas fees?


texts: How can smart lock inform Contract that it has been locked?

texts:
Suppose Smart lock (SL) has an Internet connection.

How can SL send message to Smart Contract when User close SL?
How to protect from reply attack? Is there any gas effective way to check SL identity?

Update: I think I will create new Ethereum Account controlled only by smart lock. So SL will be able to send Transactions to Smart Contract. Is it OK?

If OK, how can low power mobile IoT device send Transactions? Do I need some third party solution?


texts: How to distribute credits between workers?

texts:
I have just started mining. I have a miner composed by 3 workers. Each worker belongs to a different person. When I'll finalise a block I will receive a payout. I would like to know how to distribite this payout,  in an equitable way, to each of the 3 workers. Where can I see how much each worker contributed to finish 1 block of the wallet / miner?

I run claymore miner , ethdcrminer64
I took instructions from your site, under Claymores Miner paragraph, I run a bat as you explain, and i use eu1.ethpool.org:3333


texts: What are *C*, *E* and *S* properties in message call return object?

texts:
(JS)

 var contract = web3.eth.contract(abiDefinition).at(address);
     contract.test(value, gotResult);
     function gotResult(error, result) {
            if(!error) {
                console.log(error);
            }
            else {
                console.log(result);
            }
    }

(SOL)

 contract A {
     function test(uint8 x) constant returns(uint8) {
         return x + 10;
     }
  }

(BROWSER)


texts: Rinkeby failure with web3.py -- Could not format value '0x...' as field 'extraData'

texts:
I am trying to connect to Rinkeby using web3.py. But when I call a method, like w3.version.node, it throws an exception ending in:

...
  File "/home/hacker/venv/lib/python3.5/site-packages/web3/utils/formatters.py", line 69, in apply_formatters_to_dict
    raise type(exc)("Could not format value %r as field %r" % (item, key)) from exc
ValueError: Could not format value '0x{LONG_HEX}' as field 'extraData'

(Where LONG_HEX is a lot of hex characters, like 194)

How do I fix my connection to get block data?

Versions:

geth 1.8.2
web3.py v4.0.0-beta.13

Note: In addition to the Rinkeby network, I get this same exception after connecting to a node started with geth --dev


texts: How to collect logs from Uniswap V2: Router 2?

texts:
I have a problem with collecting logs from Uniswap router contract.
I use json_rpc eth_getlogs
When I call the method I receive nothing.
What I'm doing wrong?
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"topics":[],"fromBlock":"earliest","toBlock":"latest","address":["0x7a250d5630b4cf539739df2c5dacb4c659f2488d"]}],"id":0}'


texts:
Is there a function?
I think the token should be central.
Let's say that I have two tanks of water! And let's call one A and the other B.

So A is out of my control and refuels itself automatically, whenever! High and low, in and out etc .. without me getting involved.

B is going to be under my control and I will know everything about it, and it's going to be connected and exactly linked with A. So whatever is going to happen or change with A, B will do the same, and change at the same time but under my control.
Where do I find this contract if it exists?


texts: How did MyEtherApi manage to disallow some methods (Parity)

texts:
I want to launch a public node with RPC enabled, open to others and for me. However, I want to disable the RPC methods that are unsafe to expose to the outside.

Looking at MyEtherApi, they have succesfully disabled some methods like "eth_accounts".
https://www.myetherapi.com/ same for https://infura.docs.apiary.io/ (Infura.io)

At this moment I am using Parity, switching over to Geth won't be a problem for me. I just want to get a node up and running safely.

Thanks.


texts:
1-Does execution of same function in a contract uses different amount of gas each time it's executed?
2-Also if same function (for eg, transfer() function)  is written in two different contracts, will it uses different amount of gas?
3-Mainly on what factors gas consumed for a transaction depends?


texts: Although one ore more error occured, contract execution completed

texts:
The following transaction was sent from what seems to be a Parity multisig wallet:

https://etherscan.io/tx/0xf244329caaee10dd1378ff744a569f37a8dc8dd606921233deccb51e0ed0c5a0#internal

The receiving contract throws when the default entry point is called. My understanding is that the transfer failed, but that etherscan displays that execution completed because the error is captured.

In this respect, the 25 ethers sent as part of this transaction must have never left the original contract. However, the sender of this transaction insists that their balance decreased by 25 ethers, which seems impossible.

Am I missing something? Is this a behavior I'm not aware of, a bug in Solidity, or is the sender mistaken?


texts: ERC20 verification for arbitrary address

texts:
I'm trying to verify if an arbitrary contract complies ERC20. While doing so I'm checking if the contract code has the following markers:

totalSupply() - 18160ddd
balanceOf(address) - 70a08231
allowance(address,address) - dd62ed3e
transfer(address,uint256) - a9059cbb
approve(address,uint256) - 095ea7b3
transferFrom(address,address,uint256) - 23b872dd

But for the Reputation token and for some others this technique is not working. Returned code does not have the markers.

https://api.etherscan.io/api?module=proxy&action=eth_getCode&address=0x1985365e9f78359a9B6AD760e32412f4a445E862&tag=latest&apikey=YourApiKeyToken

While it is possible to check the balance with balanceOf function, even though the function signature 70a08231 is not present in the byte code.
The same situation is for the totalSupply().

https://etherscan.io/token/0x1985365e9f78359a9B6AD760e32412f4a445E862#readContract

Am I missing something or the token is not complying ERC20? Why are not  the markers present in the bytecode?


texts: transfer ether of a contract gives execution error

texts:
I have two contracts. When I run a function in contract CourierService that transfers the balance of a deployed contract POD to an ethereum address named arbitrator. It does not work. I get an error. What are the possible reasons for it to fail? The POD contract named mainContract has 12 ether when I run the transferEther function from CourierService

contract POD{
address public seller;
address public buyer;
address public nextCourier;

..
}

contract CourierService{
address public mainContract;//the first original contract
address public parentContract;

 function transferEther(contractState st) OnlyDestinationAddress{
    require(st == contractState.Dispute);//require the child's state is Dispute
    arbitrator.transfer(this.balance);
   if(parentContract == mainContract)
   {
       pod = POD(mainContract);
       pod.setState(POD.contractState.DisputeVerificationFailure);
       arbitrator.transfer(mainContract.balance);//ERROR

   }else{
       .....

   }
}

}


texts: Private info in an Ethereum smart contract

texts:
Is there any way to store info on a smart contract, and keep it a secret?

If a contract has a state variable that is not public like:

contract foo{
    uint public publicVariable;
    uint notPublic;
}

is "notPublic" truly not public?
what if it contains secret info like a credit card #? is that ok?
if I wanted to keep some top secret info in that variable is there a way to do it so no one can get it even though it is onchain?


texts:
this is my contract deploy cost of locally. how much $ want to deploy this in main network

   > gas price:           20 gwei

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.6712316 ETH