texts: Ecrecover function doesn't trigger when called in truffle test

texts:
I am trying to run some tests for my ecrecover function. I saw a bunch of tutorials and I always have the same problem, my contract always reverts before anything is being logged.

Contract function

event Test(bytes32 _msgHash, uint8 _v, bytes32 _r, bytes32 _s);
    function registerAddress(address _addr, bytes32 _msgHash, uint8 _v, bytes32 _r, bytes32 _s) public returns (bool) {
        emit Test(_msgHash, _v, _r, _s);
        if (_v < 27) _v += 27;
        emit Test(_msgHash, _v, _r, _s);
        if (_v != 27 && _v != 28) revert();
        emit Test(_msgHash, _v, _r, _s);
        if(ecrecover(_msgHash, _v, _r, _s) != _addr)
        {
            emit Test(_msgHash, _v, _r, _s);
            revert();
        }

        registeredAddresses[_addr] = true;

        emit LogRegisterAddress(_addr);

        return true;
    }

Test Code

it('ecrecover result matches address', async function () {
    var address = owner;
    const message = 'Lorem ipsum mark mark dolor sit amet, consectetur adipiscing elit. Tubulum fuisse, qua illum, cuius is condemnatus est rogatione, P. Eaedem res maneant alio modo.';

    var sig = await generateSignature(address, message);
    var ret = await verifySignature(address, message, sig);

    var result = await coinx.registerAddress.sendTransaction(address, ret.encoded, ret.v, ret.r, ret.s, {from: address});
    assert.equal(result, true);
  });

Functions and some variables

const web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER_URL));

var node = web3.version.node.split('/')[0];
console.log('Using node=' + node);
var testrpc = false;
var geth = false;
var parity = false;
if (node === 'Geth') geth = true;
if (node === 'EthereumJS TestRPC') testrpc = true;
if (node === 'Parity') parity = true;

function generateSignature (address, message) {
  console.log('Generating signature');
  console.log('  address=' + address);
  if (testrpc) {
    var encoded = web3.sha3(message);
  }
  if (geth || parity) {
    encoded = '0x' + Buffer.from(message).toString('hex');
  }
  console.log('  encoded message=' + encoded);
  return web3.eth.sign(address, encoded);
}

async function verifySignature (address, message, sig) {
  console.log('Verifying signature');
  console.log('  address=' + address);
  let encoded;

  if (testrpc) {
    encoded = web3.sha3(message);
  } else if (geth || parity) {
    encoded = web3.sha3('\x19Ethereum Signed Message:\n' + message.length + message);
  }
  console.log('  encoded message=' + encoded);
  if (sig.slice(0, 2) === '0x') sig = sig.substr(2);
  if (testrpc || geth) {
    var r = '0x' + sig.substr(0, 64);
    var s = '0x' + sig.substr(64, 64);
    var v = '0x' + sig.substr(128, 2);
  }
  if (parity) {
    v = '0x' + sig.substr(0, 2);
    r = '0x' + sig.substr(2, 64);
    s = '0x' + sig.substr(66, 64);
  }
  console.log('  r: ' + r);
  console.log('  s: ' + s);
  console.log('  v: ' + v);

  var ret = {};
  ret.r = r;
  ret.s = s;
  ret.v = v;
  ret.encoded = encoded;
  return ret;
}

Version:

Truffle v4.1.13 (core: 4.1.13)
Solidity v0.4.24 (solc-js)
npm v5.4.2
node v8.7.0


texts: Truffle Drizzle ContractData call keccak256 error

texts:
I started with truffle unbox drizzle
then made use of my contract.

I can make use of the ContactForm without error in App.js:

<ContractForm
  contract="TheContract"
  method="addData"
  labels={["Title", "Detail"]}
/>

However if I call:

<ContractData
  contract="TheContract"
  method="getData"
  methodArgs={[accounts[0], 0, { from: accounts[0] }]}
/>

It appears as if Drizzle goes through the entire abi and attempts to apply the generateArgsHash and fails at some point where the str is undefined.

Why it does this and not use the method args only, I do not know.

Any ideas please.


texts:
I want to have a mobile geth implementation on my android device and started with this code: https://github.com/ethereum/go-ethereum/wiki/Mobile-Clients:-Libraries-and-Inproc-Ethereum-Nodes .

Then i configured the testnet like this:

NodeConfig nc = new NodeConfig();
nc.setEthereumNetworkID(3);
String genesis = Geth.testnetGenesis();
nc.setEthereumGenesis(genesis);
node = Geth.newNode(getFilesDir() + "/.ethereum", nc);
node.start();

At first, this worked fine and the blocks were synced, but 6 weeks ago it suddenly stopped working and in the android monitor displays:

Starting P2P networking
Light client mode is an experimental feature
started whisper v.5.0
RLPx listener up self="enode://b97dcd39adedc6cedda20eae4d5827513fecb83c3744b2c499219845f89b4a8fe498b875b17ee4197702d0470cc1b33c5605bf1ccf998ce54fdf1150a8438324@[::]:38134?discport=0"
D/DisplayLatestBlock: Could not display the latest block: no suitable peers available

Does anybody have a solution for this problem?


texts: how do you check if the account exists in current state?

texts:
Currently there is no way to check somehow that an account exists in the trie. I am looking for something like this:

> web3.eth.accountExist("0x743623152a53b53be5f3463746726373")
true
>

Is a function like this available in console?

Note, I want to check in the state trie (the StateDB database stored in LevelDB), not in the list of users' wallets.


texts:
I'm working on a project where I would like to catch internal transactions and figure out the stack trace. For this reason, I have been trying to define an EVM log collector as recommended here. Unfortunately that answer is 4 years old and EtherQuery library is no longer maintained. My code is the following:

snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), map[common.Address]core.GenesisAccount{}, true)
preRoot := statedb.IntermediateRoot(false)
defer func() {
    if _, err := snaps.Journal(preRoot); err != nil {
        panic(err)
    }
}()

var tracer *tracers.Tracer
tracer, err := tracers.New("callTracer")
if err != nil { panic(err) }

vmCfg := vm.Config{ Debug: true, Tracer: tracer, NoRecursion: true }
env := vm.NewEVM(vm.Context{BlockNumber: big.NewInt(1)}, statedb, params.TestChainConfig, vmCfg)

contract := vm.NewContract(account{}, account{}, big.NewInt(0), 10000)
contract.Code = []byte{byte(vm.PUSH1), 0x1, byte(vm.PUSH1), 0x1, 0x0}

_, err = env.Interpreter().Run(contract, []byte{}, false)
if err != nil { panic(err) }
fmt.Println(tracer.GetResult())

After running this snippet, I get the following:

[] TypeError: cannot read property 'toString' of undefined    in server-side tracer function 'result'

How should I set up the tracer? Thanks!


texts: Using constructor() and the fallback function in the same contract gives error

texts:
I'm trying to compile something that mirror a pattern like this and getting the following error from remix:

"browser/ballot.sol:26:3: DeclarationError: Function with same name and arguments defined twice.
  constructor() public {
  ^ (Relevant source part starts here and spans across multiple lines).
browser/ballot.sol:31:3: Other declaration is here:
  function() public payable {}
  ^--------------------------^"

the code (if I comment out the second fallback function, it works):

pragma solidity ^0.4.0;

contract C {

  address public owner;
  address public creator;

  constructor (address _creator) public {
    owner = tx.origin;
    creator = _creator;
  }

  function() public payable {}

  function printOwner() public view returns(address h) {
      h = owner;
  }

}

//factory contract for C
contract CFactory {
  address public owner;
  address public currentContractAddress;

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

  //function() public payable {}

  function test1() public returns(address){
    C c = new C(currentContractAddress);
    return c.printOwner();
  }

}


texts: For multi sign transaction, who will pay gas?

texts: For multi sign transaction, who will pay for the gas? Any sample code? I am not quite sure about this.


texts: If statement in for loop not filtering out items

texts:
// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
    // @return _id - list of ids for homes
    function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
        uint [] results;
        for(uint i = 0 ; i<homes.length; i++) {
            if(keccak256(homes[i].physicalAddress) == keccak256(_physicalAddress) && homes[i].available == true) {
                results.push(homes[i].id);
            }
        }
        return results;

    }

The result is supposed to be a list of ids which match the physical address entered however it does not filter through but returns all the available homes.
When I change to using String utils nothing changes.

Here is the whole code:

pragma solidity ^0.4.0;

import "browser/StringUtils.sol";

// @title HomeListing

contract HomeListing {

struct Home {
    uint id;
    string physicalAddress;
    bool available;
}
Home[] public homes;
mapping (address => Home) hostToHome;
event HomeEvent(uint _id);
event Test(uint length);
constructor() {

}

// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
function addHome(string _physicalAddress) public {
    uint _id = uint(keccak256(_physicalAddress, msg.sender));
    homes.push(Home(_id, _physicalAddress, true));
}

// @param physicalAddress - the actual address of the home a host wants to list (not the ethereum address)
// @return _id - list of ids for homes
function listHomesByAddress(string _physicalAddress) public returns(uint [] _id ) {
    uint [] results;
    for(uint i = 0 ; i<homes.length; i++) {
        string location = homes[i].physicalAddress;
        if(StringUtils.equal(location,_physicalAddress )) {
            results.push(homes[i].id);
        }
    }
    return results;

    }
}


texts: web3 only works with metamask but no mobile metamask or trustwallet etc

texts:
i stripped down to the bare minimum to interact with a contract with metamask
it works nice, i can call/transact nicely with only minimum of html/js
but on mobile metamask or trustwallet it simply does not do anything at all.
please see my jsfiddle https://jsfiddle.net/540uayj6/
what did i miss? i tried putting web3.js manually in script tags, did not help.
thanks for any hints.


texts: COB token transfer failed with error: "Bad Instruction"; will I get my tokens back?

