texts: Test pass with Remix but fails with Truffle

texts:
I have two contracts: ElephanteumStorage and ElephanteumCore.
Storage just keeps some data. Core is provided to change the data in the Storage.
As a constructor argument, ElephanteumCore receives Storage address so Core can call Storage's functions. Also, I have setted Core as an owner of the Storage.
  I wrote init function in Core that must save data in storage and I tested this functionality in Remix IDE with  Rinkeby and JS VM and everything was just fine.
But in Truffle test I got revert error message.

contract ElephanteumCore is Ownable {

        ElephanteumStorage public eStorage;

        function ElephanteumCore(address _eStorage) public payable {
            eStorage = ElephanteumStorage(_eStorage);
        }

        function init(bytes32 _name, bytes32 _symbol, uint _supply) public onlyOwner {
            eStorage.setTotalSupply(_supply);
            eStorage.setElephantsRemainingToAssign(_supply);
            eStorage.setName(_name);
            eStorage.setSymbol(_symbol);
        }
}

contract ElephanteumStorage is Ownable {

        bytes32 public name;
        bytes32 public symbol;

        uint public totalSupply;

        uint public elephantsRemainingToAssign;

        function setName(bytes32 _name) onlyOwner external {
            name = _name;
        }

        function setSymbol(bytes32 _symbol) onlyOwner external {
            symbol = _symbol;
        }

        function setTotalSupply(uint _totalSupply) onlyOwner external {
            totalSupply = _totalSupply;
        }

        function setElephantsRemainingToAssign(uint _elephantsRemainingToAssign) onlyOwner external {
            elephantsRemainingToAssign = _elephantsRemainingToAssign;
        }
}

And there is my truffle test:

const elephanteumCore = artifacts.require('ElephanteumCore');
const elephanteumStorage = artifacts.require('ElephanteumStorage');

contract('ElephanteumCore', accounts => {
  let eCore, eStorage;

  before(async () => {
    eStorage = await elephanteumStorage.new();
    eCore = await elephanteumCore.new(eStorage.address);
    await eStorage.transferOwnership(eCore.address);
  })

  it('Should initialize the contract correcty', async () => {
    let name = "Elephanteum";
    let symbol = "EPH";
    let supply = 100;

    await eCore.init(name, symbol, supply);

    let rName =  await eStorage.name.call();
    let rSymbol = await eStorage.symbol.call();
    let rSupply = await eStorage.totalSupply.call();

    assert.equal(name, web3.toUtf8(rName), "name should have be initialize correctly");
    assert.equal(symbol, web3.toUtf8(rSymbol), "symbol should have be initialize correctly");
    assert.equal(supply, rSupply.toNumber(), "supply should have be initialize correctly");

  })

I tried to run test both in testrpc and rinkeby, everywhere it raise exception on line

await eCore.init(name, symbol, supply);

And I don't know why.


texts: Can events always be called directly by user accounts? Is there a way to make them internal?

texts:
I am using events to fire an order, basically using them as a vehicle for a master/slave connection with an IoT device, through the blockchain.

Ideally i want to always verify the right msg.sender is sending this order and emitting the event, so i made a function with this access control in place. However i have noticed that i can directly call the event with the proper arguments to emit it (i tested this out on truffle), so malicious users could bypass the function with access control entirely.

It doesn't seem like its possible to use the internal or private visibilities when declaring events, since they're not functions.

So my question is, is there no way to enforce access control or visibility on events? Are there any plans to address this, or am i just using them the wrong way?


texts: Unexpected implicit casting in Solidity's exponential operator

texts:
While investigating an incorrect token award bug in an ERC20, it's come to light that there is an apparent inconsistency in casting with regard to the exponential operator a**b. In particular, the output casts to type b rather than type a.

So when calculating a decimal place exponent 10**exp where exp is defined uint8 exp = 3 the output is truncated to 8 bit giving the answer of 232 rather than 1000.

If the base is definded as uint8 and exponent of longer type, e.g.uint, the compiler will throw an implicit conversion error which indicates the output should be of type base and not exponent.

This doesn't seem to be affected by non-compound parameters which are all cast to 32bit slots anyway.

contract PowerOfTest {
    // Returns 232
    uint8 public placesA = 3;
    uint public EXP_A = 10**placesA;

    // Returns 1000
    uint public placesB = 3;
    uint public EXP_B = 10**placesB;

    // Returns 1000
    uint8 public placesC = 3;
    uint public EXP_C = 10**uint(placesC);

    // Type uint256 is not implicity convertable to expected type uint 8
    // uint public EXP_D = 3;
    // uint8 public placesD = 10**EXP_D;

    // Returns 1000 for `pow(10, 3)`
    function pow(uint base, uint8 exponent) returns(uint)
    {
        return base**exponent;
    }

    // Returns 232 for `pow(10, 3)`
    function pow2() returns(uint)
    {
        uint8 EXP_D = 3;
        return 10**EXP_D;
    }
}


texts: Accessing array within struct in a mapping using web3.js

texts:
I have created a struct patient as follows, and a mapping of uint->patient.

struct patient {
    uint pId;
    string name;
    string phone;
    address payable owner;
    uint numRecords;
    uint[] cost;
    address[] uploader;
    string[] procedure;
    uint[] hospId;
    string[] doctorName;
    bool[] treated;
    string[] image;

}

mapping(uint => patient) public patients;

I am have created functions to insert data into the mapping.
However, when i try to read the data in reactjs using web3,

//REACTJS
for (var i = 1; i <= patientCount; i++) {
            const patient = await container.methods.patients(i).call()
    }

the patient variable only contains the non array parts of the struct.
i.e, only pId, name, phone, owner and numRecords is returned.

The value returned is

 {0: BigNumber, 1: "Name", 2: "1234567890", 3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", 4: BigNumber, pId: BigNumber, name: "Name", phone: "1234567890", owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06", numRecords: BigNumber}
0: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
1: "NAme"
2: "1234567890"
3: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
4: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
name: "Name"
numRecords: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
owner: "0x771D3a7C2d6C59D9030731a48D60D8296303fC06"
pId: BigNumber {_hex: "0x01", _ethersType: "BigNumber"}
phone: "1234567890"
__proto__: Object


texts:
I'm using Web3.js (@1.0) and not @0.2

This is really annoying !

My Private blockchain is running thanks to the following command : vgeth --datadir "T:\Programs\Ethereum\Own\" --networkid 2154 --rpc --rpccorsdomain "*" console

Here, how a deploy my contract: (deploy.js)

var Web3 = require('web3');
const compiledContract = require('./App');
const localhost = "http://localhost:8545";
const web3 = new Web3(new Web3.providers.HttpProvider(localhost));
const App = new web3.eth.Contract(compiledContract.abi);

var deployInstance = App.deploy({data: compiledContract.bytecode});
deployInstance.estimateGas(function(err, gas){
   console.log("gasestimate " + gas);
   web3.eth.getCoinbase().then(function(coinbase){
     console.log("coinbase " + coinbase);
     deployInstance.send({from: coinbase, gas: gas+4000}, function(error, transactionHash){})
  .on('transactionHash', function(hash){console.log("hash : " + hash); })
  .on('receipt', function (receipt) { console.log("Address: " + receipt.contractAddress); })
  .on('error', console.error);
   });
});

That's working pretty good, and my contract is deployed.
I obviously though to unlock an account (here eth.coinbase) and to call miner.start() and miner.stop() when the contract was finally mined

Then that's how I call my methods. This is a sample code: (call.js)

var Web3 = require('web3');
const compiledContract = require('./App');
const localhost = "http://localhost:8545";
const address = "0x84C210471f7C58b547129E62cdDC2D365d307212"; //address returned after deployed phase

var web3 = new Web3(new Web3.providers.HttpProvider(localhost));
var Contract = new web3.eth.Contract(compiledContract.abi, address);

set();
//get();

function get(){
   Contract.methods.getTest().call(function(err, result){
     if(err) console.log(err);
     else console.log(result);
   });
}

function set(){
   web3.eth.getCoinbase().then(function(coinbase){
      web3.eth.personal.unlockAccount(coinbase, "", function(err) {
        Contract.methods.setTest("ugonnawork").send({from: coinbase, gas: 300000}, function(error, transactionHash){})
    .on('transactionHash', function(hash){console.log("hash : " + hash); })
    .on('error', console.error);
  });
 });
}

And this annoying issue occurred :

Geth - Web3 : Invalid number of parameters for "MyMethod". Got 0 expected 1!

When I call another method called getUser(uint index) I got : Geth - Web3 : Invalid number of parameters for "MyMethod". Got 1 expected 2!

And when I call name() that's working pretty good, and my ERC20 Token name is returned.

It seems that fails or works randomly but it can't figure out what's wrong

Please help


texts: approve + safeTransferFrom ERC721 from existing smart contract

texts:
I am trying to call ERC721 from another smart contract, while calling function approveAndTransfer ,I am getting "ERC721: transfer caller is not owner nor approved", not sure reason behind it,
As require(nft.ownerOf(_tokenId) == msg.sender, "NOT OWNER"); is working as expected and not throwing any error,  but source of error is _tranfer function which gets called from
nft.safeTransferFrom(msg.sender, _to,_tokenId);
not sure what mistake I am making.
I have NFT in my wallet, but I am not owner of external smart contract.
    // SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

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

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

contract Tat is IERC721Receiver {

constructor() public {}

function approveAndTransfer(IERC721 nft, uint256 _tokenId, address _from, address _to) public {
    require(nft.ownerOf(_tokenId) == msg.sender, "NOT OWNER");
    nft.isApprovedForAll(_from, address(this));
    nft.safeTransferFrom(msg.sender, _to,_tokenId);
}

function ownerOf(IERC721 nft, uint256 tokenId) external view returns (address owner) {
    return nft.ownerOf(tokenId);
}

function test() public view returns(address sc,address own){
    return (address(this),msg.sender);
}

function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes memory _data) public override returns(bytes4) {
       return 0x150b7a02;
 }

}

Thanks in advance.


texts:
I read the Efficient Solidity storage pattern for a directional weighted graph thread, but that deals with storing graphs. I'm interested in techniques for how to traverse graphs in Solidity, at scale.

Consider the following data pattern, which uses Rob Hitchens' UnorderedKeySet library to build a table-like database with rows and keys:

contract GraphTraversal {
    using HitchensUnorderedAddressSetLib for HitchensUnorderedAddressSetLib.Set;
    using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;

    struct User {
        uint256 balance;
        uint256[] incomingStreamIds;
        mapping(uint256 => uint256) incomingStreamIdPointers; /* left is stream is row in table */
        uint256[] outgoingStreamIds;
        mapping(uint256 => uint256) outgoingStreamIdPointers; /* left is stream id, right is row in table */
    }

    mapping(address => User) public users;
    HitchensUnorderedAddressSetLib.Set userSet;

    struct Stream {
        uint256 interval;
        uint256 paymentRate;
        address sender; /* key for a User struct */
        address recipient; /* key for a User struct */
        uint256 startTime;
        uint256 stopTime;
    }

    mapping(bytes32 => Stream) public streams;
    HitchensUnorderedKeySetLib.Set streamSet;
}

Highlights:

Each user references two sets, incoming and outgoing streams, which are both capped in length - the contract enforces an upper limit on how many incoming and outgoing streams can be created
Each stream references two users, a sender and a recipient

The above is a two-to-many data relationship between users and streams. We define streams as financial agreements whereby the sender pays the recipient a specific amount of money once every so often.

Now, what I want to achieve:

Have a rebalance function that iterates over all incoming and outgoing streams that refer to a user
Recursively call rebalance for every sender of an incoming stream and every recipient of an outgoing stream - essentially a depth-first search (DFS)
If at any stage during the function call, a user is under-collateralised (the payment amount required by the the streams exceeds his current balance), delete the current stream and all streams that succeed it
At the end of the rebalance function, update each user's balance property by adding up all the income provided by the incoming streams and subtracting all payments made to outgoing streams

Obviously, this is not feasible on Ethereum mainnet (at scale). I'd hit the block gas limit with relatively few users and streams.

How could something like this be implemented? Maybe SNARKs or optimistic rollups that do the graph traversal off-chain and post a succinct proof on mainnet afterward?

For a pseudocode implementation of the rebalance function, see this gist on GitHub.


texts: smart contract Thether balanceOf method returns 0x

texts:
i used web3j-java call Tether contract method balanceOf(the server node is mine , and on ether mainnet),my address has 3USDT,but i call balanceOf , the node returns me 0x as the balance value,it is not correct ,and how to resolve this problem. the geth version is 1.9.24 . block-chain had been sync finished.
my eth node start firewall,is someone help me to solve this problem,please contact me. and provide you more info about this.
Contract Address is: 0xdAC17F958D2ee523a2206206994597C13D831ec7
My Address is: 0xf19c930fad206da25f89a6b740fb1fdb403b351c
geth process: /root/eth/geth --http --allow-insecure-unlock --http.addr 0.0.0.0 --http.api admin,debug,web3,eth,txpool,personal,ethash,miner,net --http.corsdomain "*" --http.vhosts "*"
goals: get address USDT balance under Thether Token
codes:
    Web3j web3j = Web3j.build(new HttpService("http://27.102.106.58:8545"));
    List<Type> inputParameters = new ArrayList<>();
    Address address = new Address("0xf19c930fad206da25f89a6b740fb1fdb403b351c");
    inputParameters.add(address);
    List<TypeReference<?>> outputParameters = new ArrayList<>();
    TypeReference<Uint256> typeReference = new TypeReference<Uint256>(){};
    outputParameters.add(typeReference);
    Function function = new Function("balanceOf", inputParameters, outputParameters);
    String encodeFunction = FunctionEncoder.encode(function);
    org.web3j.protocol.core.methods.request.Transaction transaction = org.web3j.protocol.core.methods.request.Transaction
            .createEthCallTransaction("0xf19c930fad206da25f89a6b740fb1fdb403b351c", "0xdAC17F958D2ee523a2206206994597C13D831ec7", encodeFunction);
    EthCall ethCall;
    BigInteger balanceValue = BigInteger.ZERO;
    try {
        ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
        List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
        balanceValue = (BigInteger) results.get(0).getValue();//here is 0x
        System.out.println(balanceValue);
    } catch (Exception e) {
        e.printStackTrace();
    }


texts: I am using Metamask for testing my contract which requires some ether, but, I don't have any ether in those accounts. I know Remix which provides four accounts with 100 eth.  I have no idea how to get ether in Metamask.


texts:
As the need of blockchain systems grows so will be the storage issues and the cost of handling such large amounts of data.

Is ethereum capable of handling petabyte storage or is it upto an
organization building an application on private ethereum blockchain network  to handle the storage
issues seperately by some other means?
Are there any available persistent storage solutions for storage on
blockchains which store application data ?
what are the standard mechanisms to transfer such data from onchain
to offchain persistent storage solutions ?
Are these solutions scalable ?


texts: Can't use token variable's method at contract that inherit zeppelin crowdsale?

texts:
Calling the method of Crowdsale's "token" on the source that inherited Crowdsale of zeppelin v1.8.0 inevitably causes "out of gas".

  Error: Error: VM Exception while executing eth_call: out of gas

Is it impossible to use token's method from crowdsale source on here?

Environment

Truffle v4.1.5 (core: 4.1.5)
Solidity v0.4.21 (solc-js)
zeppelin v1.8.0
EthereumJS TestRPC v4.0.1 (ganache-core: 1.0.1)

Crowdsale Contract

Sample of zeppelin v1.8.0 is almost intact

pragma solidity ^0.4.18;

contract SimpleToken is StandardToken {

  string public constant name = "SimpleToken"; // solium-disable-line uppercase
  string public constant symbol = "SIM"; // solium-disable-line uppercase
  uint8 public constant decimals = 18; // solium-disable-line uppercase

  uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals));

  /**
   * @dev Constructor that gives msg.sender all of existing tokens.
   */
  function SimpleToken() public {
    totalSupply_ = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
    Transfer(0x0, msg.sender, INITIAL_SUPPLY);
  }

}

