texts:
It is possible to generate truly (not pseudo) random number with specific range inside smart contacts

(for example I need random number between 1 and 60 000 )

Thx!


texts:
var greeterContract = web3.eth.contract(greeterCompiled.greeter.info.abiDefinition);

I am getting this type of error on geth console:

  TypeError:Cannot access member 'info' of undefined at :1:41

I follow this, can I add any system dependencies, I think golang is by default available in Ubuntu. Any ideas?


texts:
I'm trying to understand the purpose of EIP 1613. Related to this website says "No more Metamask".

So it assumes that a user does not have direct access to his private key / wallet. It means the key pair must be genereted by (d)app owner. In this case the (d)app owner has full access to the user account, e.g. for receiving, sending txs.

So why we need at all such complex system with Relays, RelayReciepeints, Hub etc? If the gas payer always is the only one person - the (d)app owner.

Are there some use cases where this approach is really useful and make sense?


texts: Can my rig setup guy somehow cheat me and transfer some of the mining cash to his wallet?

texts:
I am new with the mining thing and I have a question to ask regarding this. I have a guy that setup my rigs home and i want to be sure if he did the right thing or if somehow he is cheating me. I want to know if its possible for him to transfer somehow of my mining income to his wallet? And if so how i am able to protect myself from this?

Thanks,

Darko


texts:
If you create a cold storage account, by following the method described here for example:

How to send ether to a cold storage account?

And subsequently, a hard fork takes place on the Ethereum network, are there any extra steps that must be taken when moving the Ether back to hot storage?


texts: Transaction completion in Ethereum smart contract

texts: How can I calculate the deployment time and completion time of a smart contract transaction using web3.js?


texts:
I'm trying to whisper a message using web3.shh following the example here: https://github.com/paritytech/parity/wiki/Whisper-Overview

web3.shh.post({ "topic": 't', "payload": 'p'});

And it throws an error:

Error: Method not found
      at Object.InvalidResponse (/node_modules/web3/lib/web3/errors.js:35:16)
      at RequestManager.send (/node_modules/web3/lib/web3/requestmanager.js:61:22)
      at Shh.send [as post] (/node_modules/web3/lib/web3/method.js:145:58)
      at Context.done (test/index.js:33:23)

My Parity client is running with the following arguments:

parity -l all \
       --mode "active" \
       --unlock $ALICE,$BOB \
       --password $CONFIG_DIR/password \
       --chain $CHAINS_DIR/$CHAIN \
       --db-path $DB_PATH \
       --keys-path $DB_PATH/keys \
       --identity $IDENTITY \
       --no-discovery \
       --reserved-peers $CONFIG_DIR/peers.enodes \
       --jsonrpc-port "8545" \
       --jsonrpc-interface "0.0.0.0" \
       --jsonrpc-apis "web3,eth,net,parity,parity_accounts,parity_set,traces,rpc,personal,signer" \
       --jsonrpc-hosts "all" \
       --author $COINBASE \
       --reseal-min-period "10" \
       --ui-interface "0.0.0.0" \
       --ui-port "8180" \
       --ui-no-validation \
       $*


texts: Learning Ethereum development? & idea possibility?

texts:
what are some good places to learn more about ehtereum development/solidity? Usually when learning something new I tend to head to books or treehouse tutorials :) however there is fairly small amounts of resource in this new area?

Also I'm wanting to take development texts online and push out these texts to blockchain/ethereum for intelligent people to answer and push reply back to smart contract. Is this possible? My main query I'm looking to answer is "would I have to market this service like a traditional web business with marketing campaigns", or is there some way/method/framework/third party service where I can push my smart contract transactions for people to see & contribute to. It would be great if I can do this without needing to do traditional marketing. Just being able to push my items to an already populated place where people working on ethereum could see and contribute to my smart contracts when they're looking for contribution.


texts:
I see this document.
But I don't understand what is an index position of an uncle.

I'd like to get informations of uncle blocks like etherscan.io

However I don't know a value of the index position what should be set.


texts: I've a Ropsten testnet transaction that cost : 0.00254868076441 ETH, the corresponding USD cost is 5.24 US$ ? If i deploy the contract in mainnet is the same cost?


texts: Geth sync too slow on MacMini to catch up with latest blocks

texts:
My workaround used to be do a geth -removedb and start a fresh fast sync from scratch. Trying to sync with existing blockchain data instead was a lost race of catching up to the latest block.

Today even the workaround in fast sync mode (cache -1024) will not completely load the blockchain anymore. It catches up some 100-300 blocks to the latest block and stalls for hours. By the time it catches up a few hundred blocks, the latest block moved ahead again. For 4 days now. Frustrating. Any ideas?

  MacMini 4GB RAM (latest MacMini doesn't support field RAM upgrade)
  VDSL connection with an average of 20-40Mbit throughput
  Geth 1.6.1 / go1.8.1 /Ethereum Wallet 0.9.0


texts: Default gas limit set by web3 is unreasonably high?

texts:
I am trying to learn and understand solidity/defi by creating some copies of current popular protocols; I've created a small copy of the Curve Dai strategy from harvest finance, but I'm getting really high gas limits when I try to deposit funds using the depositAll() function on the DepositHelper contract.
Contract Links (Mainnet)

DepositHelper
DAI Vault

I thought this could've been because I did not verify my source code initially, but after verifying I am still seeing high gas prices in MetaMask for what should be relatively cheap (~$15-$20) transactions. As a test I deposited $40 DAI into harvest finance and the gas limit estimated ~$20 for the transaction cost, and final transaction cost was $10.
In contrast, when I called the same function on my version of the deployed contract the default gas limit set in MetaMask created a estimated transaction cost of ~$140.
I've tried to call estimateGas() so I can manually set an appropriate gas limit (not sure if this is best practice...) but this call fails with the following error:
{code: -32000, message: "gas required exceeds allowance (1500000) or always failing transaction"}

Code I wrote to call depositAll():
const depositHelper = new web3.eth.Contract(
    DepositHelper.abi, // abi for DepositHelper contract
    '0x4681ae82f6f575da63b77a6735f44c13fdc2e4df'
);

// construct depositAll method parameters
const amount = 40; // 40 DAI
const weiAmount = window.web3.utils.toWei(amount, 'ether'); // convert to wei
const amounts = [weiAmount];
const vaults = ['0x3EE8bD22Df6605c6a7074c56Abb0f3Fc1FA6a069'];

depositHelper.methods
    .depositAll(amounts, vaults).send({ from: account }) // gas limit set here by default seems unreasonably high ...
    .catch(error => {});

Code I wrote to attempt gas estimate that fails
depositHelper.methods
    .depositAll(amounts, vaults).estimateGas({ gas: 1500000 })
    .then(gasAmount => {
         console.log('gasAmount ::: ', gasAmount);
    })
    .catch(error => {});

Is there something I've done wrong in calling the depositHelper function that is causing this gas limit to be super high?


texts: Can we assume an average time to mine a block?

texts:
How safe is the assumption that, 10 years from now, it will take a certain amount of time (say, ~16s) to mine a block?

If we cannot safely assume future block solving times, how else can we measure time, given that reading the timestamp of a single block isn't very reliable? (Maybe average several blocks' timestamps?)


texts: Got hacked on metamask. Which wallet has the best security to trade on Uniswap?

texts:
So I got hacked on Metamask and all the funds lost. The hacker somehow connected to my google session and was able to get to the google drive files where I had couple of sensitive data. This was my mistake and I learnd from it. I had my 2FA enabled on google but there was not even one suspicios activity on my phone from google. The only proof I have is that I managed to get a print screen from Gmail session activity where I saw two strange IPs from other countries connected to my session. There is an asterix * that indicates the current session and it was marked at my IP and on the attacker IPs.
If you compare some Metamask wallet with let say Binance exchange the funds on exchange are infinitely more secure then Metamask. All you need for Metamask is secret phraze and the original owner cannot do anything to block the attacker from the wallet. The wallet now has basically two owners and there is nothing that can be done here. Fo Binance let say if you have good security enabled with 2FA, SMS, email confirmation it is very hard for the attacker to withdraw your funds even if he has email and password. If Binanace gets hacked and the attacker gets private key then it is the same story as with Metamask.
Basically etherum at its core I think is very very unsecure. I think some form of another confirmation of transaction either by SMS, Authenticator or email shoould be built into the network itself. Currently this implementation depends only from 3rd party developers if they implement multilayer security.
So what to use to trade some coins that are only on Uniswap and transactions have 2 layer security? Does even exisits some wallet with 2 layer security? It seems I need to become my own cybersecurity specialist just to trade some shitcoins :)


texts: Wait for next block when testing with TestRPC

texts:
I'm running some tests over my contract using TestRPC and Mocha.

I'm writing a debt manager. My data structure has a field called validity, which is semantically a date that determines until when this debt can be paid without a fine.

Some of my business rules are:

I cannot insert a registry with validity in the past
When I try to pay the debt and it is past its validity, I have to add a fine to the due value.

My contract has a rule that checks (simplified version):

function getValue() returns (uint) {
    if (now > validity)
        return value + fine;
    else
        return value;
}

I generate a registry with validity very near in the future in order to allow it to be inserted.

I tried to set a delay for the test case, in order to get the "out of validity" condition when I want to getValue() of the registry, but I'm not getting into that branch. It keeps returning only value instead of value + fine.

Then I discovered that now is just an alias to block.timestamp, which leads me to a problem:

How can I delay execution of the test until the next block is mined?


texts: Parsing the WolframAlpha string result from the Oracalize __callback function into a usable format?

texts:
I need to generate 10 unique random numbers between 0 to 100 in my smart contract.

For this I've decided to utilise Oracalize and one of the datasource called WolframAlpha. This is how I use it:

function loadNewRandomNumbers() public payable {
    oraclizeID = oraclize_query("WolframAlpha", "10 unique random numbers between 0 and 100");
}

I've deployed this to Ropsten test net and executed the loadNewRandomNumbers function and everything worked and I have the result from calling the wolfram alpha api datasource:

This is great so far; but I need to parse the string (json-like) response - so that I can use it; Ideally parse the response into an uint array.

How can I go about doing this? Is there a way parse the above string response into a usable format?


texts: How to install/use Oraclize on Windows 10?

texts:
I wanna get data from external data(web or just text files) to my smart contract.

I found how to install and use the external data!

But all the data was for Linux.

like, sudo apt-get install npm blah blah

But I wanna develop my smart contract on windows environment.

anybody knows where can i get that information?

or could you let me know how to install and use Oraclize on Windows?


texts: creating raw offline transaction alt coin

texts:
Is it possible to create a raw offline transaction using geth for alt-coins?  I'm trying to write some sample code to automatically do a shapeshift transaction and want to convert, say, between GNT and RLC.  Is there any sample code for that?