texts:
I transferred 10 COB tokens from my one address 0x782e265f911167e4FDbfbFb63a32cC27341724E7 on my Metamask wallet to another Metamask wallet address 0x0a42AD94FC81db989575365Be28DCd64417Ce564 but the transaction (TXHash: 0x195698e304112a6b1c4f5f3879c6ab796d7d1165550018250557ad73e7fd4d0a did not go through properly and returned error:

  Warning! Error encountered during contract execution [Bad instruction]

Even though the transaction history shows that the transaction was successful (see screenshot below), my transaction had failed. Failed transaction is here:


texts: Error: VM Exception while processing transaction: out of gas on TEST RPC

texts:
function allowServiceProvider(bytes32 _name,uint _votes) ifDivOptExecuted {
    // CSD can allow a service provider to submit its customers votes
    if(_votes > divOpt.votingRightsMax - divOpt.votingRightsUsed){
      // throw in case you give more votes to the service provider than allowed
      throw;
    }
    // used to dynamically map index to structure in array of structs
    // to be refactored..
    address _sp =msg.sender;
    providerOf[_sp].name = _name;
    providerOf[_sp].votingRightsMax =_votes;
    providerOf[_sp].votingRightsUsed = 0;
    providerOf[_sp].active = true;
    SpStatus('Service Provider allowed by CSD (name,votes)',_name,_votes);
  }

THE TRANSACTION IS CALLED LIKE THIS:

DividendOptionContract.deployed().then(function(instance)
  {
    return instance.allowServiceProvider(name,votes,{from:web3.eth.accounts[5]
});
  }).then(function(result)
         {
            save_th(result.tx,type)
            console.log("done");

         }).catch(function(e){
           console.log(e);

         });


texts:
Learning ethereum, I am hoping this is an easy one. I wrote a simple test contract

contract Mini{
uint balance;

// constructor
// runs once upon creation
function Mini(){
    balance = 1000;
}

function deposit(uint _value) returns(uint _newValue){
    balance += _value;
    return balance;
}

function benchmark() returns(uint _newValue){
    return 4545;
}}

When I invoke "benchmark"

    var result = myContractInstance.benchmark(function(err,res){
        console.log(res);
    });

The response is an address (e.g. 0xd1d618bcb179db8b020358710138d1a008f4f39e). I can see the transaction in etherscan. Question, how do I see the response value?


texts: How to have to two mappings to a struct?

texts:
I have a exchange type of use case in which the customer needs access to a centralised wallet based on different access methods (eg email, apikeys, actual wallet address). I tried mapping twice to the same struct and remix kicked out an error.

Here is the sample code -

struct ClientWallet {
    uint clientBalance;
    bool clientAccountExists;
    bytes32 apiKeyHash;
}

mapping (address => ClientWallet) public ClientWallets; // direct access
mapping (bytes32 => ClientWallet) public ClientWallets; // hash of email

I can code a workaround by using more structs and variables but this seems pointless. I tried mapping bytes32 to address and then to ClientWallet but that failed.

Any ideas about this?


texts:
I am writing a smart contract in solidity and I have a question in relation to the range of uint type.

My understanding is that uint is the same as uint256 and the range  of this is 0 to 2^256.

I this correct?


texts: How do I re-generate a lost Ethereum keystore file with only the Seed Phrase and Password?

texts:
If I don't have the Ethereum Software Wallet Keystore anymore, but I recorded the Seed Phrase and Password:

How can I regenerate the keystore, if possible, and

Can it be done on a Windows machine if it was originally generated on an Ubuntu 16 install, and

Will I need to use the same program to regenerate the Keystore that I used to generate it?

I ask because anyone can create a Dummy Wallet and record info, to then test how to recover wallet access after deleting Keystore.

My question is:

What text command should I use to Re-generate a lost Ethereum Wallet Keystore using only the account's Seed Phrase and Password?

I don't understand what to do as described here:
How to generate a keystore (UTC) file from the raw private key?


texts: What's happening if my variable on smart contract arrives at your limit? and what's the best practice to treat this?

texts:
I have one variable on a smart contract called count, every function call, i put one more value on her.

count++;

What's happening if my variable on smart contract arrives at your limit?

2^256 -1 ?

How i  treat this ?


texts:
When I start my app I listen for posts from the latest block. After a post has been made I'm supposed to return author (address), title (string) and an id (uint).

But what I get in the author and id field is always wrong:

returnValues:
Result {
'0': '0xc56d6494E13A21c9fe6959DC3c0F2e95317ec52d',
'1': 'something',
'2': '1404800390165147213522565871758984e835369099666681',
author: '0xc56d6494E13A21c9fe6959DC3c0F2e95317ec52d',
title: 'something',
id: '1404800390165147213522565871758984835369099666681' }

The event listener:

postListener = () => {
    web3s.eth.getBlock('latest').then((latestBlock) => {
        contract.events.Posted({
            filter: {
                author: addressList,
            },
            fromBlock: latestBlock.number,
        }).on('data', function (event) {
            console.log({ event });
        }).on('error', console.error);
    });
}

ABI:

{
    "anonymous": false,
    "inputs": [
        {
            "indexed": true,
            "name": "author",
            "type": "address"
        },
        {
            "indexed": false,
            "name": "title",
            "type": "string"
        },
        {
            "indexed": true,
            "name": "id",
            "type": "uint256"
        }
    ],
    "name": "Posted",
    "type": "event"
}

What I expect is something like:

author: '0xF6116D9AAE20eb8ca881D2D69a0456519Ae524f9',
title: 'something',
id: '10578'

The source of the contract can be found here: https://github.com/WhaleCoinOrg/WhaleNet/blob/followers/contracts/WhaleNetworkV4.sol


texts: if "address public x = tx.origin", why does "require (tx.origin == x") work and "require (tx.origin==tx.origin) not

texts:
Below is a contract that i have commented on, hoping to understand the logic of the arguments.
Below in bold is the question in question. The .sol currently works fine.

pragma solidity ^0.5.11;

contract ReceiveEther {
    uint256 public clicksfromcreatorcount;
    uint256 public count;
    address public creatorino = tx.origin;

I have a contract called "Receive Ether" with three variables. All of these variables are public, and two of them are integers,
 "clicksfromcreatorcount", and "count". The third variable is an address called "creatorino".
 It has been set to equal "tx.origin", which means "creatorino" is set to the address of the person (outside of the contract) that calls a function.

        function increaseifcreatorclicks() external {
            require (msg.sender == creatorino);
                clicksfromcreatorcount++;
        }

in this function, above, called "increaseifcreatorclicks" that is external, meaning it can be accessed from outside of the contract, "increaseifcreatorclicks" requires that that the address calling this function (msg.sender) be equal to "creatorino", the external address calling the function.
When this condition is met, the aforementioned variable "clicksfromcreatorcount" goes up by a value of 1.

        function () external payable {
            require (clicksfromcreatorcount>=1);
            if (clicksfromcreatorcount ==1) {
                require (tx.origin == creatorino);

            }
            require (count<2);
            count++;
        }
}

The function,above, that has no name can be called from outside of the contract (External) and can receive ether (payable).
Only one of these nameless functions are allowed per contract.
it requires that the value of "clicksfromcreatorcount" be greater than or equal to 1.
This means that the function can only receive ether if
"clicksfromcreatorcount" is greater than or equal to 1.
 HOWEVER, if "clicksfromcreatorcount" is exactly equal to 1, then the external address sending ether (tx.origin) must be equal to the address of creatorino???
Our payable function also has a counter called "count" that must remain less than 2 (though when i run it, it can be equal to 2 i'm not sure why) and that
every time ether is sent to the contract, the count goes up by 1
Why do I have to set tx.origin ==creatorino for this to work, and how is it different from tx.origin==tx.origin if creatorino stands for tx.origin.

contract SendEther {
        function sendViaCall (address payable _to) public payable {
            (bool sent, bytes memory data) = _to.call.value(msg.value)("");
            require (sent, "failed to send ether");
        }
}

Here we have a contract called "SendEther". It has a function called "sendViaCall". It can send ether to an address. It is public.
If it does not send, 'failed to send ether' pops up.  If it does send, we don't get a special message.

Admittedly i am still new


texts: Could Someone Explain this Mutli-Sig Smart Contract?

texts:
This code seems to be a good standard for multisig accounts on the eth chain. Could someone explain it piece by piece for me?

https://github.com/christianlundkvist/simple-multisig

pragma solidity 0.4.15;
contract SimpleMultiSig {

  uint public nonce;                // (only) mutable state
  uint public threshold;            // immutable state
  mapping (address => bool) isOwner; // immutable state
  address[] public ownersArr;        // immutable state

  function SimpleMultiSig(uint threshold_, address[] owners_) {
    require(owners_.length <= 10 && threshold_ <= owners_.length && threshold_ != 0);

    address lastAdd = address(0);
    for (uint i=0; i<owners_.length; i++) {
      require(owners_[i] > lastAdd);
      isOwner[owners_[i]] = true;
      lastAdd = owners_[i];
    }
    ownersArr = owners_;
    threshold = threshold_;
  }

  // Note that address recovered from signatures must be strictly increasing
  function execute(uint8[] sigV, bytes32[] sigR, bytes32[] sigS, address destination, uint value, bytes data) {
    require(sigR.length == threshold);
    require(sigR.length == sigS.length && sigR.length == sigV.length);

    // Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191
    bytes32 txHash = keccak256(byte(0x19), byte(0), this, destination, value, data, nonce);

    address lastAdd = address(0); // cannot have address(0) as an owner
    for (uint i = 0; i < threshold; i++) {
        address recovered = ecrecover(txHash, sigV[i], sigR[i], sigS[i]);
        require(recovered > lastAdd && isOwner[recovered]);
        lastAdd = recovered;
    }

    // If we make it here all signatures are accounted for
    nonce = nonce + 1;
    require(destination.call.value(value)(data));
  }

  function () payable {}
}


texts: On mainnet Gas required exceeds allowance or always failing transaction

texts:
When I try to deploy contract, the error comes up:

  gas required exceeds allowance or always failing transaction

on mainnet.

contract Crowdsale {
  using SafeMath for uint256;

  // The token being sold
  MintableToken public token;

  // start and end timestamps where investments are allowed (both inclusive)
  uint256 public startTime;
  uint256 public endTime;

  // address where funds are collected
  address public wallet;

  // how many token units a buyer gets per wei
  uint256 public rate;

  // amount of raised money in wei
  uint256 public weiRaised;

  /**
   * event for token purchase logging
   * @param purchaser who paid for the tokens
   * @param beneficiary who got the tokens
   * @param value weis paid for purchase
   * @param amount amount of tokens purchased
   */
  event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);

  function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public {
    require(_startTime >= now);
    require(_endTime >= _startTime);
    require(_rate > 0);
    require(_wallet != address(0));
    require(_token != address(0));

    startTime = _startTime;
    endTime = _endTime;
    rate = _rate;
    wallet = _wallet;
    token = _token;
  }

  // fallback function can be used to buy tokens
  function () external payable {
    buyTokens(msg.sender);
  }

  // low level token purchase function
  function buyTokens(address beneficiary) public payable {
    require(beneficiary != address(0));
    require(validPurchase());

    uint256 weiAmount = msg.value;

    // calculate token amount to be created
    uint256 tokens = getTokenAmount(weiAmount);

    // update state
    weiRaised = weiRaised.add(weiAmount);

    token.mint(beneficiary, tokens);
    TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);

    forwardFunds();
  }

  // @return true if crowdsale event has ended
  function hasEnded() public view returns (bool) {
    return now > endTime;
  }

  // Override this method to have a way to add business logic to your crowdsale when buying
  function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
    return weiAmount.mul(rate);
  }

  // send ether to the fund collection wallet
  // override to create custom fund forwarding mechanisms
  function forwardFunds() internal {
    wallet.transfer(msg.value);
  }

  // @return true if the transaction can buy tokens
  function validPurchase() internal view returns (bool) {
    bool withinPeriod = now >= startTime && now <= endTime;
    bool nonZeroPurchase = msg.value != 0;
    return withinPeriod && nonZeroPurchase;
  }

}