--

pragma solidity ^0.4.18;

contract SampleCrowdsale is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale {

  function SampleCrowdsale(
    uint256 _openingTime,
    uint256 _closingTime,
    uint256 _rate,
    address _wallet,
    uint256 _cap,
    MintableToken _token,
    uint256 _goal
  ) public
    Crowdsale(_rate, _wallet, _token)
    CappedCrowdsale(_cap)
    TimedCrowdsale(_openingTime, _closingTime)
    RefundableCrowdsale(_goal)
  {
    //As goal needs to be met for a successful crowdsale
    //the value needs to less or equal than a cap which is limit for accepted funds
    require(_goal <= _cap);
  }

  function tokenTotalSupply()
      public
      constant
      returns (uint256)
  {
      return token.totalSupply();
  }
}

After, deploy to testrpc, I got following error output...

truffle(testrpc)> mySale = SampleCrowdsale.at(SampleCrowdsale.address)
truffle(testrpc)> mySale.tokenToalSupply()
Error: Error: VM Exception while executing eth_call: out of gas
    at /c0ban-ico/node_modules/ethereumjs-testrpc/build/cli.node.js:59880:17
    at /c0ban-ico/node_modules/ethereumjs-testrpc/build/cli.node.js:88044:5
    :
    :


texts:
I am trying to get the block between dates . for that i use web3.js . per day average block is 6172 so if i need previous day block i use below code

fromBlock: (await web3.eth.getBlockNumber()) - 12343,
toBlock: (await web3.eth.getBlockNumber()) - 6172

then check the timestamp of the blocks in if condition .This is much time consume

is any easy way to get the blocks between dates. is any api available to get the blocks between the dates.


texts:
I create a random number starting from block.coinbase, block.number and block.timestamp, then I determine some probabilities.
Is it correct or there is a better way?

bytes32 bHash = keccak256(block.coinbase, block.number, block.timestamp);

            if (bHash[30] == 0xFF && bHash[31] >= 0xF4) {
                //one chance on 5000
                //do something
            } else if (bHash[28] == 0xFF && bHash[29] >= 0xD5) {
                //one chance on 1500
                //do something
            } else if (bHash[26] == 0xFF && bHash[27] >= 0x7E) {
                //one chance on 500
                //do something
            } else if (bHash[25] >= 0xF4) {
                //one chance on 20
                //do something
            }


texts: Convert String to Bytes32 Web3.py v4.3 Python

texts:
I'm using web3.py v4.x and I have an issue to convert string to bytes32. First I checked out Web3.py conversion APIs. So I used Web3.toBytes but still not working. Kindly check out the below error for more details:

Could not identify the intended function with name `publish`, positional argument(s) of type `(<class 'int'>, <class 'bytes'>, <class 'bytes'>)` and keyword argument(s) of type `{}`.
Found 1 function(s) with the name `publish`: ['publish(uint256,bytes32,bytes32)']
Function invocation failed due to improper argument encoding.


texts: How do I retrieve the event data related to the creation and transfer of The DAO tokens?

texts:
How do I retrieve the data related to the creation and transfer of The DAO tokens?

This data will be useful to trace the movements in The DAO balances.


texts: Why output value of Uniswap-2 SDK for token prices is different than those on its site?

texts:
I use fetchPairData method from uniswap-v2 SDK to quote two tokens conversion rates:
const uniswapPair: Pair = await Fetcher.fetchPairData(
    new Token(ChainId.MAINNET, baseToken.address, 18),
    new Token(ChainId.MAINNET, quoteToken.address, 18),
    provider
);
console.log(  Number(uniswapPair.token0Price.toFixed(pair.baseToken.decimals)) );

The return value for the token price is slightly different from the quoted value on uniswap website (This is the case for any tested pairs such as AAVE/DAI or LINK/DAI).
What is going on wrong with this method of price inquiry?


texts:
There is a code, the essence is this: I need to check the account balance for erc20 tokens, and if the balance is not zero, I need to send eth from another account to this one, after eth reaches the account, I need to send erc20 tokens to another account . How then can I get the status of a transaction? And if the status is successful, then do the token transaction?

 const balance = contractInstance.methods.balanceOf(walletAddress).call(function(err, result) {
       //console.log(err)
    if (result>0) {
    console.log("success")
    web3.eth.getTransactionCount(fromAddress)
  .then((count) => {
    let rawTransaction = {
      'from': fromAddress,
      'gasPrice': web3.utils.toHex(10 * 1e9),
      'gasLimit': web3.utils.toHex(21000),
      'to': walletAddress,
      'value': web3.utils.toHex(web3.utils.toWei("0.0002")),
      'nonce': web3.utils.toHex(count)
    }
    let transaction = new Tx(rawTransaction)
    transaction.sign(privateKey)
    web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
      .on('transactionHash', console.log)

  })

web3.eth.getTransactionCount(fromAddress)
  .then((count) => {
    let rawTransaction = {
      'from': walletAddress,
      'gasPrice': web3.utils.toHex(20 * 1e9),
      'gasLimit': web3.utils.toHex(41000),
      'to': tokenAddress,
      'value': '0x' + Number(result)/1000000000000000000,
      'data': contract.methods.transfer(fromAddress, amount).encodeABI(),
      'nonce': web3.utils.toHex(count)
    }
    let transaction = new Tx(rawTransaction)
    transaction.sign(privateKey1)
    web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
      .on('transactionHash', console.log)
  })

    }
    })