Also, does the blockchain need to be synced to do this?


texts: Why would an Infura/MetaMask watch of a contract's allEvents() that works on Rinkeby fail sporadically on Mainnet

texts:
I have some code that immediately sets up an allEvents watch for the contract, then leaves that running and uses it to handle various events generated by the contract. I've been running it on Rinkeby and it seems to always correctly pick up relevant events, including the results of transactions. However, on Mainnet, the events don't seem to be firing consistently.

var evts = rc.allEvents({}, {fromBlock:'latest', toBlock:'latest'})
evts.watch(function (error, result) {
   // handling code
});

https://github.com/realitykeys/realitycheck/blob/master/js/ui/main.js#L2959

What could be going wrong, and what could I do to fix it?


texts: Verifying/Publish Contract Source Code on BScscan not working

texts:
Verify & Publish Contract Source Code
Contract Address: 0xbb4b79a046d34c68803a755a87c8b78bdde60aa8
Solidity (1 file)
v0.6.12
No License
I put this in.
Enter the Solidity Contract Code below *
pragma solidity ^0.6.12;

import "https://github.com/safemoonprotocol/Safemoon.sol/blob/main/Safemoon.sol";

contract CANINE is ERC20 {
    constructor(uint256 initialSupply) public ERC20("CANINE", "K9") {
        _mint(msg.sender, initialSupply);
    }
}

I get an error: Error! Unable to generate Contract ByteCode and ABI (General Exception, unable to get compiled [bytecode])
This token is already on the blockchain and the code cannot be reversed. Any help will be appreciated.


texts: How can I add some balance to the address in private blockchain testnet?

texts:
Geth
Version: 1.6.1-stable
Git Commit: 021c3c281629baf2eae967dc2f0a7532ddfdc1fb
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.8.1
Operating System: windows
GOPATH=
GOROOT=c:\go

The above is my geth installation, I need to initialize testnet with some default balance for some address - how can I do this? I tried with the genesis.json from https://github.com/ethereum/go-ethereum/wiki/Private-network and initialized the private block chain, created an account, replaced the address in the custom genesis file with that and re-run the init, but it failed with

Fatal: Failed to write genesis block: database already contains an incompatible genesis block (have 15ecff6ddb9d4db4, new 834a88447f2091cc)

How can I add some balance to the address?


texts: The transaction from (account name) to ('undefined' or account name) couldn't be successfully executed

texts:
I am trying to do some testing on Ropsten testnet but I cannot deploy contract or even send Ether.

I get this error when trying to send ether:

  The transaction from "Main account (Etherbase)" to 'account1' couldn't
  be successfully executed.

Example transaction ID:

0xa85b767355c7bbd4ee8d97c30c100c8e04f2654e4fdebf2c93b4bfafdbe58bc7

It will stay at 0 confirmation and I will receive the error after about 5 mins

Version: 0.9.2

Blockchain: Ropsten testnet

OS & Version: windows
Node version: geth 1.7.2
Number of blocks synchronized: 2101823

I have seen this question asked before on here but none of the solutions help me, as I have this issue even when trying to send ether and not just contract deployment.


texts: Sell ETC from my Ledger Nano S (Ledger Wallet Ethereum)?

texts:
I have som ETC on my Ledger Nano S and now I want to send them to my bank account. In Ledger Wallet Ethereum app I get the option to send them to a "Ethereum IBAN or account"

What is that ?? Do I need an ETC account with a exchange and from there I can then transfer to my bank account or do I miss something completely.

Best regards


texts:
This is my truffle.js i've removed the credentials marked as *
var HDWalletProvider = require('@truffle/hdwallet-provider');
var fs = require('fs');
var infura_apikey = "*"
var mnemonic = "*";
var address = "*"

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // for more about customizing your Truffle configuration!
  solc: {
    optimizer: {
      enabled: true,
      runs: 200

    }
  },
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },
    ropsten: {
      provider: function() {
        return new HDWalletProvider(mnemonic, "https://ropsten.infura.io/v3/*", 3)
      },
      network_id: 3,
      from: address,
      gas: 4700388
    }
  }

};

When I'm trying to migrate my contracts "Migrations.sol" & "CertiVerify.sol"
The error is:

1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" -- sender account not recognized.

    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:364:1
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at Migration._deploy (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:70:1)
    at Migration._load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:57:1)
    at Migration.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:173:1)
    at Object.runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:148:1)
    at Object.runFrom (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:110:1)
    at Object.runAll (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:114:1)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:79:1)
    at runMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:253:1)
    at setupDryRunEnvironmentThenRunMigrations (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:241:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:207:1

Migrations.sol:
pragma solidity ^0.5.0;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

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

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

1_intial_migrations.js
var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

I do not know what exactly is the error here. Can anyone help me out with it and guide me on how do I use Metamask, Infura, Ropsten & Ganace in this application and what keys do I need to place on the '*' .


texts: I'm trying to write a contract which function calls are dependent of majority consensus from whitelisted users. E.g. the owner of the contract can initiate a transfer out of the contract, however, the transfer will only go through if majority consensus between whitelisted users are achieved. How can this be architectured?


texts: How to check provided string is a valid IPFS or IPNS path?

texts:
I want to check provided string is a valid IPFS or IPNS path or not under ipfs domain.

For example when I do:

ipfs ls <invalid-hash>
//waits keep searching ...

This will not return anything but halts within the program, so I would need to wait not knowing given hash is valid or not.

I could wait N-seconds as a threshold for ipfs to return results for ipfs cat valid-hash, ipfs ls valid-hash but results of ipfs cat valid-hash or ipfs ls valid-hash may take longer than N-seconds, which is not trustable to rely on.

[~]$ ipfs cat <hash-id that exists in the ipfs domain>
//returns a results maybe after 10 minutes if the hash-id string is valid.

[~]$ ipfs cat <hash-id that does not exists in the ipfs domain>
//HALTS. and does not return me that hash-id is invalid.

I have used: https://github.com/xicombd/is-ipfs but an invalid-hash string that I am giving into functions returns true, so it does not work properly on my side, any advice?

For example: (I am running commands inside node app.)

[$] node
const isIPFS = require('is-ipfs')
> isIPFS.multihash('QmYooooooooooooooooooooooooooooooooaoooooooooo')
true //returns true but it is an invalid ipfs hash that does not exist in the ipfs domain and should have returned false.

Thank you for your valuable time and help.


texts:
In solidity, how can I convert bytes memory buffer to bytes8 type?
Example:

bytes8 buf2 = bytes8(memory_buf); // TypeError: Explicit type conversion not allowed


texts:
I have a question regarding the possibility and probably the steps to do in order to be able to export my App via the whisper protocol.

how to do it and in which case it can be better than other ways of serving Dapps.


texts: Does it make a difference for the receiver, if the sender was an ordinary account or a smart contract?

texts:
I sold some ether through bitsquare, and used quorumwallet. It sends the funds by executing a smart contract.
The transaction is visible on the block explorers as internal tx, and the balance adds up correctly.
But the receiver didn't see it in his wallet, and claims he cannot spend it. Is there a better tool to check this claim than etherscan.io or etherchain.org? The account has about 90 transactions.


texts:
I have the below struct in a contract:

struct ServiceListStruct {
string cloudID;
address gatewayID;
string serviceProducerID;
mapping (string => string) serviceProducerMetadata;
string serviceConsumerMetaAttr;
string accessControlModel;
}
ServiceListStruct[] public BCServiceList;

ServiceListStruct sls;

Also a function to add struct elements to the array as below:

function addEntry(string _cloudID, address _gatewayID, string _serviceProducerID, string _serviceProducerMetadata, string _serviceConsumerMetaAttr, string _accessControlModel) public returns (uint)
{
require(msg.sender==_gatewayID);
sls.cloudID = _cloudID;
sls.gatewayID = _gatewayID;
sls.serviceProducerID = _serviceProducerID;
sls.serviceConsumerMetaAttr = _serviceConsumerMetaAttr;
sls.accessControlModel = _accessControlModel;
//
string memory s1;
string memory s2 = _serviceProducerMetadata;
string  memory s3;
bytes memory s2bytes = bytes(_serviceProducerMetadata);
while(s2bytes.length != 0)
{
   (s1,s2) = splitString(s2,";");
   (s1,s3) = splitString(s1,":");
   sls.serviceProducerMetadata[s1] =s3;
   s2bytes = bytes(s2);
}
BCServiceList.push(sls);
return 1;
}

The logic of split string function is as below:

function splitString(string _s, string _seperator) public returns(string, string)
{
var s_slice = _s.toSlice();
var seperator_slice = _seperator.toSlice();
string memory result = "";
var result_slice = result.toSlice();
result_slice = s_slice.split(seperator_slice);
return (result_slice.toString(), s_slice.toString());
}

it works perfectly fine, i checked it too.

if the input is "computer","p" to split string function, it returns "com" and "uter"

Here is the input i used for the addentry function - "LC2","0x14723a09acff6d2a60dcdf7aa4aff308fddc160c","SP2","location:inside;reading:degree;protocol:http","scattr","ngac" and tried to call the function from the same address in remix. the transaction was ssuccessful. Then I tried to look at the contents of the entry in struct array at position 0 and mapping key "reading" using the below function:

function getmappingentry(uint index, string s1) public returns (string, string)
{
    return (BCServiceList[index].cloudID, BCServiceList[index].serviceProducerMetadata[s1]);
}

The output is

{
    "0": "string: LC2",
    "1": "string: "
}

According to my understanding it should return

{
    "0": "string: LC2",
    "1": "string: degree"
}

Can someone help me understand what is missing here?

Thanks in advance!!!


texts:
deployedContract.deploy({
  data: bytecode,
  arguments: [listOfCandidates.map(name => web3.utils.hexToAscii(Rama))]
}).send({
  from: '0xfb9286cde20bbd5ed60ee3bb156f9d9938c5b151',
  gas: 1500000,
  gasPrice: web3.utils.toWei('0.00003', 'ether')
}).then((newContractInstance) => {
  deployedContract.options.address = newContractInstance.options.address
  console.log(newContractInstance.options.address)
});

TypeError: Cannot read property 'hexToAscii' of undefined
  at deployedContract.deploy.arguments.listOfCandidates.map.name (repl:3:55)
  at Array.map (<anonymous>)


texts:
I'm looking for a javascript wallet for Ethereum (like ethers.js for example) with support for listing the ERC20 tokens that the wallet is holding and also being able to send them to other wallet addresses.

My understanding for the later, is that all I need is the Smart Contract ABI of the ERC20 token and its address. Is that correct?

Going with web3 is not an option since I can't run a full node on the server I'll deploy my code.


texts: How much hash power is acutally used for dapp on the ehereum network

texts:
In any given block you can see 3 eth is rewarded to the miner who found it, and
0.??? is rewarded for process transactions. Both operations require computation and storage power, but clearly finding the nounce uses 97% of the resource and process transaction use only 3% at max (gas limit * block utilization) / (3 + gas limit * block utilization)
How is dapp decentralized if one ends up host their dapp on AWS or Azure.


texts:
I have two contracts, one is a Admin, other is subject. To keep things simple I am just including the functions that are invoked in the contracts relating to each other.

contract Subject {
  uint public count = 0;

  function increaseCount() returns newCount{
    count ++;
    newCount = count;
  }
}

The subject contract has a counter that can be increased via a direct call from web3.js or from Master contract.

contract Master {
  bool public isActive=false;
  uint public num=0;

  function changeState() returns bool newState{
    isActive = !isActive;
    newState = isActive;
  }

  function increaseSubjectCount(subjectAddr) returns uint newCount{
    SubjectContract subjectContract = SubjectContract(subjectAddr);
    newCount = ubjectAddr.increaseCount();
  }
}

so a transaction is fired to Master contract (once it is made of course) along with sufficient amount of gas. This function then uses the gas to call increaseCount() function in the Subject contract which returns the new counter. This in turn gets returned by the Master contract via web3.js. The issue I face is if I use browser solidity to compile the Master contract, it throws an error saying SubjectContract parametre undefined. If I add both contracts and then compile the code, when I use

var myContract = web3.eth.contract(masterContract.abi);
won't this cause issues if the abi code includes that of subject and master contract together, but if I don't do this, compiler throws bunch of errors.

Another thing I have considered is using import statements before compilation, but not sure how to safely implement it. Please help out guys!


texts: geth --dev fails to mine more than one contract

texts:
I installed geth and solc by following

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum-unstable
sudo apt-get install solc

then i ran

geth --dev

and did

geth attach

I created a contract and compiled it and "deployed" it to my blockchain.

var abi = <abi from solc>;
var jarContract = eth.contract(abi);
var bin = '0x' + "<bytecode from solc>";
var txDeploy = {from:eth.accounts[0], data: bin, gas: 1000000};
var jar = jarContract.new(txDeploy);

It was instantly mined and I got an address for it and could work with it.

But then I did

var jar2 = jarContract.new(txDeploy);

i.e. using EXACTLY the same variables as before, and nothing ever happened. It was not "mined", I got no address and could not interact with the contract.

I am a bit stumped. I only seem to be able to get one contract out of --dev and then have to stop and start it again to "mine" another one.

Any thoughts would be welcome!

Thanks


texts: Unable to transfer ERC 20 token usign web3js

texts:
I am trying to transfer ERC 20 token using web3.js. Below is my code:

<script type="text/javascript">
    var web3;
    function send() {
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://110.219.35.167:8545"));
        }
        if (!web3.isConnected()) {
            console.log('not-connected');
        } else {
            var theContract=web3.eth.contract([{my_abi}])
            var contractInstance = theContract.at('0x7b0CB0481E20490B030DeB3F292b61605EcEf050')
            web3.personal.unlockAccount('<?php echo $this->common->get_address() ?>','<?php echo $this->db_model->select('passphrase', 'member', array('id'=>$this->session->member_id)) ?>',100000)
            contractInstance.transfer('0xca2e4a5db17962d1e5ce44367731e217da8901b9',web3.toWei(1),{from:'<?php echo $this->common->get_address() ?>', gas:100})

            alert('Transfer Successful. Check confirmation status');
        }
    }