texts: Simplest way to find percentage of transactions that invoke EVM?

texts:
Firstly I want to make sure my understanding of the Ethereum is correct:
A "normal" transaction of Ether from one account to another does not usually invoke the Ethereum Virtual Machine?

Secondly:
What is the easiest way of finding out what percentage of transactions in a block have invoked the EVM from nodeJS? I am thinking of getting a block with web3, running debug.traceTransaction() for each transaction hash in the blocks transaction list. If this function returns undefined, then the EVM was not invoked.
I was originally thinking of using .getCode(destinationAddress) and counting non-zero return accounts for each transactions destination but "normal" transaction of Ether can taken place with accounts that have code present too.

Thanks


texts:
I can't compile solidity code in my Jest files, but without Jest it works fine.

Here is a test file:

const fs = require("fs")
const solc = require("solc")

describe("test", () => {
  test("", () => {
    const input = {
      "test.sol": fs.readFileSync("test.sol", "utf8")
    }

    const output = solc.compile({ sources: input })

    const bin = "0x" + output.contracts["test.sol:Test"].bytecode
    const abi = output.contracts["test.sol:Test"].interface

    console.log({ bin })
    console.log({ abi })
  })
})

Here is an error: TypeError: soljson.cwrap is not a function

If removed from this code all Jest things (describe, test), it works fine.


texts: MetaMask/mascara integration for no metamask users

texts:
I am creating iframe based metamask. github source

HTML

<script src="https://wallet.metamask.io/metamascara.js"></script>
<script src="/javascripts/ethjs-query.min.js"></script>

Javascript

var ethereumProvider;
var ethQuery;
if (typeof web3 === 'undefined')
 {
    async function loadProvider() {
      const ethereumProvider = metamask.createDefaultProvider()
      ethQuery = new Eth(ethereumProvider)
>>>>  const accounts = await ethQuery.accounts();
      window.METAMASK_ACCOUNT = accounts[0] || 'locked'
      logToDom(accounts.length ? accounts[0] : 'LOCKED or undefined', 'account')
    }
    loadProvider();
    function logToDom(message, context){
      console.log(message)
    }
}

on >>>> part, it is providing error:

  [ethjs-query] method 'accounts' requires at least undefined input
  (format type undefined), 0 provided.

I am quite new to ethjs-query, and could not find any solution for 10 hours.

It would be much appreciate if someone help me with my issue.


texts: How to solve the error “”before all“ hook: prepare suite:”

texts:
When I tested my contract, I got this error ""before all" hook: prepare suite:"

Does anyone know how to solve this error?

This is my dependencies. "truffle": "5.0.7", "web3": "1.0.0-beta.46"


texts: How to send transaction using web3 contract instance from address which is not a node's account

texts:
I succeeded creating transaction from node's account(created by ganache) to a contract using web3.js .

const contract = new web3.eth.Contract(abi, contractAddress, {
    from: from,
    gasPrice: 200000000
});
contract.methods.sendCoin(receiverAddress, '1').send() // succeeded

However, how to send transaction to a contract from address which is not node's account.

Does Contract Instance have any methods to sign transaction?? or, Contract Instance cannot be used to sign Transaction and need to use another way ??


texts: Location of ethminer start script in linux

texts: I'm trying to mine ethereum coins and for this I installed ethereum-genoil-ocl-git using package manager of my linux distro. According to their tutorial I have to configure the start.sh script and after setting up the pool server with ethminer then I have to run this start script. I ran locate ethereum | grep start but it returned no value. Where to find this script? Or it must be downloaded separetedly?


texts: Mining Rig with old motherboard with RX470 + Intel Core 2 Duo

texts:
So I am thinking of buying an Asus Radeon RX 470 ROG Strix 4GB GPU to use on an old motherboard I had lying around with 1 x PCIE 16, 2 x PCIE 1 and 1 x PCI slot.

The motherboard also has an Intel Core 2 Duo E7500 in it that I plan to use as well as 2 x 2GB RAM sticks and 2 x 1GB RAM sticks.

I have a few questions about this:
1. Will the old components slow down the GPU's ability to mine?
2. Does RAM speed matter for a mining rig?
3. Is it better to just use the 2 x 2GB RAM sticks? I have heard some things about one-sided RAM sticks not working well and the 1GB sticks are one-sided.

Thanks in advance!


texts: How to get balance of a token in 1 line of code on Ubuntu

texts:
To get the balance of ether in an address, I am using the code below. (1 line)

sudo geth --exec \
  "web3.eth.getBalance('0xf6e5911696a3729a7740cbdcd64c05bc2eec60e7')" attach

I get: 165060000000000000

I need to get balance of token (e.g. Golem) in one line like above. Can not interact with console. Return can be anything, 1 line or JSON.

Also looking for 1 line to send token like below:

sudo geth --exec \
  "eth.sendTransaction({from: '0xxxxxxxxxxxxxxxxxxxxxxxxxxx', \
  to: '0xxxxxxxxxxxxxxxxxxxxxxxxxx', value: '10000000000000000', \
  gas: '0x76D0', gasPrice: '0x4A817C800'})" attach

Is this possible?


texts: Get private key from web3.personal.newAccount('password')

texts:
I created a wallet account(ethereum) using web3.personal.newAccount('password'). Now, this method generally returns the address of new account, however, to send transactions from that account I would also need a private key. Can anyone please help from where I can get that?

Thanks in advance!


texts: How are Ethereum smart contracts deployed?

texts:
Im a little confused on how Smart contracts work on the Ethereum blockchain and with DApps.

I'm confused with the structure of DApps using Ethereum smart contracts. Is just one contract created when the app is made, or are users of the app publishing a smart contract every time? more details of my question are in the next paragraph.

Suppose you have a Ride share Ethereum Dapp, when making this Dapp, the creator of the app publishes a smart contract, for example "Ride". Can there be an implementation where a person looking for a ride can store his information into the "Ride" contract on the blockchain that was published by the creator of the app? So in essence the users of the rideshare app are interacting with the smart contract that is already published. Or, is it that each user of the Rideshare app deploys/ publishes their own smart contract every time that they enter their user details into the Rideshare app?

thank you for your help clearing this confusion.


texts: looking for ethereum account easy management process

texts: Suppose I want users to answer surveys and that each response are hashed and sent to ethereum. My issue is the user experience of creating an account and login without metamask which is not user friendly enough for the population I am targeting. Is it possible to get for each user an public/private key created in the backend stored on a server, filling their account with gas, and then triggering the ethereum transactions on their behalf but in the same time, letting the private keys visible to none except the user. Is it possible ?


texts: Error message when attempting to stop Parity in Ubuntu

texts:
I attempted to stop parity and am getting an error message:

  Failed to stop io.parity.ethereum.service: Unit
  io.parity.ethereum.service not loaded.

Any suggestion for why this occurred? This is what I did: Once logged in as the sudo user in Ubuntu, from my home directory, I entered:

sudo systemctl stop io.parity.ethereum

The error msg followed.
Here is Parity version and install info in case it helps:

  Version:
  Parity/v1.5.0-beta-d2e6fc0-20170119/x86_64-linux-gnu/rustc1.14.0

Also, in case it matters: I installed Parity with the bash command

curl https://get.parity.io -Lk

on Ubuntu.
TIA!


texts: Contract Deployed via Truffle doesn't work, Remix deployed contract does work. Why?

texts:
So, I am developing (or trying to) with Truffle against ganache.

When I do "truffle migrate" I get:

Using network 'development'.

Running migration: 1_initial_migration.js
  Replacing Migrations...
  ... 0x91a36c8c3da5085ea78c09cbbedd41b135c917ff682b64cc521442f24763e9ac
  Migrations: 0xbd2c938b9f6bfc1a66368d08cb44dc3eb2ae27be
Saving successful migration to network...
  ... 0xae5622d12af119348c09ed0e544d2fd1670096571106c4fd61bb6b8dce8b633f
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying shitlist...
  ... 0xc1a103c54c154947a2e86c77c3a94c1ae8eacf6f173b1a1e66204582b4c6f7fc
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: out of gas
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-migrate/index.js:225:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
    at IncomingMessage.emit (events.js:132:15)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:114:19)

However, if I dig into Ganache to actually check the last transaction, I see my contract address.

If I plug this contract address into Remix (Which is connected to Ganache as well), it seems as though it's deployed just fine.

So why do I keep getting this error?

EDIT: Actually maybe it doesn't correctly migrate- as the contract does not work as expected. When I Deploy using remix (to the same network), the contract works as expected. The contract which was deployed via Truffle, does not however function, even though I find it in the blockchain.

Thanks!


texts: the change of storage trie tree when the data in smart contract is changed

texts:
As we all know,the data in smart contract is stored in storage trie tree. If the data of a smart contract is modified, will a new storage trie tree be generated, or will the data is modified on the original storage trie tree?
I want to know what happend to storage trie tree when the data in smart contract is changed.
Hope you can give me some help!


texts: How to edit transaction data of an ethereum transaction? Or in other words, create a manual transaction, for contracts with no front end?

texts:
This strikes me as a very stupid question, but I have googled and cannot find an easy answer. I have identified a contract that I want to interact with- I know the function selector and the variables I want to pass- ie everything that I need to know for the transaction data. But there is no front-end layer on this contract so I can't use metamask or similar.

Wat do?


texts: How to replay all events from the start?

texts:
I want to replay all events on a bsc chain and index them.
If I understand correctly, the only way of doing this at the moment would be to call getBlock(0) and go from there, checking every transaction one by one.
Is that correct?


texts: how to call a function of a smart contract from a c program using JSON-RPC

