texts: What does the assembly part of this function do? (in receiveApproval )

texts:
I'm trying to wrap my head around the approveAndCall() function, because I want to allow users to pay for functions of my main contract with the associated tokens.

I'm trying to understand the example of this article. In the "approveAndCall()" section, the following functions are shown:

function approveAndCall(address _recipient,
                    uint256 _value,
                    bytes _extraData) {
  approve(_recipient, _value);
  TokenRecipient(_recipient).receiveApproval(msg.sender,
                                         _value,
                                         address(this),
                                         _extraData);
}

and

function receiveApproval(address _sender,
                         uint256 _value,
                         TokenContract _tokenContract,
                         bytes _extraData) {
  require(_tokenContract == tokenContract);
  require(tokenContract.transferFrom(_sender, address(this), 1));
  uint256 payloadSize;
  uint256 payload;
  assembly {
    payloadSize := mload(_extraData)
    payload := mload(add(_extraData, 0x20))
  }
  payload = payload >> 8*(32 - payloadSize);
  info[sender] = payload;
}

What does the assembly part in the second function do?

The example function stores data, so all the actual function called via the token contract does is info[sender] = payload;. Do I need a payload if I replace it with my function that only has "simple" arguments? (No bytes, just uints, addresses, etc.) Do they need to be converted to bytes?