</script>

but getting the below error:Error: insufficient funds for gas * price + value


texts: Is there a way to track block synchronization progress in geth?

texts:
I just started up geth after importing my presale wallet. I'm getting a lot of block import messages like this:

I0305 17:40:03.815435   10833 blockchain.go:1251] imported 256 block(s) (0 queued 0 ignored) including 1162 txs in 3.915381827s. #1083988 [3ff3cc37 / 5db2cea7]
I0305 17:40:08.434452   10833 blockchain.go:1251] imported 256 block(s) (0 queued 0 ignored) including 1350 txs in 4.618004564s. #1084244 [55d6cbb2 / 722f56a4]
I0305 17:40:12.582012   10833 blockchain.go:1251] imported 256 block(s) (0 queued 0 ignored) including 1274 txs in 4.146564747s. #1084500 [fe0f2e27 / ca63792c]
I0305 17:40:15.234566   10833 blockchain.go:1251] imported 256 block(s) (0 queued 0 ignored) including 1262 txs in 2.645272129s. #1084756 [03653029 / 761d29e0]

I assume this means that my client is still downloading the blockchain. Is there a way I can tell how much longer this is going to take and how much space it will take on my machine? Is anything done to conserve space such as block compression and/or digesting?


texts:
I'm designing a new business with blockchain technology. And I would like to create a very user friendly app. I do not want to force people to have a wallet and ethers to interact with blockchain.

So I designed a process to interact on the blockchain with user friendly approach.

Steps : - a user create an account on an application - once logged the user do an action and want communicate with blockchain - the application will estimate the amount of gas to make the transaction on Ethereum - the application will convert ethers amount on eur - the application will ask the user to pay with credit card - when the application received payment, the application will use its own wallet to sign and send the transaction - once the transaction has been mined and validated, the application will store the transaction receipt on database

I would like to know if this model is correct, feasible and interesting.

Thanks


texts: Is it possible to call debug_traceTransaction from nodejs?