texts: Watching for events returns 0 blocknumber

texts:
I am trying to listen for recently mined events from a live smartcontract(EtherDelta).
      //https://github.com/praneethmendu/ethualizer/blob/master/backnd.js

      tradeEvent = contractIns.Trade({}, {fromBlock: '4221476', toBlock: 'latest'});

      tradeEvent.watch(function (error, eventResult) {
          if (error) {
              console.error(error);
          } else {
              loco.play();
              console.log(JSON.stringify(eventResult, null, 4));
          }

I am returned results by the watch callback but blocknumber and other hashes and indexes are 0, although args seem genuine, I suspect I am looking at pending transactions
{
    "address": "0x8d12a197cb00d4747a1fe03395095ce2a5cc6819",
    "blockNumber": 0,
    "transactionHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "transactionIndex": 0,
    "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "logIndex": 0,
    "removed": false,
    "event": "Trade",
    "args": {
        "tokenGet": "0x0000000000000000000000000000000000000000",
        "amountGet": "3909184320983949755",
        "tokenGive": "0xe41d2489571d322189246dafa5ebde1f4699f498",
        "amountGive": "4.093386723543402884816e+21",
        "get": "0x798888341bfc01b30196091d27613fc6c68df159",
        "give": "0xafe15d1c5baab8f6fc9ba107a90a5729964ea14c"
    }
}

I can get the current latest block and interact with getters in the contract, I am using a geth lightnode in rpc mode to connect, so no connectivity problems.
other details :
OS: Ubuntu 17.04
Edit: improved question using @farhankhwaja 's answer.


texts: Why does solidity not throw an error when I try to .call.value() without actually calling it?

texts:
If I do

msg.sender.call.value(1 ether);

It looks like I will send msg.sender 1 ether where I want to execute the fallback function.

However, it does NOT call it because I did not provide the brackets () for the arguments.

Why is this valid syntax?


texts: JSONRPC method should be specified for params: "undefined" while batching the requests in web3 js

texts:
I am able to get the balance for an ERC20 tokens in a loop, but when I try to use BatchRequest I get the following error JSONRPC method should be specified for params: "undefined"

Below code is throwing an error:

async function getBalanceInBatch(address) {
  const batch = new web3.BatchRequest();
  const contractData = balanceHex + address.substring(2);

  for (let token of tokens) {
    const params = { to: token.address, data: contractData, from: address };
    batch.add(web3.eth.call(params), callBack)
  }

  batch.execute()
}

balanceOf method name is mentioned in balanceHex which is
const balanceHex = "0x70a08231000000000000000000000000";

Working code without batch request:

const contractData = balanceHex + address.substring(2);
const params = { to: contractAddress, data: contractData };
const result = await web3.eth.call(params);

Is anything I am missing, any help will be appreciated.

Callback:

function callBack(result) {
  console.warn("callback:", result)
}


texts: Event not exactly working (Inexperienced OP)

texts:
pragma solidity ^0.4.0;

contract CustodialContract{

    address client;
    bool public _switch = false;

    event UpdateStatus(string _msg);
    event UserStatus(string _msg, address user, uint amount);

    function CustodialContract(){
        client = msg.sender;
}

    modifier IfClient(){
        if(msg.sender !=client){
            revert();
    }
    _;
}

    function depositFunds() payable{
        emit UserStatus('User has deposited money!', msg.sender, msg.value);

}

    function withdrawFunds(uint amount) IfClient{
        if(client.send(amount)){
            emit UpdateStatus('User has transferred some money!');
            _switch=true;
    }
        else{
            _switch = false ;
    }
}

    function getFunds() constant returns(uint) {
        emit UpdateStatus('Someone called a getter!');
        return address(this).balance;
}

I know this is not a bug, but my inexperience with Solidity is the cause of this. Anyway, I want to fire off the UpdateStatus('Someone called a getter!'). I receive this error on the Solidity VM.

(browser/Untitled.sol:38:14: Warning: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.)

I would like an explanation breaking down this error and suggestions on how to make the event fire.


texts: When smart contract is executed every time, will the related action be repeated?

texts: Assume I have a smart contract to wire 0.01 Eth to a predefined address when it is triggered. The smart contact is executed when the transaction gets included in a block by miner and the 0.01 Eth shall be sended out. I understand that the smart contract will be executed whenever the transaction is being validated by other nodes. My question is that the wiring by smart contract will happen for each validation. It would be a big problem if it does. Many thanks.


texts: How a contract notifies its event listener when an event trigged?

texts:
It's confusing for me about how the event listener obtains event in time.

Does it mean the listener APP(web3 code) keeps online and just waiting for notificaiton from the contract generating event, or listener APP checks event record written in block data and get the event info itself?

How to understand the procedure about event generation, notificaiton, and so on?
Thanks.


texts:
I'm wondering how to transfer ownership of tokens in Daohub. I was looking at the answer  to the similar question on their forums, but after further inspection of the source code, method transfer is overridden and additional checks performed:

isFueled
isBlocked
transferPaidOut

The last one suggest, that only reward can be transferred, meaning ownership can not be changed, or I'm missing something?


texts: How are we going to mitigate DDoS Attacks in Proof of Stake?

texts: I would like to know if I am connected to the network as a validator, how I my node will be protected of DDoS attacks.


texts: state variables are not saved on private chain

texts:
I set up a private blockchain and it works.
I tried a very simple contract, it was mined successfully, but the state variables are not saved in the blockchain or this is what it seems. The getter functions returns no value.

What is wrong here?

The contract code:

pragma solidity ^0.4.0;

contract MyContract{
uint constant value = 90;
string constant mystr = "Hello";

function getValue() constant returns(uint){
    return value;
}

function getMystr() constant returns(string){
    return mystr;
}
}

The result in solidity browser (run offline, web3 provider connected to localhost:8545):


texts: Geth Clique: can change config params in genesis and still retain the existing blocks?

texts:
I have altered my custom Geth private chain Clique PoA, but it seems after I do that I encounter:

BAD BLOCK
Error: invalid receipt root hash

Is it possible to:

change the Geth code
add a new hard fork block in config.go
specify the block in genesis.json
re-init the genesis file
retain the existing blocks and have my private chain continue as normal?

I am assuming that adding new hard fork blocks in config.go work the same in Clique. Is my assumption correct?

Or do I need to wipe the entire chaindata every time I change the geth code?


texts: Unhandled Rejection (Error): invalid string value (arg="x", coderType="string", value=5)

texts:
Using Truffle unbox react to unbox a boilerplate.

received the following error from running npm run start

Changes:

Addition of "memory" parameters in the simpleStorage.sol
Changed unit to string in the simpleStorage.sol
Adjusted port address to "7545" to match Ganache's port.
Changed truffle-config to truffle.js for mac

Other than those changes, the boilerplate is still pretty much barebones.

Attempts for a solution:

Uninstalled and reinstalled -g and local truffle
Attempted multiple solutions for pragma requiring specific compiler to no avail. <- (I am sure this is probably the problem. However, me not being able to find this error searching all day tells me it could be something else before I even get to that.)
Attempted brew re-installation & updates from solc docs.
Updated Ganache to latest v.
Attempted optimizer & versions properties suggested for the compiler object in truffle.js.
Attempted complete wipes and resets and following the documentations for truffle unbox react documentation's step by step instead of other guides.

I would post the code, but literally re-attempting from a clean slate 3-4 times with most of these methods repeatedly already labels this code as barebones besides the subtle changes I listed.


texts: How to detect false data feed from Chainlink oracles

texts: I understand Chainlink uses explicit and implicit staking to enforce honest behavior. However, what is the mechanism used to catch the misbehavior of oracles (i.e., reporting wrong data)?


texts:
I'm coding a smart contract for an ICO and I have a problem. I have a modifier wich checks if NOW > timestamp,
but it's not working for some reason. Here is the function:

function DeleteModerator(uint _ModeratorId, address _ModeratorAddress) onlyOwner checkICOtime public
{
        delete moderators[_ModeratorAddress];
        delete Moderators[_ModeratorId];
}

and the modifier:

modifier checkICOtime()
{
     require(now > 1515868200);
     _;
}

When im trying to send this function using Mist it's keep saying: "We couldn't estimate the gas" and "this transaction will fail". I have no idead what is the problem here. It's very simple thing, but im stack. Please help.


texts: Error cannot allocate big buffer for dag

texts: Someone can help me? It's nvidia 920mx, my laptop model is Asus x441u.


texts:
I'm working on deploying a factory contract which in turn has a function to deploy a three-contract ecosystem. One of those contracts also has a library contract with it.
Factory.sol
A.sol
B.sol
C.sol
Library_C.sol

I'm using the scaffold-eth repo from Austin Griffith, which ships with Buidler. I'm trying to figure out how to deploy this ecosystem using Buidler.
I can alter /packages/buidler/scripts/deploy.js to not do an auto-deploy on everything all at once, and deploy Factory.sol manually. (I don't need the other contracts deployed yet anyway.) The thing is, Factory doesn't deploy out of the constructor - it has a deployEcosystem function.
I see that Buidler has an Ethers plugin. That made me think that I could maybe deploy the Factory, then use Ethers to hit the deployEcosystem function, but I'm not all that sure that will work, since I can't figure out where a signer or gas would come from. I was looking at an Etherlime script that deploys the same suite of contracts, and I see that it has a function which can do this:
const deployer = new etherlime.JSONRPCPrivateKeyDeployer(
        secret,
        RPC,
        defaultConfigs
    );

Which I assume will then charge gas to this account. Does Buidler have anything similar?
If I have to use Ethers to do this, how do I tell Ethers to unlock an account from the dev chain in a script and use it as the deployer?
Alternatively, is there something else I should be doing in order to deploy the ecosystem?


texts: How can I monitor a contract for transactions?

texts:
Here's what I've done so far.

import json
import sys

import web3
from web3 import Web3, IPCProvider

ADDRESS = '...' #contract address
PIPE = '\\\\.\\pipe\\geth.ipc'

w3 = Web3(IPCProvider(PIPE))
f = w3.eth.filter({
    'contract_address': ADDRESS,
    'toBlock': "latest"
})
def callback(block_hash):
    sys.stdout.write("New Block: {0}".format(block_hash))
f.watch(callback)

however this doesn't seem to monitor just the contract I specify with contract_address it seems to monitor all (as if I had done f = w3.eth.filter('latest'))


texts: Is there a "Hello world" smart contract in ewasm?

texts:
Is there any ewasm smart contract for testing?

The example contracts of parity cannot be deployed due to exceeding block gas
https://github.com/paritytech/pwasm-tutorial/


texts: why do i get the error Contract Token" and "Ethswap" token contract is not deployed to detected network error

texts:
I deployed my contract sent my decentralized application to Github pages.

(GH.pages) here is the link to see it, it will say error not deployed to the detected network if you want to see the application you click "ok" a couple of times,  on here https://nmlm99.github.io/new-dapp/ I have verified it and even made sure it worked in the test net first and even did it in ropsten, kovan rinkeby and  I was able to swap it and all, I have neglected to launch the "ethswap" contract in fear of wasting Ethereum, I just want to know what I am doing wrong, can someone please have a look here's the contract address to "Moore",  code to my contract. I have tried all test nets. and even tried on the main net, I can send the token to another address granted, the fee is 30 $ which is pointless I feel if I risk the chance of it still not fixing my issue I have checked into everything it was compiled on the remix and verified with a perfect match on MAIN-NET.
`
'0xd3798b9db4e8850fe6090a7b9fa0bd41d0e3d21f'  is my token contract address. any help would be great. Also when I go to deploy the "ethswap" contract in remix it asks at the bottom "_token address" to put into it before I can launch, would that be my 'MOORE' contract address? Is it one of ethereal?
here is my main "MOORE Token contract address"


texts: Is it possible to get HMM (Heterogeneous Memory Management) to work with GPU's mining Ethereum? Trying to use low memory cards

texts:
Many GPU's are capable of doing the computing for Eth, but they lack the GPU memory to actually hold the DAG file.
It seems like HMM (Heterogeneous Memory Management) may be able to resolve this issue, but I can't figure out how to apply it.
Does anyone know how to use HMM, and if so would it be possible to use older cards with little ram to mine Ethereum by means of this new feature? (Perhaps I misunderstood the feature)
https://lwn.net/Articles/752964/
https://www.kernel.org/doc/html/v4.18/vm/hmm.html
https://forums.developer.nvidia.com/t/enabling-heterogeneous-memory-management/60843


texts: How do I put an Ethereum address in an HTML link?

texts:
I'm sure I've seen this done, but I cannot for the life of me remember where. I'm writing a simple HTML page, and on it I'd like to have an Ethereum address as a clickable link, so people with Web3.0-enabled browsers can interact with it e.g., to send some Ether to it. I'm familiar with how to create links to other pages, images, etc. but I don't even know where to start researching this particular case, and many, many hours of searching hasn't yielded anything useful.
I'm familiar with Ethereum and how it works, but basically I just can't seem to figure out where to start to get it onto a web page. Can anyone at least point me in the right direction, where I can learn what I need to know?


texts: How do I uninstall ethereum-unstable from ubantu 17.10?

texts:
I want to install the stable version of ethereum.

I have performed the below steps to download the unstable version of it.

sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum-unstable


texts: Transfer erc20 tokens from a wallet to a new contract's total supply

texts:
I have an ERC20 token deployed on mainnet and I would like to transfer tokens from my wallet to a new contract and use it as the total supply of the new contract.
Any help would be highly appreciated.


texts: Best ways to get only "active" in arrays - get group members

texts:
let's say I have an group contract where users can join and leave groups. When a user joins a group, his address will be added to members[groupId]. When he lefts, the members[groupId] will be set to 0x0. Let's say members[0] is 2,000 values long. The problem is, that not all of these 2,000 members are active/in the group as some addresses in that array are 0x0 addresses.

Let's say I have now a website where I want to get all active members of group 0.
What are now the best ways to get the active users? A 2,000 times loop in javascript? Or are there maybe more efficient ways to solve it?


texts:
I have this crontract:

pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

contract Tickets {
  struct Ticket {
    uint serie;
    uint number;
    uint datetime;
  }

  Ticket[] tickets;

  function addTicket(Ticket memory newTicket) public returns(bool success) {
    tickets.push(newTicket);
    return true;
  }

  function getTickets() public view returns(Ticket[] memory) {
    return tickets;
  }
}

I compile it with truffle truffle compile, then I run truffle develop and finally run migrate with all ok.

When I try to create a ticket with:

contract.methods.addTicket({serie: 1, number: 2000, datetime: 1583942530609}).send({from: account})

I get this error:

UnhandledPromiseRejectionWarning: Error: Returned error: VM Exception while processing transaction: out of gas

Any help?


texts: Converting web3.sha3() bytes to string (Python)?

texts:
The code I am having trouble with:

new_address = Web3.sha3(rlp.encode([normalize_address(accountAddress), nonce]))[-40:]
return '0x'+new_address

new_adress remains in bytes and I can't join it with 0x to produce normal string that will be the ethereum address. How to turn the bytes to string again? just new_address.decode() doesn't work and anything with utf-8 in it?


texts:
I am new to blockchain. I am trying to understand the use cases of blockchain as a technology in healthcare. There are number of articles about different cryptocurrencies. I was going through this article at
https://www.intelligenthq.com/innovation-management/blockchain-use-cases-in-healthcare/

Here they are talking about blockchain for drug traceability.

I am failing to understand how blockchain would help to trace the product which is not digital.? Product, packaging material, shipping vehicles etc. everything is going to be the same. Only probably the labeling will be added with some QR codes. In this case its about identification only than why the existing solution can not work. When they say that the manufacturer produces a drug and would mark the drug with unique code, are they talking about marking each tablet or capsules.? or talking about the container/box..?

Here, if we are talking about cryptography as a solution then whats the problem with traditional cryptography solution is which is being solved by blockchain..?


texts: Could I give higher priority to transactions to mined right away?

texts:
For example on Linux we can give higher priority to processes for Linux Kernel to schedule. I am the owner of my Private Ethereum Network. As an owner, could I give higher priority to deploy or mine my contract's selected methods, like on Linux? or is it against to Ethereum.

Thank you for your valuable time and help.


texts: Deposit ether from another account in Solidity

texts:
In my case I have an application that should transfer ethers. Is it possible that msg.sender deposits ether from another account?
For instance I have all information for account A and account B. Account A calls a function of the smart contract and in that a specific amount of ethers will be transfered to A from B. B receives for this a token.
How can this be implemented?


texts:
I want to send a data to a function created in a smart contract.

function notarizeHash(uint256 id, bytes32 documentHash) public onlyOwner noHashExistsYet(id) {
        hashesById[id] = documentHash;

        emit ProofCreated(id, documentHash);
    }

How can I call this function in backend using truffle contract? Or need I do it with send transaction and if yes how?


texts: Does metamask store private key on server or anywhere else?

texts:
I have created my private key using myetherwallet using offline option.

Now Metamask allows us to import account by providing private key or Json File that has private key.

Does metamask store that private key on its server? or somewhere else? How secure it is to upload my own private key to metamask?


texts: Why DS-Math add WAD/2 or RAY/2 in WAD,RAY multiply function

texts:
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
    z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
    z = add(mul(x, y), RAY / 2) / RAY;
}

I think it'll add artifact small number ex. 2WAD x 1WAD = 2WAD + 0.5
Is it for safety reasons?
and what is

//rounds to zero if x*y < WAD / 2

I can’t figure it out.
DS-Math


texts:
As I understand scrypt was designed to be computationally intensive, so that it takes a relatively long time to compute. For what geth need this?
 And why it does not use, for example, SHA-256?


texts: How to get all the function names with their respective parameters from smart contract?

texts: I want to fetch the list of all functions with their parameters which are present in any smart contract.


texts: what are the challenges of mobility on top of blockchains and smart contracts, and why?

texts: I want to develop mobile smart contracts so my question is basically related to mobility regarding blockchain and smart contracts.


texts: Conversion from calendar format into timestamp format

texts:
I see a lot of discussion about date and time, timestamp... But they don't answer to my question: How can i convert from calendar format into timestamp format for comparing datetime?

e.g: I have this smart contract:

pragma solidity >=0.4.21 <0.6.0;

contract User {

    address userWalletAddr;
    string userName;
    string userEmail; //The start date of the production

    struct UserActivity{
        address userWalletAddr;
        string activityDescription;
        uint dateTime;
    }

    UserActivity[] private activities;

    constructor(string  memory _userName, string memory _userEmail) public {
        userWalletAddr = msg.sender;
        userName = _userName;
        userEmail = _userEmail;
    }

    function addUserActivity(string  memory _activityDescription) public {
            activities.push(UserActivity({
                    userWalletAddr : msg.sender,
                    activityDescription: _activityDescription,
                    dateTime: now
            }));
        }

    //Retrieve activities of a user according to an intervall of time
    function listUserActivities(address _userWalletAddr, uint _startInterVal, uint _endInterval)
        public view returns(address, string memory,  uint){
        for(uint i = 0; i <= activities.length; i ++){
            while(
                activities[i].userWalletAddr == _userWalletAddr &&
                activities[i].dateTime >= _startInterVal &&
                activities[i].dateTime < _endInterval)
                    {
                    return
                    (
                    activities[i].userWalletAddr,
                    activities[i].activityDescription,
                    activities[i].dateTime
                );
            }
        }
    }
}

Now, i want to retrieve a list of activities of a user according an intervall [ _startInterVal, _endInterval] like indicated in the function listUserActivities().

Your help would please me


texts:
The 10b tokens
transferred into the deployer address of that token from address 0x000000
are they real tokens?
https://etherscan.io/token/0x4574562E9310a94F9Ca962bd23168d8a06875b1A?a=0x0000000000000000000000000000000000000000
thanks ,


texts: How does Ethereum handle undeterministic results from oracles?

texts:
Since when a transaction is done, every node in the blockchain runs the smart contract in their machines, what if the smart contract is calling an oracle to get a random value? Shouldn't it return different output for every node?
How does Ethereum handle it?


texts: how I use to users to send ethereum transactions through a php website?My server is Apache. Is the Ethereum JavaScript API useful to doing this? Thank you!


texts: Is running a light Ethereum node in a local server a good solution for not having to pay a 3rd party provider?

texts:
I've been looking into some providers for Ethereum blockchain data via web3 and the prices might get a little bit crazy. How feasible is to run light node in a local server to use it on my code instead of a (for instance) infura project? If I run a light mode, would I have access as well to characteristics like the mempool, historical transactions from old blocks, etc.?
From my total lack of understanding and from the little I've read so far it seems fairly easy to run a node, but what are some of the drawbacks or limitations in this case?
Thanks!


texts: How to implement role-based access control to user's private data?

texts:
We have this application scenario and try to see if Ethereum, or blockchain in general, is a good solution for this.

The basic idea is the user controls a small amount of private sensitive data (e.g., individual profile change history, transaction history). The user can control who has access to that data. When user A toggles on the access for another user B, B can see the whole transaction history. Obviously other users without access shouldn't see A's data.

We are thinking of storing user's encrypted data in the public blockchain. Ethereum is one of the options we are considering. The advantages of doing so is:

De-centralized, or zero downtime
Any user with access see the un-alterable transaction trail (good for auditing purpose)

Questions:

How would you implement the role based access control to the content encryption key?

Obviously we can't encrypt the content with the user's own private key, otherwise when user wants to share data, he/she would have to give away the private key in order to decrypt the content.

So each unit of private data should have a unique encryption key. And we have to change the encryption key and re-encrypt the content every time the user revokes someone else's access.

So that leads to another question:

Where should we store these encryption keys?

Should we store them in a privately owned database? A more general question is, since blockchain achieves tracking the ownership in a public shared ledger, can it implement role-based access control completely with everything (except user's private keys) in public chain as well?

UPDATES

Thanks for the answer of Rob Hitchens. I read Vitalik's blog post and found that it's difficult to implement obfuscated computing on chain. So it's impossible to store everything on the public chain while keeping user's data privacy.

That mandates we need some kind of private storage to realize the privacy. One idea is to use the public chain for permissions record keeping only. e.g., we declare

mapping (address => bool) permissions;

And only sender can assign set any account's permission to true or false. Our private authentication server respects this permission mapping (stored in public chain) and only allows an authenticated user (i.e., the user that owns the private key to an authorized account) to access the content encryption key.

If we use the above design, to authenticate herself, the account owner needs to use the private key to compute a signature, and the auth server needs to verify that. That seems to similar to the way how identity is verified in ethereum transactions.

Will the above approach work? or more importantly, is there a better design?


texts: Transfer an amount between two ethereum accounts using json-rpc

texts:
I am trying to transfer some funds between 2 ethereum accounts of my own. I have a node and communicate with it using json-rpc protocol. I guess I need to use eth_sendTransaction method, but I find it quite confusing because data field is supposed to be filled with a smart contract, but I don't want to use any smart contract right now, just a simple transaction of a given amount between my ethereum accounts.

Do I have to call eth_sendTransaction method? How do I fill data field? What does nonce field is used for?


texts: JsonParseException while generating java wrapper object with web3j

texts:
so a few weeks ago I created a java wrapper object with web3j for a smart contract and was able to work with it with no problems. following exactly what I did a few weeks ago I keep getting a JsonParseException now without changing anything. The command I am using:
web3j solidity generate --javaTypes greeter_sol_Greeter.abi greeter_sol_Greeter.bin -o src/main/java -p com.example.ethgreeter

and the error I am getting is:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('f' (code 102)): Expected space separating root-level values
 at [Source: greeter_sol_Greeter.bin; line: 1, column: 32]
        at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1702)
        at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558)
        at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:456)
        at com.fasterxml.jackson.core.base.ParserMinimalBase._reportMissingRootWS(ParserMinimalBase.java:503)
        at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._verifyRootSpace(UTF8StreamJsonParser.java:1689)
        at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._parsePosNumber(UTF8StreamJsonParser.java:1426)
        at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:876)
        at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:772)
        at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834)
        at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783)
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2740)
        at org.web3j.codegen.SolidityFunctionWrapperGenerator.loadContractDefinition(SolidityFunctionWrapperGenerator.java:93)
        at org.web3j.codegen.SolidityFunctionWrapperGenerator.generate(SolidityFunctionWrapperGenerator.java:116)
        at org.web3j.codegen.SolidityFunctionWrapperGenerator.main(SolidityFunctionWrapperGenerator.java:87)
        at org.web3j.codegen.SolidityFunctionWrapperGenerator.run(SolidityFunctionWrapperGenerator.java:48)
        at org.web3j.console.Runner.main(Runner.java:38)

Does anyone have any clue why this could have started happening out of the blue? I am using web3j version 3.4.0, it is the same version I used a couple of weeks ago and it seems to be the latest version still. Here is a link for web3j documentation


texts: What are the virtual and override keywords in Solidity?

texts: Solidity 0.6.0 introduced the keywords virtual and override. What do they do?


texts:
I have a hash time lock contract on remix and using my metamask test accounts on Kovan testnet. I am trying to test the hash time lock contract by deploying the contract and funding it with some erc20 tokens. I can successfully deploy the contract, but when I try to run the fund function i get the following error:
"Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? The execution failed due to an exception. Reverted"
pragma solidity ^0.7.4;

interface IERC20 {
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}

contract HTLC {
  uint public startTime;
  uint public lockTime = 120 seconds;
  string public secret; //abracadabra
  bytes32 public hash = 0xfd69353b27210d2567bc0ade61674bbc3fc01a558a61c2a0cb2b13d96f9387cd;
  address public recipient;
  address public owner;
  uint public amount;
  IERC20 public token;

  constructor(address _recipient, address _token, uint _amount) {
    recipient = _recipient;
    owner = msg.sender;
    amount = _amount;
    token = IERC20(_token);
  }

  function fund() external {
    startTime = block.timestamp;
    token.transferFrom(msg.sender, address(this), amount);
  }

  function withdraw(string memory _secret) external {
    require(keccak256(abi.encodePacked(_secret)) == hash, 'wrong secret');
    secret = _secret;
    token.transfer(recipient, amount);
  }

  function refund() external {
    require(block.timestamp > startTime + lockTime, 'too early');
    token.transfer(owner, amount);
  }
}

I am fairly new to solidity and smart contracts so any help is appreciated.


texts: How to generate a empty block in dev chain on parity? like dev.period in geth?

texts:
I use config like this:

[parity]
mode="active"
chain = "dev"
base_path = "./data"
db_path = "./data/chains"
keys_path = "./data/keys"
identity = ""
light = false

[rpc]
disable = false
port = 8545
interface = "local"
cors = ["null"]
apis = ["all"]
hosts = ["all"]
server_threads = 10

[websockets]
disable = false
port = 8546
interface = "local"
origins = ["*"]
apis = ["all"]
hosts = ["all"]

[mining]
author = "00a329c0648769a73afac7f9381e08fb43dbea72"
engine_signer = "00a329c0648769a73afac7f9381e08fb43dbea72"
force_sealing = true
reseal_on_txs = "all"
reseal_min_period = 2000
reseal_max_period = 10000
min_gas_price = 20000000000
price_update_period = "10"
gas_floor_target = "4700000"

[network]
min_peers = 0
max_peers = 50

[account]
unlock = ["00a329c0648769a73afac7f9381e08fb43dbea72"]
password = ["./pass"]
keys_iterations = 10240

in dev chain, parity will autogenerate a block when a transaction is sent. But I need it to generate a block every 15 sec, so that I can test the confirmation number of a transaction. In geth, i can set --dev.period=15 to fulfill my need. But in parity, i can not find a way. If really can't mine on dev chain, I might have to send a transaction every 10sec by myself. Any suggestions? Thanks!


texts: Is it possible to set a fixed price for a Token via Smart Contract?

texts:
My Q:
Is it possible to set a fixed amount of ETH for a token via smart contract?

The goal:
I sell a token for lets say 0,001ETH. The owner can resell it, but only for the same amount of ETH. Same for the next one, and so on..

I heard about something like using two smart contracts. Maybe this is the way?

At the moment i am pretty new into smart contracts - any help (or related reading advice) is appreciated.

I saw this nice thingy, but as i understood it is not related:
Is it possible to set up a token with a fixed amount available, where all coins can be redistributed among token holders?

Thanks :-)


texts: Where to post: Rinkeby Authenticated Faucet down with respect to Twitter?

texts:
When attempting to use the Rinkeby Authenticated Faucet from Chrome or FF, I just get the error:
zlib: invalid header

It's not due to time limits (not even close), the Tweet post includes the address and the address only, and the CAPTCHA is done correctly (many times in trying to debug).  While debugging, I saw a Google+ account post get funded, but something seems to be broken with the Twitter API use.
Where would such issues get properly posted?


texts: What is the cheapest way to send ERC20 to multiple Addresses?

texts:
Let's say I got 100 tokens of any ERC20, and I want to send one of each to 100 differents addresses.

What would be the cheapest in term of gas between

1) creating a smart contract which takes in parameters 100 addresses and perform that transaction
2) Making 100 individuals regulars transactions ?

Thanks


texts: Looking for an elegant way of waiting for a payment

texts: Is there a better way of awaiting a payment in ETH on a certain eth-address other than looping over getBalance()? And how do exchanges manage to find transactions even when they are not confirmed yet?


texts: Hi guys i am working on my final year project on blockchain tecnology using etherium i havent benn able to get free ethers please help

texts: I have tried every means to get some free testnet ether for my etheerium blockchain final year project for testing please guys help me with some testnet ether 0x521F137871082aAF01EEC7E10C70315d588A7772


texts:
I have a question about the node limitation for mainnet. I want to send a lot of transactions at the same time (let's say 1k), on the ropsten network it queues every tx and send batches of 64 every 10 minutes.

I believe the mainnet is faster, but not sure what would be the limit.
Let's say that the gas price is no problem and will be high.

EDIT: I'm doing some tests on the main network and I'm seeing same pattern... 64tx each 10 minutes. Why is that? Any way to change it?


texts:
I am trying to testa a smart contract function that receives an arg. I'm using truffle javascript tests, this is the smart contract function, very simple:

function addExam(string memory hash) public returns (string memory examProfessorHash) {
        // save the exam hash and link it with the professors address
        professorsExam[msg.sender] = hash;

        return hash;
    }

As you can see, it receives a hash as an argument. Now I want to test this in Truffle js:

 it("should add an exam to the exams list", async () => {
        // This should test the complete functionality
        let hash_test = "fB03aA5E2E71De1470ae2";
        let instance = await Exam.deployed();
        let hash = instance.addExam().call(hash_test, {from: accounts[0]});
        assert.equal(hash.valueOf(), hash_test, "Not returning the correct address")
    })

I can improve the test of course, but first, I need to be able to call the function and pass it an argument, how do I do that? The code above doesnt work, it gives me an error:

  Error: Invalid number of parameters for "addExam". Got 0 expected 1!


texts: How can we find "the DAO" attacker on 17 June 2016?

texts:
This question is about the level of anonymity in the system.

I would like to know how anonymous one can be at this ecosystem?

In other words, is it possible to track down an individual responsible for one or more transactions (considering the fact that he is trying to hide himself)?


texts: What is best deployment practice for block-chain nodes?

texts: What is the best practice for the deployment of block-chain/peers node? Is it best to have all the node in single cloud server or it should be decentralized and co-located on different server at different locations ?


texts: Solidity smart contract inherited function output failed

texts:
I'm trying to inherit a function from the parent contract into child contract and its working fine in remix JavaScript VM. I did the following steps:

Deployed the parent contract in remix JavaScript VM.
stored some random values by executing the storeValue function from the parent contract
copied the address of the parent contract and instantiated it in child contract
Now if I call the getValue function from the child contract that is basically calling the getting stored value function from the parent contract, the output is an array of values and everything is working perfectly fine.

BUT

If I deploy both contracts on the private blockchain, I'm getting an empty array of values. I did following steps:

started the private blockchain (geth client)
Change the environment to Web3 Provider in the remix
deploy the WEB3DEPLOY code from remix in private chain and copied
the address of mined address from the private chain
used the address to instantiate the parent contract in child
contract
repeated the process of deployment for the child contract
feed the values using web3.py in python jupyter notebook

Now, if I directly call the function accountTx from parent contract in the frontend, its working fine. But, if I call the inherited function getValue from the child contract in the frontend, the result is an empty array.

So, the problem is that I'm unable to get the output of the function getValue that is calling the function from another contract when deployed on a private chain. But its working fine in remix JavaScript VM.

Parent contract:

pragma solidity ^0.4.20;

contract Parent {

    uint256[] values;
    mapping (address => uint256[])transactions;

    function storeValue(uint256 _value) {

        transactions[msg.sender].push(_value);
    }

    function accountTx(address addr) constant returns(uint256[]) {

        return (transactions[addr]);
    }

}

Child contract:

pragma solidity ^0.4.20;

import './Parent.sol';

contract Child {

  /* instantiating parent contract*/
  Parent p = Parent(0x9dd1e8169e76a9226b07ab9f85cc20a5e1ed44dd);

   function getValue() public view returns (uint256[]){
      return p.accountTx(msg.sender);
  }

}

I have created the instance of parent contract as a global because I do want to use it for some functions.

Am missing something like to declare the function as an external?
Any guidance would definitely be appreciated, thanks.


texts: Understanding "eth_estimateGas" results estimating gas

texts:
I have been playing around with parity's "eth_estimateGas" call to determine different tokens gas requirements. Generally using this code:

 let transfer_data = contract.transfer.getData("<destinaton ETH address>", 1);
    let gas_limit = await rpcCall("eth_estimateGas",[{
        to: contractData.contractAddress,
        from: "<source ETH address>",
        data:transfer_data
    }]);

I'm getting different results based on the from address. If that address has done thousands of transactions (like exchange's) the amount of gas used is significantly higher then an address thats only done 10's of transactions. Nothing else modified beside the from address.

My only theory is if the nonce is quite high, the contract or evm has to do more verification that it does in fact have the correct balance to complete the send.

What am I missing?

EDIT: Here's an example data. Token: FunFair

From address has high nonce
Contract Address: 0x419d0d8bdd9af5e606ae2232ed285aff190e711b
From Address: 0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98
To Adress: 0x6d8401b8ed8755bb4d01a89072860c98c236dc78
https://etherscan.io/tx/0xc407d8320f44745f88244400c3750875e1858e0ee6a1106bafbde424c289a6ef
Gas Used: 58999

From address has low nonce
Contract Address: 0x419d0d8bdd9af5e606ae2232ed285aff190e711b
From Address: 0x8c301c986e6d23117f17394722272fcd16d43efd
To Adress: 0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be
https://etherscan.io/tx/0x708fb93a22f4ddd3d410f7280fb3800c8ff96deed5d4fafa12244d0f74e48045
Gas Used: 29127

Plugging those values into the parity call, the estimate results have roughly the same variance.


texts: How is difficulty used by mining clients?

texts: I understand how it's calculated and what its intent is. I'm unsure of how the value is being used in practice.


texts: when i call balance function it shows 0 all the time ? I am deploying at remix - solidity

texts:
pragma solidity 0.4.19;

contract blackeye {
    uint public max_amount = 1000000;
    uint public total_balance_bought = 0;

    mapping(address => uint) total_balance;

    address owneraddress;

    modifier onlyowner {
        require(owneraddress == msg.sender);
        _;
    }

    modifier can_buy_amount(uint rupee_invested) {
        require(rupee_invested + total_balance_bought <= max_amount);
        _;
    }

    function balance(address investor) external constant returns(uint) {
        return total_balance[investor];
    }

    function deposit(address creator, address investor, uint rupee_invested) external {
        if (msg.sender == address(creator)) {
            uint amount_bought = rupee_invested;
            total_balance[investor] += amount_bought;
            total_balance_bought += amount_bought;
        }
    }

    function withdraw(address creator, address investor, uint amount_sold) external {
        if (msg.sender == address(creator)) {
            total_balance[investor] -= amount_sold;
            total_balance_bought -= amount_sold;
        }
    }

    function send_money(address sender, address receiver, uint amount_send) external {
        total_balance[sender] -= amount_send;
        total_balance[receiver] += amount_send;
    }
}


texts: In an Ethereum 2.0 with sharding, do shards produce their own blocks?

texts: In a sharded state (the hypercube one for example), does each shard produce their own blocks (is each shard their own unique block-chain) ?


texts: Out of gas when calling smart contract function from web3/Meteor Dapp

texts:
The following smart contract function works when called in the Remix-Solidity IDE and connected to testrpc.
function submitAsset(string ownerName, string assetName, string assetDesc, string barcode, string sku, string countryOrigin) public returns (bool success) {
    if (!map_assets[msg.sender].initialized) {
        map_assets[msg.sender] = Asset(msg.sender, ownerName, assetName, assetDesc, barcode, sku, countryOrigin, true);
        assetAddresses.push(msg.sender);
        noOfAssets = assetAddresses.length;
        AssetSubmitted(msg.sender, ownerName, assetName, assetDesc, barcode, sku, countryOrigin, true);
        return true;
    }
    return false;
}

However, I get out of gas error when calling from Meteor/web3 app. The followings are the code in my javascript file:
instance.contract.submitAsset(ownerName, assetName, assetDesc, barcode, sku, countryOrigin).call({gas: estimateGas}, function(error, result) {
    if(!error) {
        console.log("yeah!: " + result);
    }
    else {
        console.log("ooops!: " + error);
    }
});

Please note that the estimated gas is 260385 (referred to the Solidity IDE). So, then I set estimatedGas to be 300000 in the javascript file - just to ensure it will go through. Still to no avail.
Again, I appreciate if anyone could point me to tips/advise. Thank you.


texts: How to debug Web3JS for a not yet deployed contract?

texts:
I have remix-ide installed.

I want to debug how my contract can be interacted in a browser using Web3JS.

How can I can run it in browser? Can it be done with JavaScript VM? Or which VM I should install? how to run it?

Do I need to install any browser plugins in order to do debugging? If yes, which plugins to install?


texts: Maximum totalSupply of an ERC-20 token? And is it different for any other ERC specifictiond?

texts:
uint256

This storage implies that it should give us a max totalSupply of 2^256 - 1. A HUGE number. Note: I only need to store integers, not fractional values for my application.

Is this true?
Is this true for other ERC standards also, or do they differ?
Also, are there other practical implications to consider, perhaps a smaller data structure is used when the 256bits are not needed, so it's better to use a smaller number?

I know this is really three questions, but I think it is better to shoot for one post. Thanks for your time.


texts: I was wondering whether Ganache GUI is real EVM or just a replica of it. Because its throughput and latency are way better than Geth client. Any comments on it?


texts: How to use the testrpc `evm_increaseTime` parameter from truffle console?

texts: I am creating smart contracts with truffle and testrpc. When writing unit tests I wish to change the block time to simulate different times that smart contracts may be called. How does one set evm_increaseTime inside truffle console?


texts: How to estimate block number at future date/time?

texts:
I am creating a smart contract that will allow actions to be taken during a specific time period.

Ideally, I would like to let users know in advance the start block/end block that the contract will be available.

If I had a date in mind (say September 30 at 00:00:00 UTC), is it possible for me to calculate which block will likely be mined at that time? It doesn't have to be exact.


texts: Remove coinbase transactions in private net

texts:
I was willing to setup a private ethereum network with low difficulty. I can fix the difficulty of each block to 1 (or constant) to avoid problem of very high difficulty with increase in no of blocks.

But this has a downside of decreased block time and hence running out of disk space sooner.

Is there any way geth source code could be modified to remove miners reward and hence coinbase transactions? So a block is added to chain when there is some real transaction. This will save disk space to great extent and we can enjoy constant difficulty.


texts: How to validate a BTC transaction in an Ethereum smart contract?

texts:
Can an Ethereum smart contract use SPV to validate a BTC or BCH transaction?
If so, are there any functioning libraries?
What are the drawbacks or challenges when doing so?


texts:
I have one issue, I can't send accurate custom ERC 20 token to an ether address.

Here is my custom token detail.

Balance:   0.000000000000000324 BucksTec

Decimals:   18

I sent 44 tokens to an ether address but it shows 0.000000000000000068 Tokens Transfered.

My question is how can I send accurately tokens, please need your best advice and experience.

Some code:

var web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/xyz'));

module.exports.sendTokensTest = function(req, res){

    var toAddress = req.body.toAddress;
    var coins  = req.body.quantity;
    coins = "0x"+coins;
    var fromAddress  = req.body.fromAddress;
    var privateKey  = req.body.fromAddressPvtKey;

    try{

        var contractAddress = contractConfigTest.contractAddress;
        var contractAbi = contractConfigTest.abiArray;

        //res.send({contractAddress:contractAddress, contractAbi:contractAbi});

        var myContract = new web3.eth.Contract(contractAbi, contractAddress);

        myContract.options.from = fromAddress;

        var transactionObject = {
            from: fromAddress,
            to: contractAddress,
            value: '0x00',
            data: myContract.methods.transfer(toAddress, coins).encodeABI(),
            chainId: 3
        };

        web3.eth.estimateGas(transactionObject, function(err1, estimateGas){
            transactionObject.gasLimit = estimateGas;

            if(err1){
                res.send({error:true, errorMsg:err1.message, errorFunction:'estimateGas' });
            }

            web3.eth.accounts.signTransaction(transactionObject, privateKey , function(err2, signed){

                if(err2){
                    res.send({error:true, errorMsg:err2.message, errorFunction:'signTransaction'});
                }

                web3.eth.sendSignedTransaction(signed.rawTransaction, function(err3, txHash){

                    if(err3){
                        res.send({error:true, errorMsg:err3.message, errorFunction:'sendSignedTransaction'});
                    }

                    res.send({txHash:txHash});
                });

            });

        });

    }catch(err){
        res.send({error:true, errorMsg:err.message, errorFunction:'sendTokens' });
    }

}

Thanks


texts: Hardware wallet support of ERC-721 or Storing cryptokitties on Ledger Nano

texts:
I have a question related to hardware wallet support of ERC 721 tokens.
I plan to move a cryptokittie to a Ledger Nano wallet.

It's relatively easy to send it to an account controlled by Ledger. In the Cryptokitties UI I could select Send and type (or better paste) an address. The question is how to send it back from Ledger to an account controlled by Metamask, e.g. for breeding purposes.

Appreciate your help


texts:
I am new on this area. I am trying to create an ERC20 token with a fixed price per token such as USDT.

In other words, there is any way on the contract to issue my token to establish a constant price per token? Let's say 1 USD per token.

Thanks in advance!


texts: In Ethereum where and how exactly a deployed smart contract is stored?


texts: Where to put message (=data, payload) in geth transaction

texts:
Basic transaction in geth is

eth.sendTransaction({from:sender, to:receiver, value: amount})

if I want to put some HEX message (eg.FF) to this transaction, where do I put it?


texts: What type of decentralized programs require a Turing Complete programming language?

texts:
I have an idea for a smart contract but I want to program it on the right blockchain.

And from my understanding the Ethereum blockchain provides Turing Completeness, while the Bitcoin blockchain doesn't.

So my question is what type of program must require a Turing Complete language?

For example many Solidity (the Ethereum programming language) tutorials use a voting smart contract as an example to introduce smart contract programming basics.

But does a voting smart contract really require a Turing Complete language?


texts:
I want to create a super simple token for my community. I read some tutorials and I found this code:

pragma solidity ^0.5.2;

import "./lib/oz/contracts/token/ERC20/ERC20Pausable.sol";
import "./lib/oz/contracts/token/ERC20/ERC20Capped.sol";
import "./lib/oz/contracts/token/ERC20/ERC20Detailed.sol";

contract CappedToken is ERC20Detailed, ERC20Capped, ERC20Pausable {

    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------
    constructor()
    ERC20Detailed("DEMO Tokens", "DEMO", 18)
    ERC20Capped(1000000000000000000000000000) // 1B
    public {}
}

3 questions:
Is this code secure or hackable in any sort of way?
Only the smart contract creator address is allowed to mint token right?
Is Pausable strictly necessary?
Thank you very much.


texts: How does Ethereum regulate the time between blocks?

texts:
I was reading "Explanation of genesis file" and I found the description of the timestamp:

  A scalar value equal to the reasonable output of Unix’ time() function
  at this block inception.

  This mechanism enforces a homeostasis in terms of the time between
  blocks. A smaller period between the last two blocks results in an
  increase in the difficulty level and thus additional computation
  required to find the next valid block. If the period is too large, the
  difficulty, and expected time to the next block, is reduced.

  The timestamp also allows to verify the order of block within the
  chain (Yellowpaper, 4.3.4. (43)).

  Note: Homeostasis is the property of a system in which variables are
  regulated so that internal conditions remain stable and relatively
  constant.

How does, generally speaking, Ethereum maintain it's homeostasis and regulate the time between blocks? Now it's 15 sec, but is it possible for the Ethereum developers to increase or decrease that time without touching the client or is  this a paramether harcoded in the client? How can I set, for example, a 30 sec time between blocks on my testnet?


texts:
Let's say contract A has function F.

If someone uses a regular account to call A::F a transaction is laid down on the blockchain. That transaction is easily found on EtherScan for example.

If a contract account, say contract B, uses call to call the function A::F, this is called an "internal transaction," and this is not laid down as a transaction on the blockchain. So, for example, you would not see a transaction on contract A 'transactions' page on EtherScan or by interrogating the blockchain with something like web3.

Two questions:

1) Is what I said above correct?

2) Other than by clicking on EtherScan's 'Internal transactions' link, how can I possibly know about these 'internal' transactions?

In other words, what if I wanted to audit EtherScan by using the blockchain directly? Can I do that? How?


texts:
I am trying to execute unit tests for a solidity smart contract:

I have:

mapping (bytes16=>Device) public Device_Table

struct Device
{
    bytes16 UUID;
    bytes16 hardware_UUID;
    string phone_Number;
    uint256 created_at;
}

I wrote a function that returns a Device struct but I get an error?

I am also facing a problem when a struct to a function


texts:
Base on this answer related to How Ethereum estimate the gas for running a contract?:

  Which brings the second point. geth gets its estimate by simulating
  the transaction itself, based on the latest block. There is
  essentially no other way to do so.

Based on that: miners are able to simulate the transactions before they accept them. Since all miners are using GPU this should be pretty fast for them and all miner's have the latest block.

The image is take from Ethereum white-paper:

  6.Let TX be the block's transaction list, with n transactions. For all i in 0...n-1, set S[i+1] = APPLY(S[i],TX[i]). If any application
  returns an error, or if the total gas consumed in the block up until
  this point exceeds the GASLIMIT, return an error.

In the simulation if a miner detects an exceeds the GASLIMIT for a transaction(Tx), for example for the Tx[1] on the image Tx[1] could be discarded.

Example:

for(i=0->n-1)
   if(i!=1)
     set S[i+1] = APPLY(S[i],TX[i])

This would save sender to pay additional GAS-fee for his Tx that will return an error due to GASLIMIT, with the help of the simulation on the miner-side.

[Q] Why miners do not simulate their list of transactions to detect a gas exceed and discard those Txs that exceed gas?

Thank you for your valuable time and help.


texts: What is the difference between a static node and a trusted node?

texts:
In the docs, static nodes are described as

  Geth supports a feature called static nodes if you have certain peers you always want to connect to. Static nodes are re-connected on disconnects.

There is a <datadir>/static-nodes.json and a trusted-nodes.json too.

I can't find anywhere that explains the difference though.


texts: How hard is it for Ethereum clients to get on the new fork in case of an attack?

texts:
Vitalik Buterin writes:

  Assuming ~20% participation in PoS and current prices, you could stall or break the network at a cost of ~$7 million. However, unlike PoW, recovery is simpler: Ethereum just hard-forks to delete the ether of the malfeasors (if /u/vladzamfir does his job correctly, all currently online nodes may even be able to coordinate on this automatically) and moves on.

If such a hardfork would happen, would a Slock.it lock easily be able to go along to the new fork or could it stay stuck in the old chain?


texts: Can we create a HD-Wallet with many sub-wallets but a single shared transfer()-method?

texts:
Can we create a HD-Wallet-Contract with a transfer()-method for specific business-logic and make it inheritable or shareable for sub wallets?

Let's say we have this HD-Wallet and sum sub wallets that were created dynamically for our needs:

+ 0xHDWALLET
  - 0xsubwallet1
  - 0xsubwallet2
  - 0xsubwallet3

The HDWallet has a wallet-contract with a transfer()-method (and many other business logic implemented).

So, if one would send some Ether to 0xHDWALLET it would pass the transfer()-method of 0xHDWALLET-Contract.

But if someone would send some Ether to 0xsubwallet1 or 0xsubwallet2, can we implement this wallet contract this way, that these payments would also went through the transfer()-method of the parent 0xHDWALLET without to deploy new contracts with each new sub wallet?


texts: get undefined when using web3js, calling view function

texts:
I am using web3js (version 1.3.4) and connected correctly to the provider and I can make a transaction. but when I want to call one of the view function in the contract I get undefined.
const Web3 = require("web3");
var Contract = require("web3-eth-contract");

window.addEventListener("load", async () => {

if (window.ethereum) {
console.log("here1");

try {
  // Request account access if needed
  await ethereum.enable();
  window.web3 = new Web3(ethereum);

} catch (error) {
  console.log(error);

}
}
else if (window.web3) {
 window.web3 = new Web3(web3.currentProvider);
}
// Non-dapp browsers...
else {
console.log(
  "Non-Ethereum browser detected. You should consider trying MetaMask!"
);
  }
  });
   const sc = new Contract(
     [... ],
    "0x48be3E5aA066A3901b9F422bbA884467A67bc6f4",
 {
   gasPrice: "20000000000", // default gas price in wei, 20 gwei in this case
 }
  );

i have this in my smart contract
 function ethDeposit() public payable {
    etherBalances[msg.sender] = etherBalances[msg.sender] + msg.value;
}
function getBalance() public view returns (uint256) {
    return address(this).balance;
}

I can send a transaction with
const accounts = await ethereum.request({
    method: "eth_requestAccounts",
  });
  const account = accounts[0];
   sc.methods.withdrawEther().send({ from: account }, function (err, res) {
    if (err) alert(err.message);
    });

but I get undefined from below code
sc.methods
    .getBalance()
    .call({ from: account }, function (err, res) {
      console.log("res:", res); // res:undefined       <<----------------------
      if (err) alert(err.message);
    });


texts: Problem when unlocking account in private ethereum blockchain

texts:
I tried this statement

  personal.unlockAccount(web3.eth.coinbase, "password")

But I am getting this error .

Error: account unlock with HTTP access is forbidden

Any suggestion would be helpful.
Thank you.


texts:
As I see it dapps can only be used from webbrowsers (apart from the outdated secret open source release of the mist browser or whatever that was called). That leaves the question how to send transactions from a dapp.

I was hoping that there would be a way to ask a mist wallet running at the same time to send/sign a transaction, which would then display the usual transaction summary and ask for the account password. However, I have not found anything like this.

Is there any way to send a transaction without handing the dapp the unlocked account data, which implies trusting the dapp with the whole account balance?


texts: How can I form a random group of 5 people from an array of 100 people?


texts:
I have created a private blockchain on two different machines. Now I want these nodes to connect with each other as "peers". I am using geth console.

I have tried the following command:

> admin.addPeer("enode://3414c01c19aa75a34f2dbd2f8d0898dc79d6b219ad77f8155abf1a287ce2ba60f14998a3a98c0cf14915eabfdacf914a92b27a01769de18fa2d049dbf4c17694@10.10.23.196:30301");

Here 10.10.23.196 is the IP of the 2nd machine and 30301 is the port on which it's running.

A true value is displayed but when I type:

> admin.peers

[] is displayed.

Is there something wrong with the approach? If it helps I am using following command to run the geth in both machines.

geth --identity "Sukhi" --genesis CustomGenesis.json \
     --rpc --rpcport "8001" --rpccorsdomain "*" \
     --datadir "chaindata" --port "30301" \
     --ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" \
     --rpcapi "db,eth,net,web3" --autodag --networkid 1900 --nat "any" console

Moreover, the same procedure works for two unique nodes on the same machine.


texts: What is a big number, and why are big numbers used?

texts: I noticed that BigNumber is a special data type in ethereum, and you can't do typical arithmetic operations on it that you would a regular uint. What is the big number, and why does ethereum/(solidity?) have it?


texts: How to convert NEthereum's BigInteger balance from WEI to ETH?

texts:
I'm using this simple code to get the balances with NEthereum:

using System;
using System.Numerics;

namespace TestConsole
{
    class Program
    {
        static readonly BigInteger ethToWeiRatio = new BigInteger(1000000000000000000m);

        static void Main(string[] args)
        {
            var web3 = new Nethereum.Web3.Web3();
            var accountsTask = web3.Eth.Accounts.SendRequestAsync();
            accountsTask.Wait();
            var accounts = accountsTask.Result;
            foreach (var account in accounts)
            {
                Console.WriteLine("account " + account);
            }
            foreach (var account in accounts)
            {
                var balanceTask = web3.Eth.GetBalance.SendRequestAsync(account);
                balanceTask.Wait();
                var balance = balanceTask.Result;
                Console.WriteLine("account " + account + "; balance in wei: "
                                  + balance.Value);
            }
            foreach (var account in accounts)
            {
                var balanceTask = web3.Eth.GetBalance.SendRequestAsync(account);
                balanceTask.Wait();
                var balance = balanceTask.Result;
                Console.WriteLine("account " + account + "; balance in eth: "
                      + BigInteger.Divide(balance.Value, ethToWeiRatio));
            }
        }
    }
}

The first foreach loops work, but the 3rd doesn't. My guess was that the balances being printed in the second foreach are in Wei units, so I had to convert them to Eth. But when doing that, the result is 0 for both cases, which is wrong because the balances are different between the accounts.

This is the full output:

account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5
account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755; balance in wei: 542316352000000000
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5; balance in wei: 300000000000000000
account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755; balance in eth: 0
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5; balance in eth: 0

UPDATE 1: Just found an ugly workaround: decimal.Parse(balance.Value.ToString())/10000000000000000m.

UPDATE 2: Author of library recommended a new API: https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Util/UnitConversion.cs (haven't tested it yet).


texts: How to get the hash of a smart contract deployment transaction with only a smart contract address?

texts: Is it possible to derive the hash of a smart contract deployment transaction using only a smart contract address? If so, what is the best way of doing so?


texts:
I'm using Truffle Version 2.1 and I'm trying to send test ether to my contract using Testrpc.
I run testrpc -u 0 -u 1

And the accounts shows a balance of 99351632199997083360 wei
I'm trying to send Ether to a function that contains the payable modifier and returns true (no inner code), and it is returning with a VM jump.

    function fund() payable returns (bool) {

    return true;
}

And this is the truffle javascript calling the function

var projectBeingFunded = Project.at(projectToFund);
return projectBeingFunded.fund({from: account, amount:amountToGive});
}).then(function(txHash) {
    waitForTransaction();
    return web3.eth.getTransactionReceipt(txHash);
  }).then(function(receipt) {
        console.log("transaction receipt");
        console.log(receipt.valueOf());
        setStatus("Project successfully funded");
      }).catch(function(e) {
        console.log(e);
        setStatus("Project funding didn't work");


texts: Why does the go Ethereum code reject odd number of digit hex numbers?

texts:
This is a question specific to the go-ethereum implementation. It may be present in other implementations, but I haven't looked yet.

In go-ethereum/common/bytes.go, the function isHex returns false if an input has an odd number of digits, and I was wondering why:

func isHex(str string) bool {
    if len(str)%2 != 0 {
        return false
    }
    for _, c := range []byte(str) {
        if !isHexCharacter(c) {
            return false
        }
    }
    return true
}


texts: Etherscan like contract explorer for network deployed on localhost

texts:
Is there any EtherScan like explorer that I can run on my machine? I am running a network using Ganache, but it won't let me view the abi/details of my deployed contracts. I tried downloading MyEtherWallet and running it on my machine but that too won't let me see my deployed contracts.
Is there any alternative that I can use for development purpose to view my deployed contracts?


texts:
All of my transactions was stuck in pool as pending around 2days and not getting broadcast to mainnet.

> txpool.status
{
  pending: 4096,
  queued: 1024
}

So I have 2 questions here:

Will those transactions broadcast if I keep waiting? If the answer is NO then how do I solve this issue?
I have 300+ transaction stuck in pending, is it possible to remove those transactions not belong to my node?

Note: This issue happened suddenly and I really don't know why, because my node is working fine and done a lot of transactions in the past 5months. My account is enough eth to pay the fee and don't have any lower nonce stuck before.


texts:
var contract = await tronWeb.contract().at(contractAddress);
var result = await contract.getPlayerDeposit("").call();

Output:
I got in array:
(4) [Array(1), Array(1), Array(1), Array(1)]
0: Array(1)
0: v {_hex: "0x00", _ethersType: "BigNumber"}
length: 1
proto: Array(0)
1: Array(1)
0: v
_hex: "0x5f887761"
_ethersType: "BigNumber"
proto: Object
length: 1
proto: Array(0)
2: [v]
3: [v]
length: 4
proto: Array(0)
How to convert hex number? I'm using javascript to retrieve data from contract?
Best
Chris


texts: Is a fully private blockchain network immutable?

texts:
I always hear that immutability is one of the great assets of using blockchains in banks. An auditor can come and look at the list of transactions and it will trust them because blockchains are immutable.

But consider the scenario where a bank has its own blockchain and controls all miners. How can an external party then trust anything about the blockchain. The bank could create forks as long as they want in the chain since they control all the miners, right?

Could someone please help me understand if I got something wrong ?


texts: I sent a transaction and got a hash, but blockchain explorers don't see it. What happened?

texts:
I used in the eth client web3.eth.sendTransaction({from:sender,to:receiver,value:amount) to try send some ether, typed yes to the question, then got a hash number  0x6ec7a8ea0e4cf1b381abea7a03e84338fe75a1c8f47767a8da18255508066ac5.

Looking at etherscan it looks like the transaction is non-existent.

Checking my accounts values, they didn't move.

How can I know it failed or succeeded and if it failed, then why?


texts:
I have seen other posts in reddit where users experienced slow sync times. I am using windows 10 and version 3.7 (I saw on gitter that other users on windows 10 had trouble with version 3.8 crashing).

My download speed is 4.19 MBS. I have adjusted clock to (time.nist.gov). I am still not able to sync and it has been hours, probably at least 10 and I am only halfway through.

Any suggestions? Also I notice that when I close and reopen, only about a third of the time am I offered the option to "skip search for peers". Lastly, I tried to open an account when not in sync. I was able to enter and confirm password, however no new account showed.

Is it a problem with Windows ?
Is it a problem with network speed?


texts: How to query data from Uniswap using the JS SDK?

texts:
I'm having problems retrieving some data metrics using the Uniswap JS SDK.
When I try to query getInputAmount it returns this error:
(node:88) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'equals' of undefined
    at Pair.involvesToken (/mnt/c/Users/Joe/node_modules/@uniswap/sdk/dist/sdk.cjs.development.js:790:18)
    at Pair.getInputAmount (/mnt/c/Users/Joe/node_modules/@uniswap/sdk/dist/sdk.cjs.development.js:837:11)
    at init (/mnt/c/Users/Joe/Desktop/JStest/myScripts/TEST.js:8:31)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:88) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or
by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:88) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is the JS code I'm running:
const { ChainId, Token, WETH, Fetcher } = require('@uniswap/sdk')

const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)

const init = async () => {
    const pair = await Fetcher.fetchPairData(DAI, WETH[DAI.chainId])
    const amount = await pair.getInputAmount('1000000000000000000');
    console.log(amount);
}

init();

I would really appreciate your guidance on how to proceed!


texts: Querying Account Balance of an ERC20 on a Test Network

texts:
I'm trying to debug some code that checks for an account's token balance.

Is it possible to query this on the Rinkeby network? My code isn't returning anything.

contract ERC20 {
    function totalSupply() constant returns (uint totalSupply);
    function balanceOf(address _owner) constant returns (uint balance);
    function transfer(address _to, uint _value) returns (bool success);
    event Transfer(address indexed _from, address indexed _to, uint _value);
}

contract Test{

    ERC20 icoToken;

    function Test(){
        icoToken = ERC20(0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0);
        //this is the EOS token address
    }

    function getMyBalance(address myAddress) constant returns (uint256 theB){
        theB = icoToken.balanceOf(myAddress);
        return theB;
    }
}

Nothing happens when I input an ETH address into getMyBalance.


texts: RPC: Asking for TX info while blockchain still not synced

texts:
I am wondering whether geth looks inside the network to search for the Tx. Or is it doing everything locally (i.e. looks inside blockchain on disk)?

For example, consider this UseCase:

1) I have installed fresh geth.

2) Started geth with RPC enabled (it starts to sync):

geth --testnet --rpc --rpcport "8545" --rpcaddr "0.0.0.0" --rpccorsdomain "*"

3) Calling some RPC methods, like 'show me balance of the address' or 'show TX info'.

Question:
If blockchain sync is still not complete -> will it show me the correct values?


texts: Standard Truffle assertions documentation

texts:
I have found Assert.sol which is the code that defines the standard Truffle assertions.

Is there a document which describes the available functions? An index would be useful as a start...


texts: How to integrate Ethereum support into CoinSpace?

texts:
CoinSpace is a fork of the Hive Bitcoin Wallet and is in active development at github. I'm am interested in adding Ethereum to the wallet in the same way Litecoin is supported.

I'm looking for any resources that our developers can go to with questions.