(I might ask a different question for more details about approveAndCall() and recieveApproval, for now I'd just want to understand that payload part.)


texts:
I've create a contract in Remix imporing 2 differents libreries and it works ok, but when I copy and paste it into Mist I got an error at the import statement.

Code goes like this:

pragma solidity ^0.4.18;
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
import "github.com/Arachnid/solidity-stringutils/strings.sol";

contract WeatherBet is usingOraclize{
    using strings for *;
...

Error msg:

Could not compile source code.
Source "github.com/oraclize/ethereum-api/blob/master/oraclizeAPI.sol" not found

Thanks.


texts: How does the increasing array size affect contract throughput?

texts:
I was working with arrays in my contract and I came across the fact that I'm deleting the middle element from an array and because I don't want to ruin the order I don't shift the last element to the deleted one. I also don't want to shift all elements because it might take more gas to do the transaction. So how does this affect my contract, in what sense?
Also, will it be more expensive to have a mapping for indexing elements of an array or a having a for loop(up to 20-30 elements)? Any help appreciated.


texts:
I updated to the latest version of Truffle using:

npm uninstall -g truffle

followed by:

npm install -g truffle

I verified this succeeded by doing:

truffle --version

and got this:

You can clearly see that I'm on version 5.0.3

I read that updating Truffle would pretty much also automatically update the Solidity compiler.

but when I do:

solc --version

I get this:

So its still on version 0.4.24

So I did again.
And again.
And its not working.

I've done it globally - and I've done it locally, meaning in my specific project's Directory.

Nothing works.

I tried doing it directly, by uninstalling Solidity - like this:

npm uninstall solc -g

-then reinstalling it using:

npm install solc -g

I've done pretty much everything I can think of, but its still telling me that I'm on version 0.4.24.

What's going on? What am I missing here?

========================================================

UPDATE:

I added the following to my truffle.js file:

compilers: {
    solc: {
        version: "0.5.0"  // ex:  "0.4.20". (Default: Truffle's installed solc)
    }
}

That's obviously supposed to force the use of that particular version of the compiler.

I recompiled and redeployed to ropsten - and that all worked.

So at this point, I'm assuming that the project is being compiled using v 0.5.0 of Solidity - but is it?

Here's my big question right now: how can I tell - like during run time, what compiler version is actually being used on my project at any given time?
Cause at this point, I'm still getting errors in my DApp - the HTML & JS files that are querying the contract I deployed - that seem to do with the compiler+solidity versions - which was the reason I updated truffle to version 5 in the first place, to solve these issued. (But that's another matter. One thing at a time.)

===========================================================================

UPDATE#2

This shows everything:

-I'm installing solc v. 0.5.3 directly into my project's folder (I've already done the Global install several times.)

-I get 2 warnings - I don't know what they mean - but it says it installed 14 packages from 5 contributors, which sounds pretty good.

-but then when I do solc version, it tells me I'm on version 0.4.24

I've literally spent all day trying to resolve this.


texts: Does the Poloniex minimum deposit amount apply to mining rewards?

texts:
I am setting up my mining pool and need to set a payment threshold.

The minimum deposit for ETH on Poloniex is 1 ETH. Does this apply to mining rewards?

Say (hypothetically) I set my threshold to 0.1 ETH. Would it be the case that I never get any deposits into my Poloniex wallet, or would it just be a case of waiting until 1 whole ETH had built up before it gets credited?


texts: How to state private keys when using node.js and ethereum to run a contract?

texts:
I have to run node.js to execute smart contracts. My quetsion is about the keys.

I have seen this from the docs -

1. Code to sign
2. Code to execute

But I am unsure how the two are combined. Could someone clarify this?

I have a deployed contract which has this function -

 function addBonus( string bonusType, uint bonusTarget,  uint bonusEndYear,
        uint bonusEndMonth, uint bonusEndDay,
        string bonusToken, uint bonusAmount, string bonusName, uint ineq ) public {
// processing
}

From the docs -

var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')
var rawTx = {
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057' }
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385" });

And this -

// contract abi
var abi = [{
    name: 'myConstantMethod',
    type: 'function',
    constant: true,
    inputs: [{ name: 'a', type: 'string' }],
    outputs: [{name: 'd', type: 'string' }]
}, {
    name: 'myStateChangingMethod',
    type: 'function',
    constant: false,
    inputs: [{ name: 'a', type: 'string' }, { name: 'b', type: 'int' }],
    outputs: []
}, {
    name: 'myEvent',
    type: 'event',
    inputs: [{name: 'a', type: 'int', indexed: true},{name: 'b', type: 'bool', indexed: false}]
}];
// creation of contract object
var MyContract = web3.eth.contract(abi);
// initiate contract for an address
var myContractInstance = MyContract.at('0xc4abd0339eb8d57087278718986382264244252f');
// call constant function
var result = myContractInstance.myConstantMethod('myParam');
console.log(result) // '0x25434534534'
// send a transaction to a function
myContractInstance.myStateChangingMethod('someParam1', 23, {value: 200, gas: 2000});
// short hand style
web3.eth.contract(abi).at(address).myAwesomeMethod(...);
// create filter
var filter = myContractInstance.myEvent({a: 5}, function (error, result) {
 if (!error)
   console.log(result);
   /*
   {
       address: '0x8718986382264244252fc4abd0339eb8d5708727',
       topics: "0x12345678901234567890123456789012", "0x0000000000000000000000000000000000000000000000000000000000000005",
       data: "0x0000000000000000000000000000000000000000000000000000000000000001",
       ...
   }
   */
});

I assume we have to combine these two expressed ideas somehow. I cannot see any private keys in the second example and the first one has no example of running a contract.


texts: How to send Ether Using Web3 and Gas Charges are Paid from Another Address?

texts:
I know using this for send Ether (web3):
web3.eth.sendTransaction({
    from: 'Address A',
    to: 'Address B',
    value: '1000000000000000'
})
.then(function(receipt){
    ...
});

I'm trying to send ether from address A to address B, then the gas fee is paid by address C for the transaction. Does anyone know about that?


texts: How to import my current wallet in Mist?

texts:
I generated my wallet with geth command line "geth new account", with password, and got my key.

Following a guide, I just downloaded Claymore's Dual Miner, setup the start.bat pasting my key and started mining on Nanopool.
Now I'm about to get my first payment reaching the minimum payout so... what should I do? I found the Mist Wallet to keep track of my wallet, is this the correct way? should I import my key in some way in it?
Please help, because I think I miss something very basilar..

thank you!


texts: Migrate with truffle deployer by using new

texts:
Hi I am trying to figure out what is the right way to migrate the contract by using new() method of the contract. The following does not work, the contract does not seam to be migrated (though it is deployed). What am I missing here?
var UidProvider = artifacts.require("./UidProvider.sol");

module.exports = async function(deployer) {

  await deployer.then(async function() {
   return UidProvider.new();
  });

  return;

}


texts: What action would actually lead to an invalid block and what happens to the valid transactions in that block

texts:
I'm trying to figure out how an invalid block would come into existence and what happens (technically) to valid transactions in the invalid block.

From what I understand, invalid transactions (like spending more ETH than the account balance) won't even make it into the block. So is it always fraud or chance (when 2 miners solve the puzzle at the same time for instance)?

Also, when a block does turn out to be invalid, are the valid transactions that were included returned to the transaction pool? Can someone explain to me how this works? Also in the case of two miners publishing a block at the same time...are both including the same transactions, are they still in the pool until ..x.. confirmations have occured?

A lot of questions, I'm just a bit unclear on actual 'invalid block' reasons and how the system makes sure all valid transactions will still be included in another block

thanks!


texts: Can Ethereum be successful in a world where EOS meets all of its promises? Why/Why Not?

texts:
As the title states, the EOS platform looks incredibly promising, but looking at the recent blog posts the maximum 6k transactions per second is much less than the promised 100k+ per second. I'm aware that this is because multi-threading isn't implemented yet, but EOS has made many exciting promises that are yet to come to fruition.

So my question is, do you believe Ethereum still has a place in the blockchain industry if EOS can follow through on all promises? What will Ethereum's niche be or do you believe it will still be a dominant technology?


texts:
I'm new to blockchain devolop, I created a contract with a withdrawal function
    function withdraw() {
    require(msg.sender == contractOwner);
    withdrawWallet.transfer(this.balance);
}

I did some tests on the Rinkeby network
Now I have about 2 eth in my contract balance
https://rinkeby.etherscan.io/address/0xba5919b1d7762ac7cbee6ef4a4fa39098c52439c
how can i make the withdrawal to receive the funds in my wallet?
how can i call the withdrawal function?
Thanks in advance


texts: Simple contract Transaction has been reverted by the EVM

texts:
I create a very simple contract as follows:

pragma solidity >=0.4.24 <0.6.0;
contract Test {

// There is minimum and maximum bets.
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;

// 测试1
function getTest(uint modulo) external payable {

    // Validate input data ranges.
    uint amount = msg.value;
    require (modulo > 1 && modulo <= 100, "Modulo should be within range.");
    require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");

}
}

Then I used truffle compile, truffle migrate, after that, I wrote a test file as followa:

const assert = require('assert');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
const json = require('../build/contracts/Test.json');
const utils = require('ethereumjs-util');
let accounts;
let contract;
let manager;
let result;
const interface = json['abi'];
const bytecode = json['bytecode'];
const address = '0x059F708ffFB51719074349A172838285BF1C33BF';
beforeEach(async () => {
accounts = await web3.eth.getAccounts();
manager = accounts[0];
contract = new web3.eth.Contract(interface, address, {from: manager});
});
describe('Test', () => {
it('get test', async () => {
result = await contract.methods.getTest(100).send({
from: manager,
value: web3.utils.toWei('0.01', 'ether'),
gas: 500000
});
console.log('### result:');
console.log(result);
});
});

I ran "mocha test", then got this:

  Error: Transaction has been reverted by the EVM:    {
  "transactionHash":"0x6a21a921326725709e1d1cd549b862e9abc5faf691886d5c6d9081b89a2e9ff2",
  "transactionIndex": 0,
  "blockHash":"0x8ee0d6f54d2ea010d782400fa348e8b253e66a2f4ed54e04f36d992d326c5662",
  "blockNumber": 6,      "from":
  "0x99aa63cceea343c81ccff19e9366a67a5d3635cc",      "to":
  "0x059f708fffb51719074349a172838285bf1c33bf",      "gasUsed": 21772,
  "cumulativeGasUsed": 21772,      "contractAddress": null,      "logs":
  [],      "status": true,      "logsBloom":
  "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "v": "0x1b",   "r":
  "0xda47199fde41e787bffb63ef1ab2275362914ccb673aac1333911f4f6f30997e",
  "s":
  "0x38faafb77a25155c758d7c3fc998b8c9486c83136ef8dbd445c1be4996041dfc"
  }


texts: How to filter events with indexed bytes32 array?

texts:
I have the following event in my contract:
event onDocHashSubmission(bytes32[] indexed docHash);

I want to filter the indexed docHash array using web3.js
var filter = {docHash: ["0x35629f728d841f9ab4d4698eee5a49c0358056c2d2ffc1f0e76625d4f9969b41"]}
const filtered = await contract.getPastEvents('onDocHashSubmission', {filters:filter,fromBlock:0},function (error,event){
  console.log(event)})

I get all the past events of onDocHashSubmission. But the problem is the returned docHash is not an array of docHash, but a single Hash of all the docHashes that was passed to the event.
Eg:
I passed this:
0x35629f728d841f9ab4d4698eee5a49c0358056c2d2ffc1f0e76625d4f9969b41
0x35629f728d841f9ab4d4698eee5a49c0358056c2d2ffc1f0e76625d4f9969b42
0x7e90bed6c8016039f3e22380c6b60f29a542dcd0d4492742dc7aaa6a5e4dcb10
0x7e90bed6c8016039f3e22380c6b60f29a542dcd0d4492742dc7aaa6a5e4dcb11
0x7e90bed6c8016039f3e22380c6b60f29a542dcd0d4492742dc7aaa6a5e4dcb12
0x7e90bed6c8016039f3e22380c6b60f29a542dcd0d4492742dc7aaa6a5e4dcb13
0x7e90bed6c8016039f3e22380c6b60f29a542dcd0d4492742dc7aaa6a5e4dcb14

But in the event I get this:
docHash: '0x7f0baee0f897e20d9e4d8aa90f4cbb27a597beb657920e474337137a70469e11'

I get returned all the transaction hashes consisting of event onDocHashSubmission but not filterd.
How do I filter the returned event to get my docHash only?


texts: Why does clef not implement ethereum's JSON-RPC

texts:
Assuming that the RPC standard still matches what is to be found today on the ethereum wiki, I was rather surprised to learn that the method calls provided by clef do not match the signer methods in the JSON-RPC standard.
That means the signer is not interchangeable with that offered by geth, metamask etc.
What advantage does this bring?


texts: Private Ethereum blockchain to implement in-game currency--legit?

texts:
I've been toying with the idea to implement a reward system for a game on top of Ethereum. Mostly for self-study because I'm interested in blockchain technology, but also because Ethereum appears to come with a lot of desirable properties out of the box that would make such a system easier to implement than with off-the-shelf databases (less application logic required, easy to deploy, concept of contracts and transactions built in.) I also like the prospect of being able to look at your rewards using a wallet app, and perhaps at some point being able to trade or exchange them for actual cash (or another crypto currency.) It opens up interesting use cases.

To my question: The main problem with all this is of course that running any such logic on the public blockchain is just not economic, since I'd either have to make people pay real dollars to get an ether balance and use that to compute their own rewards (doesn't really make sense), or fund all computations out of my own pocket. It also introduces a lot of risk, since with more people joining, txn cost might explode. I want something predictable.

So basically what I'm aiming for is to make computations cheaper, or even free, by running a couple nodes on a publicly accessible but private blockchain. I already dug through the documentation and it appears that I can turn off node discovery altogether, and hard code the nodes that I would allow to connect. That said, are the following assumptions correct?

I'd be able to control the ether supply and gas price and make computations available for free; a transaction would always be accepted if the preconditions (implied by the game logic) hold
security/integrity should not be an issue, since all nodes are trusted, so no 51% attack could occur unless I initiated it myself
I'd still benefit from Ethereum as a reliable backend to log transactions

I know it sounds weird, since I'm essentially nullifying one of the main ideas behind Ethereum: making compute resources an asset and blockchain modifications costly. But that is simply not what I care about, since I'm not looking for the world's consensus around the game's blockchain integrity. I do care about everything else, however: accounts and identity, transactional storage, a replicated persistent log (the blockchain), contracts, a JSON API, the whole shebang.

I've read several opinions on the web on private blockchains, and looked at a number of games running on Ethereum, and none seem to follow the approach I outlined.

Is my idea a viable one or does it sound to you like too much shoehorning?


texts: In javascript, what does the line var meta = MetaCoin.deployed(); mean and what does it return?

texts:
I am following the official Truffle docs to create a Dapp and am reviewing the code. I am repeatedly seeing the line

var meta = MetaCoin.deployed();

What is the deployed function? What does it return?


texts: if I use parity -d "path" to sync with a modify path.will i type -d again when next time open parity?

texts: this is my first time to use parity, so if i just type parity -d \abc to sync in the folder named abc.  and should I type it again the next time I use the rpc service with parity? if not, will it sync again in default folder?


texts: How to read token balance of another token

texts:
I'm trying to write a contract which reads the token balance of an address. The token contract is already deployed. What would I need to do to read data from another contract?

Assume I'm trying to read the GNT balance of an address, this is how I'm trying to reference the Golem contract:

 GolemNetworkToken temp = GolemNetworkToken(0xa74476443119A942dE498590Fe1f2454d7D4aC0d);

However this doesn't seem to be valid Solidity syntax.

EDIT: with suggestions:

 pragma solidity ^0.4.16;

contract ERC20Basic {
  uint256 public totalSupply;
  function balanceOf(address who) constant returns (uint256);
  function transfer(address to, uint256 value) returns (bool);
  event Transfer(address indexed from, address indexed to, uint256 value);
}

contract ERC20 is ERC20Basic {
  function allowance(address owner, address spender) constant returns (uint256);
  function transferFrom(address from, address to, uint256 value) returns (bool);
  function approve(address spender, uint256 value) returns (bool);
  event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract test{

  ERC20 myToken = ERC20(0xa74476443119A942dE498590Fe1f2454d7D4aC0d);

  function getTokenBalanceOf(address a) constant returns (uint balance) {
    return myToken.balanceOf(a);
  }
}


texts: Can someone imitate and create a fake erc20 contract? If so, how can we identify a contract?

texts:
If a project A deployed a erc20 token contract Mytoken, can a scammer create another Mytoken with some internal data modified (e.g., founder address)?

Can etherscan identify such fake contracts?

Or the only solution it to put the address of the real Mytoken on project's website? But there could be fake website...


texts: Solidity: Info on How it works on the low level

texts:
I'm looking for information on how Solidity works on the low level and how exactly it gets executed or run on the EVM?

Do you have any documentation or Papers that describe that?
Thank you!


texts:
I am new to ethereum and I am trying to build something like a vault where you can withdraw and deposit assets, based on the dApps protocols you are using (e.g :- yEarn, aave).
I know there will be gas costs for using any method of these various dApps.
How will I be able to know the estimated gas costs for each these on-chain using the estimateGas functionality of web3?


texts: Where is blockchain scalability bottleneck?

texts:
There is a moment I still don't understand about blockchain. I've never seen ethereum client coniniously under 100% CPU or network load. So why isn't it possible to process transactions faster? I assume that 100% GPU load on mining machine is not a bottleneck, because block size is arbitrary. So, where is exactly the bottleneck?

Thanx!


texts:
I just learnt using web3 to interact with Ethereum.

Is there a similar library to web3 to work with Ethereum Classic?
Is there a testnet faucet?
Does it work with Parity?

Thanks in advance for your help.


texts: Concatenating byte strings in assembly for call input data

texts:
I have the following piece of code in my contract. It's supposed to take in a byte string composed of a uint flag that is followed by a variable list of uint numbers and contruct a call using those numbers. For example, for a byte string made up of the flag and just one number

0x00000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000503b65

it is supposed to construct a call to the the provided contract address with the input

0x912610ab0000000000000000000000000000000000000000000000000000000000503b65

which should return a nonzero value, followed by an internal call to handle with a flag of 3. However, when I test this code, the input that is provided to the contract call is missing the first argument:

0x912610ab0000000000000000000000000000000000000000000000000000000000000000

What am I doing wrong? Is this an issue with the stack? I am borrowing some of the code from this question, which did not seem to have this problem.

function record(bytes script, address contract) public {

    bytes4 sig = bytes4(0x912610ab);
    uint256 flag = uint256At(script, 0);
    uint256 location = 0x20;

    while (location < script.length) {
        uint256 id = uint256At(script, location);
        assembly {
            let x := mload(0x40)
            mstore(x,sig)
            mstore(add(x,0x04),id)
            switch call(sub(gas, 5000), contract, 0, x, 0x24, 0, 0)
            case 0 {
                revert(0, 0)
            }
        }
        location += 0x20;
    }

    handle(flag);
}

function uint256At(bytes data, uint256 location) pure internal returns (uint256 result) {
    assembly {
        result := mload(add(data, add(0x20, location)))
    }
}


texts: Extracting Ethereum Wallet "extract without encryption"

texts:
When I download the wallet and extract the files, I get an alert that indicates that I am extracting the files "without encryption"

Is this normal?

Also, my security software won't allow the program to run.

Is that normal?


texts: Does The Ethereum Wallet / Mist Standard Multisig Wallet Support ERC20 Tokens?

texts:
This question was prompted by Any multisig wallets for Ether?:

  Are there any multisig wallets available for ether and other ethereum-based tokens?


texts: Problem installing Ethereum via apt-get on Debian Buster

texts:
I want to run a geth fullnode (with fast syncmode) to be able to use the JSON RPC. I have a VMWare-based vm set up which fits all the requirements as far as I can see. Domain. Fixed IP address. Disk space. RAM. The works.
Now this is a Debian system on Buster (10) on kernel 4.19 on an emulated x86_64. uname -a gives you Linux hostname 4.19.0-13-amd64 #1 SMP Debian 4.19.160-2 (2020-11-28) x86_64 GNU/Linux
Now I want to install ethereum via apt-get to be able to have it automatically updated instead of having to do this always manually. I encountered some problems installing the sources, as the ppa-keys for whatever reason weren't imported. Anyhow, everything is set now:
$ ls -l /etc/apt/sources.list.d/ | grep eth
-rw-r--r-- 1 root root 144 Jan 11 17:19 ethereum-ubuntu-ethereum-hirsute.list
-rw-r--r-- 1 root root 140 Jan 11 17:04 ethereum-ubuntu-ethereum-hirsute.list.save

and
$ apt-key list
/etc/apt/trusted.gpg
## truncated
pub   rsa1024 2014-02-10 [SC]
      2A51 8C81 9BE3 7D2C 2031  944D 1C52 189C 923F 6CA9
uid           [ unknown] Launchpad PPA for Ethereum
## truncated

which I achieved via sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 2A518C819BE37D2C2031944D1C52189C923F6CA9 (key ID from the launchpad site) and now my apt-get update works without any errors:
$ sudo apt-get update
## truncated
Hit:5 http://ppa.launchpad.net/ethereum/ethereum/ubuntu hirsute InRelease
## truncated
Reading package lists... Done

Yet, when trying to install ethereum (or the packages geth, ethereum-unstable, or so), I get the message "unable to locate package":
$ sudo apt-get install ethereum
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package ethereum

EDIT: Also followed this here: https://linuxconfig.org/install-packages-from-an-ubuntu-ppa-on-debian-linux, but with the same result: "unable to locate..."
Anyone knows how to solve this?


texts: Is there any available sandbox for Ethereum's OPCODES?

texts:
In case of Bitcoin, there are few tools, which allow you to play with Script OPCODES - one, two.

So, is there any handy way to simulate / debug Ethereum's OPCODES execution?


texts: Any known implementations for on-chain merkle proofs of historical balances?

texts:
I know it is possible to verify historical ETH balances (for the last 256 blocks) using a merkle proof on-chain - are there any known implementations?

NB - I'm looking for Solidity code (i.e. on-chain) ways of doing this.


texts: Using vanilla javascript with web3 and metamask

texts:
I have searched severally on how to use web3 with metamask without nodejs without any success.
I want to be able to get an instance of a user's metamask account through web3 and vanilla javascript without having to go through nodejs and all it's dependencies.
I have included web3.mim.js on the head tag and have this code running fine.

window.addEventListener('load', function () {
    if (typeof web3 !== 'undefined') {
        console.log('Web3 Detected! ' + web3.currentProvider.constructor.name);
        window.web3 = new Web3(web3.currentProvider);
    } else {
        console.log('No Web3 Detected... using HTTP Provider')
        window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
})

The issue however is that when i try to get default account using web3.eth.defaultAccount i get a null value returned to me.
How can i get access to the current account on metamask?
I am running the script in an apache server.


texts: Solidity - ether transfer from contract to contract issue

texts:
I have an issue to transfer the ether from a contract to another contract.
Here is the concept code.

If the address _to is a user address. The function can transfer the ether to the user.

If the address _to is a contract address. The program will stop working.

Need help. Thanks.

pragma solidity ^0.4.19;

contract ethTransferTest {
    function ethTrans(address _to) payable public {
        uint256 pay = msg.value;
        _to.transfer(pay);
    }
}


texts: Can the result of a call trigger the execution of a transaction?

texts:
Supposing I have a transaction (A) = a call (B) + other storage operations (C). Executing A, beeing a transaction, I have to pay the gasUsed by B and C.
Beeing B an expensive call and since I need the result of B to verify if is possible to exectue C, is there a way to split A in B and C (call + transaction) with the result of B automatically triggering the execution of C?


texts: Geth server - How to run lightweight server?

texts:
I am doing test development to run smart contracts on Ethereum client. I downloaded geth, but still unable to setup geth client. I run geth command and it keeps on running for next 10 minutes. I think it is downloading the whole Ethereum block chain on my computer. I killed it fearing it may blow up my computer. Please tell me how to download the light version so that I can run test my smart contracts? Went through various articles on internet, but not able to find solution.

Thanks


texts: Quorum: Extending list of participants that can access private transactions post transaction creation?

texts:
According to the Quorum roadmap (which is over a year old now) the team at JPM was planning to add a feature whereby additional parties could be given rights to view private transactions after those transactions had been created and sent through the network. It's listed as a short-term goal.

https://github.com/jpmorganchase/quorum/wiki/Product-Roadmap

Ostensibly, there would be some approval mechanism (implemented through the Quorum API perhaps?) that granted the new party the right to store encrypted private transaction payload in their own enclaves?

I'm at a bit of a loss as to whether or not this was ever actually implmented. And if it was, any examples or documentation?

Many thanks in advance!


texts: How do I install solc on Mac Osx? Error encountered "Error: No formulae found in taps."

texts:
I'm trying to install a solidity compiler on my Mac.
I've followed the guide here: https://github.com/ethereum/go-ethereum/wiki/Contract-Tutorial

The error that I've gotten when installing ccp-ethereum is "Error: No formulae found in taps."

zhongqin-imac:~ ngzhongqin$ brew install cpp-ethereum
Error: No available formula with the name "cpp-ethereum"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.


texts:
I have a very simple contract as below:-

contract Test{
    address public creator;

    function Test(){
        creator = msg.sender;
    }

    function get1() returns (address){
        return creator;
    }
}

When I call test.creator(), I get the address back but when I call the test.get1(), I get an "invalid address" error message.

Can we not return addresses back?


texts: Using contract balance as gas/tx fee for external call

texts:
Currently I have a hosted wallet Solidity contract as described below. It has a execute() method that calls another contract from a hosted wallet. However looks like call() uses the balance of the original caller (owner) as the gas fee. I'd like to account this fee to the hosted wallet balance. What options I have and are the following viable

call() or similar method that uses the balance of the current contract as the gas fee instead of the balance of the caller
The original execute() caller calculates the cumulative gas cost and the end of transaction (from transaction receipt RPC API) and calls another method in the hosted wallet to credit this back to the original caller in a separate transaction

Contract code:

   /**
     * Simple hosted wallet contract.
     */
    contract Wallet {

        // Smart contract call events
        event PreExecute(address to, uint value, uint gas);
        event Execute(address to, uint value, uint balanceAfter, uint spentGas);
        event ExceededExecuteWithValue(address to, uint value);
        event FailedExecute(address to, uint value, uint balanceAfter);

        // Who is the owner of this hosted wallet. This is the (coinbase) address or geth node
        // that your server speaks to via RPC
        address owner;

        function Wallet() {
            // Lock down the wallet, so that only our private geth
            // has the owner private key to speak to us
            owner = msg.sender;
        }

        /**
         * Executes a transaction from this wallet.
         *
         * We call a function in another smart contract and for the gas use value stored on this contract.
         */
        function execute(address _to, uint _value, uint _gas, bytes _data) external {

            uint balanceBefore;
            uint balanceAfter;
            bool success;

            if(msg.sender != owner) {
                throw;
            }

            if(_value > this.balance) {
                ExceededExecuteWithValue(_to, _value);
                return;
            }

            balanceBefore = this.balance;

            // http://ethereum.stackexchange.com/a/2971/620
            if(_value > 0) {
                success = _to.call.value(_value)(_data);
            } else {
                success = _to.call(_data);
            }

            balanceAfter = this.balance;

            if(success) {
                Execute(_to, _value, balanceAfter, (balanceBefore - balanceAfter) - _value);
            } else {
                FailedExecute(_to, _value, balanceAfter);
            }
        }

        /**
         * Somebody sends ETH to this contract address
         */
        function() {
            // just being sent some cash?
            if (msg.value > 0) {
                Deposit(msg.sender, msg.value);
            }
        }

    }


texts: If statement doesn't hit certain conditions

texts:
I'm currently working on a very simple(first project) market in solidity and i'm having an issue with a piece of code :

  contract smallMarket{

    struct transaction {
      uint timeStamp;
      uint qtyT;
      uint price;
      address client;
      bytes32 typee;
    }
    struct sellOrder {
      uint timeStamp;
      uint qty;
      uint price;
      address seller;
    }

    mapping(uint => transaction) public transactions;
    mapping(uint => sellOrder) public sellorders;

    uint public lastTransactionId;
    uint public lastBOrderId;
    uint public lastSOrderId;
    address public owner;

    function smallMarket(){
      owner = msg.sender;
      lastSOrderId = 0;
    }
    function newTransaction(uint amount,uint price,bytes32 typee){
      uint transac = lastTransactionId + 1;
      transaction t = transactions[transac];
      t.timeStamp = block.timestamp;
      t.qtyT = amount;
      t.price = price;
      t.client = msg.sender;
      t.typee = typee;
      lastTransactionId = transac;
    }

    function newSellOrder(uint amount,uint price,uint currency) {
        uint order = lastSOrderId + 1;
        sellOrder s = sellorders[order];
        s.timeStamp = block.timestamp;
        s.qty = amount;
        s.price = price;
        s.seller = msg.sender;
        lastSOrderId = order;
    }
    function buy(uint amount, uint price) {
      uint idCounter = lastSOrderId;
      uint _amountLeftToBuy = amount;
      while (_amountLeftToBuy > 0){
          if (price >= sellorders[idCounter].price && sellorders[idCounter].qty >= amount) {
            newTransaction(amount,price,'cas 1');
            _amountLeftToBuy = 0;

          }
          else if (price >= sellorders[idCounter].price && amount > sellorders[idCounter].qty ){
              newTransaction(amount,price,'cas 2');
              _amountLeftToBuy =  amount - sellorders[idCounter].qty;
              idCounter = idCounter - 1;
          }
          else if (sellorders[idCounter].price > price){
              newTransaction(amount,price,'cas 3');
              _amountLeftToBuy = 0;
          }
          else{}
      }
    }
  }

I'm manually creating a sellorder struct for testing purpose and it fails on the buy function.

Manually create SO:

newSellOrder(5,200,1)  #=> (uint amount,uint price,uint currency)

Then calling buy function with different cases:

buy(6,201)  #=>(uint amount, uint price)
buy(4,201)
buy(4,199)

In my Buy function , there are 3 case :

price >= sellorders[idCounter].price && sellorders[idCounter].qty >= amount

Should work with => buy(4,201)

price >= sellorders[idCounter].price && amount > sellorders[idCounter].qty

=>buy(6,201)

sellorders[idCounter].price > price

=>buy(4,199)

My issue is that for some reason the cause #2 ( buy(6,201) ) never get triggered.( so only 2 transaction are created instead of 3)

Anybody see what i'm doing wrong here ?


texts: How to run two nodes on the same device?

texts: I want to run two separate nodes on my computer but it seems that the two nodes will collide with other. I know some considerations should be taken such as the ports, but anything else should I take care of?


texts: Adding a pending transaction to get the balance results in a different outcome

texts:
language : python 3.7
network : kovan
use web3(infura)

I want to check the balance as well as the pending transaction.
The address below is the address with the Pending transaction.
Testing in the Kovan network may include or exclude fending as follows.

Do you know why?

address = '0x1Dcc3E38d55aac34C5e20Aa74da53a4F56Aa4189'
for x in range(5):
    data = w3.eth.getBalance(address, 'pending')
    print(data)

ssh://centos@192.168.0.132:22/data/venv/python3/bin/python -u /data/wallet_test/web3_test.py
1514315008999999959
1514315008999999959
2450527368999999961
2450527368999999961
2450527368999999961


texts: Network configuration for Fortmatic on 'ropsten' -- typescript

texts:
So I am trying to configure the the ropsten network by injecting the fortmatic provider into web3, but am getting these errors. My code is exactly how they have it in their documentation, so idk why I am getting these errors (shown in the image provided) :
export const fortmatic_ropsten = new Fortmatic('my api key', 'ropsten');
window.web3 = new Web3(fortmatic_ropsten.getProvider())

it looks like the fortmatic provider contains slightly different parameters that web3 uses. What am I doing wrong here?


texts: geth transactions stuck in pending, resend fails

texts:
I sent 115 transactions with geth, and they are stuck in pending for over an hour. Etherscan doesn't recognize them. I try to resend, and get a confusing error. Some details from geth console:

> eth.pendingTransactions.length
115

> eth.resend(eth.pendingTransactions[0], web3.toWei(20, 'gwei'))
Error: Transaction a075b95c7242178330ae22373a1138e9ec22cbd9dd54964980fc1a36182acdbe not found
    at web3.js:3104:20
    at web3.js:6191:15
    at web3.js:5004:36
    at <anonymous>:1:1

> eth.pendingTransactions[0].hash == "0xa075b95c7242178330ae22373a1138e9ec22cbd9dd54964980fc1a36182acdbe"
false

The eth.resend docs don't offer much more help.

This might be a duplicate of: geth: can not resend transaction - transaction not found

*Edit: fixed code typo in the writeup (but typo was not in the console).

Interestingly, the pool did eventually clear out on its own, after 24 hours, and all the transactions were successfully sent. But the question about why eth.resend() was failing still stands. (or perhaps clarification on the purpose of the function)


texts: Can I use uport for authenticating users in a private blockchain network ? If yes, Are there any tutorials or implementations available for the same ?


texts: Is it possible to write emacs dunnet game in solidity? Not that there is any reason for the game to be on a blockchain, it is for a class assignment. I tried 2048 game. But it seems to have some tricky code to be created in solidity. I could find the dunnet game but I am not sure if there is any place i can find the algorithm or design pattern for it. Please let me know if anyone knows about it.


texts: Can one receive (fractions of) ETH by simply running Mist?

texts:
This document about Ethereum briefly explains how decentralized Apps work:

  To connect to the network, [people] installed a special program called Mist. (...) Every participating computer receives a reward for their work, because they paid for hardware, electricity and shared their processing power. [They get] a digital asset called ETHER.

Is it true, and is that what is called mining?
(I might be wrong but I believe mining is actually more complicated than installing Mist and helping dApps run.)

Also, I installed Mist and would happily share resources to make decentralized Apps work, as explained in the aforementioned document, but I don't see any ETH coming to my wallet... How does it work, did I misunderstand something?


texts: Port number for connecting web3 to mainnet using Geth

texts: I am trying to connect web3j  object to the mainnet using geth. I can't use infura because i am working with replay transaction observable function which doesn't work with infura. To connect with the testnet we use port 8545, what port number should we use to connect to the mainnet. Also, is it necessary that all the blockchain should be allowed to synchronize before I start using the mainnet?


texts: Can we avoid the protocol overhead of JSON-RPC and directly connect to GETH through some interface?

texts:
I want to build a middleware that adds additional data to JSON RPC responses. This middleware would sit on the same hardware or machine as the GETH node.
The traditional approach would be to simply accept the JSON-RPC requests from a client, forward it to the GETH node and add some additional data in the response on its way back to the client.
I wanted to know if there is a way through which I can completely avoid the protocol overhead of JSON-RPC and directly interface with the GETH node? Because this way I could theoretically, handle more requests. Also I wouldn't have to redundantly parse and stringify the response.
By a direct interface, I mean, interface through some API and not actually manually changing GETH code.


texts: Solidity inherited constructors and calling the parent constructor

texts:
I'm trying to inherit from a contract.  I'm expecting the child contract to have the same constructor as the parent (or be overwritten)

pragma solidity ^0.4.2;

contract parent{
    string public name;
    function parent(string _name){
        name=_name;
    }
}

contract child is parent{}

If I try

contract child2 is parent{
    function child2(string _name){
        name=_name;
    }
}

Then the string entered at construction, that should go into name, doesn't get stored.

What's going on?  How do constructors work with inheritance?
Thanks in advance.


texts: Contract creating another contract in a single source file

texts:
When deployed as a single source file is the address stored in variable creator = TokenCreator(msg.sender) within function OwnedToken referring to the address of the contract TokenCreator or the address of an external account?

contract OwnedToken {

TokenCreator creator;
address owner;
bytes32 name;

function OwnedToken(bytes32 _name) {
    owner = msg.sender;

    creator = TokenCreator(msg.sender);
    name = _name;
}
function changeName(bytes32 newName) {

    if (msg.sender == creator) name = newName;
}
function transfer(address newOwner) {
    if (msg.sender != owner) return;

    if (creator.isTokenTransferOK(owner, newOwner))
        owner = newOwner;
}

contract TokenCreator {
    function createToken(bytes32 name)
       returns (OwnedToken tokenAddress)
    {

        return new OwnedToken(name);
    }
    function changeName(OwnedToken tokenAddress, bytes32 name) {

        tokenAddress.changeName(name);
    }
    function isTokenTransferOK(
        address currentOwner,
        address newOwner
    ) returns (bool ok) {
        address tokenAddress = msg.sender;
        return (sha3(newOwner) & 0xff) == (bytes20(tokenAddress) & 0xff);
    }
}


texts:
Looking for permissioned blockchain for company governance and equity accounting with ability to interact with cryptocurrencies (permissionless blockchains), ie. sale some stake for ether.
Could proof-of-authority based solution be used in this case, and what are general pitfalls?
Is there some complete solutions with UI aimed to company governance task, eg. initiate proposals, voting, dispute tracking ..?


texts: Am I mining? Which part of log has to do with it? (Geth)

texts:
I'm starting to mine on CPU with geth but am not sure,

Is something like that

I0519 06:26:02.720818 ethash.go:291] Generating DAG: 67%

Supposed to mean that I'm mining? Do I stop mining when generating DAG stops then?

Or is something like that:

I0519 06:26:05.475875 core/blockchain.go:1001] imported 11 block(s) (0 queued 0 ignored) including 402 txs in 8.545847414s. #756963 [0ef146c0 / d65fca69]

should tell me that I'm mining?

Why does mining sometimes stop with a long message looking like this
goroutine 118 [IO wait, 8 minutes]:
net.runtime_pollWait(0x7fc130005f40, 0x72, 0x0)
        /usr/lib/go/src/runtime/netpoll.go:160 +0x59
net.(*pollDesc).wait(0xc4204395d0, 0x72, 0xc422d12dc0, 0xc4200101e0)
        /usr/lib/go/src/net/fd_poll_runtime.go:73 +0x38
net.(*pollDesc).waitRead(0xc4204395d0, 0x1482c00, 0xc4200101e0)
        /usr/lib/go/src/net/fd_poll_runtime.go:78 +0x34
net.(*netFD).accept(0xc420439570, 0x0, 0x14809c0, 0xc422d18020)
        /usr/lib/go/src/net/fd_unix.go:419 +0x238
net.(*TCPListener).accept(0xc42003e0a8, 0xc422d12e98, 0xc422d12e98, 0x418385)
        /usr/lib/go/src/net/tcpsock_posix.go:132 +0x2e
net.(*TCPListener).Accept(0xc42003e0a8, 0xc422d1c000, 0x0, 0x2, 0xc4204d2000)
        /usr/lib/go/src/net/tcpsock.go:222 +0x49
github.com/ethereum/go-ethereum/p2p.(*Server).listenLoop(0xc42045c300)
        /var/tmp/portage/net-p2p/go-ethereum-1.4.18/work/go-ethereum-1.4.18/build/_workspace/src/github.com/ethereum/go-ethereum/p2p/server.go:579 +0x276
created by github.com/ethereum/go-ethereum/p2p.(*Server).startListening
        /var/tmp/portage/net-p2p/go-ethereum-1.4.18/work/go-ethereum-1.4.18/build/_workspace/src/github.com/ethereum/go-ethereum/p2p/server.go:382 +0x156

Is it an error or is it good and I have mined something?

I'm new and unfortunately this is not described in the manual. The manual says to check everything in the console mode, but it doesn't work (answers 'undefined' on all interesting questions)

Thank you


texts:
This is my contract-

pragma solidity ^0.4.0;
contract helloworld {
     uint public balance;
    function helloworld(){
        balance = 1000;
    }

    function getBalance()  returns(uint) {
        return balance;
    }
}

I ran truffle compile and truffle migrate.
Then I'm trying to access the balance variable by

helloworld.deployed().balance.call();

I'm getting the following error-

TypeError: Cannot read property 'call' of undefined
    at evalmachine.<anonymous>:1:30
    at ContextifyScript.Script.runInContext (vm.js:35:29)
    at Object.runInContext (vm.js:89:6)
    at TruffleInterpreter.interpret (C:\Users\ujjwa\AppData\Roaming\npm\node_modules\truffle\lib\repl.js:136:17)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:538:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:230:10)


texts:
I have a contract with the decimals hardcoded to 8

    // Hardcoded to be a constant
    uint8 public constant decimals = 8;

I think this is the reason Im having problems with wallets and explorer to show token balances..

Metamask says: "We had trouble loading your token balances. You can view them here"

How can I show correctly my tokens?

Also can be possible to use 18 decimals, but then I would need to modify this:

    // constant to simplify conversion of token amounts into integer form
    uint256 public tokenUnit = uint256(10)**decimals;

Any tip about what can be the best solution and how I can do it?

Thanks!


texts:
I have set up a private ethereum block chain and I have created a .net application that uses nethereum to interface with the geth node.
After submitting a transaction I try to start the miner by using

var miningResult = await web3.Miner.Start.SendRequestAsync(6);
 var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

But sometimes the mining takes a long time to start. I checked on the windows task manager and found that geth.exe remains dormant even after Miner.Start command. after a minute or so it starts mining.
What causes the delay ?


texts: problem with the task function in truffle development

texts:
I am doing the "TodoList" exercise and when I use truffle (development), I do not return the call with task, I get the following error:

truffle (development)> todoList = await TodoList.deployed ()
undefined
truffle (development)> task = await TodoList.task (1)
TypeError: TodoList.task is not a function
     at evalmachine. <anonymous>: 1: 16

Truffle version 5.0.22

This is my first post, your help will be very important to me


texts:
Is it possible to artificially delete a given block from local chain database without causing any problems? for example, how could I delete the latest block from my local eth node, and resync newly generated blocks from other nodes?
If no known RPCs are available, could I write myself an API to do a delete block operation? As far as I can see, the core.blockchain.go has supported a SetHead function with the following comments:
// SetHead rewinds the local chain to a new head. In the case of headers, everything

// above the new head will be deleted and the new one set. In the case of blocks

// though, the head may be further rewound if block bodies are missing (non-archive

// nodes after a fast sync).

dose that mean I can use this method to reset my local chain head? If so, what will happen to the blocks after this chain head? will these blocks be deleted?


texts: How do I set up Geth to accept remote requests?

texts:
Go morning fellow Ethereum developers, I am currently developing my first DApp using web3, js and solidity and I would like to set up my own node service similar to Infura, where remote users would need to possess an API key to use the Node service.
How should I go about setting up such geth node, Nginx and access control with Api?


texts: Multiple DAG generation while syncing on testnet

texts:
While blockchain synchronisation on testnet, I see multiple DAG generation messages along with the percentage of DAG generated?

After this when I check the eth.syncing output my value of currentBlock has gone down from 477000 to nearly 400000 and also geth exited.

I am attaching images for the DAG messages as well as the message occurred when geth exited?

What is wrong here?


texts:
I have been running a geth testnet instance for the last 2 months and learning this. But after the hard-fork i have seen the syncing to be extremely slow. I updated geth to Version: 1.7.0-stable.

eth.syncing shows:

{
  currentBlock: 1701957,
  highestBlock: 1711644,
  knownStates: 0,
  pulledStates: 0,
  startingBlock: 1699999
}

I am still behind < 10,000 blocks. Is there anything else I need to to do apart from updating geth to latest. Any help, would be appreciated. :)


texts:
I want to make a script to restart my server and it's prerequisites, which one of them is geth.
I don't see a command line to restart it. I want something like

geth --restart --xxxx --yyyyy

Does this exist?

In caso no, is it safe to just kill the process and run it again?


texts: How to test abstract contracts using truffle?

texts: Is it possible to test abstract contract using truffle? If yes, how I can to do it?


texts:
pragma solidity ^0.4.23;

import'./ID.sol';
import'./Whitelisted.sol';

contract IDFactory is Ownable {

    Whitelisted whitelist;

    event IDCreated(uint id, address idContractAddress);

    mapping (uint => address) public ids;

    modifier idExists(uint id) {
      require(ids[id]);
      _;
     }
      constructor() public {
        owner = msg.sender;
        whitelist = new Whitelisted(owner);
        whitelist.addToWhitelist(owner);
    }
}

Hello, i'm trying to compile a solidity contract using truffle. The contract is called IDFactory.sol.
When I execute truffle compile I get this error:

MacBook-Pro-de-Alicia-2:a alicialombarte$ truffle compile
TypeError: Error parsing /Users/alicialombarte/notary-contract/a/contracts/IDFactory.sol: Cannot read property '2' of null
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-core/~/truffle-compile/parser.js:171:1
    at Array.map (<anonymous>)
    at Object.parseImports (/usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-core/~/truffle-compile/parser.js:167:6)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-core/~/truffle-compile/profiler.js:302:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/index.js:79:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/~/async/internal/onlyOnce.js:12:1
    at next (/usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/~/async/whilst.js:68:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/index.js:64:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/fs.js:85:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-resolver/~/async/internal/once.js:12:1

I don't have any '2' in my contract.

Thanks!

Here are the other 2 contracts:

pragma solidity ^0.4.23;

import'./Whitelisted.sol';

contract ID{

    uint id;
    Whitelisted whitelist;
    mapping (string => MessageData) public messages;

    event MessageSaved(string messageHash);

    constructor(uint _id, address _whitelist) public {
        owner = msg.sender;
        id = _id;
        whitelist = Whitelisted(_whitelist);
    }

    struct MessageData {
        string messageSender;
        uint64 timestamp;
    }
}

pragma solidity ^0.4.23;

import 'Ownable.sol';

contract Whitelisted is Ownable {

    constructor(_owner) public {
        owner = _owner;
    }

    mapping(address => bool) internal whitelistedAddresses;

    function isWhitelisted(address addr) internal view returns (bool) {
        return whitelistedAddresses[addr];
    }

    function addToWhitelist(address addr) public onlyOwner {
        require(!isWhitelisted(addr));
        whitelistedAddresses[addr] = true;
    }

    function removeFromWhitelist(address addr) public onlyOwner {
        require(isWhitelisted(addr));
        whitelistedAddresses[addr] = false;
    }

    modifier onlyWhitelisted {
        require(isWhitelisted(msg.sender));
        _;
    }
}


texts: Is there a way to see what variables were set when deploying a contract?

texts:
I have a few variables in my contract that coded like so:

string test;
bool public isFrozen = false;

From testing I see that I cannot call the test State variable when calling test().call() but I can call the isFrozen public variable with isFrozen().call() and receive the isFrozen variable.

My question is, if I set the test State variable during deployment, is there ANY way for anyone to view what variables were set during deployment? From my testing I cannot get this information, but I just wanted some guidance.

Also, if there is a way to call a State variable, without using a function please let me know.


texts:
I am trying to send requests to the jsonrpc server as instructed in this link https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblocktransactioncountbynumber

The command works fine in the terminal

curl http://localhost:8545 -X POST --data '{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByNumber","params":["0xe8"],"id":1}'

However, when I execute it from Python as in the following script

import urllib
import urllib2
url = 'http://localhost:8545/'
values = dict(jsonrpc = "2.0",
            method = "eth_getBlockTransactionCountByNumber",
            params = ["0xe8"],
            id =67)

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
req.add_header("Content-Type",'application/json')
response = urllib2.urlopen(req)
print response.read()

It returns this error

  {"id":-1,"jsonrpc":"2.0","error":{"code":-32600,"message":"Could not
  decode request"}}

The same error shows up when I tried

r = requests.post(url, data=str(values), allow_redirects=True)
print r.content

or

print subprocess.check_output(['curl', url, "-X",  "POST", "--data",  str(values)])

is there something wrong in my Python script?


texts: Contracting Party has a legal right of rescission - what possibilities are possible, e.g. Procedere of Reverse Transaction

texts:
if one party has a legal right to rescission; how can the blockchain deal with it?
Is it possible to implement a reverse transaction if
- the other party does not accept that?
- the other party just ignores the right of rescission?
Thank you very much!


texts: How to resolve 'ethereumjs-testrpc@beta' error while using 'npm –g install ethereumjs-testrpc@beta' in Nodejs command prompt

texts:
While setting up my Solidity Environment Using NodeJS, Node Package Manager (NPM) and Truffle which was successfully installed. But at the point of running "npm –g install ethereumjs-testrpc@beta" I was getting error

I was running everything for the first time on Windows 10 operating system with the latest NodeJS installed. I have tried to check online for various similar error code and how it was solved and still not working

C:\Users\****>npm -g install ethereumjs-testrpc@beta

I expected to get successful result but got this error code

npm ERR! code ETARGET
npm ERR! notarget No matching version found for ethereumjs-testrpc@beta
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.


texts: Is my ethereum solidity contract correct and safe

texts:
I am very new using Solidity to create Ethereum contracts and would like to know if the contract I have created is first correct and safe to use.

What I am doing in this contract is allowing the user to send some ETH from their wallet to a friends wallet but also take a $0.05 fee (194740000000000 wei at time of writing) for using my services.

Now when testing the contract using remix all works fine, but as I am new to solidity contracts I just wanted to get some expert opinions to make sure I am doing everything correctly and safety.

My contract code is:

 pragma solidity ^0.5.1;

 contract Forwarder {

 address payable public receiversAddress = 0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C;
 address payable public feeAddress = 0xdD870fA1b7C4700F2BD7f44238821C26f7392148;

 constructor() payable public {
   uint amountToSendReceiver = msg.value-194740000000000;
   receiversAddress.transfer(amountToSendReceiver);
   feeAddress.transfer(194740000000000);
  }

 }

As mentioned everything works fine in remix, but is my contract code correct and safe to use? There is no way to use the contract after to maybe steal funds or have any vulnerabilities?


texts:
I'm calling an ethereum contract function with the following inputs. However it returns an error saying the numbers are not a base 16 number.

Code

function checkResult(string str1, uint num1, uint num2) public returns (bytes){
// do something

Geth Input

testcontract.checkResult("test",4,21);

Error

Error: new BigNumber() not a base 16 number:
    at L (bignumber.js:3:2876)
    at bignumber.js:3:8435
    at a (bignumber.js:3:389)
    at web3.js:1098:23
    at web3.js:1634:20
    at web3.js:826:16
    at map (<native code>)
    at web3.js:825:12
    at web3.js:4080:18


texts: I've been seeing too many threads about this. I was curious about what are they how do they function? Is it basically an automated trading algorithm that just executes trades when a cryptocurrency is first released to the public?  If so why is this a problem, this can be easily done through web scraping and python, no? Can someone explain this to me with details all the youtube videos I watched so far are kind of vague


texts:
Shouldn't following function

function transferOwnership(address newOwner) public onlyOwner {
    require(newOwner != address(0));
    OwnershipTransferred(owner, newOwner);
    owner = newOwner;
  }

be written like this:

function transferOwnership(address newOwner) public onlyOwner {
    require(newOwner != address(0));
    owner = newOwner;
    OwnershipTransferred(owner, newOwner);
  }

To follow best practices of Check-Interact-Effect pattern?


texts: I set the --targetgaslimit parameter of all nodes of my private network, but the gas limit keep falling towards the default value, it is like it's not set.


texts: ETH transaction sent at a very low gas price, failed, but still says pending

texts:
I am using Atomic Wallet, and I sent some ETH to an online exchange.

The (1) first time it Failed from Etherscan status at 9 Gwei and and Gas Limit of 21,000. It said 100% limit was used.

The (2) second time, I used 6 Gwei and Gas Limit of 29,243, and it failed because 100% gas limit was used. This transaction took 2 hours and 8 minutes.

Due to the fear that I set a value too low, I sent a very small (3) third transaction to "replace" this one, thereby cancelling it, but I could not set the nonce value, and thus, it was different than the previous transaction. So it was a waste at the end. And it Failed as well as the Gas limit 100 % was reached.

My concern now is that, on my Atomic Wallet it is saying that these last two transactions are still pending, but on Etherscan, the status is "Fail". "Out of gas". So what do I do now to get the ETH onto the exchange? Should I wait for the Atomic Wallet to remove the Pending status, or send it again? And, if so at what Gas Price and Gas Limit? I would like it up there within 30 mins or so.

Thank you very much,
R.K


texts: buidler: address already in use (port 8545)

texts:
I'm trying out the buidler suite using scaffold-eth. I can start up using yarn start fine, but when I run yarn run chain I get the following error:

Error: listen EADDRINUSE: address already in use 127.0.0.1:8545
    at Server.setupListenHandle [as_listen_2] (net.js:1309:16)
    at listenInCluster (net.js:1357:12)
    at GetAddrInfoReqWrap.doListen (net.js:1496:7)
    at GetAddrInfoReqWrap.onLookup [as oncomplete] (dns.js:69:10)
error Command failed with exit code 1

Looking at yarn run chain in the package.json yields that it moves in to the buidler directory and executes npx buidler node. A cursory look at the error looks like buidler defaults to port 8545, but that port is indeed already in use on my machine.

The answer should be simple enough - I just need to have buidler launch the dev chain on a different port. I've looked through the docs, though, and I'm not finding anything.

How do I tell buidler to use a different port?


texts: How to properly simulate mining time with Ganache CLI

texts:
I am using the Ganache CLI for testing my smart contracts and frontends. I need a way to incorporate a delay into ganache-cli when performing write transactions in order for it to more closely resemble the mainnet

I read that I should use the -b or --blockTime flag, however whenever launching ganache-cli with -b 15  my write transactions are still mined instantly.

Can anyone suggest the proper approach here?

Thanks!


texts: How to pass value when calling contract function?

texts:
Currently in Truffle I'm passing in value manually, but how do I make this value something I require. For example when I want to make a transaction on MetaMask, there's a transaction that appears requesting x value and I approve it. How would I request value from the user? I want to deploy and test this contract on Rinkeby.

TokenSaleContract.at(this.props.address)
        .then(instance => {
            contractInstance = instance;
            contractInstance.buyToken(2, {value: 507087936329796580})
            return c.numberOfTokensFromAddress('0x...')
        })
        .then(numberOfTokens => {
            console.log(`You (0x...) now have ${numberOfTokens}`);
        })


texts: Mining Nanopool for 24H with Radeon RX 480 and yet no shares found

texts:
I am mining with Ethminer in Nanopool for around 24h (or more) and I still didn't find any shares so my account is not yet created in Nanopool. I think this is not right.

I use the miner like this:

ethminer -F http://eth1.nanopool.org:8888/0xXXXXXXX -G

Am I doing something wrong? Is this normal?

Thank you

EDIT:

I might have found the solution. As I am using Lubuntu 16.10 the AMD Property driver is not supported so I will roll back to 14.10 tonight and I will edit if I am succeed.


texts: How to protect your state variables from getting modified?

texts:
from what I understood, any state variables that are not private can be called and modified by any contract that inherets the parent contract.
it usually takes more than one contract to develope a DApp. so you eventualy need to make several contracts and may use state variables of other contracts. Or even if you don't, some one can copy your code and inherets it and modify(delete/update some data from them) your state variables.
making the sate variables private is like erasing the question. because you will lose the access to your state variables in other contracts you need.
there is a thing in solidity that if you make a state variable public. the solidity automatically creates a getter/ view fucntion for that variable callable by all users.
so how do you protect it from getting modified by other contracts/attackers?
I know that modifying them costs money but still , is there a safe way to prtect non-private state variables from getting attacked?
see the code below:
contract Reputation{
   uint[] points;          // internal, or public
}

contract Market is Reputaion{
   functio foo() public{
       points[0]= 1;
       delete points[1];
   }
}

Imagine if the Market contract is made by attacker to modify your data!


texts:
I'm using web3, truffle and testrpc.

In my smart contract, some of the functions can only be called by the owner (or creator) of the contract (i.e. onlyOwner functions). So, I've defined some modifier for that. Also, in the smart contract, I have defined a variable called owner that can be called by anyone to see who the owner is.

I'm designing a UI. I'd like to alert the users, in UI, if they call the onlyOwner functions (e.g. you're not the owner). In my .js file I can call owner.call(); to get the owner address. But I don't know how to get the users address to compare it with the owner address.

Question: How can I get the user's address via web3?

Also, when we switch the default account (i.e. the first account) in MetaMask to 2nd, 3rd, .. account, how the .js file can recognize it and use that account as the default one?


texts: What makes the value of custom/created erc20 tokens go up and down?

texts:
So suppose a million custom erc20 tokens are created/pre-mined and sent to an address on the ethereum network.  The coins have a starting worth of 0 eth. The coins are then somehow distributed to a bunch of people who have some sort of arbitrary use for the tokens.
What makes the tokens gain some eth value? What makes this value go up and down? Is there an algorythm in place that rates the token value based on how decentralized the token is, transfer frequency, etc? What other factors can cause the stated value of the coin on the block chain to go up and down?


texts: Deploy new contract through another contract function in Truffle

texts:
I have a function in my contract minter.sol that creates another contract etnX.sol:

function createNewContract(string memory name, string memory symbol, uint256 _maxSupply)
public onlyOwner {
    etnX c = new etnX(name, symbol, _maxSupply, address(store));
}

I want to call this function in truffle and get new contract address.
I'm trying to do so:

const minter = artifacts.require('../contracts/minter.sol')
const etnX = artifacts.require('etnX')
const etnXs = [100,200,500,1000,10000,100000,1000000,10000000]
module.exports = async function(deployer) {
    deployer.deploy(minter).then(async() => {
       var minterInstance = await minter.deployed();
       for (var i=0; i<etnXs.length;i++)
           await minterInstance.createNewContract("x","x", etnXs[i]);
           var x = await etnX.deployed();
           console.log(x.address);
    })
};

However, it doesn't deploy. Can someone explain me how to do this?


texts: I'm trying to call a function contract from web3. The web3 provider is metamask and the metamask popup opens up when it should however when I click confirm I just see a loader and nothing happens. When I click away and open metamask again, it just says that the transaction is approved but not confirmed. The code I'm using is pretty much exactly whats in the docs. Why is this happening?


texts: Revert() workflow in re-entrancy vulnerablity?

texts:
I am studying the following code

contract Mutex {
bool locked;
modifier noReentrancy() {
    require(!locked);
    locked = true;
    _;
    locked = false;
}
 function f(unit256 amount) public noReentrancy returns (uint) {
    msg.sender.call.value(amount)("");
  }
}

Below is the execution  flow that I am following (Please let me know if I am  wrong):

The attacker contract calls the vulnerable function to withdraw 10 ether.
The victim contract executes the opcode and transfers 10 ether to the attackers contract.
The fall back func gets executed in the attacker contract.
The fall back func calls the withdraw function again.
But require statement catches the attack and reverts the whole transaction.

My question is:
Would revert statement also revert the ether flow in step 2. If yes, How? because  ether has already been deposited into the attackers account.


texts: Lightweight Ethereum client for Android and IOS

texts: Are there any available Lightweight version of Geth or Parity client on Android or IOS in order to avoid using Infura service when accessing blockchain form a mobile app?


texts: Contract state variable change after throw

texts:
Is there a possibility to change a state variable and then throw an error, so that the state is maintained. e.g.:

uint minAmount = 1 ether;
uint state;
function payDeposit() payable {
    if(msg.value < minAmount ) {
        state = 2;
        throw;
    }
    state = 1;
 }

In the example above, the state variable is not set. Is there any way to solve this problem?


texts: How to run geth and miner.start automatically when ubuntu startup(private blockchains)

texts:
I know write this in etc/rc.local

geth --datadir "./" --networkid 15 --identity testnode --port 30303
--rpc --rpcapi=db,eth,net,web3,personal --rpcport 8545 --rpccorsdomain "*" --rpcaddr 192.168.XX.XX --allow-insecure-unlock console

but I do not know how to miner.start() when ubuntu startup automatically


texts:
I have seen two burnable ERC20-compatible token patterns:

implement a burn function that decreases balances[msg.sender] and totalBalance
Don't implement burn function but rather transfer tokens (that you want to burn) to 0x0 address and implement 'totalBalance()function astotalBalance - balances[0x0]`

Which one is preferred? Why would I choose one over the other?


texts:
I seem to be running the following error when I try to run this script:  ,
from brownie import AdvancedCollectible, accounts, network, config

def main():
    dev = accounts.add(config['wallets']['from_key'])
    print(dev)

My brownie-config.yaml:
# exclude SafeMath when calculating test coverage
# https://eth-brownie.readthedocs.io/en/v1.10.3/config.html#exclude_paths
reports:
  exclude_contracts:
    - SafeMath
dependencies:
  - smartcontractkit/chainlink-brownie-contracts@1.0.2
  - OpenZeppelin/openzeppelin-contracts@3.4.0
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.0.2'
      - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@3.4.0'
dotenv: .env
wallets:
  from_key: ${PRIVATE_KEY}
  from_mnemonic: ${MNEMONIC}

The error:
brownie run scripts/advanced_collectible/deploy_advanced.py

Brownie v1.14.3 - Python development framework for Ethereum

NftdemoProject is the active project.

Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'...

Running 'scripts/advanced_collectible/deploy_advanced.py::main'...
  File "brownie/_cli/run.py", line 49, in main
    return_value, frame = run(
  File "brownie/project/scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File "./scripts/advanced_collectible/deploy_advanced.py", line 4, in main
    dev = accounts.add(config['wallets']['from_key'])
  File "brownie/network/account.py", line 132, in add
    w3account = web3.eth.account.from_key(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 246, in from_key
    key = self._parsePrivateKey(private_key)
  File "eth_utils/decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "eth_account/account.py", line 694, in _parsePrivateKey
    return self._keys.PrivateKey(HexBytes(key))
  File "hexbytes/main.py", line 23, in __new__
    bytesval = to_bytes(val)
  File "hexbytes/_utils.py", line 17, in to_bytes
    return hexstr_to_bytes(val)
  File "hexbytes/_utils.py", line 50, in hexstr_to_bytes
    return binascii.unhexlify(ascii_hex)
Error: Non-hexadecimal digit found

I made sure I have my keys set in my .env file as export PRIVATE_KEY='0x...", so why is it not able to pull the variable from it or am I missing some step here? Any advice would be appreciated. Thanks!


texts: Should I use `storage` or `memory` when just reading the value and not changing state?

texts:
pragma solidity 0.4.24;

contract Test {

    struct Book {
        uint id;
    }

    Book[] books;

    uint public status;

    constructor() public {
        books.push(Book(10));
    }

    function changeStatus1() external {
        Book storage book = books[0];
        if (book.id == 10) {
            status = 1;
        }
    }

    function changeStatus2() external {
        Book memory book = books[0];
        if (book.id == 10) {
            status = 2;
        }
    }
}

It seems like the method that uses storage costs less gas (26982 vs 27063). What is the best practice when just reading the value (and maybe using it in an if statement). Should I use storage or memory?


texts:
I am getting the error Error: Invalid number of arguments to Solidity function for the constructor of my contract and no idea why.

I just upgraded to Truffle 4.0.0 beta and using the truffle develop test environment instead of testrpc. These tests used to pass, but now they are giving me errors.

Contract constructor

function MyContract(
        bytes _eventName,
        bytes32[] _eventResultNames,
        uint256 _eventBettingEndBlock,
        uint256 _decisionEndBlock,
        uint8 _averageBlockTime,
        uint256 _arbitrationOptionMinutes)
        public
        payable
    {
        ...
    }

Mocha test class

const params = {
        _eventName: "test",
        _eventResultNames: ["first", "second", "third"],
        _eventBettingEndBlock: 100,
        _decisionEndBlock: 120,
        _averageBlockTime: 10,
        _arbitrationOptionMinutes: 1440
    };
const baseReward = Utils.getBigNumberWithDecimals(10, nativeDecimals);

let myContract;

beforeEach(async function() {
        myContract = await MyContract.new(...Object.values(params), { from: creator, value: baseReward });
    });

Error message

1) Contract: MyContract New MyContract inits the MyContract with the correct values:
     Error: Invalid number of arguments to Solidity function
      at Object.InvalidNumberOfSolidityArgs (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43993:16)
      at SolidityFunction.validateArgs (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:357969:22)
      at SolidityFunction.toPayload (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:357985:10)
      at SolidityFunction.call (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:358026:24)
      at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:326504:16
      at Promise (<anonymous>)
      at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:326495:18
      at <anonymous>

How do I fix this error?


texts: Data storage and replication in a private blockchain

texts:
What type of data is Ethereum storing (file? data row in DB)?

Where does it put it (theoreticaly it is stored in peers, does this mean every node must have a local db)?

How the peers of the p2p network get the recent copy of the blockchain?

how a peer learn that there is a new block created and need to be mined?


texts:
Did I miss any trie below and get things right?

Transaction tries, one per block, root hash included in the block header
Transaction receipt tries, one per block, root hash included in the block header
Storage tries, one per account, root hashes across accounts used to build the state trie
State trie, one per world state, updated root hash included in the block header


texts: How can I add two plus two on the Ethereum virtual machine

texts: Ethereum is quite different from bitcoin, and in my opinion better. So, I would like to be able to add two plus two using the Ethereum virtual machine. I don’t have any ether, and I’m just curious how to do it and how much money the calculation would cost and if this is feasible.


texts: Why is the price of ether on CEX.io higher than on Coinbase?

texts:
When I checked the price of Ether on CEX.io I noticed that there is a difference compared to Coinbase's price. Actually, the difference is more than 20$!

Does anyone know why there is a difference between these sites?


texts: When will the difficulty bomb make mining impossible?

texts: I know the answer must be out there in the code already, but I couldn't figure out where exactly. Could someone do the maths for me: With block 200k the difficulty bomb started increasing the difficulty, but when will the difficulty bomb make mining impossible?


texts: What economical GPUs are available and in-stock now for mining ETH?

texts:
I'm new to this and I want to get into building an Ethereum mining rig. But everywhere I look it seems that the usually suggested GPUs (Rx 480s, R9 Furys, etc.) for mining ETH are all sold out / unavailable! I've tried the new RX 5xx series but they just crash my computer.

Can anyone suggest a GPU that can mine at average speeds of 20-30 MH/s and be reasonably priced?


texts:
Can contract find the nonce of EOA while executing?

Is there any way to make contract to check nonce of EOA while execution?

Thank you.


texts: How to upload contract metadata to Swarm from command line?

texts:
I'm running a geth node in a private network, and running swarm in singleton mode on that network. I'm deploying contracts via JSON-RPC; I'm not using JavaScript.

I run the command solc --optimize --metadata --bin -o . ./coin.sol which produces the files Coin_metadata.json and Coin.bin

The file Coin.bin contains the string:

60606040...a165627a7a723058208686fb331b117b51a664d9295258b00944f066540bfda4eef32934b197d5cbf60029

Solidity documentation says

  So in order to retrieve the data, the end of the deployed bytecode can
  be checked to match that pattern and use the Swarm hash to retrieve
  the file.

So, the Swarm hash is

8686fb331b117b51a664d9295258b00944f066540bfda4eef32934b197d5cbf6

My question is: What content must I upload to Swarm, via command line, to get exactly the previous hash?

I've upload all files individually and the directory containing them, but any upload produces the previous hash.

Thanks in advance.


texts: Best way to burn ethers and other ethereum tokens?

texts:
Is it correct that any ethers or tokens sent to the address 0x0000000000000000000000000000000000000000 will be destroyed?

Or what is the best way of burning ethers / tokens?


texts:
How to get length of foo[1] in example below in assembly?

uint[][] foo; // foo.length = 2, foo[1].length = 3

function getLength() returns (uint len) {
    assembly {
        len := sload(foo) // returns 2
        len := sload(........) // how to return foo[1] ?
    }
}


texts:
I am new to React and don't know where I should put the code to .watch() for Solidity events.

Right now, I the code in a member function of my main App class. As is, I am successfully capturing events emitted by my contract ... but only when the page loads.

My goal is to subscribe to events so that I can log them as soon as they occur, but with React, I'm not sure where the proper place to put that code would be:

import React, { Component } from 'react';
import AttendanceData from '../build/contracts/AttendanceData.json';
import getWeb3 from './utils/getWeb3';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      contract: null,
      name: "",
      storageValue: 0,
      eventId: 0,
      currentEventValue: 0,
      hasContributed: false,
      isLoggedIn: false,
      loggedInAddress: "",
      web3: null
    }
  }

  componentDidMount() {
    getWeb3
    .then(results => {
        this.setState({
            web3: results.web3
        })
        const contract = require('truffle-contract');
        const attendanceData = contract(AttendanceData);
        attendanceData.setProvider(this.state.web3.currentProvider);
        this.setState({contract: attendanceData});
        attendanceData.Contributed({}, {fromBlock: 1, toBlock: 'latest'});
        contributedEvent.watch(function(error, result) {
            if(!error){
                console.log("Event captured:", result);
            }
            else{
                console.log("Error capturing event:", error);
            }
        });
    })
    .catch(() => {
      console.log('Error finding web3.')
    })
  }

  contribute() {
    const attendanceData = this.state.contract;

    // Declaring this for later so we can chain functions on AttendanceData.
    var attendanceDataInstance;

    // Get accounts.
    this.state.web3.eth.getAccounts((error, accounts) => {
      attendanceData.deployed().then((instance) => {
        attendanceDataInstance = instance;
        // Stores a given value, 5 by default.
        return attendanceDataInstance.contribute({value: this.state.web3.toWei(this.state.amountToContribute, 'ether'), gasPrice: 2000000000, gas: 300000, from: accounts[0]})
      }).then((result) => {
        console.log("Was successful: "+result);
      }).catch((err) => {
        console.log("Failed with error: " + err);
      });
    })
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.contribute}>CONTRIBUTE!</button>
      </div>
    );
  }
}

export default App;


texts: Someone sent 0 ETH to my contract and got 134100 tokens

texts:
we have just finished a phase of our ICO and we were looking among the transactions. Someone managed to send 0 ETH to our contract and in return got 130 000 tokens. How did he do that and how vulnerable is our system?

This is the holder with our tokens:
https://etherscan.io/token/0x9a9ae6884c65725c8f5378dbb6d3900bff36da53?a=0x2bf6064d8fdb75af047d3db4743d436adb326312

These are his transactions. He seems to have created his own contract and he has done the same to someone else:
https://etherscan.io/address/0x2bf6064d8fdb75af047d3db4743d436adb326312

Please help


texts:
I have a private network for testing. My problem is when ever I stop running geth network, all of my mined blocks are gone. I run like

geth --datadir "ethereum/node1" --port 30301 --networkid 1234 --rpc --rpcport "8545" --rpcapi db,eth,net,web3,personal --ws --wsport "8546" --rpccorsdomain "*"

(sometimes I use nohup) and I stop the server using cntrl+c. When geth is running I check block number using eth.blockNumber and it will show block number and it will increment. After I stop and start my server then I check using eth.blockNumber it always shows 0 and it takes some hour to mine blocks. Due to this, I'm lossing many of test data. Is this a common problem? Is there any work around to prevent this? Any idea will be helpful. Thank you.


texts: What's the best way to receive ether payments in rails?

texts:
I'm new to the field, I usually work with Stripe on Rails to get traditional payments. Do you have some advice to get paid with Ether crypto coins on Rails ?

Which online merchant services or Ruby libraries can you suggest ?


texts: Can we use Ethereum Swarm to store normal data other than blockchain or dapp data.

texts: I want some basic data to be stored like name and city phone no etc.So just want to ask can I use ethereum swarm just to store file and make several node to create decentralized storage.


texts: org.web3j 4.5.18 ethGetBalance get stuck

texts:
I'm using the following simple code in order to obtain the wallet balance:

Credentials credentials = Credentials.create(privateKey);
web3.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).sendAsync().get().getBalance();

After retrieving the correct amount, the method simply get stuck, keeping running. Any idea?


texts:
I picked up an Ethereum Blockchain at AWS ECS almost 3 months ago, it was working perfectly until I got this bug yesterday from the mining node:

unexpected fault address 0x7fb93c71d000
[signal SIGBUS: bus error code=0x2 addr=0x7fb99641a000 pc=0x4733c0]
goroutine 273542628 [running]
runtime.throw(0xf75488, 0x5)

I managed to get the mineral back and have it replicated from the client, but it turns out that it has happened again and it has even happened to me already in the client. This address is not linked to any wallet or hash of transaction or anything processed by the Blockchain. What could be the cause of this error and how to avoid it?
Using Geth/v1.8.2-stable/linux-amd64/go1.9.7


texts: Replacement of Bitcoin's 'account' and 'listunspent'

texts:
I accept Bitcoin at my website. I use self-developed merchant, based on Bitcoin Core JSON-RPC calls. Now I also want to accept Ethereum. I downloaded geth and as I see it has absolutely different, counter-intuitive API.

I can't see any 'account' paradigm there. How can I map order id to address in Ethereum. I need to create additional database for mapping? Actually, I can't even manage how to create new addresses for every order. What method I have to use?
What methods I need to use instead of ListUnspent, CreateRawTransaction, SignRawTransaction and SendRawTransaction?


texts: I understand the process of development of dapp in javascript. Web3 api is used in order to access deployed contracts and truffle can be used for deployment. I want to create an api using Go language for my ethereum contracts so that I can connect it to the rest of the application that is created in go. Is it possible to develop everything in go instead of js? If yes, please point me to the resources. I couldn't find equivalent of this on ethereum's github page.


texts: I have a private ethereum network made up of multiple nodes and I would like one of them to interact with the a deployed smart contract without my input. Is it possible for create a script that will write to and read from a smart contract once an hour?


texts: Ether Address returned is different (second half) from the one stored in contract's array


texts: Private Ethereum Smart Contract API call to notify (without needing the external api response to update the state) without using Oraclize

texts:
In a Private Ethereum Smart Contract, can we do an external API call just to notify (without needing the external api response to update the state) without using Oraclize?

Understand Oraclize is required for external API calls like those internet ones. If one only needs an api call to notify an external system that this step is completed, how would one achieve this without the need of Oraclize?

Thank you.

Nathan Aw


texts: Remix Unit Testing: Fail message is giving wrong name of the test file

texts:
I am trying to do unit testing using Remix using the tutorial at Simple Contract at Medium, but it is giving me a FAIL message with “browser/tests/4_Ballot_test.sol) file highlighted with blue background. On the other hand , I am using the file browser/tests/SimpleStorage_test.sol.
I have attached the image.
Somebody please guide me.
Zulfi.


texts: I'm looking for a lightweight wallet. I can't find one listed on the site. Just the full node. What are your recommendations.


texts: How to access a token instance created by another smart contract constructor

texts:
I am using a smart contract which creates a token instance in its constructor:

contract Exemple{

       Token public myToken

       function Exemple(){
               myToken=Token(this);
       }
}

How can i access this token instance from outside of the contract (using truffle console)? For instance to make a command such as: myToken.approve(address,value, {from: other_account})

Hope my question makes sense. Just a beginner here...


texts: How to know, inside the contract function, the amount of gas that will be refunded in the end

texts:
Consider the following situation: my function can be divided into 2 parts

Always consumes constant gas;
Always results in a refund of 0 < R < 1500000 gas.

After the second part had happened, but before the end of a function call, how do I know the value of R?

The problem is that the msg.gas(which is remaining gas) doesn't account for the refund(cause the refund cannot be used inside the transaction itself). Due to this the following approach will fail:

uint startGas = msg.gas;                   // e.g. 100000 gas
delete myArray;                            // consumes 40000 gas, but will refund 20000 in the end
uint gasUsed = startGas - msg.gas + 21500; // gasUsed = 100000 - 60000 + 21500 == 61500 gas (21500 is for initial tx and function call)

We estimated that the gas spent for execution will be 61500, but in fact, after the refund, transaction receipt gasUsed value will be 41500.

I wonder if there is something like msg.refundGas is planned, or should I create a feature request?


texts:
I am building an auction smart contract in Remix with random winners being picked.
And I am not getting any value out of the following function:

 }
    function revealWinners() public {
        for (uint id = 0; id <3; id++) {
            Item storage currentItem=items[id];
            if(currentItem.itemTokens.length != 0) {
                uint randomIndex = (block.number /
                currentItem.itemTokens.length)% currentItem.itemTokens.length;
                uint winnerId = currentItem.itemTokens[randomIndex];

            }

Everything else is working as it should but I have been stuck on this for a while, anyone here have an idea what I am missing?


texts: Transaction disappeared from the pending transactions in node

texts:
My ether wallet has been working for more than 1 year. Today There was a memory issue in my node and the node shutdown. When I restarted the node via geth client the node resound ~5000 blocks behind and started syncing again. My node was traying to catch up ~5000 blocks which took hours.

One of my customers had submitted a transaction during this time and it was stuck in the nodes pending transactions for 3 hours.

I was continuously checking the status of the transaction.

Since the sync was slow, I restarted the node.

I checked the node again after sometime and suddenly I noticed that the transaction was no longer in the pool.

eth.getTransaction was returning null. Its not showing-up on etherscan also.

What happened to my transaction?
Did the node restart clear the transaction from the pool?
Did it timeout and disappear?

Any help to figure this out is appreciated.


texts: Is there any GUI Ethereum Wallet that let's you manually set gas price?

texts: Is there any GUI wallet that lets you manually set the gas price? I've tried MyEtherWallet and Mist but both only have a sliding fee bar with an upper limit to the fee. Is my only alternative a command line wallet like Geth?


texts: Issue in Dapp using Angular 11.1.0 and web3 1.3.4 and Rinkeby metamask, getting error on new Web3(window.web3.currentProvider)

texts:
I am trying to create DAPP using Angular 11.1.0. I am able to deploy the contract on Rinkeby test network successfully. But on Client side getting below error on loading Web3@1.3.4 js.
Getting error:
Error: Uncaught (in promise): TypeError: Class extends value undefined is not a constructor or null
TypeError: Class extends value undefined is not a constructor or null
    at push.4HPa.module.exports (keccak.js:3)
    at push.yYxu.module.exports (index.js:5)
    at Object.aYMp (js.js:1)
    at __webpack_require__ (bootstrap:84)
    at Object.wzGL (keccak.js:4)
    at __webpack_require__ (bootstrap:84)
    at Object.6yEv (hash.js:4)
    at __webpack_require__ (bootstrap:84)
    at Object.cAFe (account.js:9)
    at __webpack_require__ (bootstrap:84)
    at resolvePromise (zone-evergreen.js:1209)
    at resolvePromise (zone-evergreen.js:1163)
    at zone-evergreen.js:1275
    at ZoneDelegate.invokeTask (zone-evergreen.js:402)
    at Object.onInvokeTask (core.js:28481)
    at ZoneDelegate.invokeTask (zone-evergreen.js:401)
    at Zone.runTask (zone-evergreen.js:174)
    at drainMicroTaskQueue (zone-evergreen.js:578)

This is my config:
Angular 11.1.0 and web3 1.3.4
This is my code:
import { Injectable} from '@angular/core';
import Web3 from 'web3';

declare let require: any;
declare let window: any;

@Injectable({
  providedIn: 'root'
})
export class TransferService implements OnInit {
  private _web3: any;

  constructor() {
    if (typeof window.web3 !== 'undefined') {
      this._web3 = new Web3(window.web3.currentProvider);
  }
 }
}

In polyfills.ts added below
declare var require: any;
declare var global: any;
(window as any).process = {
  env: { DEBUG: undefined },
  version: ''
};
(window as any).global = window;
global.Buffer = global.Buffer || require('buffer/').Buffer;

Please guide me to solve this as I am stuck with this issue for 2 days now.


texts: How can I arrange conditional branching in truffle migration based on the chosen of the network for migration(development, ropsten, main, etc) or based on the Linux environment variables?


texts: Can we use web3 on the client side only?

texts:
I have low cost hosting and I cannot install node etc. I have basically just rights to use html and run javascript. Can we use web3 on that basis or do I need a server side installation of node or something like that?

I tried using -

const Web3 = require('web3');

and I get not defined because I have no node installed I think.


texts:
Several hours ago I sent the transaction 0xe9cca30f9d8d2040a3c6c5ceb6601240b0c095a47ac9117dd34e36c0d66be2f7 into Ethereum testnet. When asking a node about it, everything seems right (confirmed transaction):

> eth.getTransactionReceipt("0xe9cca30f9d8d2040a3c6c5ceb6601240b0c095a47ac9117dd34e36c0d66be2f7");
{
  blockHash: "0xed3c145b87b83a52c42eb9f54c02e05be0da4b0723faf82ee1237b1b599bd180",
  blockNumber: 1806280,
  contractAddress: null,
  cumulativeGasUsed: 43282,
  from: "0xbeb1c53c48f916e099f0d13d3c65f8943dd8ddd2",
  gasUsed: 22282,
  logs: [],
  root: "53f83e77cd68ccee638efcb753426238d5483bf9879086fd3e19288742515596",
  to: "0x27c042342c9ba937214117e11a4970a6145034cb",
  transactionHash: "0xe9cca30f9d8d2040a3c6c5ceb6601240b0c095a47ac9117dd34e36c0d66be2f7",
  transactionIndex: 1
}

Nevertheless, this transaction is not visible through etherscan explorer:

https://testnet.etherscan.io/tx/0xe9cca30f9d8d2040a3c6c5ceb6601240b0c095a47ac9117dd34e36c0d66be2f7

  Unable to locate Transaction entry

Not sure if it has something to do with Incoming transaction confirmed but not showing in Mist wallet

Is there any reason that can explain the anomaly? Thx!


texts: Is there best practice for graceful exit on low gas?

texts:
In unbound loops I often use a low gas test to break and allow the function to complete gracefully.

while (msg.gas > 40000) { ...do something...}

In some previous code review, the reviewer mentioned that gas costs (or other dynamics) may change in the protocol at some future time.

Q1. Does anyone have any reference to possible changes?

Q2. Can anyone suggest other graceful exit practices?


texts:
I'm new in Ethereum, and I would like to buy a very smart amount of Ethereum.

I want to learn more about ETH, and at the moment I would like to invest $10 or $15.

Do you know any website where I can buy this small amount? I already have a wallet.

Thank you.


texts: how to remove all traces of parity on windows

texts:
I previously tried to delete parity from this machine, ans succeeded to an extent.  but there is still something running in the background, taking up memory.  until the thing stops running, it won't let me delete the info.

does the following picture help any with diagnosis?  the memory amounts associated with these folders keep changing, so something is running.  I've tried using task manager, but don't see anything obvious.. thanks!