texts:
Following answer (https://ethereum.stackexchange.com/a/9437/4575)  [ 1 ] guide us to call debug_trace through using geth:

  As documented in debug.traceTransaction(...), you can only access this API call using the geth JavaScript console or the JSON-RPC API. There
  is no web3 API that I know of. There are some unofficial extension
  web3 APIs, but I don't know if debug.traceTransaction is supported by
  these. Looks like you have to use JSON-RPC to access this data.

but I was wondering is it possible to call debug_Transaction inside nodejs ?

I tried the steps on https://ethereum.stackexchange.com/a/9462/4575 [ 2 ] but it seems does not work for me and this answer seems contradict with the previous answer I have lined on [ 1 ].

var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

web3.currentProvider.sendAsync({
        method: "debug_traceTransaction",
        params: ['<transaction_id>', {}],
        jsonrpc: "2.0",
        id: "2"
    }, function (err, result) {
        console.log( result );
    });

Output result:

{ jsonrpc: '2.0',
  id: '2',
  error:
   { code: -32601,
     message: 'The method debug_traceTransaction does not exist/is not available' } }

Thank you for your valuable time and help.


texts: How to call a contract method using the eth_call JSON-RPC API

texts:
Ok, so I'm trying to call a contract method using the methods provided by the Ethereum JSON RPC interface. The JSON RPC is running on an Ubuntu machine. Unfortunately, I can't really get a result back from the test contract I created.

The first thing I did was start Go Ethereum on the Testnet with:

geth --rpc --testnet

I then open another console and open the JS console with

geth attach

I then compiled my contract using Browser Solidity, where my code is:

 contract test { function double(int a) returns(int) {   return 2*a;   } }

Which gives me the following byte code:

606060405260728060106000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480636ffa1caa146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000816002029050606d565b91905056

Then I created the contract with:

curl localhost:8545 -X POST --data '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from": "0x8aff0a12f3e8d55cc718d36f84e002c335df2f4a", "data": "606060405260728060106000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480636ffa1caa146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000816002029050606d565b91905056"}],"id":1}

Which gives me back the transaction hash, which I use to get the contract address:

curl localhost:8545 -X POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x8290c22bd9b4d61bc57222698799edd7bbc8df5214be44e239a95f679249c59c"],"id":1}'

Which gives me back the following:

{"id":1,"jsonrpc":"2.0","result":{"transactionHash":"0x8290c22bd9b4d61bc57222698799edd7bbc8df5214be44e239a95f679249c59c","transactionIndex":"0x0","blockNumber":"0xd32da","blockHash":"0xf13f185f0eb1e4797885400e3b371c972eedebcf3eef27815a45b649283ec669","cumulativeGasUsed":"0x14293","gasUsed":"0x14293","contractAddress":"0x5c7687810ce3eae6cda44d0e6c896245cd4f97c6","logs":[]}}

I then wanted to call the method "double" with the number "5". The Contract ABI documentation says that you have to take the first 4 bytes of the Keccak hash.
The method signature is

double(int)

Which gives the hash with web3.sha3("double(int)":

6740d36c7d42fba12b8eb3b047193c9761224c267d7a2e96dc50949860652317

The first four bytes, prefixed with "0x" are:

0x6740d36c

The documentation then tells to take the parameter, encode it in hex and pad it left to 32 bytes. Which would be the following, using the number "5":

0x0000000000000000000000000000000000000000000000000000000000000005

In total, the encoded string should look like this:

0x6740d36c0000000000000000000000000000000000000000000000000000000000000005

So, using this to call the method:

 curl localhost:8545 -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from": "0x8aff0a12f3e8d55cc718d36f84e002c335df2f4a", "to": "0x5c7687810ce3eae6cda44d0e6c896245cd4f97c6", "data": "0x6740d36c0000000000000000000000000000000000000000000000000000000000000005"}, "latest"],"id":1}'

Which gives me this result:

{"id":1,"jsonrpc":"2.0","result":"0x"}

Am I doing something wrong here or forgetting an important step?

Also, are there any way to access already-existing methods within the Go Ethereum library that would free me from having to implement for example methods that to the padding myself?

Thank your very much in advance!


texts: Passing more than 20 parameters in solidity

texts: How to pass more than 20 parameters in solidity function? I have tried using array[] parameter that uses pragma ABIENCODERV2 experimental feature. But this feature cannot be used in production purpose.So is there any other way which passes 20 parameter to the solidity function at a time?


texts: Hyperledger Besu: Unable to decode the hex string returned by solidity function containing multiple values

texts:
I have set  up a Hyperledger Besu network for private transactions using Orion.
I am using a javascript client to write to and read data from a smart contract
written in Solidity. I am following the approach as described here: https://github.com/ConsenSys/web3js-eea/tree/master/example/multiNodeExamplePrivacyGroup
My smart contract function returns back multiple values and the output is encoded in Hex format.
Problem: I am not able to decode the Hex data and convert it into ascii or UTF-8 string so that I can use the returned data in my Javascript client app.
How I can parse or decode the hex string in the output so that I can identify and read the multiple values in my javascript client?
Below you see the log which shows the output as logged by the Javascript client. Only one piece of the data is decoded well and it is the description string "Package is super damaged!" but not the other values.
console.log:
GOT Value from http://10.0.0.46:8545:
{
  from: '0x62a...1f9787',
  to: '0x408b...d3d',
  output: '0x00000000000000000000000062ac1677fdeea5c187e3d8ab6ad200bb951f978700000000000000000000000000000000000000000000000000000000000007770000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000005fd7d50f00000000000000000000000000000000000000000000000000000000000000195061636b6167652069732073757065722064616d616765642100000000000000',
  commitmentHash: '0xf6b5356117958ef625bfeae49bab832c06de798bc67e1de3a9d166d4640e265d',
  transactionHash: '0x5f09b2d984e977e3fdd86299c12dc1bc5ef57b9bc264f63632d97e0c94434154',
  privateFrom: 'JpYbuv...SE=',
  privacyGroupId: 'omCbE+ixKq...MTw6M=',
  status: '0x1',
  logs: [],
  logsBloom: '0x00...000',
  blockHash: '0x3a5d43856e1f80b12497a0177e55a2c14c55d3088fa17409496eccb132c39f19',
  blockNumber: '0xad2',
  transactionIndex: '0x0'
}
GOT result.output hex to ascii from http://10.0.0.46:8545: b¬wýî¥ÁãØ«jÒ»wÀ_×ÕPackage is super damaged!

Code snippet (Solidity smart contract function):
function value(uint _deliveryNumber) view public returns (address, uint, ClaimStatus, Category, string memory, uint)  {
        return (claims[_deliveryNumber].issuer, claims[_deliveryNumber].deliveryNumber, claims[_deliveryNumber].status, claims[_deliveryNumber].category, claims[_deliveryNumber].description, claims[_deliveryNumber].timestamp);
    }

Code snippet (Javascript client):
 const getValue = (value, url, address, privateFrom, privacyGroupId, privateKey) => {
  const web3 = new EEAClient(new Web3(url), 2018);
  const contract = new web3.eth.Contract(ClaimsAbi);

  // eslint-disable-next-line no-underscore-dangle
  const functionAbi = contract._jsonInterface.find(e => {
    return e.name === "value";
  });

  const functionArgs = web3.eth.abi
  .encodeParameters(functionAbi.inputs, [value])
  .slice(2);

  const functionCall = {
    to: address,
    data: functionAbi.signature + functionArgs,
    privateFrom,
    privacyGroupId,
    privateKey
  };

  return web3.eea
    .sendRawTransaction(functionCall)
    .then(transactionHash => {
      console.log("transactionHash:" + transactionHash);
      return web3.priv.getTransactionReceipt(
        transactionHash,
        orion.node3.publicKey
      );
    })
    .then(result => {
      console.log(`GOT Value from ${url}:`, result);
      console.log(`GOT result.output hex to ascii from ${url}:`, web3.utils.hexToAscii(result.output));
      return result.output;
    });
};


texts: using "eth_sendRawTransaction" by Go but got invalid argument 0: json: cannot unmarshal non-string into Go value of type hexutil.Bytes

texts:
I signed my transaction and my transaction used the standard structure: *types.Transaction
here is my transaction:
to := common.HexToAddress(toStr)
gasPrice_ :=new(big.Int).SetUint64(gasPrice)
realValue := myTools.GetRealDecimalValue(valueStr,18)
amount,_ := new(big.Int).SetString(realValue,10)
nonce := r.nonceManager.GetNonce(fromStr)
data := []byte("")

transaction := types.NewTransaction(nonce.Uint64(),to,amount,gasLimit,gasPrice_, data)

signTx,err := myTools.SignETHTransaction(address,transaction)

txHash = ""
methodName := "eth_sendRawTransaction"
err = r.client.GetRPC().Call(&txHash,methodName,signTx)

but I got an error :
invalid argument 0: json: cannot unmarshal non-string into Go value of type hexutil.Bytes

It said its a json error, but I have no way to solve it. Help,plz.
And if
txRlpData,err := rlp.EncodeToBytes(signTx)
err = r.client.Getrpc().Call(&txHash,methodName,common.BytesToHash(txRlpData))

still got an error:
rlp: expected input list for types.txdata


texts:
I have used Ganache to compile and deploy my contract successfully. Now I would like to do the same on the Ropsten network using my Metamask account. I don't want the Metamask plugin to pop up every time, therefore I'm using it in the background.

Here is my code:

from web3 import Web3, HTTPProvider

w3 = Web3(HTTPProvider('https://ropsten.infura.io/v3/ce8e130db56748dba7af3ebd7fbe4430'))

w3.eth.defaultAddress = <metamask address>

I'm receiving the following error when I try to deploy:

Traceback (most recent call last):
  File "walkthrough.py", line 29, in <module>
    greeter_interface = ContractInterface(w3, 'Contract', contract_dir)
  File "D:\blockchain\bpoc\scripts\interface.py", line 23, in __init__
    self.web3.eth.defaultAccount = web3.eth.coinbase
  File "D:\blockchain\venv\lib\site-packages\web3\eth.py", line 82, in coinbase
    return self.web3.manager.request_blocking("eth_coinbase", [])
  File "D:\blockchain\venv\lib\site-packages\web3\manager.py", line 112, in request_blocking
    raise ValueError(response["error"])
ValueError: {'code': -32601, 'message': 'The method eth_coinbase does not exist/is not available'}


texts:
in many standard documentation and many blogs, I have found the example for list with two strings like below

[“cat”, “dog” ] -> C8 83 636174 83 646F67

and thats how it is decoded
1) Retrieve the first byte : 0xc8
2) Find the closest Byte Range which the first byte falls within; In this case, the First byte falls within the range [0xc0 .. 0xf7] hence the data is a List.
3) Create an empty List [] to accumulate
4) Length of the list, [0xc8 -0xc0] = 8
5) Start deciphering after c8 to get the encoded data from the List until end of List. C8 83 63 61 74 83 64 6F 67

We know we have a list [ and it has eight elements], now let’s look at what’s inside the List.

6) Figure out length which is: first byte-range, 0x83–0x80 = 3
7) The data type is String, and its length is 3
8) Parse and decipher the next 3 bytes 0x63, 0x61, 0x74
9) Repeat Steps 6 through 8 until end of the list for the next set of bytes resulting in 0x83, 0x64, 0x6f, 0x67

10) Calculate the Length and interpret the data, in this case, the data is 0x64,0x6f,0x67.

Every thing looks good and as per the RLP documentation But

I was wondering how we will decode if the example will be something like below

[131, “dog”, “cat”]

1) It is a list so start 0xc0
 2) 131 → 0x83 ,
 3) dog to byte string → [0x80+3, 0x63, 0x61, 0x74]
 4) cat to byte string → [0x80+3, 0x64, 0x6F, 0x67]

Final encoding → [0xc7, 0x83, 0x83, 0x63, 0x61, 0x74, 0x83, 0x64, 0x6F, 0x67]

Now during decoding
→ 0xc7 — indicate that it’s a list
→ list length is 7 (0xc7–0xc0)
→ Now what 0x83 should be assumed it could indicate that its is a byte string with 3 length or is it a number 131 which has a hex value 0x83
 →


texts: infura return null when eth_getTransactionReceipt

texts:
I am trying to send some test ether on Rinkeby network using Infura, Im using some php library to make it.
<?php
use Web3p\EthereumTx\Transaction;
use Web3\Web3;

$valueSend = dechex(0.1 * 10**18);

$transaction = new Transaction([
  'nonce' => '0x'. dechex(282),
  'from' => '0xaDa4f3bB20A3658c1d25B6e687F5CF1b20e38BaA',
  'to' => '0xa73537dF8aECBE66240C2C53b748AF2F30FD2b71',
  'gas' => '0x76c0',
  'gasPrice' => '0x9184e72a000',
  'value' => '0x'.$valueSend,
  'chainId' => 4,
]);

// sign by private key
$signedTransaction = $transaction->sign('<PRIVATE_KEY>');

// Call Function
$createTransaction = json_decode(loadCURL('0x'.$signedTransaction, 'eth_sendRawTransaction'));
$getTransaction = json_decode(loadCURL($createTransaction->result, 'eth_getTransactionReceipt'));

/***************************/
function loadCURL($txKey, $method){
    $url = 'https://rinkeby.infura.io/v3/461ae29f1e0f4509bbe4fe9bf0440fd4';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $data = array(
        'jsonrpc' => '2.0',
        'method' => $method,
        'params' => [$txKey],
        'id' => 4,
    );
    $payload = json_encode($data);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    if(curl_errno($ch)){
        throw new Exception(curl_error($ch));
    }

    return $response;
}

result: eth_sendRawTransaction
{
    "jsonrpc": "2.0",
    "id": 4,
    "result": "0x952f8831051cb7febe93d7409afc470a00953e0eece686a1be120afb4d43401f"
}

result: eth_getTransactionReceipt
{
    "jsonrpc": "2.0",
    "id": 4,
    "result": null
}

and I cant check on https://rinkeby.etherscan.io/tx/<Transaction_Hask>
https://rinkeby.etherscan.io/tx/$createTransaction->result
Please let me know problem in my code, I want use PHP to create transaction and can check address info.


texts: Custom tokens disappear after closing Ethereum Wallet

texts: I'm on Ethereum Wallet 0.9.0 and I need to add the ICO token addresses every time I restart the wallet. The custom token(s) don't get saved after I exit the wallet. How do I solve this?


texts: Remix + Metamask: The method personal_sendTransaction does not exist

texts:
I'm trying to deploy a contract to the Rinkeby Test Network through Remix and Metamask.

Metamask seems to be properly configured:

However, at Remix Run tab, the address dropdown shows no accounts:

If I go to Remix Settings and enable "personal mode", some addresses appear in the dropdown, but they are not my metamask address.

If I try to deploy the contract, I get the following error:

   The method personal_sendTransaction does not exist

At this point I'm a bit lost.

What am I doing wrong?

Edit:

Remix settiings:

Metamask settings:

However, I'm still getting this error:

  Cannot get account list: Error: The method personal_listAccounts does not exist/is not available

I'm using MetaMask @ 6.4.1.


texts:
I have recently tried to build my own cryptocurrency on the Ethereum platform and deployed. All seemed to work fine but now the contract is still not deployed / completed. Is it normal that it takes a while sometimes? You can check it here https://etherscan.io/address/0xD0d798A8ecc21C49c9ab29F513C2257083072e97

All the best and thanks for your reply.
Tim


texts: Invalid response at function call from time to time

texts:
I am continuously trying to fetch all pair addresses from a PancakeSwap contract but while doing so it always fails after some time saying:
Error: invalid response - 0
    at exports.XMLHttpRequest.request.onreadystatechange (/Users/paulus/node_modules/ethers/utils/web.js:84:29)
    at exports.XMLHttpRequest.dispatchEvent (/Users/paulus/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:591:25)
    at setState (/Users/paulus/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:610:14)
    at exports.XMLHttpRequest.handleError (/Users/paulus/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:532:5)
    at ClientRequest.errorHandler (/Users/paulus/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:459:14)
    at ClientRequest.emit (node:events:378:20)
    at TLSSocket.socketErrorListener (node:_http_client:462:9)
    at TLSSocket.emit (node:events:378:20)
    at emitErrorNT (node:internal/streams/destroy:188:8)
    at emitErrorCloseNT (node:internal/streams/destroy:153:3) {
  statusCode: 0,
  responseText: 'Error: getaddrinfo ENOTFOUND bsc-dataseed3.defibit.io\n' +
    '    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26)'
}