texts:
Indeed, i installed ganache where i deployed a smart contract.
I wanted to write a c program that would allow me to call the functions of my smart contract and read the messages.
This program would then have to be executed in connected objects.
I did some research, but I can't figure out how to do it, but i guess i will use the JSON-RPC protocol, in this case how to call json-rpc from my c program to access my smart contract


texts:
I have 3  contract, all they uses SafeMath libraries and a couple of my. I connect them all (library to contract) and everything works (I work in REMIX)
so how do I deploy all these 3 contracts with all my libraries and then verificate in etherscan all contracts? I need deploy 3 contract separately, and all my library separately. Beacouse i will write more contract that will use same libraries. And all need to be verificated.

I dont understand, beacouse to verificate contract we need send all code with library, but i connect library from other file.


texts: Understanding serialized unsigned raw transaction

texts:
I'm currently learning about RLP (ethereum-under-the-hood-part-ii, wiki-eth-rlp) and Ethereum transaction structure, my goal is to create an unsigned raw tx and then sign it.

Right now I'm playing around with code snipped which I assume are working such as raw_tx_demo which produces:

RLP-Encoded Tx: 0xe6808609184e72a0008303000094b0920c523d582040f2bcb1bd7fb1c7c1ecebdb3480801c8080
Tx Hash: 0x3a2fd1a5ea9ffee477f449be53a49398533d2c006a5815023920d1c397298df3

Given ethereum tx structure, below what I extract from the RLP-Encoded Tx:

0x {e6} {80} {86 09 18 4e 72 a0 00} {83 03 00 00} {94 b0 92 0c 52 3d 58 20 40 f2 bc b1 bd 7f b1 c7 c1 ec eb db 34} {80} {80} {1c} {80} {80}

{e6} - ?: 230
{80} - nonce: 0
gasPrice: 10000000000000
gasLimit: 196608
to: "0xb0920c523d582040f2bcb1bd7fb1c7c1ecebdb34"
{80} - value: 0
{80} - data: 0
{1c} - v: 28
{80} - r: 0
{80} - s: 0

From here, I got some questions:

What the first byte 0xe6 or 230 is for ? How is it computed ?
Why does the ChainId is 0x1c or 28 ? Given this list it don't understand.


texts:
I previously used web3 to validate an addresses and am looking for a new solution since metamask no longer injects web3 therefore address validation can no longer be called from the chrome console

I've switched over to using the ethereum. ... method but there doesn't seem to be a command for "isAddress" (please view screenshots)
is there another solution for validating an Ethereum address with web3 in the Chrome Console ?

I've been searching for one and can't seem to locate it.
Thanks in advance!


texts: How do programs on the 'Ethereum World Computer' compare to traditional programs or websites?

texts:
So this question has been bugging for me for a while and I can't seem to find the answer to it.

Context

I have been a web developer for many years.

When I access a website, any frontend code is run in my browser, using the computing power on my computer. Any backend code is run on a different server. Any data is stored in someone else's centralised database. Some data is stored in cookies or local storage in my browser.

When I run a video game on my computer, the program is fully executed on my laptop (with the exception of some data probably being pulled from a database, e.g. if I use Steam).

Alternatively, platforms such as 'gaming as a service' would move most processing power onto a server.

Question/s

Ethereum is described as a 'World Computer' but how does this relate to traditional architectures:

Is the blockchain element like for example a Wordpress database, with smart contracts being like my server side code? If this is the case, is that code only executed when I make a call to it (like with Lambda functions on AWS)?

Is Ethereum therefore just a distributed serverless architecture?

If a platform was to be built like 'gaming as a service', I'm guessing that I would be drawing processing power from millions of computers in the network? (I'm also assuming that this is part of the current debate about scaling).

In 10 years, if Ethereum is where we hope it will be, would it theoretically be able to support much more processor intensive use cases such as gaming as a service, or is that never the best use case for it?

Thanks


texts: How to optimize ETH donations in an ICO when receiving ETH from an exchange? (Best user experience)

texts:
I'd like to make raising funds in ETH as easy as possible. This is the flow that I'm imagining for my average user:

1) User visits my ICO page

2) They download a key and address file generated in-browser

3) They're also shown a second address that says "send ETH here to convert it to a token in the wallet you just downloaded"

4) (Important) because the user is only a trader, they go to their exchange page and type in the address from step 3

5) When the exchange processes the withdrawal, they get tokens from the address in step 2

What I'm asking is how to optimize this process from a smart contract perspective. The way I see it, each user needs a "token receipt" address (to receive their tokens; downloaded from my page) and a "eth receiving" address (to send ETH to from the exchange; already recognized by the smart contract). But, while "token receipt" addresses can be generated on the fly, there should be "eth receiving" addresses already in the smart contract (so that a user can load the page and already have an eth receiving address assigned to them).

I guess my first question is, are there any existing smart contract libraries already available that enable the overrall scope of this question? No need to re-invent the wheel.

If there aren't, what's the best approach to do? Launch the smart contract with 10,000 "eth receiving" addresses? Is there any way I can automatically forward money sent to the "Eth Receiving" addresses to a single multi-sign address? (To protect funds better and not have 10000 of keys for each eth transaction received).


texts:
I have deployed a contract.

Now I would like to periodically poll it for data.

I can do this one time by opening geth, using my abi statement, creating a contract variable and then interrogating that contract instance.

But how do I do this in a scripted way that I can call from a cron job?


texts: Why the maximum number of transactions in a block is 221?

texts:
I made a private network with only one node in it, then I sent 2000  transactions like so:

var amount = 1;
var sender = personal.listAccounts[0]
var receiver = personal.listAccounts[0]
for (i = 0; i < 2000; ++i) {
   eth.sendTransaction({from:sender, to:receiver, value: amount});
}

Then, I can see that there are 2000 transactions in the txpool, so I start to mine and this was the result:

INFO [10-10|16:12:25] Commit new mining work                   number=2684 txs=221 uncles=0 elapsed=1h10m51.957s

Looking at the source code, I have found that in the function commitTransactions in worker.go:

func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address) {
    fmt.Println("commitTransactions")
    gp := new(core.GasPool).AddGas(env.header.GasLimit)

    var coalescedLogs []*types.Log
    //var i int = 0
    for {
        // Retrieve the next transaction and abort if all done
        tx := txs.Peek()
        //i+=1
        if tx == nil {
            break
        }

tx := txs.Peek() returns nil after 221 times, but I don't know why. Would you please help me?

My geth version is

v1.6.6-unstable/windows-amd64/go1.9beta2


texts: How do I pull a private key out of a keystore using eth-lightwallet "No seed set"

texts:
I am using eth-lightwallet on a NodeJS server. I am getting a stack trace when I try and get the private key from the keystore. It is flagging this line "keystore.generateNewAddress(pwDerivedKey);" I cannot see how it is related. When I comment out the line "account.prv_key = keystore.exportPrivateKey(sendingAddr, pwDerivedKey);" it appears to work flawlessly. Am I doing something wrong? The error is throwing "No seed set" however when I look in debug mode the seed is most certainly set. I am new to Node and suspect it has something to do with the asynchronous nature of Node. I have included the code and the stacktrace below. Thank you.

lightwallet.keystore.deriveKeyFromPassword('mypassword',
    function (err, pwDerivedKey) {
      var seed = lightwallet.keystore.generateRandomSeed();
      var keystore = new lightwallet.keystore(seed, pwDerivedKey);

      keystore.generateNewAddress(pwDerivedKey);
      account.address = keystore.getAddresses()[0];
      account.prv_key = keystore.exportPrivateKey(sendingAddr, pwDerivedKey);
    })

/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:389
    throw new Error('KeyStore.generateNewAddress: No seed set');
    ^

Error: KeyStore.generateNewAddress: No seed set
    at KeyStore.generateNewAddress (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:389:11)
    at /Users/username/WebstormProjects/eth-project/nodejs-server/controllers/ActorService.js:39:20
    at cb (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/lib/keystore.js:459:7)
    at /Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:474:9
    at Immediate._onImmediate (/Users/username/WebstormProjects/eth-project/nodejs-server/node_modules/eth-lightwallet/node_modules/scrypt-async/scrypt-async.js:433:11)
    at processImmediate [as _immediateCallback] (timers.js:383:17)


texts: I want to build a small project to simulate app.compound.finance (with just eth token let's say) with The Graph , how can I get supply/borrows balance per users? (my defi app initial setup is done, already connected with wallet with web3js)


texts: Confidential data encryption on blockchain

texts:
I already built a supply chain that is able to collect product information on Ethereum. Now, that data can be confidential, but I still want to do Matrix calculations on it. I came across homomorphic encryption, but I'm not sure if it would help me. My product information has a JSON format like that:

{
"Timestamp": UNIX,
"Materials": [
{
 "Chemical1": XXXX mol,
 "Chemical2": XXXX mol,
}
],
"CO2": XXX kg,
"Energy": XXX kWh,
"Water": XXX m²,
"Price": XXX €,
"Amount": XXX,
"Totalprice": Price * Amount
}

I want to be able to extract the specific information I want from that file and calculate with it but it also has to be confidential/encrypted. Does someone have an idea which method would be the best to do that and is there maybe a JavaScript package for that?

Thank you

Max


texts: How to connect Mist to the private blockchain on remote server (Azure)?

texts:
I've installed Mist on my local PC (Windows 10), but I don't want to sync Main/Test networks. So I've used this Ethereum + Azure tutorial and now I can work via SSH on my private network.

geth --dev console

More than that, I know that it's possible to run Mist on custom blockchain using special flag

mist.exe --rpc http://YOUR_IP:PORT

So, according to geth --help, I'm running geth --dev --rpc console on Azure's virtual machine, after that I'm running mist.exe --rpc http://VM_IP:8545 and there is an error:

[2016-09-24 18:01:21.928] [INFO] Sockets/node-ipc - Connect to {"hostPort":"http://VM_IP:8545"}
[2016-09-24 18:01:24.968] [ERROR] Sockets/node-ipc - Connection failed (3000ms elapsed)
[2016-09-24 18:01:24.971] [WARN] EthereumNode - Failed to connect to node. Maybe it's not running so let's start our own...
[2016-09-24 18:01:24.979] [INFO] EthereumNode - Node type: geth
[2016-09-24 18:01:24.982] [INFO] EthereumNode - Network: test
[2016-09-24 18:01:24.983] [INFO] EthereumNode - Start node: geth test
[2016-09-24 18:01:32.284] [INFO] EthereumNode - 3000ms elapsed, assuming node started up successfully
[2016-09-24 18:01:32.286] [INFO] EthereumNode - Started node successfully: geth test
[2016-09-24 18:01:32.327] [INFO] Sockets/node-ipc - Connect to {"hostPort":"http://VM_IP:8545"}
[2016-09-24 18:02:02.332] [ERROR] Sockets/node-ipc - Connection failed (30000ms elapsed)
[2016-09-24 18:02:02.333] [ERROR] EthereumNode - Failed to connect to node Error: Unable to connect to socket: timeout

P.S. Mist version - 0.8.2


texts: Mapping vs Arrays: duplicating variables gas consumption

texts:
I have a contract that has a struct including address and unit, and mapping of a struct, like this.
  struct User {
    uint count;
    address userAddress;
  }
  mapping (address => User) users;

There is a point at which I need to make a copy of this mapping and clear out the entries of the old one, like this pseudo code:
  users_backup = users;
  users = [];

Of course this code won't work, so I learned you can loop through it like this:
Assignment of mapping in Solidity
But that seems expensive, especially after reading:
Copying a mapping from Contract A to contract B
So How do I do this efficiently?
With a mapping of 100k users or 1 million or even 100 million entries would this looping method be feasible? Or would it be better to change my architecture?
uint[] userCounts;
address[] userAddresses;

I could use a series of arrays instead of maps. Then, would I be able to copy one array to a new variable and clear the old variable out in one or two lines with less gas? The Hard thing is, even the arrays will have to be variable arrays because I can't know beforehand how many users will use it.
What would you do to minimize gas consumption? I'm just not sure what the best pattern is, thanks!


texts: Truffle best practices - unit vs integration tests

texts:
Think about having two contracts:

MockToken
Faucet (which takes token address as constructor parameter)

To unit test Faucet I would create two new instances:

const token = await MockToken.new()
const faucet = await Faucet.new(token.address)

Now I can perform all my tests in isolation to be sure that Faucet works as expected but how do I make sure that the deployed Faucet refers to the correct token address and that I have not mistakenly provided a wrong address in the migration?

Do I just get the Faucet.deployed() and check that his token address is the one that I expect? If so, should I do it inside the same file that contains unit tests or in a sepate file?


texts:
Solidity allows for unnamed function params, how to use them?

contract C {

 // omitted parameters
 function func(uint k, uint ) returns(uint) {
    return k;
 }

}


texts: Passing data to smart contract via constructor

texts:
Is it possible to pass data into the constructor to be used for the smart contract? Essentially I want to let a user on the front end enter data that will be used to generate a token.

contract TicketToken is ERC20 {

    string public symbol;
    string public name;
    uint256 public price;

    function TicketToken(string _name, string _symbol, uint256 _price) {
        owner = msg.sender;
        name = _name;
        symbol = _symbol;
        price = _price;
}

How would I be able to do this on web3/React?


texts: Ethers.js filters events (Only new events)

texts:
I have an event set up in the Contract.
Contact Packages
   emit Spend(msg.sender, msg);

   function sendPackage(msg) external payable returns(bool) {
     require(
       msg.value == price,
       'Please send the correct amount of ETH to make send a message'
     );

     emit Spend(msg.sender, msg);
     return true;
}

And a script in NodeJS that listens to new events.
The intention is to kick off some NodeJS code whenever a new event on the contract takes place.
But whenever I start the script, the Contract.on(.. fires and the last event is passed to it, even though the event fired a hour ago.
Is there a way to config the callback to NOT include previous events?
  Contract.on('Spend', (sender, event) => {
    console.log(sender);
    console.log(event);
  });

EDIT
I've tried to use Contact.once and the same result occurs.


texts: How to forward tokens without paying a gas

texts:
I'm working on a project and I need to know if this statement is possible:

I have 10 registered users. Each user has an erc20 wallet. It is possible that when user A, C, E, or whoever deposit their token to their specific address the funds goes to the main wallet instead of the alias one? we could avoid the gas expenses if we create an alias that works as a wallet.

We are going to receive our own token, which has no value at the moment, so we can't use it to pay comission
I have been reading a lot, but can't find out a solution


texts: Ethereum protocol - description fields on Alethio block explorer

texts:
I am using Alethio block explorer in an IBFT2 based chain. I am trying to understand some fields there.
Does anyone know what they mean?

Are the COMMITSEALS the signature of the validators?
What is MIX HASH?
What is LOGS BLOOM? Are the logs of the blocks? Is it a kind of processing using a bloom filter?
I also do not understand what SHA3UNCLES. It also appears on EtherScan with the following description: "The mechanism which Ethereum Javascript RLP encodes an empty string". I know RLP but I still could not understand why this info is relevant to be presented in a block explorer.

Thank you


texts:
I have used the ideas from the link [1]How to make miner to mine only when there are Pending Transactions? in my private chain. I have a couple of questions,
- How can I add custom code on the miners to do some extra verification before picking transactions?
- How can I enforce all miners on my network to follow this logic?


texts: Unhandled rejection Error: Couldn't decode uint256 from ABI

texts:
I am working on using a sample Contract using NodeJS, Web3, and Solc but I encountered some error that the given address in the Contract that I've created couldn't decode. Am I doing something wrong? Here is the JS code that I'm working on

const Web3  = require('web3');
const fs    = require('fs');
const solc  = require('solc');

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

const source = fs.readFileSync(__dirname + '/solidity/Token.sol');
const output = solc.compile(source.toString(), 1);
const bytecode = output.contracts[':Token'].bytecode;
const abi = JSON.parse(output.contracts[':Token'].interface);

const contract = new web3.eth.Contract(abi, '0x5bbf74f1e804bfe671d55cd6b9f3ada66568d5dd', {
  from: web3.eth.coinbase,
  gasPrice: 90000*2
});

contract.methods.totalSupply().call().then(function (err, result) {
  console.log('error', err);
  console.log('result', result);
});

Here is the solidity code that I am using.

pragma solidity ^0.4.4;

contract Token {
    // stores the balances of the addresses
    mapping(address => uint) balances;
    mapping(address => mapping(address => uint)) approved;

    // number of tokens in circulation
    uint supply;

    event Transfer(address indexed _from, address indexed _to, uint256 _value);

    function Token() {
        // constructor
        // balances[tx.origin] = 10000;
    }

    function totalSupply() constant returns (uint) {
        return supply;
    }

    function balanceOf(address _owner) constant returns (uint balance) {
        return balances[_owner];
    }

    function transfer(address _to, uint _value) returns (bool success) {
        if (balances[msg.sender] >= _value
            && _value > 0
        ) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;

            // trigger an event
            Transfer(msg.sender, _to, _value);
            return true;
        }

        return false;
    }

    // sets how many can a spender spend from a certain address
    function approve(address _spender, uint _value) returns (bool success) {
        if (balances[msg.sender] > _value) {
            approved[msg.sender][_spender] = _value;
            return true;
        }

        return false;
    }

    // check the value of the spender can spend
    function allowance(address _owner, address _spender) constant returns (uint remaining) {
        return approved[_owner][_spender];
    }

    // transfer the approved value to spend
    function transferFrom(address _from, address _to, uint _value) constant returns (bool success) {
        if (balances[_from] >= _value
            && approved[_from][msg.sender] >= _value
            && _value > 0
        ) {
            balances[_from] -= _value;
            approved[_from][msg.sender] -= _value;

            balances[_to] += _value;
            return true;
        }

        return false;
    }
}

PS: I'm using testrpc as my ethereum provider.


texts: Deploying contract with arguments using raw transaction

texts:
I want to deployed to deploy the following contract that has a constructor with the following arguments.

contract test{
    constructor(address _recipient, address _user){
      ...
    }
}

I want to deploy this using web3's sendrawtransaction

How do I go about making the raw TX to do so? I already have the signing key generated. Just not sure what to put in the "data" field of the TX and where to put in the arguments.


texts: Schedule a transaction without making a deposit

texts:
Is it possible in solidity to schedule a transaction without making a deposit and without specifying the amount? As far as I know with the Ethereum Alarm Clock you need to deposit the ethereum and the gas that you want to transact into the address of the contract.
For example would it be possible to schedule the transfer of the 50% of my future address balance to xxx in one year.
In the case that its not possible would it be if the amount to transfer is specified but not deposited, for example transfer 10 eth to yyy in 6 months.
Thanks for the help


texts: How does Oraclize handle the TLSnotary secret?

texts:
Oraclize claims to offer a provably honest secure retrieval of a webpage by taking advantage of TLSnotary (a service that allows an auditor to verify if a specific web page was accurately retrieved)

The purpose of Oraclize seems to be to make this information available to smart contracts.

But to my understanding, the only factor keeping the TLSnotary proof secure is that the person doing the auditing generates and withholds a secret piece of data until the person being audited provides them with the hash of the retrieved web page.  A contract obviously cannot generate and withhold a secret.  Doesn't this mean that the contract itself is unable to verify the TLSnotary proof?

It seems like some clarification is needed of how exactly Oraclize is handling the TLSnotary secret.

Oraclize also seems to offer a web tool allowing you to play the role of the auditor.  Can multiple people audit the same TLSnotary proof in parallel?  And suppose I do somehow manage catch Oraclize cheating.  How can I prove this to a third party?

Put in more simple terms, how much can I trust Oraclize's service?

Don't take my questions the wrong way--I'm very excited by the idea of oracles actually proving their claims.  I just like to ask difficult questions!


texts:
I have a shopping website and I decide to use Ethereum

Do u have any solution for this conditions?

we have 2 kinds of users
we have 2 products with non-content price (price change randomly)
we don't want to know users address and also users don't know about or wallet balance too
I just want to user click on payment button and pay, nothing more! And then I check the payment status

What is the best idea for :

user select a product and see price, click on payment button and pay the price (that not constant and change each day), so how can figure out that user paid it and complete the order?

Is there any way such as Bitcoin to generate new payment addresses for each click (and save it in my DB and check transaction)?

Or any idea? (if u suggest smart contract, please right full code of the contract)

Edit 1 :

Also I prefer users each time see a new payment address for each product, it's so easy to trace


texts: What does this error "invalid opcode 0xfd" mean?

texts:
I found an error message, 'invalid opcode 0xfd'. What does this mean?

I googled, and found just one result here.

Quote: "I the invalid opcode 0xfd is never hit
(Some compilers encode safety properties using 0xfd)"


texts:
Can't connect to the Ethereum blockchain with web3j 4  for Android Kotlin. Worked in the previous version of web3j.

fun web3(): Web3j =  Web3jFactory.build(HttpService("http://192.168.38.148:7545"))

Unresolved reference: Web3jFactory

if I try:

fun web3(): Web3j = Web3j.build(HttpService("http://192.168.38.148:7545"))

I get this error message:

W/System.err: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
W/System.err: java.lang.BootstrapMethodError: Exception from call site #59 bootstrap method
W/System.err:     at org.web3j.utils.Async.<clinit>(Async.java:19)
at org.web3j.utils.Async.defaultExecutorService(Async.java:49)
at org.web3j.protocol.core.JsonRpc2_0Web3j.<init>(JsonRpc2_0Web3j.java:88)
at org.web3j.protocol.Web3j.build(Web3j.java:21)

Any Idea how to solve this?


texts: Push to different parts of array in Solidity

texts: push() pushes to the back of an array. What possible solutions are there for pushing either to the front of an array, or to a specified index in an array?


texts:
I have a simple contract that takes integer inputs from different clients and eventually calls a function to calculate average. When I run the contract in Remix debugger, I can see the function go through correctly. But, I can't seem to get the same from web3.js. Can you please suggest what am I missing?

The Solidity documentation on storage is so poorly worded that, I can't follow it at all!

  The types where the so-called storage location is important are
  structs and arrays. If you e.g. pass such variables in function calls,
  their data is not copied if it can stay in memory or stay in storage.
  This means that you can modify their content in the called function
  and these modifications will still be visible in the caller.

This is with Ethereum Testrpc.

Contract

Setting runningNumber and members[] is not shown here.

contract Lister {
    struct ListMembers {
        bytes32[] members;
        uint256 averageNumber;
        uint256 runningNumber;
    }

    // Instance of the ListMemebers struct
    ListMembers public lm;

   function calculateAverageNumber() {
        uint256 numMembers = uint256(lm.members.length);
        uint256 sampleSum = lm.runningNumber - lm.randomNumber;
        uint256 avgSum = sampleSum / numMembers;
        lm.averageNumber = avgSum;
    }

     function getAverageNumber() returns (uint256) {
        return lm.averageNumber;
    }

web3.js

var Web3 = require('web3');
var fs = require('fs');
//
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var abiFile = fs.readFileSync('Lister.abi').toString();
var abiDef = JSON.parse(abiFile);
var ListingContract = web3.eth.contract(abiDef);
var contractInstance = ListingContract.at('0xdc80....3aff');
//
contractInstance.getAverageNumber.call(
    (err, res) => {
        if (err) {
            console.log(err)
        } else {
            console.log(res)
        }
    }
)


texts: How can we deploy smart contract, its front end and backend server based on Mongodb to Rinkeby

texts: I have designed a dapp (based on nodeJS and Mongodb) which uses IPFS, Oraclize, a front end and off chain Mongodb server (based on mLab). Till now I was using Ganache for all local testing and development. Now I have to launch this dapp on Rinkeby network and make front-end and backend available to users. What is the preferred way/platform for such kind of dapp deployments which can be done easily.


texts: What is a blockchain oracle for smart contracts? And why is it needed? I've seen a lot of posts about "how do oracles work", and "what is the oracle problem" but I don't understand what they are?


texts: Ethereum send transactions are unsuccessful when I run the node and miner in same machine

texts:
I have started the Ethereum client using the Go Ethereum. And also started the Ethereum miner on the same machine.

Now node and miner are running in the single windows function.

If I try to send ether from one account to another account, it is not getting there successfully.

Everything is set up in private blockchain.

Steps I Followed :

I have installed the ethereum wallet.
Installed the ethereum go client, go ethereum.
Created the genesis file, created an account with some ethers in it.
Called the "geth init genesis file ......"
Check the account with some ethers in balance.
Started the miner in the same machine using the same network Id.
Created an another account using get client.
Now unlocked the account and sent some ethers to the newly created account.
Transaction came into miner logs, but it didn't get mined so the amount was not added to receiver.

What could be the problem. What am I missing?


texts:
I saw some website selling cryptocurrencies:

If I buy Ethereum (ETH) what does that mean ?
What can I do with it when I buy it ?
Does that mean that I am investing in Ethereum or helping the industry ?

Thank you


texts: How to set multiple nodes in HttpProvider web3 v1.2.0

texts:
I'm working with Nodejs application, and using a multi-node setup on different servers.
If I have single node end point like http://localhost:8545 I can use Web3 providers as below
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

However, I'm not sure how to setup multiple nodes into it. So the first node becomes unhealthy, the system uses the second node and so on.
I have tried with multi-http-provider but it seems not working with web3 v1.2.0
but it seems not working: having an error of uncaughtException : RangeError: Maximum call stack size exceeded


texts: Overclocking and Incorrect/rejected shares

texts:
I recently started mining on my personal computer, hoping to get better results, I overclocked my GPU (I went from 48MH/s to 60MH/s) but after having done so, I started getting "Eth: Incorrect ETH share from GPU0" and "Eth: Share rejected in x ms" messages on the console, what does this mean?
(GPU is an RTX 3060 ti)


texts: Storing a document with multiple large video files

texts:
What's the best way to store a document with multiple large video and CAD files on Ethereum. I am just a beginner to Ethereum. The document is a science experiment with multiple documents linked.

I'd like to keep it online forever. How much would that cost? Is it possible? Could/should I create a Dapp to do that? Maybe it's worth using BitTorrent as well.

Any examples of other people doing that? Is Ethereum suitable for this task?


texts: Am I allowed to copy and reuse a smart contract?

texts: Let's say i'd like to take an existing smart contract from the Ethereum blockchain and use it for my own project on the Tron chain. Apart from any technical issues: Is it legal to do that? Can i just grab it and use it for my own stuff without any legal implications or does it depend on some license agreement or am I always free to do it?


texts: Blockchain structure with smart contracts and access data

texts: I found several articles explaining how smart contracts used and stored in blockchain but where does the smart contract actually resides in a blockchain (block or transaction or separate structure in the blockchain)? Is it possible to get trasactions related to a smart contract from the blockchain.


texts: How can I transfer my Ethereum from Etherdelta to Coinbase?

texts: Does anyone know how to transfer ETH from Etherdelta to Coinbase? Thanks Bob


texts: How to solve clique is not defined error?

texts:
I have going a PoA network, and everything looks like it works. But I cannot get clique to show up in geth.

> clique
ReferenceError: 'clique' is not defined
    at <anonymous>:1:1

Has anyone any idea about the cause of this?


texts: How do you calculate gas limit for transaction with data in Ethereum?

texts: What is the correct algorithm to calculate gas limit for transaction with data in Ethereum?


texts: Raw transaction with web3j, tx hash is always null

texts:
I'm trying to send raw transaction with Web3j, to call a smart contract function.
I try to set very high values for gas to avoid problems with it.
But I always get a null tx hash. What is wrong in my code ?
    // get nonce
        EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
                ethereumAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
        BigInteger nonce = ethGetTransactionCount.getTransactionCount();
        log.debug("nonce: "+nonce.toString());

        // build function call
        Function function = new Function(
                "setClaim",
                Arrays.asList(new Address(subjectAddress), new Utf8String(claimId), new Utf8String(claimValue), new DynamicBytes("".getBytes())),
                Collections.emptyList());

        // encode function call to tx data
        String encodedFunction = FunctionEncoder.encode(function);
        log.debug("encodedFunction: "+encodedFunction);

        RawTransaction rawTx = RawTransaction.createTransaction(
                nonce
                ,DefaultGasProvider.GAS_PRICE.multiply(new BigInteger("1000000"))
                ,DefaultGasProvider.GAS_LIMIT.multiply(new BigInteger("1000000"))
                ,DefaultParams.contractAddress
                ,BigInteger.ZERO
                ,encodedFunction);

        byte[] signedMessage = TransactionEncoder.signMessage(rawTx, Credentials.create(privateKey));
        String hexValue = Numeric.toHexString(signedMessage);

        EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).send();

        String transactionHash = ethSendTransaction.getTransactionHash();
        log.info("Tx hash: "+transactionHash);

I've tried this with Ganache and Infura. Both of them log an eth_sendRawTransaction. But I got no error, no message.
Thanks


texts: As issuer of a token how do I know the owners of a token bought on an exchange

texts: If I create a membership token = own the token to get rewards - how as the issuer of the token do I know the new owners of the token [so they are registered for rewards as owners] if the token is bought on an listed exchange after the ICO


texts: receiveAprroval through tokenRecipient interface

texts:
I received an error by the compiler regarding the following solidity code and I would like to know what's this error and what's the fix?

    interface tokenRecipient { function   receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }

Error in

    TypeError: Data location must be "calldata" for parameter in external function, but none was given.
    interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }


texts: Why is there a minimum amount for transfer (0.001 Ether)?

texts:
Ethereum newbie here.
I tried transfering 0.0001ETH to one of my accounts for some testing. I realized there is a minimum limit of 0.001 ETH for transfers on the blockchain as shown by the error.

I was under the impression Ethereum and Bitcoin will enable Micropayments. How would this be possible with a minimum limit on the chain?


texts: Transfer / Burn "From" Functions Using ethereum.org

texts:
I've deployed my contract using the unaltered "Full Code" as specified here: https://www.ethereum.org/token#full-coin-code.

Once the contract has been formed, I seem to be able to administer it without issue using the - Burn, Mint Token, Transfer, Freeze Account & Transfer Ownership functions.

I'm now testing the Burn From & Transfer From functions, however when I try to execute a contract to say burn half of the tokens from the target accounts balance, executed from the contract owner account I get the message "It seems this transaction will fail.  If you submit it, it may consume all the gas you provide."  When I execute the contract I get a message "Intrinsic Gas Too Low".

Is there a bug in the sample code or (more likely) what am I doing wrong?  Is there some security issue (do I need to turn on the ability to transfer from users accounts somewhere else)?

Thanks


texts:
Sorry, i'm newbie about ERC-721. I have deployed my contract and verified it. https://ropsten.etherscan.io/address/0x677f76d276355c382da948d2476da06cf5dc6219

But I don't see inventory tabs like other tokens (crypto kitties, etc.). And I want  to display this tab.

Is this inventory tab related to metadata on the ERC-721 standard or is it automatically created? and then, what information can be displayed on this inventory tab? like the CryptoKitties token, I saw a token image, token id, and owner. But on other tokens only give a token id and owner.

Would someone explain to me? thanks


texts: geth event newPendingTransactions does not occur

texts:
I've got running geth with next command:

$ geth --testnet --networkid 3 --verbosity 3 --syncmode light --ipcdisable --ws --wsapi "db,eth,net,web3,personal,txpool,admin,miner" --wsorigins '*'

In second console I connect to geth jsonrpc with wscat.

Subscribing to an event "newHeads" works fine:

$ wscat -c ws://localhost:8546
> {"id": 2, "method": "eth_subscribe", "params": ["newHeads"]}
< {"jsonrpc":"2.0","id":2,"result":"0x660135584e36a9edb0c55f89c389848"}
< {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x660135584e36a9edb0c55f89c389848","result":{"parentHash":"0xe7d0...","hash":"0x1dcc...

But subscribing to an event "newPendingTransactions" not works:

$ wscat -c ws://localhost:8546
> {"id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}
< {"jsonrpc":"2.0","id":1,"result":"0x511b3274aa5dec44bb79d178c238e7fe"}

And it's all: I do not get new pending transactions.

Subscribing to an event "newPendingTransactions" on ropsten.infura.io works fine:

$ wscat -c wss://ropsten.infura.io/ws
> {"id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}
< {"jsonrpc":"2.0","id":1,"result":"0x18fda7bf20ee9c5b5f1f08edf5c3e482"}
< {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x18fda7bf20ee9c5b5f1f08edf5c3e482","result":"0xc1e00266ab9f2c512d6c1967c300fc00381586e868611b7dff6fd94f230dd707"}}

Info:

$ geth version
Geth
Version: 1.8.22-stable
Git Commit: 7fa3509e2eaf1a4ebc12344590e5699406690f15
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.10.4
Operating System: linux
GOPATH=
GOROOT=/usr/lib/go-1.10

I have two questions:

1. Why subscribing to event "newPendingTransactions" not works?

2. What am I doing wrong?


texts: Call private internal function from another contract

texts: Is it possible for me to call from a contract B, that has an instance of A, a private or internal function of contract A?


texts:
I have a transaction hash (for example 0xd97a7f7e15709ce345842a52a6e8db395e6ba779fd76a426b1878512a34a8128) I would need the information in red, basically the tokens involved (the first one is an ERC20 token, while the latter is an ERC721).

can you point me in the right direction to get this information via API? I would like to use a Python script but I can give also a try to JS.
I tried with blockcypher API but it seems they only give me basic information (nothing I can recognize on tokens)
I don't own a full node, maybe I can use infura.io with a free account?
I think to fetch directly the
etherscan web page but it seems a bit dirty...
thank you


texts: What is an IDE? What's the difference between mix, and browser based IDE?

texts: I'm reading up IDE and I don't understand them from a lay person's perspective.  What's the difference between mix and browser based IDE.  How do you use them?


texts:
I am trying to understand how MetaMask works in browser.

Metamask, as a browser extension, is used to send transactions for ethereum blockchain. After reading some articles, I think one of important things Metamask does is to inject a Web3 instance into the browser's global variable window so that DApp's script could find a provider to make JSON_RPC call.

In web3 instance, there is a currentProvider already defined by MetaMask. I am wondering where this currentProvider pointing to.

I develop and test my own dApp based on a my local private chain so I have an IP and port to create a HttpProvider to allow Dapp to connect to. But I don't know what is the IP and Port used by MetaMask to create a provider.

My questions:
1. Is there a server or cluster set up by MetaMask itself in order to receive transactions from MetaMask browser extension?
2. If no, what mechanism for MetaMask to get active node?
3. Can you provide source code for this part? There are too many projects under metamask so that I cannot find it.


texts: Can you safely change your Ethereum password without creating a new Account?

texts:
Apparently Ethereum provides the ability to change the password associated with one of your Accounts.

What exactly happens when you do this?  Do your private keys change, too?  Afterward, are you still at risk if someone were to obtain any combination of the old/new keys and old password?

I'm guessing the safest way to change your password is to simply create a new Account and move your funds to it, but since the password change command is there I'm curious what it does.


texts: Is transaction triggered by web3 secure on the internet?

texts:
I'm trying to construct my business architecture using ethereum.

I'll operate public ethereum node and private business server on the AWS.

I'll trigger transaction from the private business server using web3.js to public ethereum node.

Q1 : On this case, Do I have to sign the transaction using private key on the private business server. right?

Q2 : The transaction will go through internet because ethereum node and business server node are physically separated. On this case, Is the transaction(signed data) which triggered by web3 safe through the internet? I'm worry that the signed data packets are captured on the internet and translated by hackers.


texts: Truffle compile fails: could not find file from any sources

texts:
I'm following the steps of this tutorial. I created a simple contract, TodoList.sol

pragma solidity ^0.5.0;

contract TodoList {
    uint public taskCount = 0;
}

Then I run truffle compile and get this error message

Error: Could not find .../todolist/contracts/TodoList.sol from any sources
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-resolver/index.js:76:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/async/internal/onlyOnce.js:12:1
    at next (/usr/local/lib/node_modules/truffle/build/webpack:/~/async/whilst.js:68:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-resolver/index.js:64:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-resolver/fs.js:85:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/async/internal/once.js:12:1
    at replenish (/usr/local/lib/node_modules/truffle/build/webpack:/~/async/internal/eachOfLimit.js:61:1)
    at iterateeCallback (/usr/local/lib/node_modules/truffle/build/webpack:/~/async/internal/eachOfLimit.js:50:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/async/internal/onlyOnce.js:12:1
    at ReadFileContext.callback (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-resolver/fs.js:81:1)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:242:13)
Truffle v5.0.2 (core: 5.0.2)
Node v11.12.0

The file is there. If I remove that file, truffle compiles the  Migrations.sol automatically generated by truffle init without errors.

When I edit TodoList.sol with VSCode and try to compile it with the Solidity plugin, it doesn't complain, but it doesn't generate any output in the build folder.


texts:
I am facing this error :

  Error: exceeds block gas limit

When i run below command it returns 5000.

web3.eth.getBlock("latest").gasLimit

so as per someone's suggestion 21000 gasLimit is needed to initiate a transaction so i tried to increase it using below command.

sudo geth --rpcapi eth,web3,personal --rpc --networkid=15 --targetgaslimit=47123880

but after above command execution also gasLimit is still same as 5000.

My purpose is to increase gas limit.

Thanks.


texts: Upload large mapping into smart contract

texts:
Lets say you have very large array file in the following format:

[{
   "address": "0x123",
   "state": true
},
{
   "address: "0x234",
   "state": false
}]

Implement a function that would allow you to record this data into smart contract.


texts:
In my smart contract (in moment erc20), is possible create payment function receive eth
I would like to receive usdt (or usdc) and not eth, how could I do it?
Thanks


texts: What’s the opcode chain for sending ethereum from a smart contract?

texts:
Simple question, but I couldn’t find the answer anywhere.
I know CALL is used and sometimes CALLER, but I don’t have any idea on how msg.sender.call.value(100) would be performed.


texts: How to calculate the amount of dead tokens?

texts:
Let's take Saturna as an example.
The contract says that the total supply is 1000000000000000000000000. Meanwhile, Bogged shows that:

token price is USD 0.00000000922018, and
market cap is USD 6,152,615

I would expect that supply x token price = market cap, however, that is not the case:
1000000000000000000000000
*
0.00000000927378
=
9,273,780,000,000,000

I suspect that the reason for this is that total supply != circulating supply.
How do I get total supply - burned tokens?


texts: Why stateRoot, transactionsRoot and receiptsRoot not included in the blockheader of any etherscan ?

texts:
My question may be stupid. I'm trying to understand how ethereum is made and in all articles I read that a block header include a list of things and the stateRoot, the transactionsRoot and the receiptsRoot. However, I cannot see any of these three things in any ether scan (for instance https://etherscan.io/block/5958485).

How is that possible ? Where are the roots of the patricia tree ??
Thank you for your answers ! If you can show me a root, I would warmly thank you !! :)


texts: Unable to install Mocha Web3 and Ganache-cli

texts:
I have been trying to install mocha,Web3 and ganache all through one command but I am facing an issue while installing can someone help me in sorting our this error. Quick response will be appreciated .

npm install --save mocha ganache-cli web3@1.0.0-beta.26

Error
https://i.imgur.com/YEfxBPZ.png


texts: What algorithm Ethereum use POS(proof of shake) or POW(proof of work)?

texts: I am very much curious to know what algorithm Ethereum is using and what is the impact of this algorithm in the current blockchain .


texts: Best Method to Increase TPS on PoA Blockchain

texts:
In creating a PoA blockchain where a high TPS is needed, how will you define the genesis.json configuration? There will be sealer nodes on opposite ends of the globe with ~ 0.1-0.2 second latency.

What problems will you encounter when you

Set the block time very short, to 0.5 second
Set the block gas limit very high, say 1,000,000,000

If the block gas limit is 1,000,000,000 and there are 3 transactions with gas limits 999,999,999, 2 and 1, which transactions will be included in that block? If the block gas limit fixed in the genesis.json, or does it change dynamically?


texts:
I initialized a full uint256 array like this:

uint256[2**256-1] private test;

And I get this warning for the compiler:

Warning: Variable covers a large part of storage and thus makes collisions likely. Either use mappings or dynamic arrays and allow their size to be increased only in small quantities per transaction.

Can anyone explain to me exactly what this means?


texts:
I am trying to compile a contract on remix and have run into the following warning :

  Use assert(x) if you never ever want x to be false, not
  in any circumstance (apart from a bug in your code). Use
  require(x) if x can be false, due to e.g. invalid input
  or a failing external component.

The parts of my code that use assert are :

assert(checkPlayerExists(msg.sender) == false);
assert(number >= 1 && number <= 10);
assert(msg.value >= minimumBet);

Would love someone to explain this as it seems a bit cryptic.


texts: TypeError: Cannot create property 'constant' on number '123' web3js

texts:
I am trying to send transaction to my contract via node js but I am encountering many problems.

This is my node js code:

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

var myAddress = '0x4e5d87aB06D13a17E9f35dfC235B4fC70669151d';
var fs = require('fs');
var contractABI = fs.readFileSync('../abis/Marketplace.json')
var contractAddress = '0x15Cb1e185b0269fFd93516BE007B2aF4BA59f2F5';
var contract = new web3.eth.Contract(contractABI,contractAddress);

contract.methods.updateModifications("fileName","Changes were made", new Date()).call({from: myAddress});

console.log("Notified successfully");

This is my contract:

pragma solidity ^0.5.0;

contract Marketplace {
    uint public notificationCount = 0;
    mapping(uint => FileChanges) public modifications;
    struct FileChanges
    {
        string name;
        address madeBy;
        string changesMade;
        string timeStamp;
    }
    function updateModifications(string memory _name, string memory _message, string memory _date) onlyOwner public payable
    {
        notificationCount++;
        modifications[notificationCount] = FileChanges(_name, msg.sender, "Contract created", _date);
    }
}

And when I try to run my code, this is my error:

C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth-contract\dist\web3-eth-contract.cjs.js:293
        abiItem.constant = _this.isConstant(abiItem);
                         ^

TypeError: Cannot create property 'constant' on number '123'
    at C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth-contract\dist\web3-eth-contract.cjs.js:293:26
    at Buffer.forEach (<anonymous>)
    at AbiMapper.map (C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth-contract\dist\web3-eth-contract.cjs.js:292:11)
    at new AbstractContract (C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth-contract\dist\web3-eth-contract.cjs.js:984:38)
    at ContractModuleFactory.createContract (C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth-contract\dist\web3-eth-contract.cjs.js:1089:14)
    at new Eth._this.Contract (C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\node_modules\web3-eth\dist\web3-eth.cjs.js:403:50)
    at Object.<anonymous> (C:\Users\Vishnu.Siripuram\Desktop\project\marketplace\src\components\notifier.js:17:16)
    at Module._compile (internal/modules/cjs/loader.js:945:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
    at Module.load (internal/modules/cjs/loader.js:798:32)


texts: To get event args when I using ethers.js

texts:
I'm a three months old programmer.
So if what I'm saying is ambiguous, please let me know and help me being a better programmer.
Now I'm coding a test code as using hardhat and ether.js.
My solidity contract is about orderbook token exchange.
When people make an order, the contract emit specific event named "Make".

event Make(
    bytes32 indexed orderId,
    address indexed maker,
    address makerToken,
    address takerToken,
    uint256 amountSell,
    uint256 amountBuy
);

orderId is made by hashing some data.
And I want to check if event is emitted correctly.
While coding test codes, I've spent quite a long time to know how to get emitted events.
finally I can get events using code below.
but what I really want is

get 1st arg of event and put it a var. (in case, bytes32 hash)
looks like,   const hash = await events.args[0];

compare 2nd arg of event and compare it with value. (in case, address maker)
looks like,   expect(await events.args[1]).to.equal(add1.address);

actually it's not a two question. just one.
here's my test code.
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("EX contract", function () {
    let EX, ex, token, Token, add0, add1, add2, add3;

    before(async function () {
      EX = await ethers.getContractFactory("EX");
      Token = await ethers.getContractFactory("Token");
      ex = await EX.deploy(1000);
      token = await Token.deploy();
      [add0, add1, add2, add3] = await ethers.getSigners();
    });

    beforeEach(async function () {
      await token.mint(add1.address, 200000);
    });

    describe("Make / Take order", function () {
        await ex.connect(add1).makeOrder(token.address, 100, {value : 100});
        await ex.connect(add1).makeOrder(token.address, 100, {value : 200});

        let eventFilter = ex.filters.Make();
        let events = await ex.queryFilter(eventFilter, "latest");

        console.log(events);            //"events" contains too many information.
    });
});

Help me please, mates!


texts:
I am using mist to connect to private blockchain and i get this error continuously in the terminal.

[2018-04-04 14:08:45.452] [ERROR] ipcProviderBackend - Send request failed TypeError: Cannot read property 'contractAddress' of null
at /opt/Mist/resources/app.asar/modules/ipc/methods/eth_getTransactionReceipt.js:29:34
at Generator.next (<anonymous>)
at step (/opt/Mist/resources/app.asar/modules/ipc/methods/eth_getTransactionReceipt.js:3:191)
at /opt/Mist/resources/app.asar/modules/ipc/methods/eth_getTransactionReceipt.js:3:361
at <anonymous>

can someone help me understand why i get this error.

Thanks


texts: Running Ethereum Wallet and geth console together

texts:
I am a newbie with blockchain overall. What I am trying an an experimental basis is: having a webpage display my balance in one of my accounts (on test-net).

I am using meteor for my web interface, web3 for connecting with client, client being go-ethereum. And I have geth installed on OSX as well. Problem is I can either run Ethereum Wallet or geth at one time. I understand that if the purpose is syncing with respect to chain, there is no point running two instances - wallet and geth together.

The issue is when I am trying to do some web development. I would be creating contracts etc. on JS and I would be pushing those on blockchain. (Note: everything till now is on testnet)

At the same time, I also want to do experiments on contracts using Ethereum wallet because of it's easy UI.

Question then is how to have geth and Ethereum running at the same time. Currently, when I have one running and I am trying to run another, the error is:

OR

if Wallet is running, same kind of resource temporarily unavailable error pops up, when I am trying to run geth using

[~]$ geth --testnet --mine --rpc --rpccorsdomain "http://localhost:3000"

What am I doing wrong?


texts: wallet.ethereum.org How to send from multisig contract

texts: I have a multisig contract with 2 required signatures. The first singature will be made by account key. I have a private key from the second, but how to sign it?


texts: Syntax error on official Ethereum ERC20 Code?

texts:
I copy and pasted the code found here: https://www.ethereum.org/token
into a file called TokenERC20.sol

When I run

truffle compile

I get this error:

SyntaxError: Expected "contract", "import", "library", "pragma", "using", comment, end of input, end of line, or whitespace but "i" found.
    at peg$buildStructuredError (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:177767:12)
    at Object.peg$parse [as parse] (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:181366:11)
    at Object.parse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:89808:23)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:57847:36
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:50141:5
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:66021:16
    at next (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:75933:18)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:50126:7
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:96942:5
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:75838:16

Anyone know what could be causing this?

EDIT
The problem appears to be here:

pragma solidity ^0.4.8;

interface tokenRecipient {
   function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}

contract TokenERC20 {
    // Public variables of the token
    string public name;
    string public symbol;
    uint8 public decimals = 18;
    // 18 decimals is the strongly suggested default, avoid changing it
    uint256 public totalSupply;

If I comment out the interface and every line that uses it then it compiles fine. Is there some problem with how the interface is declared?


texts:
Here's a scenario:

Dapp backend connects to a remote Ethereum node using external
HTTP RPC:

const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/janNFDJkMgDfan"));

Dapp user sends transaction to a contract and then submits this
transaction's hash to dapp backend.
Dapp backend waits for the pending block to get confirmed and checks
if the transaction is included in it.

Here's the problem:

As it turns out when web3 object is provided by an external node backend can't use events. For example, backend can't watch for new blocks. The following doesn't work:

var filter = web3.eth.filter('latest');

filter.watch(function(error, result){
  var block = web3.eth.getBlock(result, true);
  console.log('current block #' + block.number);
});

  TypeError: filterCreationErrorCallback is not a function

So, the problem is that backend doesn't know when a new block is mined.

One way to handle this:

Backend can query the blockchain every ~20 seconds to check if a new block has been mined.

check(){
    web3.eth.getBlock("pending", (error, result) => {
      console.log('error:', error);
      console.log('results', result);
    });
}
setTimeout(check, 20000);

and then make sure that the user's transaction was included.

Another way of handling this is:

?????


texts: How to connect truffle using HDWallet provider to Websocket-powered node?

texts: I am using truffle-hdwallet-provider to connect to the node that operates over https and it works perfectly. Now I want to connect to websocket-powered node but keep my HD Wallet provider. I cannot find how to do that. All I found is package web3-providers-ws but cannot find is it possible (and how) to chain multiple providers?


texts:
I wrapped a smart-contract generated in remix into a Java Project. Im trying to get the two values that return me this function.

function getValues(address _a) external returns(bool, uint32) {
    uint32 n= data[_a].number;
    return (true, n);
}

The problem is that the returned value is a TransactionReceipt. How can I recover bouth value; The boolean and the uint??


texts:
I have a smart contract where the user inputs temperature readings, I'd like to add a time stamp to relate those reading with a current time of submission. I understand that in Ethereum we only have now to assist with block time but we don't have a time of a transaction, but that's not what I want.

Any ideas on how to do so, is it possible? Or if using a Dapp I'll have to do so via HTML or JS?


texts: where to host my Java web app to fully decentralised?

texts: I need a idea to host my webapp to be on some secure distributed network. my client doesn't want to deployed on aws or gcp. he wants it to be on decentralised network p2p. Your suggestion and advice will be great to figure the right technology and network for this app.Thanks already.


texts: what is contract type in solidity and what is the use of it

texts:
contract DappToken {
        string  public name = "MDV";
        string  public symbol = "$$$";
        string  public standard = "DApp Token v1.0";
        uint256 public totalSupply;
        // having more code
    }

I have Imported the These contract in my next file  and used the the contract name as the name of the variable

contract DappTokenSale {
    address admin;
    **DappToken public tokenContract;**
    uint256 public tokenPrice;
    uint256 public tokensSold;

function DappTokenSale(DappToken _tokenContract, uint256 _tokenPrice) public {
    admin = msg.sender;
    tokenContract = _tokenContract;
    tokenPrice = _tokenPrice;
}
}

In migrations we passed the the addess of the deployed contract to the token contract

function DappTokenSale(DappToken _tokenContract, uint256 _tokenPrice) public {
    admin = msg.sender;
    tokenContract = _tokenContract;
    tokenPrice = _tokenPrice;
}

1) Why do we even have to declare a varable a contract type  here

2) We know it is the address we are going to pass so why can't we declare a address type insted of contract type

3) What is diffrence between defining a varble a  contract type and some data type

4) I have observed the same behaviour in interface  defining the interface type before the varable initlization


texts: Does the Ethereum Foundation foundation accept proposals?

texts: Can you expand on the role of the foundation in supporting new projects? What is the proposal time-frame and format if there is one? How does one interact with the foundation? Etc...


texts: web3.eth.getTransaction("txh") , is this call searches the entire blockchain data or  is there an indexing ?


texts:
I am using an openZepplin crowdsale contract which has the following constructor

contract myContract is Crowdsale {
    function myContract
    (
        uint256 _rate,
        address _wallet,
        MintableToken _token
    )
        public
        Crowdsale(_rate, _wallet, _token)
}

I want to make my "_wallet" address the same as the "myContract" address.
Is there a way to get the current contract address within the contract?

Sudo code would be something alongs these lines:

contract myContract is Crowdsale {
    function myContract
    (
        uint256 _rate,
        address _wallet,
        MintableToken _token
    )
        public
        Crowdsale(_rate, <<this.address>>, _token)
}