Also I didn't recognize any patterns which means it fails at different points and the time intervals also vary. My function to get all the addresses looks like this:
async function fetchPairAddresses2() {
    const allPairsLength = await pancakeFactory.allPairsLength()
    let alreadyFetched = pancakePairs.length

    for (let i = alreadyFetched; i < allPairsLength; i++) {
        let pairAddress = pancakeFactory.allPairs(i)
        writeToFile(await pairAddress)
    }
}

Any ideas? Maybe I could switch the RPC when such an error occurs but I don't know how I could do that if it is possible.
EDIT:
There should be no problem with my internet connection cause when I cut my connection I get an other error:
Error timeout
    at Timeout._onTimeout (/Users/paulus/node_modules/ethers/utils/web.js:54:20)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7)


texts: Help! Parity Error: account not found for current chain (ropsten)

texts:
I have downloaded Parity and its connecting with accounts created from Pariy-Ui, When I tries to connect Parity using an account created from MetaMask Chrome Extension, then its showing below error message:

Account 0x3314…b168 not found for the current chain. You can create an account via RPC, UI or `parity account new --chain ropsten --keys-path /home/user/.local/share/io.parity.ethereum/keys`.

I am using below command in order to run Parity and unlock account:

parity --chain ropsten --rpcapi "eth,net,web3,personal,parity" --unlock 0x00E76a64CF25d7T23rRYE0aD74as214Bc2F0F1 --password $HOME/password1.txt

Any help would be appreciated.


texts: possible to implement abstract base function with property in derived contract?

texts:
Is there any way to have an abstract base contract with an abstract function which gets implemented in a derived contract by a property (and not a function)?

e.g. the following attempts failed:

contract Base {
    //function f() public returns (uint256);
    function f() external view returns (uint256); // also not working
}

contract Derived is Base {
    uint256 public f;
}

In all cases Derived is still abstract because it does not implement f from the Base contract although the ABI is identical. A typical scenario is e.g. a tokens which implements the ERC20 interface an totalSupply might just be implemented with a property and not a getter and a property (in most simple cases that would suffice).


texts:
I'm currently performing my Ethereum logic using pyethereum and then sending transactions via a remote node using https://infura.io/.  It's not fast enough for my needs.  What can I do to ensure my transactions hit the blockchain as fast as possible?  Should I run a full node myself?  Is there something better?

Please ignore gas price for this discussion.


texts: Why does ethereum.org suggest different prototypes for 'buy' and 'sell' functions?

texts:
Scrolling https://www.ethereum.org/token approximately half way down, I read this:

  The next step is making the buy and sell functions:

function buy() payable returns (uint amount){
    amount = msg.value / buyPrice;                    // calculates the amount
    require(balanceOf[this] >= amount);               // checks if it has enough to sell
    balanceOf[msg.sender] += amount;                  // adds the amount to buyer's balance
    balanceOf[this] -= amount;                        // subtracts amount from seller's balance
    Transfer(this, msg.sender, amount);               // execute an event reflecting the change
    return amount;                                    // ends function and returns
}

function sell(uint amount) returns (uint revenue){
    require(balanceOf[msg.sender] >= amount);         // checks if the sender has enough to sell
    balanceOf[this] += amount;                        // adds the amount to owner's balance
    balanceOf[msg.sender] -= amount;                  // subtracts the amount from seller's balance
    revenue = amount * sellPrice;
    msg.sender.transfer(revenue);                     // sends ether to the seller: it's important to do this last to prevent recursion attacks
    Transfer(msg.sender, this, amount);               // executes an event reflecting on the change
    return revenue;                                   // ends function and returns
}

Why does the sell function take the input amount as an argument, whereas the buy function receives it inside msg.value?

I initially thought the reason might be that standard wallets (Mist, MyEtherWallet, Parity, etc), which see the payable keyword and detect this function as an "Ether Receiver", pass everything inside msg.

But it doesn't quite make sense to me that ethereum.org conforms to standard wallets (i.e., ethereum.org should be the one dictating the standard, not the one complying to it).

So what exactly am I missing here?

Thank you!


texts: unable to insert into a struct from a address where the contract is not deployed

texts:
I am planning to make a blog using solidity. I've made a contract. Here it is.

pragma solidity ^0.4.0;

contract Post{
    address author;
    uint _id;
    struct UserDetails{
     string title;
     string description;
     address owner;
}

mapping (uint => UserDetails) postDetails;

function Post() public{
    author = msg.sender;
}

function addPost(string title, string description) public returns (uint){
    _id += 1;
    postDetails[_id] = UserDetails(title, description, author);
    return _id;
}

function getPost(uint id) constant returns (string title, string description, address owner){
    return (postDetails[id].title, postDetails[id].description, postDetails[id].owner);
}

function getPostCount() constant returns (uint){
    return _id;
}

}

now I want to call addPost function from another pc of my network which has different etherbase accounts and both pcs are running in same private-net. Is it possible? Or how can this be done on another approach.


texts: Distribution of chain-reorganization events?

texts:
I'm curious about, for instance, the frequency of chain reorganizations, and the distribution of their depths. Is this information available anywhere?

Mostly this is because I'm interested in rules for monitoring an ethereum node and comparing it to, say, etherscan's block history, in order to raise an alarm if the node is running incorrectly. But I'm also interested in things like how exchanges determine the depth at which they'll consider a transaction to be settled.


texts: Ethereum wallet is stuck at "looking for peers"

texts:
I'm trying to create a private network or test network to work with smart contracts. But when I start ethereum wallet it is always getting stuck at "Looking for peers....". Below is the screenshot for the same.

Can someone help me with this?

I'm using ubuntu 16.04(64-bit) and Geth version is: 1.7.3-stable


texts: Confusion due to shared keystore of Mist and Ethereum Wallet

texts:
I wasn't aware of the fact that Mist and Ethereum Wallet would use the same Geth and keys in the background and as a result made a big mistake to operate them at the same time...

So now there's the following weird situation, which I am trying to understand:

Scenario 1:

Open Ethereum Wallet (mainnet)
I can see an "Account 1" with 0 ETH
Status: Remote, 8,xxx,xxx blocks, last block xx seconds ago

Scenario 2:

Open Mist on testnet (Ropstein)
Open Ethereum Wallet (mainnet)
I can see an "Account 2" in Ethereum Wallet with 0.09xxx ETH (https://etherscan.io/address/0x72c674E4FE33C71D839a81d925ec618962320fd0)
Status in Ethereum Wallet: Remote, 8,xxx,xxx blocks, xx minutes ago (this does never update, just keeps going up)
Try to transfer it out: "Insufficient funds for gas * price + value", I get this error even if I only transfer 0.04 and have plenty of ETH left

What is happening?

Thank you for your help!


texts: Price of PYRO on Uniswap doesn't match price on Coinbase. If I make a small trade on Uniswap, can I expect Uniswap price to update?

texts: I'm a noob to crypto trading. The price of PYRO on Uniswap is reflecting much, much lower than the price shown on Coinbase. If I make a small trade on Uniswap, should I expect the Uniswap price to update? I successfully swapped a very small amount of PYRO for ETH, but the price hadn't been updated at all when I immediately previewed a 2nd, similar swap (it was still reflecting much, much lower than the price shown on Coinbase). I was told that the price on uniswap is updated by trade operations, so I expected to see it update in Uniswap.


texts:
I'm building a business application (in a private ethereum network) in which certain users should be able to perform some transactions.

The thing is that the blockchain authentication is hard to understand for business users, they are used to having username/password and the possibility to reset their passwords.

I was thinking of creating a web application in which users authenticate with username/password and in the server side of the webapp i have mapped the username with the ethereum account.
This way each time a user makes a transaction, the backend unlocks the ethereum account from geth and performs the transaction on behalf this account.

Does anyone knows if this is a bad idea or not? Any possible consequences?

Thanks!


texts: No bytecode,no ABI code showed in the Remix

texts:
Sir,
   I use Remix to developing smart contracts. After I develop one contract ,I  prepare to copy the bytecode or ABI code. I click the Details button,the Remix doesn't show the bytecode or ABI code information. This works before,but not works now . I use JavaScript VM and Solidity version is 0.4.4.

How to solve this problem?

Thanks~


texts:
I was using a wallet on uniswap. and a wallet uniswap provided. I attached a MetaMask wallet and now that is the default wallet. I cannot access the other wallet though I can see the eth in the wallet. It stated it was on injected and needed to confirm via the wallet.  However, there isn't an injected wallet listed.  How do I recover this eth?
Does Uniswap allow a wallet to be attached via a QR code? If so, I can attach the wallet that way.


texts: How to send some ether to all token holders?

texts: I created contract A which generates and sends my tokens. I would like to send some ether to each token holder from another contract B. So how to find all token holders from contract B?


texts: Why won't this Ether distribution function execute properly?

texts:
I have written and deployed the following contract (source published):

https://ropsten.etherscan.io/address/0xCaD97e58Ea88De59802F676e911E60099C5Df714

When executing the function 'fillBid' using Mist I am being told: "it seems this transaction will fail if you submit it it may consume all the gas you send"

Sending the transaction non the less (https://ropsten.etherscan.io/tx/0x4c309daead9b976aa742c0ac30a75a5f6d22a083f46ba1753c88115a8b391c69) results in:

"Warning! Error encountered during contract execution [Bad instruction]"

I am starting to think it is something bleedingly obvious but I just can't figure it out. I am especially perplexed because there are literally no conditions on it.

UPDATE 2017-07-02:

(Almost) exact same code over at https://ropsten.etherscan.io/address/0x26c8532AE5953053Ea721c9922c3Ec8A1ab8129a

works just fine: https://ropsten.etherscan.io/tx/0xe8f0f4e2ea04a4cccb370766fc94e2d3f9d3e2e585865285c11a41433a4dd7b0

UPDATE 2017-07-03:

So I removed everything but the amount calculations and the transfer commands and it still fails: https://ropsten.etherscan.io/tx/0x683bcdbc4f4250b439b53692302dc8e75c6f42f6ce8243200b94d74565964267

UPDATE 2017-07-03_2: I have isolated the problem to this code:

uint256 _amountEthart;
_amountEthart = highestBidPrice / 40;
registrar.transfer(_amountEthart);

Executing fillBid1 errors out: https://ropsten.etherscan.io/tx/0xddc9505f4e794310091ffad933594da182d4c18f83764e33b39d3a5ca065e365

Executing fillBid or fillBid2 is fine: https://ropsten.etherscan.io/tx/0xce73e6a7cbc95e28538a29ff3e774462697e985897a5b924d1f719c46194bd12


texts: Ways to access the live (and test) Ethereum blockchain

texts:
I know that I can access the live Ethereum blockchain (and the test "ropsten" blockchain) blockchain using geth, and I know I can access a fake local blockchain with tools like truffle.

What I'd like to know is ways to access the live blockchain without needing to download the entire thing.
Ideally with instructions or links to instructions that are straight forward enough that I can actually go and put something on the blockchain right now.

When I say access, I'd like to do the following:

install my own smart contracts
run smart contracts


texts: How to catch error thrown by require in node.js

texts:
I have a solidity function with only one statement i.e., require(). My logic is if that function throws error then the data is invalid otherwise valid. But that error is not caught in err parameter of callback but instead express's error middleware is invoked. Although there is a way to specifically catch that error in middleware ( something like: app.use('/api', function(err, req, res, next(){ ... }) }. But that would put the could in different file which i dont want. Is there any way to catch it.

//routes/user.js
router.get('/', function(req,res,next){
try{
myContract.verify(username, password, function(err,result){
if(!err){
res.render('error','user already exist');
}
});
}catch(e){
// Do something
}
});

//myContract.sol

contract mContract {

function verify(string memory _user, string memory _passwd) public view {
require(
      (keccak256(bytes(userMap[_user].user)) == keccak256(bytes(_user))) &&
      (keccak256(bytes(userMap[_user].passwd)) == keccak256(bytes(_passwd))),
      "Invalid"
);
}

I have used require() such that when the user/passwd does not match the require function throws error, which should be caught in err parameter of callback provided to contact method; otherwise it renders error page saying 'user already exist'. As of now when condition within require fails, the control flow does not go inside catch block but instead goes to error handler function defined in app.js. Although i can catch that error, using the example mentioned above, but then logic will be inside app.js.


texts: ETC/ETH split still safe after October 18 2016 hardfork?

texts:
Does this Steemit solution still work in exactly the same manner as before the HF of October 18th? Do I need to wait for the second HF/ETC HF coming next week, or can I try splitting already (since the etc price is dropping)?

https://steemit.com/ethereum/@pauls/ethereum-fork-step-by-step-guide-to-safely-splitting-your-eth-etc

One more question: is it safe to use my etc deposit address on poloniex as my etc recipient address for the split contract? This way i don't have to create a pre(dao)fork etc wallet in mist

Thanks in advance!


texts: What would cause nodes on a private blockchain to gradually lose connectivity?

texts:
I have a private blockchain with 6 nodes, and a total of three miners.  When I initialize the blockchain everything looks great and the nodes find each other starting with the bootnodes.

After about 12 hours the connections drop to 3 or 4 peers, and by 48 hours each node has zero peers.  I can't figure out why.

The times are synced.

Each one uses the exact same chain specification file (verified by md5sum)

The chain spec has a unique networkid.

The nodes do find each other in the beginning.  And they exchange data with each other.

Most of the nodes are on the same local area network.

All machines have 30303 and 30304/udp open and the bootnodes also have 30301 open.

I can manually add nodes back using api.parity.addReservedPeer('enode://....') but even when I do, the node that I add is the only one that shows up.  They do not discover each other even if I add one node in common.

What could I be doing wrong?


texts:
pragma solidity 0.4.16 contract code - Am receiving the following message:

  Could not compile source code

  No visibility specified.  Defaulting to "public".

  function transfer (address, receiver, uint, amount);

  ^ ----------------^  ,


texts: I want to change 17k addresses password on ubuntu server

texts:
I have 17k ethereum addresses. I want to change passphrase all of them. Are there any way to change all addresses passphrase?

geth account update 0x... It is really hard to change 17k addresses password. I need suggestion.


texts: How does BtcRelay ensure the transaction was signed by the claimer?

texts: I noticed in the btcrelay docs that it asks for the tx index, raw transaction, merkle sibling and blockhash. It does not ask for the user to prove ownership of the key that created the transaction via a signed message so how does it ensure that someone else isn't claiming to have made the transaction when they haven't?


texts: Getting "VM Exception while executing eth_call: invalid opcode"

texts:
I have a very basic contract to test out some functionality, but when I call the functions getContractAddress() and getThrowaway(), I get the invalid opcode error. I'm using truffle and testrpc, and I get the error after running some commands in truffle console (below).

Here is the full contract in question:

pragma solidity ^0.4.4;

import "./MetaCoin.sol";

contract Guess {

// Constructor, gives this contract 10k coins
function Guess(){
    MetaCoin metaCoin = new MetaCoin(); //I think this should give the contract 10k coins
}

function getContractAddress() constant returns (address){
    return this;
}

function getThrowaway() constant returns (string){
    return "Hello";
}

}

And here are the commands I'm running in truffle console.

guess = Guess.deployed();
guess.then(function(instance){return instance.getThrowaway.call();})

Same problem when I run getContractAddress().

Here is the full repo for reference: https://github.com/willikers19/GuessTheEth

When I run commands in a similar fashion from this contract (https://github.com/willikers19/ethereum-demo-tools/blob/master/GeektSolidity/contracts/Geekt.sol), they succeed so it feels like I'm doing something wrong.


texts: Problem deploying a smart contract in web3 to the Ropsten testnet

texts:
I am having trouble deploying a smart contract to the Ropsten testnet.  I have dug through a lot of tutorials and questions and I cannot seem to find an suitable answer.  Thanks so much for you time!

Currently, the code runs and appears to be successfully deploying.  However, it will always use all the gas I provide and never actually deploy.  Here is the account I am trying to deploy from: etherscan.  You can see that whenever I deploy a contract, it errors out with not enough gas.  As I understand it, there should be plenty of gas provided.

Here is my code in question:

const endpoint = 'https://ropsten.infura.io/<mykey>';
const solc = require('solc');
const Web3 = require('web3');
const EthTx = require('ethereumjs-tx');
const web3 = new Web3(new Web3.providers.HttpProvider(endpoint));

const addr1 = "0xa8f157e9c445faad451bd07e6e8780db76f066b3";
const pKey1 = 'd6be926bd949...';               //private key
const pKey1x = new Buffer(pKey1, 'hex');

const source = `contract HellowWorld {         //source in plaintext for readability
  function displayMessage() constant returns (string) {
    return "Hello";
  }
}
`
const compiled = solc.compile(source);

const estGasPrice = new Promise((resolve) => {
  resolve(web3.eth.getGasPrice())
});

const getNonce = new Promise((resolve) => {
  resolve(web3.eth.getTransactionCount(addr1))
});

Promise.all([estGasPrice, getNonce])
  .then(([gasAmt, nonce]) => {
    let tx = new EthTx({
      from:     addr1,
      nonce:    Web3.utils.toHex(nonce),
      value:    Web3.utils.toHex(10000),
      gasLimit: Web3.utils.toHex(10000000),
      gasPrice: Web3.utils.toHex(2000000000),
      data:     Web3.utils.toHex(compiled.contracts[":HellowWorld"].bytecode)
  })
  tx.sign(pKey1x)
  let serializedTx = `0x${tx.serialize().toString('hex')}`
  web3.eth.sendSignedTransaction(serializedTx, (err, data) => {
    return !err
      ? console.log(`Success! Data: ${data}`)
      : console.log(`Error: ${err}`)
    })
  })
  .catch((err) => {
    console.log('Error' + err)
  })

And for reference, the error I get on the terminal when I run this code is:

Error: Transaction ran out of gas. Please provide more gas:

My intuition is that I haven't formatted the raw transaction correctly.  Or it may be that I don't understand how much gas this thing needs.  Whatever the case, I appreciate any insight you can provide!

EDIT:  My code is refactored, should make more sense


texts:
To create an upgradeable contract I have to use multiple proxies. The contract applies to Proxy A, then Proxy A applies to Proxy B. But delegatecall doesn't work in this case.

The simplified code of my contracts:

pragma solidity ^0.4.24;

contract A {
    uint256 public value = 100;

    function mul() public {
        value *= 2;
    }
}

contract B {
    uint256 public value = 200;
    address a;

    constructor(address _a) {
        a = _a;
    }

    function delegate() public {
        a.delegatecall(bytes4(keccak256("mul()")));
    }
}

contract C {
    uint256 public value = 500;
    address b;

    constructor(address _b) {
        b = _b;
    }

    function delegate() public {
        b.delegatecall(bytes4(keccak256("delegate()")));
    }
}

delegate() function works only if it called at contract B

Thanks!


texts: If we are running a private chain with multiple nodes, as a connected node still do I need to start mining?

texts:
I have a Private Ethereum Network. As a node I connected to the network as a peer. When I submit a transaction from my node, it won't fall into mining pool, in case I start mining on my node.

When I start mining on my node, the transaction get eventually mined.[1]

  Start mining:

  The transaction that has deployed the contract needs to be verified by
  the network, if we are running a private chain with a single node we
  will need to mine the transaction. [1]

[Q] If we are running a private chain with multiple nodes as a connected node still do I need to mine the transaction? As I understand each node is forced to do mining for their transactions to get into mining pool. Is there any way to push my transactions into mining pool without start mining?

Thank you for your valuable time and help.

[1] https://ethereum.stackexchange.com/a/9316/4575


texts: Private testnet transaction submitted but not executed

texts: I was able to setup a private testnet with geth and I was also able to deploy a contract which I previously tested in truffle and testrpc. I can also connect my meteor app to it. If I write some data to my contract with my app I see that the transaction was submitted but somehow it is not executed. What am I missing here?


texts: bytes32 comparison returning true when values are very near


texts:
So I'm trying to call Comptroller's function enterMarkets(address[] calldata cTokens) returns (uint[] memory). The problem that I have is if I call the function with my array of markets, it gives me the error, TypeError: Type address[1] memory is not implicitly convertible to expected type address[] memory.

I understand that the function expects an address array of an undefined length, but every method I can think of to pass an array to the function gives me the same error. For example, the following methods return the same error:

address[] memory markets = [address(cdaitoken)];
comptroller.enterMarkets(markets);

comptroller.enterMarkets([address(cdaitoken)]);


texts:
I am trying to deploy my contracts, but I keep getting the same error message:

   Deploying 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" -- sender account not recognized.

Here is my migrations.sol file:
pragma solidity >=0.4.21 <0.6.0;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

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

  modifier restricted() {
    if (msg.sender == owner) _;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}

Does anyone know why this is and could anyone assist me in resolving my issue?


texts: ethers.js - How to derive child addresses + private keys from HD private key

texts:
I have a HD private key which I have derived from my mnemonic using the ethers library. I would now like to derive child addresses and corresponding private keys from it.

Does anybody know how I can do this?

This is how I have obtained the HD private key:

const xKey = ethers.Wallet.fromMnemonic(...)

Thanks in advance!


texts:
The swarm doesn't support the backend of a website (this part I think we're working on with minimongo), and the block chain can't store confidential information... unless it's encrypted. Okay, so, is this really going to be a storage solution?

And is it really incentivized for business owners, trying to create Dapps? It sounds like anyone can just clone an app on the swarm and publish it themselves, leading to copyright infringement (similar to music file-sharing). Sure the incentive is there for peer to peer mining, but what about the business owners incentive to use swarm?

I want a website that'll work in normal browsers (chrome/firefox) without extensions. Does ethereum, as a technology, really have the capacity to be a storage solution for a website that needs a user database, with private credentials?


texts: I am having trouble doing the initial sync of Ethereum-Wallet, what can I do to troubleshoot?

texts:
I am trying to sync Ethereum-Wallet (aka Mist) for the first time.  Unfortunately, it is taking a really long time (days) and I was told that this should only take a couple hours.

What can I do to troubleshoot my problem or otherwise speed up the process?


texts: How data is secured on ethereum network?

texts: Blockchain is distributed decentralized database and same data is present on every node on network so now anybody on the network can see my data, so how it is secured over blockchain network?


texts: Quorum: Sending Private Transaction With Python

texts:
I am trying to experiment with GoQuorum and Python. I have read the documentation about how privateTransactions work and I am trying to perform one. Since Python's web3py does not support the sendTransaction(tx, {privateFor: }) I am trying to use the Tessera's API. So I am executing the following code.
set_hash = member_1_contract.encodeABI('set', args=[18])
r = requests.post('http://192.168.1.159:9081/send', json={"payload": set_hash, 'from': member_1_pub_key,
                                                          'to': [member_3_pub_key]})

I get the error HTTP 404. What am I supposed to do here?


texts: How to fix "address already in use" error when attempting to launch geth console?

texts:
I'm downloading the chain and I've processed more than 2 million blocks so far. I'm trying to attach to the geth console to view the syncing status, but I've tried typing geth console in another terminal (on Mac) and I get an error:

Fatal: Error starting protocol stack: listen udp :30303: bind: address already in use

If I've understood correctly I should type geth console and then eth.syncing.


texts: what is the right way to check out balance of erc20 token on geth console

texts:
I setup a private chain and deploy an erc20 contract. I tried sending transaction of balanceOf and can get nothing but a transaction number as the return value. how can i get the balance of erc20 on geth console? My code is given below FYI

var contract = eth.contract(abi).at(eth.accounts[0])
contract.balanceOf.sendTransaction(eth.accounts[0],{from:eth.accounts[0],gas:60000})


texts:
I have Solidity contract that is meant to send ether to someone. Unfortunately it's giving me a cryptic error message after I confirm the transaction in MetaMask.

I'm testing on a local ethereum network running on ganache and the project was built using a react truffle box.

Contract:

pragma solidity ^0.4.24;

contract Sender {
    uint256 public balance;

    function send(address _receiver) payable {
        msg.sender.transfer(msg.value);
    }

    function getBalance() public returns (uint) {
        return address(this).balance;
    }

}

JavaScript

userInputHandler = (event) => {
    this.setState({amountToPay: event.target.value})

    const contract = require('truffle-contract')
    const sender = contract(Sender);
    sender.setProvider(this.state.web3.currentProvider);

    this.state.web3.eth.getAccounts((error, accounts) => {
        sender.deployed().then((instance) => {

            console.log("Seems to explode after here" );
            return instance.sendTransaction({
                from: accounts[0],
                to: accounts[4],
                value: this.state.web3.toWei(this.state.amountToPay, "ether"),
                gas: "220000"}).then((result) => {

                console.log("result: " + result);
        })
    })
})

};

ErrorMessage

inpage.js:1
MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with payload
{
"id": 8476063269707,
"jsonrpc": "2.0",
"params": ["0xf87182011a85174876e80083035b609406c1939f6cbb68d42333f140cae815cc36d341b0880de0b6b3a764000080822d46a011d708c9d53a5e7e9195c32fab4f6f3cad259887436eadd521d93ac853541455a0176061761d6d14c063eb2b0c359457dec982d72d52f19bdf33fa8f5be20ed939"],
"method": "eth_sendRawTransaction"
} Error: VM Exception while processing transaction: revert

Uncaught (in promise) Error: Error: Error: [ethjs-rpc] rpc error with payload  Error: VM Exception while processing transaction: revert

Solution
send seems to be some kind of reserved word or function that was getting overridden. I changed the function name to sendMoney and all suggestions from @Jaime which fixed my problems.


texts: Ethj spring boot blockchain transaction app error the method subscribe is undefined for the type object

texts:
package org.web3j.web3jspringbootstarter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthCoinbase;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.web3jspringbootstarter.service.BlockchainService;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigInteger;

@SpringBootApplication
public class BlockchainApp {

private static final Logger LOGGER = LoggerFactory.getLogger(BlockchainService.class);

private final Web3j web3j;

public BlockchainApp(Web3j web3j) {
    this.web3j = web3j;
}

public static void main(String[] args) {
    SpringApplication.run(BlockchainApp.class, args);
}

@PostConstruct
public void listen() {

    web3j.transactionObservable().subscribe(tx -> {

        LOGGER.info("New tx: id={}, block={}, from={}, to={}, value={}", tx.getHash(), tx.getBlockHash(), tx.getFrom(), tx.getTo(), tx.getValue().intValue());

        try {

            EthCoinbase coinbase = web3j.ethCoinbase().send();
            EthGetTransactionCount transactionCount = web3j.ethGetTransactionCount(tx.getFrom(), DefaultBlockParameterName.LATEST).send();
            LOGGER.info("Tx count: {}", transactionCount.getTransactionCount().intValue());

            if (transactionCount.getTransactionCount().intValue() % 10 == 0) {

                EthGetTransactionCount tc = web3j.ethGetTransactionCount(coinbase.getAddress(), DefaultBlockParameterName.LATEST).send();
                Transaction transaction = Transaction.createEtherTransaction(coinbase.getAddress(), tc.getTransactionCount(), tx.getValue(), BigInteger.valueOf(21_000), tx.getFrom(), tx.getValue());
                web3j.ethSendTransaction(transaction).send();

            }

        } catch (IOException e) {
            LOGGER.error("Error getting transactions", e);
        }

    });

    LOGGER.info("Subscribed");

}

}

Where it says: "web3j.transactionObservable().subscribe(tx -> {"
I keep getting the error "the method subscribe is undefined for the type object".  Does anyone have any pointers on how to fix this?


texts: Contract addresses and Unused Wallet addresses

texts:
As I understand it, you can instantiate a contract at any valid address that hasn't yet received ether, by sending a transaction, which contains the contract code as the data payload, to that address. Is this correct?

I was wondering what would happen if I directed my client to generate an address and then sent a contract to that address before loading the new wallet with ether, and then subsequently sent ether to the address. Is there something with the nonce that prevents what I am describing?


texts:
Say I have a contract with several functions that apply various particular constants.

circumference = 628318 * radius / 1e5;
dividend = balance * 123 / 1e4;

It would be easier for readers to understand my contract by having these constants defined at the top, and then :

    uint public constant tau = 628318;
    uint public constant dividendYield = 123;
...
    circumference = tau * radius / 1e5;
    dividend = balance * dividendYield / 1e4;

Is there a significant extra memory cost for doing this?


texts: METAMASK NO confirmation popup (Truffle tutorial)

texts:
The first time i tried the pet shop tutorial of Truffle, it worked without problem.

The problem:
The second time today I don't get a metamask pop-up to confirm an adoption. It goes straight to "success". In Ganache I can see a contract call, but it says "value 0".

I checked:
Ganache server, port & metamask. All in order. I can even send ether from one account to the other through meta mask.

I also did migrate --reset.

I have no idea what the problem is. I get no console log errors.

Ganache:

Metamask:

App.js:

```JavaScript

App = {
  web3Provider: null,
  contracts: {},

  init: function() {
    // Load pets.
    $.getJSON('../pets.json', function(data) {
      var petsRow = $('#petsRow');
      var petTemplate = $('#petTemplate');

      for (i = 0; i < data.length; i ++) {
        petTemplate.find('.panel-title').text(data[i].name);
        petTemplate.find('img').attr('src', data[i].picture);
        petTemplate.find('.pet-breed').text(data[i].breed);
        petTemplate.find('.pet-age').text(data[i].age);
        petTemplate.find('.pet-location').text(data[i].location);
        petTemplate.find('.btn-adopt').attr('data-id', data[i].id);

        petsRow.append(petTemplate.html());
      }
    });

    return App.initWeb3();
  },

  initWeb3: function() {
    // Is there an injected web3 instance?
    if (typeof web3 !== 'undefined') {
      // App.web3Provider = web3.currentProvider;
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
    } else {
      // If no injected web3 instance is detected, fall back to Ganache
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function() {
    $.getJSON('Adoption.json', function(data) {
      // Get the necessary contract artifact file and instantiate it with truffle-contract
      var AdoptionArtifact = data;
      App.contracts.Adoption = TruffleContract(AdoptionArtifact);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      // Use our contract to retrieve and mark the adopted pets
      return App.markAdopted();
    });
    return App.bindEvents();
  },

  bindEvents: function() {
    $(document).on('click', '.btn-adopt', App.handleAdopt);
  },

  markAdopted: function(adopters, account) {
    var adoptionInstance;

    App.contracts.Adoption.deployed().then(function(instance) {
      adoptionInstance = instance;

      return adoptionInstance.getAdopters.call();
    }).then(function(adopters) {
      for (i = 0; i < adopters.length; i++) {
        if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
          $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
        }
      }
    }).catch(function(err) {
      console.log(err.message);
    });
  },

  handleAdopt: function(event) {
    event.preventDefault();

    var petId = parseInt($(event.target).data('id'));

    var adoptionInstance;
    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.Adoption.deployed().then(function(instance) {
        adoptionInstance = instance;

        // Execute adopt as a transaction by sending account
        return adoptionInstance.adopt(petId, {from: account});
      }).then(function(result) {
        return App.markAdopted();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  }
};

$(function() {
  $(window).load(function() {
    App.init();
  });
});

```


texts: Why do I get multiple contracts when using the standard token code?

texts: When using the standard token code given at https://ethereum.org/token#the-code I notice that I get the option to deploy multiple contracts. By deploying all 3 separately, it does not create the intended effect of creating a token. You can see in the attached screenshot there are three contracts to deploy. The screenshot is from the IDE remix.ethereum.org


texts:
This is the error code:

Adoption.sol code:

TestAdoption.sol code:

I dont know how to solve this, it fails when i try to use this comand: "truffle test".
Thanks.


texts:
I have installed ethereum(go-eth) in a folder named "blockchain". In that "blockchain" folder, i have 2 more folders, 'node2' and 'node3'.

Step 1:

I have used the following genesis.json file and stored the same json file in both folders:

{
"nonce": "0x0000000000000042",
"timestamp": "0x0",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x0",
"gasLimit": "0x8000000",
"difficulty": "0x400",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x3333333333333333333333333333333333333333",
"alloc": {

 }
}

saved the file with name "genesis.json"

Step 2:

For initializing the genesis block i executed the following commands from 2 different command prompts:

terminal 1(node2):

geth init "C:\Rahul1306\blockchain\node2\genesis.json" networkid 100

terminal 2(node3):

geth init "C:\Rahul1306\blockchain\node3\genesis.json" networkid 100

Genesis block gets initialized and space is allocated to me, for both nodes.

Step 3

Now i run the following commands to get "chaindata" and other files in respective nodes:

terminal 1(node2)

geth --identity "node2" --ipcdisable --rpc --rpcport "8001" --rpccorsdomain "*" --datadir "C:\Rahul1306\blockchain\node2" --port "30304" --nodiscover --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi "db,eth,net,web3,personal,admin" --autodag -verbosity 6 --networkid 100 --nat "any" console

terminal 2(node3)

geth --identity "node3" --ipcdisable --rpc --rpcport "8002" --rpccorsdomain "*" --datadir "C:\Rahul1306\blockchain\node3" --port "30305" --nodiscover --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi "db,eth,net,web3,personal,admin" --autodag -verbosity 6 --networkid 100 --nat "any" console

All  the required files are added in both the folders

Step 4

I use the following command in both the terminals to fetch their enode address:

admin.nodeInfo

I receive the following addresses:

node2:

enode://b94f327b518b68f33304078352f7b74cd6290c7601f42ec5cc5f4f50813de2
489171769124f93a4047f1e55a49aee6e5a45869b40bb0b18e395acd0bb40b625e@[::]:30305

node3:

enode://b94f327b518b68f33304078352f7b74cd6290c7601f42ec5cc5f4f50813de2
489171769124f93a4047f1e55a49aee6e5a45869b40bb0b18e395acd0bb40b625e@[::]:30305

Step 5

Now in order to connect these nodes/ attach them to the private network, I use the following command:

Here i am trying to add node3 as a peer of node2. So the following command is executed on terminal 1 ,i.e on node2 terminal.
Notice, i have changed '[::]' with localhost address,i.e '127.0.0.1'

admin.addPeer("enode://b94f327b518b68f33304078352f7b74cd6290c7601f42ec5cc5f4f50813de2
489171769124f93a4047f1e55a49aee6e5a45869b40bb0b18e395acd0bb40b625e@127.0.0.1:30305?di
scport=0")

Now, here is where the problem occurs. I should receive a boolean value, 'true'. Both the geth consoles are working and i execute this command and i receive the following error:

(anonymous): Line 1:15 Unexpected token ILLEGAL (and 2 more errors)

I am not able to understand where i went wrong. So, i need to be able to add the above two nodes as peers in private blockchain network. Please help!


texts:
I am checking if an address is a smart contract. Similarly to many articles and example-codes out there, i do this within my function:

uint32 size;
assembly{
    size := extcodesize(_to)
}
if(size > 0){}

However, when I do this, as so many others seem to do, I get this error:

  security/no-inline-assembly: Avoid using Inline Assembly.

I seem to struggle to find a solution to this. Even in the solidity 0.5.0 documentation they describe inline assembly, so seems weird that it is not allowed. Has anyone else encountered this, and found a solution to it?


texts: How can we compile and call a smart contract in ethereum wallet

texts:
I have created a sample smart contract in the online solidity compiler called Remix and I have also created a private blockchain. Then I also have an ethereum wallet running on this private test network.
 Can anyone tell me how can I use this smart contract in the ethereum wallet?


texts:
How do I dynamically call an event with a name?
For example, my contract has a few events and based on some conditions I would like to call one of them. I don't want to use a switch or an if statement but would like to specify the name of the event and call it with data

I tried the following simple example but it didn't work.

event StoredValue(
   string data);

function callEvent(string eventName, data) {
this.call(bytes4(sha3("StoredValue(data)")));
}

I want to pass a name and arguments into a function which will be used to call the event


texts: Use ERC165Checker library function in web3

texts: As I understand the ERC165Checker library provides the _supportsInterface function which takes a contract address and an interfaceId and returns whether that contract has the specific functions. How can I call this function in js with web3?


texts: Can I "cancel" a token transfer transaction by sending ether?

texts: The OMG transaction is listed here on etherscan. I initiated it around 7:30 AM this morning, even though the timestamp on that page always seems to restart everytime I refresh the page. I found a myetherwallet.com help page for cancelling a pending transaction. The instructions for cancelling a transaction involve generating a '0 ETH' transaction to your own address, along with other details. My question is, should I still be doing a 0 ETH transaction to myself, or a 0 OMG transaction to myself since the original transaction was OMG and not ETH?


texts:
I was trying to use the running geth, i used the wallet app to connect to this. nonetheless, i cannot seem to get the wallet to use the running instance of geth, even though i have the running instance of geth with

geth --rpc --datadir="mi/dir"

i am currently in windows10, using the wallet from https://github.com/ethereum/mist/releases

thanks!!


texts: How to hide the private key for sign trnx with NodeJS?

texts:
When I sign a transacction in a website I do it with Metamask and my private key is safe.
Now I am signing transactions automatically from a NodeJS like the next code.
Can I somehow hide my privateKey in case someone has access to the server?
const privateKey = 'my wallet secret private key';

const rawTransaction = { "to": 0x000000, "value": value, "gas": 100000 };

web3js.eth.accounts.signTransaction(rawTransaction, privateKey)
    .then(signedTx => web3js.eth.sendSignedTransaction(signedTx.rawTransaction))
    .then(function(receipt){ console.log("Tranx Done!");
})


texts: Why doesn't the solidity perform rounding off to nearest whole number

texts: The function getInt() is always returning more than 1. Shouldn't it do a round off for values less than 0.5 and return 0 ? Please check the image and let me know, if I am doing something incorrectly or if there is a way out.


texts:
I have read in the documentation that the miner set the gas cost. Does this means that gas cost varies miner to miner ? If not, how it is determined ?

Moreover, when a contract is referred in geth we write:

  var token = tokenContract.new(
    supply,
    {
      from:web3.eth.accounts[0],
      data:tokenCompiled.token.code,
      gas: 1000000
    }..........

What gas is this? Is it the gas cost set by the client? Or the max gas to be used for the transaction?


texts: Is it profitable to mine Ethereum on AWS?

texts: I got $5000 on AWS from Facebook by being part of FbStart. Since I wont be using these credits for web development, I want to know if it would be profitable for me to mine Ethereum? Can I at least make $5000? If so how long would it take?


texts: Decoding contract output of web3 eth call


texts: Does knowing half private key provide any useful information?

texts:
I have a private key and I want to store a paper version of it. I would like to split it in 2 equal parts (first 32 numbers and last 32 numbers) and store them in 2 different locations.
Let's assume I'm 100% sure no one can access both parts, but it's possible that someone can steal one of them.

How much am I compromised?

To explain the question: I understand the attacker needs to guess only 32 hexadecimal numbers instead of 64 to complete the private key. Is that so much easier than guessing 64? Does this seriously undermine the security of my account? And is there something I'm missing that makes it even easier than guessing the remaining 32 numbers (ex: given the first 32 numbers only a possible subset of all remaining 32 numbers is possible due to some constraint)?


texts:
If I have a function like the following - will the now value be preserved at the time encodeABI was called, or will now be the actual now time?

function doSomething(uint start) public {
    require(now - start < 1 day);
}


texts: Are Ether and ERC20 compliant Token interoperable?

texts:
I know ERC20 compliant tokens are interoperable but are Ether and ERC20 compliant tokens are interoperable?
If so, where can I find the proof, such as whitepaper, journal, blog, etc.?


texts: Authenticating a user via MetaMask (like Cryptokitties)?

texts:
I'm trying to understand how a user could be authenticated (like a sign in) using MetaMask, similar to how Cryptokitties makes you sign up/login?

From what I understand, we need to have the user sign a message to authenticate the ownership of the private key that generates a user's address. So If I have a web3 instance in my .js file, how can I prompt the user with a metamask login kinda like Cryptokitties?

I have this in my javascript file:

// Is there is an injected web3 instance?
if (typeof web3 !== 'undefined') {
  App.web3Provider = web3.currentProvider;
  web3 = new Web3(web3.currentProvider);
} else {
  // If no injected web3 instance is detected, fallback to Ganache.
  App.web3Provider = new web3.providers.HttpProvider('http://127.0.0.1:7545');
  web3 = new Web3(App.web3Provider);
}


texts: Is it possible for a contract to update the amount of tokens owned by an address, according to a parameter called with Oraclize?

texts: I am trying to figure out if a contract can change the amount of tokens owned by an address according to certain parameters. I couldn't find anything.


texts:
Both are mining distributions for Ether. GenEthOs is free, EthOs is not. Both are based on Ubunut.

What's the difference between EthOS and GenEthOs?


texts: How do I send Ether using geth on Windows?

texts: I've mined Ether and it has gone into a wallet that I created using geth. When I look online, people say to use eth.sendTransaction({from: 'address', to: 'address', value: web3.toWei(1, "ether")}), however I'm not sure how to use this command on Windows.


texts:
pragma solidity 0.6.6;

// import "./XYZToken.sol";

contract Vault {

    mapping(address => uint256) balanceOf;
    mapping(address => bool) hasDepositedEther;
    mapping(address => bool) hasntDepositedEther;

    function depositEther(uint _amount) public payable returns(bool success) {
        balanceOf[msg.sender] += _amount;
        hasDepositedEther[msg.sender] = true;
        hasntDepositedEther[msg.sender] = false;
        return true;
    }

      function issueTokens() public view returns(bool success) {
        require(balanceOf[msg.sender] != 0 ether, "You need to deposit Ether in order to receive tokens");
        require(hasntDepositedEther[msg.sender] == false, "You need to deposit Ether in order to receive tokens");
        require(hasDepositedEther[msg.sender] == true, "You need to deposit Ether in order to receive tokens");

        balanceOf[msg.sender].transfer

        return true;
    }

}

Where balanceOf[msg.sender].transfer is, how can I turn that into code where I can issue tokens 1-to-1 for each eth they've deposited?


texts:
I was wondering if there a tool or a sample smart contract that allows to send out a mass payment to a list of addresses?

I have a table containing

Users' ETH addresses, different amounts of ETH to send to each one of them individually.

Thanks.