texts: Release / Debug build generated json-rpc calls are different

texts:
I'm trying to make simple web3 calls in React Native with web3.js, but generated json-rpc calls are different between release / debug builds - IOS/Xcode.

Expected behavior

    const web3 = new Web3(`https://ropsten.infura.io/${Config.INFURA_API_KEY}`);

    return new Promise((resolve, reject) => {
            web3.eth.getBalance(walletAddress, (error, weiBalance) => {

              if (error) {
                console.error;
                reject(error);
              }

              const balance = weiBalance / Math.pow(10, 18);
              console.log("================BALANCE================");
              console.log(balance);

              resolve(balance);
            });
          });

should return balance.
In Debug build, there is no problem.

Actual behavior

In Release build, it fails with Node error: {"code":-32600,"message":"invalid json request"}

i've inspected that in my release build the json -rpc request becomes like this:

{"jsonrpc":"2.0","id":1,"method":{"jsonrpc":"2.0","id":0,"method":"eth_getBalance","params":["0xe1f42aa9aec952f61c5d929dd0b33690faaef976","latest"]}}

whereas in debug build the json-rpc request is like this:

{"jsonrpc":"2.0","id":0,"method":"eth_getBalance","params":["0xe1f42aa9aec952f61c5d929dd0b33690faaef976","latest"]}

how can the request get nested in the release build, this i don't understand...

Versions

web3.js: 1.0.0-beta.48
browser: react native 0.59
ethereum node: infura

    System:
      OS: macOS High Sierra 10.13.6
      CPU: (12) x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
      Memory: 107.09 MB / 32.00 GB
      Shell: 3.2.57 - /bin/bash
    Binaries:
      Node: 11.3.0 - /usr/local/bin/node
      Yarn: 1.12.3 - /usr/local/bin/yarn
      npm: 6.4.1 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
      Android SDK:
        API Levels: 23, 24, 25, 26, 27, 28
        Build Tools: 26.0.3, 28.0.3
        System Images: android-23 | Google APIs Intel x86 Atom, android-24 | Google APIs Intel x86 Atom, android-26 | Google APIs Intel x86 Atom, android-26 | GooglePlay Intel x86 Atom, android-27 | Google APIs Intel x86 Atom
    IDEs:
      Android Studio: 3.2 AI-181.5540.7.32.5056338
      Xcode: 10.1/10B61 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.6.3 => 16.6.3
      react-native: 0.59.0 => 0.59.0
    npmGlobalPackages:
      create-react-native-app: 2.0.2
      react-native-cli: 2.0.1

Release build json-rpc call made by simulator/device, captured by Charles proxy.

UPDATE:
I've included console.log/error statements in web3-providers/dist/web3-providers.umd.js before every sendPayload statement, here is what i've found:

In Debug build, i get this, and everything works as intended:

2019-03-15 01:24:31.243 [error][tid:com.facebook.react.JavaScript] 'sendPayload_httpprovider_umd', { jsonrpc: '2.0',
  id: 0,
  method: 'eth_getBalance',
  params: [ '0xe1f42aa9aec952f61c5d929dd0b33690faaef976', 'latest' ] }

In Release build. i strangely get this:
Notice how it first gets into sendPayload_CustomProvider_umd and nests the payload on sendPayload_httpprovider_umd

2019-03-15 01:17:10.433692+0300[48645:314312] 'sendPayload_CustomProvider_umd', { jsonrpc: '2.0',
  id: 1,
  method:
   { jsonrpc: '2.0',
     id: 0,
     method: 'eth_getBalance',
     params: [ '0xe1f42aa9aec952f61c5d929dd0b33690faaef976', 'latest' ] },
  params: [Function] }
2019-03-15 01:17:10.434 [error][tid:com.facebook.react.JavaScript] 'sendPayload_httpprovider_umd', { jsonrpc: '2.0',
  id: 2,
  method:
   { jsonrpc: '2.0',
     id: 1,
     method:
      { jsonrpc: '2.0',
        id: 0,
        method: 'eth_getBalance',
        params: [ '0xe1f42aa9aec952f61c5d929dd0b33690faaef976', 'latest' ] },
     params: [Function] },
  params: [Function] }

I'm using

import './shim' // Provided by rn-nodeify --hack -- install
require('node-libs-react-native/globals');

in my start file, for react native web3 compatibility.


texts: How can Contracts sign transactions, when they dont have a private key?

texts:
When transactions are made the sender is identified by his signature. But Contracts dont have a private key to sign any transaction or message. So I have some questions:

Can a Contract initiate a transaction? I mean transfering ETH from his account to another EOA or Contract. And if yes, will this transaction be included in the transaction list? And how do they sign the transacion?


texts: I'm running a private testnet miner on a VPS with only 8 GB of hard drive space. Is there some measure I can take to reduce the size of the .ethash directory?


texts: When to use "memory" and "storage" keyword in solidity 0.6.0?

texts:
From what I've learned and noticed. Please add more point and rectify me if I'm wrong.
Use of memory keyword
1)When initialising/declaring Struct, Array , and mapping.
2)In the parameters of functions and constructor. With string only.
Not with uint or int or address.
function verifier (uint age, address add,string memory location)

Use of storage keyword
1)storage cannot be newly created in a function. Any storage referenced variable in a function always refers a piece of data pre-allocated on the contract storage (state variable). Any mutation persists after function call.
function vote(uint8 toProposal) public validStage(Stage.Vote)  {
    Voter storage sender = voters[msg.sender];
  }


texts: How do I send the etheruem I mined? Let's say I mined some etheruem. How do I send it to coinbase so I can sell it? I use Geth. (GPU)


texts: Why does the transaction exceed block gas limit?

texts:
When I try sending ether to another account, I keep getting the message "Exceeds block gas limit".

I changed the gas amount from 5,000 to 100,000 but nothing else happened. Why does the transaction exceed the block gas limit?  How can I fix that?


texts: Web3 & Solidity | How can I get return value from my method?

texts:
Is there any way to get return value from my method/function using web3?

    function sell(address _seller, uint256 _amount) public returns (uint256 _ethUserShouldReceive) {
        uint256 _etherAmount = _amount.div(sellPrice);
        uint256 _ownerBalance = owner.balance;
        require(_ownerBalance >= _ownerBalance.sub(_etherAmount));
        require(balances[owner] >= _amount);
        _transfer(_seller, owner, _amount);
        Sell(_seller, _amount, sellPrice);

        return _etherAmount;
    }

Above code is part of my Smart contract which return value. I want to call the function to execute _transer() and then get the value.

I tried the send() function like below.

myContract.methods
    .sell(address, amount)
    .send({ from : tokenOwner})
    .then(res => {
      console.log("res: ", res);
    })
    .catch(err => {
      console.log("err: ", err);
    });

But I got JSON RPC error.

err:  Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (errors.js:42)
at XMLHttpRequest.request.onreadystatechange (index.js:73)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:546)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)

I thought the _transfer function need a signed Serialized Transaction so I changed like below.

const data = myContract.methods.sell(address, amount).encodeABI();

I signed the transaction with that data above. It works well but I can't get the return value which I really want to know about.
How can I deal with this? Is there any way to get the return value right away after _transfer() is succeed?

Please give me some idea How to optimize or fix this.


texts: Returning output of a constant function using web3

texts:
Consider the following contract:

contract Test {
  struct person {
    uint id;
    string name;
  }

  person[] p;
  function addPerson (string _name) returns (bool added) {
    person memory per;
    per.id = msg.sender;
    per.name = _name;
    p.push[per];
  }

  function getPerson (address a) constant returns (address d, string n) {
    for (uint k = 0; k <= k++) {
      if (p[k].id == a)  {
        d = p[k].id;
        n = p[k].name;
      }
    }
  }
}

Upon making a web3 based sendTransaction to the 'addPerson' function, a transaction hash is produced. While retrieving the output of the constant function using eth.call as below:

TestObject.getPerson("0x1234", function(error, result){
     if(!error)
         console.log(result)
     else
         console.error(error);
 });

the result is:  ['0x','0x']

When the tested the same in the online solidity compiler, it results in the actual values passed in during the sendTransaction interaction. Any suggestions,as to how to get around this situation, to retrieve the actual results?


texts: Truffle-contract: how to subscribe to certain event

texts:
I am using truffle-contract for connecting between frontend and smart contract. Currently, I can call method on smart contract. But now I want to subscribe to certain events on smart contract. How can I do this.

Thanks


texts:
Is it possible to have decimals balances in ERC721 ?
I mean is it possible to say i own 50% of an NFT for example ?
Thanks


texts: Are there any standards followed to generate Hash Time Locked Contracts (HTLC) secrets (pre-image)?

texts: I am going to design and work on HTLC system. I wanted to know do these HTLC supporting exchanges or Decentralized exchanges have some kind of standard for pre-image? Its structure or anything. Or is it just a random thing?


texts:
I want to buy some ico tokens from other users. However I don't have a wallet for that specific type of token(e.g. BasicAttentionToken).
Can I do that?


texts: what is ERC20 ERC20 token = ERC20(_tokenAddress)

texts:
How can I call transfer function of a ERC20 token contract from another contract?
in this question there is one answer from pabloruiz55 but in this example or demo code
ERC20 token = ERC20(_tokenAddress);

What exactly is ERC20 here? i Is it an ABI of the other smart contract, is it any other imported smart contract or a place holder to explain the concept? If it is a placeholder can you please explain what I should replace it with in order to transfer tokens?


texts: How are returns objects converted in geth?

texts:
I have a function which returns an uint, but actually gets an object - how is that converted.

e.g.

  f

   "0x91f35a1267f2c8d763f7a3fb35ffac845fcbb1417a64b030ed79cbaa4e29694f"

f is defined as the return to the following function:

function testReturn() returns (uint) {
    studentAge=90;
    return 89;
 }

There must be a way to convert the return from this function.

The contract is defined as:

contract CollegeAdmin {
    uint8 public studentAge=21;
    uint16 public studentIncome=15000;
    uint8 public studentScore=4;

    uint8 public studentAttendance=96;

    function testReturn() returns (uint) {
        studentAge=90;
        return 89;
    }
}

Hence f is defined using:

f = con.testReturn()

Also, con is defined:

con = eth.contract(abi).at(addr)

abi - abi for contract
addr - contract address


texts:
How to secure ethereum data at rest, in transit and in use?

Perhaps for data at rest through disk encryption?

For in transit, through end to end HTTPS?

Finally, data in use through the use of secure enclaves?

Has anyone secured ethereum data at rest, in transit and in use successfully?

Nathan Aw


texts:
Here is my smart contract that uses oraclize to buy bitcoin with ether.

pragma solidity ^0.4.0;

import "https://github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";

contract BuyBitcoin is usingOraclize {

    address owner;
    string public temp;

    function BuyBitcoin() {
        owner = msg.sender;

        OAR = OraclizeAddrResolverI(0x51efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa);
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        result;
    }

    function update() payable {
        oraclize_query("URL", "json(https://www.shapeshift.io/shift).orderId", '{"withdrawal":"3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy", "pair":"eth_btc" , "amount" : 1000}');
    }

    function kill(){
        if (msg.sender == owner) suicide(msg.sender);
    }

}

Update :

I'm sending 0.01 ether as part of transaction

I can compile the contract but when I attempt to run the update function I receive 'VM Exception: invalid JUMP'

Have I omitted something with my contract ?

and using Javascript VM :

Have I missed a step ?

I'm using metamask and have ether in account :


texts: How can I listen for Truffle Actions such as TX_BROADCASTED, TX_ERROR via the Drizzle Vue Plugin?

texts:
In my Vue JS Dapp, which uses Drizzle Vue Plugin, I listen for contract events using $drizzleEvents like so:

this.$drizzleEvents.$on('drizzle/contractEvent', (payload) => {
  this.contractEventHandler(payload);
});

This works well for custom events emitted from my registered contract. However, how can I listen to general Drizzle Action events such as TX_CONFIRMAITON, TX_BROADCASTED, TX_ERROR, BLOCK_PROCESSING and so on as listed here: https://www.trufflesuite.com/docs/drizzle/reference/drizzle-actions


texts: Can we create an ethereum address with a public key of my choice?

texts:
We suppose that I have a private key I used to sign my data with it before the comming of ethereum.
is't possible to create an ethereum address based on my existent public key ?


texts: Using Solidity to write a contract that uses an existing token

texts:
I am trying to learn Solidity. I recently did this tutorial here: https://ethereumdev.io/transfers-and-approval-or-erc20-tokens-from-a-solidity-smart-contract/
I found it very informative. I was looking and there is an interesting question about using an existing erc20 token like USDT.There was a reply about approve and transferFrom.
It got my brain spinning and I’m wondering: could this same approach be used to write a smart contract that pays out an existing erc20 token, in varying amounts to a list of wallets? Say I have a webapp with a database table named user with an address column (eth address provided by user at sign up) and a amount column(generated by the app). Is there a way to use approve and  transferFrom to allow users to request a cash out of the amount column from a smart contract that I load with USDT for example? Or maybe it just reads the database and send the amount every month? Is this possible and are there any example contracts I can use for reference?


texts: Match web3py hashing function to solidity hashing function

texts:
If I am using web3py to hash some data, like so,

msgHash = w3.soliditySha3(['bytes32','bytes32'], [dataBytes, saltBytes]);

What would be the correct way to hash inside of a Solidity contract and expect the same resultant hash?

In Solidity (v0.4.24) I have tried,

keccak256(abi.encodePacked(data, salt))

sha3(data, salt)

and a few other ways but no luck. I believe there is a specific way to do this and the exact hashing algorithms don't always match. In Solidity the data type I am using is,

bytes32

Could the text= prefix be messing this up? Also is there a specific prefix that Solidity uses?

dataBytes = w3.toBytes(text=data);
saltBytes = w3.toBytes(text=salt);


texts: Miners are not working when running geth command in background in linux

texts:
I am running my private blockchain using geth on my ubuntu server with following cmd then its working fine

geth --datadir ~/chaindata/ --networkid 45123 --verbosity 3 --rpc --port 30304 --rpcport 8545 --rpcaddr "<private IP>" --rpccorsdomain "<private IP>" --rpcapi "web3,eth,personal,net"  --preload "/home/ubuntu/scripts/mineWhenNeeded.js" --nodiscover  --gcmode archive  --allow-insecure-unlock console 2

But when I try to run it in background using following cmd then my miner is not working

nohup geth --datadir ~/chaindata/ --networkid 45123 --verbosity 3 --rpc --port 30304 --rpcport 8545 --rpcaddr "<private IP>" --rpccorsdomain "<private IP>" --rpcapi "web3,eth,personal,net"  --preload "/home/ubuntu/scripts/mineWhenNeeded.js" --nodiscover  --gcmode archive  --allow-insecure-unlock > ~/myLogs/bcLogs.out 2>&1 &

I am using following script to mine the blocks using -preload "/home/ubuntu/scripts/mineWhenNeeded.js" flag

var minimum_confirmations = 3;
var mining_threads = 1
var txBlock = 0
function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        txBlock = eth.getBlock("pending").number
        if (eth.mining) return;
        console.log("  Transactions pending. Mining...");
        miner.start(mining_threads)
        interval = setInterval(function () {
            if (eth.getBlock("latest").number < txBlock + minimum_confirmations) {
                if (eth.getBlock("pending").transactions.length > 0) txBlock = eth.getBlock("pending").number;
            } else {
                console.log(minimum_confirmations + " confirmations achieved; mining stopped.");
                miner.stop()
                clearInterval(interval);
            }
        }, 600)
    }
}

eth.filter("latest", function (err, block) { checkWork(); });
eth.filter("pending", function (err, block) { checkWork(); });

checkWork();

How can we run geth in background with miners?


texts: Proper way to implement "buyable" ERC721 tokens

texts:
I have a contract that implements the ERC721 interface, and I want to allow token owners to set their tokens as "buyable", so that any other address can buy their token without any action on the part of the owner, given constraints are met (proper price, etc).

It seems that approve and transferFrom are only callable by the owner of the transferred token, not a to-be buyer. So there would not be a straightforward way to let a buyer take ownership of a token without a transaction from the seller first.

Whats the standard way to implement this? Examples such as this marketplace implementation seem to suggest that marking a token as "buyable" results in approving a third party contract that takes control of asset, and does the transfer on behalf of the owner. Curious if there's an easier way or if this is the process implied by the spec.


texts: transaction value does not match signed transaction params in ethereumJS-TX

texts:
I sign this transaction with Ethereumjs-tx:

{
    nonce: 8,
    gasPrice: 20,
    gasLimit: 25000,
    to: '0x45cc01d4b9ad49b81527d5b6629da8664bb525d3',
    value: 1000000,
    data: '0x00',
    chainId: 3
}

however, the value on etherscan shows 0.013845257383850032 Ether

https://ropsten.etherscan.io/tx/0xa891e47b6fad75750a40d6ea2698fe409e4650c59acbc910eaa5cabe1169a4e0

Where doe the 0.0038xxxx extra ether come from?


texts: First time setup of my Ledger X nano: I wanted to send some ETH for gas to allow sending my CHAIN from  Coinbase to my new ETH 1 account. Unfortunately I sent $30 worth of ETH for gas to the ETH 1 address. According to Coinbase the transaction was made and a commission was taken. However on my Ledger X it says the transaction was not allowed (since ETH 1 was set to receive CHAIN and not ETH). Is there anything I can do to recover my ETH and put it in the regular ETH address?


texts:
Is there any service that sends messages to smart contracts in a pre-determined future time?
Need also to re-send the message if the gas was low and it is stalled too long.


texts: What's the suggested way to create a 2D array which can be sparse at the beginning and grow dense later?

texts:
I can think of two ways:

1) Allocate a 2D array:

uint256 public W = 15;
uint256 public H = 15;
uint256[W][H] public grid;

2) Use mapping:

mapping (uint8) => mapping(uint8 => uint256)) public grid;

(I'm asking about if we can use tuple as key in this question: Tuple as mapping key?)

Q: What are the aspects to compare? I can think of transaction fees (and maybe speed).

Q: How do we compare the two?

Q: Is there another (better) way?

Regarding transaction fee, I don't know much about how contracts exactly work in Ethereum yet, but my guess is that the fixed 2D array is more expensive at the beginning since it has to write the whole array into the block. Not sure if mapping is more expensive when both are near full.


texts: How to manually add numbers to CappedCrowdsale

texts:
How do I add number of hard cap tokens in the below code (where in code), for instance 2000 ETH. I cant add it in Create of RUn (Remix) since Crowdsale and CappedCrowdsale are separate contracts.

contract CappedCrowdsale is Crowdsale {
  using SafeMath for uint256;

  uint256 public cap;

  function CappedCrowdsale(uint256 _cap) public {
    require(_cap > 0);
    cap = _cap;
  }

  function validPurchase() internal view returns (bool) {
    bool withinCap = weiRaised.add(msg.value) <= cap;
    return super.validPurchase() && withinCap;
  }

  function hasEnded() public view returns (bool) {
    bool capReached = weiRaised >= cap;
    return super.hasEnded() || capReached;
  }

}


texts: A problem in building a private network using Ethereum

texts:
There is a problem in in building a private network using Ethereum.

Geth version : 1.8.3 stable
OS & Version : windows 10

My scenario is as follows:

The genesis block is as follows

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

On the first PC(windows10, 192.168.0.7), the following commands is executed

  bootnode --nodekey=bootnode.key <=== started botstrap node

  geth --networkid 7686 --datadir "C:\EPN" --ethash.dagdir "C:\EPN" init genesis_block.json

  geth --networkid 7686 --datadir "C:\EPN" --ethash.dagdir "C:\EPN" --rpc --rpcapi "db,eth,net,web3" --rpccorsdomain "*"
  --nat "none" --netrestrict "192.168.0.0/16" --syncmode "full" --mine --gasprice 1 --etherbase "0x554C2C877aFc8A8EA0cDD2eA97ea5b5B9A7960e2"
  --bootnodes "enode://342a241c8baab9e6ff69a6df015a8dc37df2b477e43338f2e7d98078a115f6b1282e280ed444719d8c5d2bac89837693149771ed10b7bf1e9c1cd13930a270a5@127.0.0.1:30301"

On the second PC, the following commands is executed

  geth --networkid 7686 --datadir "C:\EPN" --ethash.dagdir "C:\EPN" init genesis_block.json

  geth --networkid 7686 --datadir "C:\EPN" --ethash.dagdir "C:\EPN" --rpc --rpcapi "db,eth,net,web3" --rpccorsdomain "*"
  --nat "none" --netrestrict "192.168.0.0/16" --syncmode "full"
  --bootnodes "enode://342a241c8baab9e6ff69a6df015a8dc37df2b477e43338f2e7d98078a115f6b1282e280ed444719d8c5d2bac89837693149771ed10b7bf1e9c1cd13930a270a5@192.168.0.7:30301"

The first PC(windows10) is no problem, on the second PC, however, the following error message is displayed

ERROR[04-17|19:26:01]
########## BAD BLOCK #########
Chain config: {ChainID: 7686 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: <nil> EIP155: 0 EIP158: 0 Byzantium: <nil> Constantinople: <nil> Engine: unknown}

Number: 1
Hash: 0xcc00615c7554b7c9d8813943e43216e7c4a8dcea6db6e262a8bc6c213d78733c

Error: invalid mix digest
##############################

WARN [04-17|19:26:01] Synchronisation failed, dropping peer    peer=cadcc80d87d6245a err="retrieved hash chain is invalid"

What is the problem?


texts:
I have a function as follows i.e. transfer.

function transfer(address _to, uint256 ENvalue, uint256 PWvalue) public returns (bool) {
require(_to != address(0));

balances[_to].bEN = balances[_to].bEN + ENvalue;

balances[_to].bPW = balances[_to].bPW + PWvalue;

return true;

}

When I invoke this function as follows:

    contractInstance.methods.transfer('0x31c5f6A1fDb0C142742478eb31B710E9D47eAEe9', 5, 10).send({ from: '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773' }, function(error, result) {
    console.log(error);
    console.log(result)
});

I receive following message:

> contractInstance.methods.transfer('0x31c5f6A1fDb0C142742478eb31B710E9D47eAEe9', 5, 10).send({ from: '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773' }, function(error, result) {
...     console.log(error);
...     console.log(result)
... });
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] },
  _events: undefined,
  emit: [Function: emit],
  on: [Function: on],
  once: [Function: once],
  off: [Function: removeListener],
  listeners: [Function: listeners],
  addListener: [Function: on],
  removeListener: [Function: removeListener],
  removeAllListeners: [Function: removeAllListeners] }

and when I get the balance of 0x31c5f6A1fDb0C142742478eb31B710E9D47eAEe9 it is still zero. Is there something wrong ?

> contractInstance.methods.balanceOfPW('0x31c5f6A1fDb0C142742478eb31B710E9D47eAEe9').call({ from: '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773' }, function(error, result) {
...     console.log(error);
...     console.log(result)
... });
Promise {
  <pending>,
  domain:
   Domain {
     domain: null,
     _events:
      { removeListener: [Function: updateExceptionCapture],
        newListener: [Function: updateExceptionCapture],
        error: [Function: debugDomainError] },
     _eventsCount: 3,
     _maxListeners: undefined,
     members: [] } }
> null
0

And for getting balances :

struct Balances {
    uint256 bEN;
    uint256 bPW;
  }
  mapping(address => Balances) balances;
function balanceOfEN(address _owner) constant returns (uint256 balance) {
    return balances[_owner].bEN;
  }
  function balanceOfPW(address _owner) constant returns (uint256 balance) {
    return balances[_owner].bPW;
  }


texts: tracking state changes via function calls that does not include event usage

texts:
Is it possible to track changes made to a smart contracts via its functions if the functions are not emitting events. I suppose if I know the function signature representation, then I should be able to use web3 to listen for this. I'm not sure if what I'm asking is possible - How can I subscribe to state changes that are not emitting events?
contract NameChange {

string public name;

function changeName(string calldata new) external returns (bool) {
name = new;
return true;
}

}


texts: Solidity compile Error: Expected primary expression

texts:
pragma solidity ^0.4.11;<br/>

    contract ERC165 {

         function interfaceID() constant returns (uint)
         {
            bytes4[] sigs = type(this).signatures;
            uint mask = 0;
            for (var i = 0; i < sigs.length; i++)
            mask ^= uint(sigs[i]);
        return mask;
    }
}


texts: Slackness issue and time in smart contracts

texts:
At a high level, slackness issue says, it is not possible to guarantee that at any given point in time all honest miners see exactly the same blockchain length [1].

On the other hand, as we know the value returned by a function in a smart contract is the result of the blockchain consensus.

Assume, we define a function, time(), that returns the current time, i.e. "now", in a smart contract.

Question: How does the slackness issue affect the value returned by the function time()?

[1]. https://eprint.iacr.org/2017/149.pdf


texts: How to set up Geth in a Docker container on a VM such that RPC works?

texts:
The Geth team conveniently provides a Docker container for the latest Geth builds, but when using Docker on Windows or Mac OS (where Docker is using a virtual machine to host containers) how to run it such that RPC calls can be seen on the local workstation? Running docker run -p 8545:8545 --name geth ethereum/cilent-go --rpc doesn't seem to do it.

Testing with CURL:

curl -X POST -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id":"curltest", "method": "web3_clientVersion", "params": [] }' \
  "http://192.168.99.100:8545"

I get no response from the above command, it just spins until it times out.


texts: How to change the sender of a function call?

texts:
I have this code from truffle unbox metacoin:
ontract('MetaCoin', (accounts) => {
  it('should put 10000 MetaCoin in the first account', async () => {
    const metaCoinInstance = await MetaCoin.deployed();
    const balance = await metaCoinInstance.getBalance.call(accounts[0]);

    assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
  });

Which account has deployed Metacoin? Is it accounts[0]?

How do I change the sender of a call in these tests? I am using the Owner contract from open zeppelin and I'd like to test its functionality via a unit test


texts:
I have been studying ipfs for a few days.. still a newbie.. its a amazing protocol. So is Swarm. Correct me, if I am wrong, but right now ipfs cant be used for long term storage or even as a backup. There are workarounds and external providers (eternum, sia), but the alternate options using centralized storage is much cheaper and reliable. Filecoin is supposed to be the incentivizing layer, but its not publicly developed and searching for its status didnt return anything.

I also learnt that they maybe releasing it to accredited investors only. (Reddit post on: Why is filecoin being released only to accredited investors?)

I am curious to know about the status of swarm?

Is there a document which provides the current capabilities (semi-technical) of swarm? is the incentivization protocols mentioned here: https://ethereum.stackexchange.com/a/10113/14143, implemented yet?


texts: How does spam prevention work in light clients?

texts: When you have a full client it means that everything that is stored on the Blockchain is on your computer. When you call a static function on some contract through web3, for example, there are no outgoing requests, everything is performed on your machine. How does it work when you have a light wallet? As I understand it, when you have a light client there's a special much smaller copy of blockchain on your computer. This copy, I believe, holds only a part of blockchain data. If that's true then how is the rest of the data retrieved when needed? Who is supplying responses to requests? Full nodes? What's stopping the attackers from spamming the network with multiple requests?


texts: How to use / see refunded gas in ETH blockchain?

texts:
I buy a GAStoken contract which requires say 21000 GAS at 1 Gwei and later when we delete/destroy the contract when the Gwei is around 50. I understand that we will get around 50% refund of GAS at the current Gwei.  The idea behind this is to use the refunded GAS to lower the transaction costs for subsequent transactions. Can someone point me as to how to claim/use this refund?

I'm a newbie to this space and AFAIK GAS cannot be stored. Please correct if I'm wrong.


texts: Keccak256 hash different in solidity and web3js

texts:
I am trying to sign a message in NodeJS and verify the signature with smart contract. Here is my code:
async function prepareAndSignMessage(to, amount, referenceTransaction){
    let contractInstance = new web3.eth.Contract(multisigABI, process.env.MULTISIG_CONTRACT_ADDRESS);
    //get keccak256 hash from contract
    let messageHash = await contractInstance.methods.getMessageHash(to, amount,  referenceTransaction).call();
    //sign message
    let signature = await web3.eth.accounts.sign(messageHash, process.env.ETHEREUM_PRIVATE_KEY);
    //{
    //  message: '0x9705f46c17b68492339627f99af8d148a9bf3a3075b89bb1a663bc26db530072',
    //  messageHash: '0x9ba3f82569283f1c3899ddec04c526b4f55d92d2ed6963497bbb09ee31bbd924', <-- This hash should match
    //  v: '0x1c',
    //  r: '...',
    //  s: '...',
    //  signature: '...'
    //}

}

And smart contract to recover & verify a signature:
function recover(address _to, uint256 _amount, string memory _reference) public returns(address){
    bytes32 hash = addPrefixAndHash(getMessageHash(_to, _amount, _referenece));
    //This hash should be same as one returned by web3. But it's different?????
    //....
}

function addPrefixAndHash(bytes32 _hash) public returns(bytes32) {
    return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash));
}

function getMessageHash(address _to, uint256 _amount, string memory _reference) public returns(bytes32) {
    return keccak256(abi.encodePacked(_to, _amount, _reference));
}

Hash from addPrefixAndHash should match hash returned by web3js web3.eth.accounts.sign function. But it's not.
web3.eth.accounts.sign is defined here: https://github.com/ChainSafe/web3.js/blob/1.x/packages/web3-eth-accounts/src/index.js#L302
Any ideas what's wrong? Thanks in advance.


texts: mining requires access to the entire blockchain?

texts:
I am reading the white paper and confused by two sentences bellow:

In the Section of Mining Centralization:

  ... miners are required to fetch random data from the state, compute some randomly selected transactions from the last N blocks in the blockchain, ... This has two important beneﬁts. ... Second, mining requires access to the entire blockchain, forcing miners to store the entire blockchain and at least be capable of verifying every transaction. This removes the need for centralized mining pools;

However, in the Section of Scalability:

  Ethereum is likely to suffer a similar growth pattern, ..., but ameliorated by the fact that Ethereum full nodes need to store just the state instead of the entire blockchain history.

So, my questions are:

Who needs to store entire blockchain history? And Who only needs the state?
What is this so called state?
Is by saying a miner implying that it is a full node? If so, why it is saying "mining requires access to the entire blockchain" but "full nodes need to store just the state instead of the entire blockchain history"?


texts: I backed up the BID, it saved as * .json file. But can not restore the four domain name. I just want to return to my ETHER. Please help。I have lost domain names "netcoin.eth", "hongkong.eth" "unionpay.eth" "porte -monnaie "


texts: How to use a customised Data Directory in Dev mode(private blockchain)

texts:
I have created the data directory in /home/ubuntu/ethchain.
Then I created two accounts in this directory using the command (ran the command twice)
geth -datadir "/home/ubuntu/ethchain" -dev account new
 Then I run the following command
geth -fast console -dev to start the geth instance.
Then I run following command
geth -datadir "/home/ubuntu/ethchain" -dev attach ipc:/tmp/ethereum_dev_mode/geth.ipc

Now when I run the above command, I expect that since I have mentioned the data directory, any account query which I run in the interactive javascript console,i.e.,eth.accounts should return me details of the accounts I have created in the directory /home/ubuntu/ethchain. But it returns me an empty list. So how do I change the default data directory? Is there any change in some config file?


texts: Using uint array as an argument in Solidity function

texts:
I am trying to compile following on Remix IDE:

 pragma solidity ^0.5.1;
 contract testArray{
    address addr;
    function testA(uint _addr, uint[] emp) public{
       addr = _addr;
       for(uint i=0; i<emp.length; ++i){
          addr.send(emp[i].value);
      }
   }
}

I am getting following error:

  browser/arr.sol:4:31: TypeError: Data location must be "memory" for parameter in function, but none was given.
  function testA(uint _addr, uint[] emp) public{
  ^--------^
  Somebody please guide me.


texts: Local ethereum node returns different than Javascript vm

texts:
contract Marketplace {
    uint256 transferBudget = 1 ether;
    bytes32[] ids;
    enum Position{
        Goalkeeper, Defender, Midfielder, Attacker, Coach
    }

    struct Footballer{
        bytes32 id;
        string name;
        address owner;
        Position position;
        uint price;
    }
    Footballer[] footballers;

    //function buy(uint ID, uint quantity) public payable {}

    function deposit() public payable {
        if(msg.value>0){
            transferBudget = transferBudget+msg.value;
        }
    }

    function getTransferBudget() public view returns(uint256){
        return transferBudget;
    }

    function update(bytes32 ID, uint newPrice) public {
        for(uint i=0; i<footballers.length; i++){
            if(footballers[i].id==ID && msg.sender==footballers[i].owner){
                footballers[i].price = newPrice;
                break;
            }
        }
    }

     function newProduct2() public pure returns(uint) {
        return 12;
    }

    //creates a new product and returns its ID
    function newProduct(string name, uint price, Position position) public returns(bytes32 id) {
        bytes32 hashId = keccak256(name,price,position);
        Footballer memory footballer = Footballer(hashId, name, msg.sender,position,price);
        footballers.push(footballer);
        ids.push(hashId);
        return hashId;
    }

    function getProducts() public view returns(bytes32[]) {
       return ids;
    }

    function getPrice(bytes32 ID) public view returns (uint) {
        for(uint i=0; i<footballers.length; i++){
            if(footballers[i].id==ID){
                return footballers[i].price;
            }
        }
    }
}

So here is the problem... the functions which are not views do not return any value when I run my local ethereum node but it works as expected in Javascript VM.


texts: I am wanting to create a paper wallet in Costa Rica and buy ether with us checking account. Coinbase will not work in Costa Rica. Please tell me what you know will work. What exchanges will work and what else do I need to know. thank you Rain


texts: Where is the gas cost subtracted? From the value of the transaction or the balance of the account?

texts: For the sendTransaction method, will the gas cost be subtracted from the value parameter or will it be subtracted from the remaining balance of the account?


texts: Is there a host node for ETC similar to infura?

texts: I want to connect to a node test using web3's HTTPProvider, and I don't want to spend time deploying a node.


texts: Verifying contract on bsc testnet using truffle plugin verify fails

texts: I have a project that compiles and deploys successfully on binance smart chain testnet. I am trying to verify the contract using truffle run verify NiftRouter --network bscTestnet --debug command but it gives me the following error. This is strange because the TransferHelper.sol does exist in that folder. My truffle version is 5.1.49. Any idea what is the issue.


texts: How to parse trace output using ABI & web3?

texts:
I am pulling a trace from a Parity node using the JSONRPC API. It looks like this:
print(trace)
{
    'action': {
        'callType': 'staticcall',
        'from': '0xXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        'gas': '0x1ad02e',
        'input': '0x2f58b80d',
        'to': '0xZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ',
        'value': '0x0'
    },
    'result': {'gasUsed': '0x501', 'output': '0x000000000000000000000000082b0ca59f2122c94e5f57db0085907fa9584ba6'},
    'subtraces': 0,
    'traceAddress': [0, 0],
    'type': 'call'
}

I can decode the input using the ABI from the to address, but this doesn't seem to work for the result.output field.
# this works
print(contract.decode_function_input(trace['action']['input']))
(<Function balanceOf(address)>, {'': '0xYYYYYYYYYYYYYYYYYYYYYYYY'})

# this does not
print(contract.decode_function_input(trace['result']['output']))
*** ValueError: Could not find any function with matching selector

Is the output encoded in a different way, maybe one that isn't tied to the ABI for the input?
I am not able to find documentation on how to decode it. I also tried using decode_function_input() for the ABI it calls, but that didn't seem to work either.


texts: How do I set initial price of my coin in smart contract

texts:
I am writing ERC20 based smart contract using solidity. I want to specify the amount on which user can actually buy my coin. I had tested my smart contract on ropsten test network and it shows 0.00$ as my coin price.

My questions are:

Is it possible to set the initial coin price while deploying smart contract? If yes, code snippet or some url are welcomed. If no, Please explain how to set coin price?
Is there any way to increase the coin price such that if my 25% coins are sold the price will be set to (2 x current price).

I am a newbie to ERC20 and solidity.
Any help/comment would be appreciated.


texts: Best way to replay (and track) blockchain to build own indices. Is it hooking into web3.eth.subscribe('logs',..)?

texts:
As a nice project to get my hands dirty with Web3 I want to attempt to build something like poocoin which shows historic OHLCV candles for BEP-20 tokens.
To this end I want to replay the entire blockchain (going with a smaller testnet chain for now), and subscribe/filter out events that allow me to construct BEP20 token price over time.
I'm specifically thinking about tracking interactions with liquidity pools on Pancakeswap (provideLiquidity, widthdraw, swap, etc.): although each of these interactions constitute a delta/change, as long as I have the current state of the pool plus this change my rationale is I can calculate the new state, and repeat. The result is saved in a timeseries db, and I'll go from there.
I was planning on using web3.eth.subscribe('logs', ... possibly in combination with web3.eth.getTransactionReceipt to get the above data. I could filter based on topics (keccak hash) of the abi-method calls I know I'm interested in.
I have some questions concerning the above:

Is the above indeed sufficient to fetch these deltas and calculate the pool (and thus price) at any given point in time?
Are there more efficient methods then the above?

Perhaps most important of all, I'm concerned that hooking into events to begin with, instead of hooking into actual transaction data somehow (transaction-tracing with JS debugging?), is barking up the wrong tree. After all, a contract can emit anything they want in an event, it doesn't have to represent that actual stuff that went down at all, correct?
Any pointers on how best to approach this, or how other projects approach this, much appreciated.


texts: Does `address.transfer` forward all gas (suceptible to re-entrancy)?

texts: From the Solidity documentation I do not understand if the recently introduced address.transfer forwards all gas to the target contract or just gives a minimal gas stipend. I.e.: Would it facilitate re-entrancy attacks?


texts:
I'm trying to establish if it's possible to use the etherscan API to establish the Transaction Action information (e.g. Swap 1 Ether For 2 Yf-DAI). If not, how are they doing it? I had a look to see how I could do it with web3 but I can't see how I would do that either.
Specifically I want to fetch a list of transactions of ETH and ERC20 tokens so I have a ledger of all activity associated with an account which I can use to calculate ROI etc..


texts: Is there something like `help` or `dir` on the geth console?

texts: In python I can run help(<function>) to get some basic info or use __doc__ to find out about what an object does. Is there something like that in the geth client?


texts: Truffle test failing with "Error: Returned error: VM Exception while processing transaction: revert" - how can I debug it?

texts:
I'm using truffle, the ganache AppImage to run a personal blockchain, and have 2 solidity smart contracts Migrations.sol and PassportManager.sol
I'm running a truffle test and getting Error: Returned error: VM Exception while processing transaction: revert so I'm guessing something's wrong with my deployed contract, something is throwing an exception in my deployed code.
How can I debug this?
I'm not using Remix and I'd hate to add MORE tools to my toolbox. Just truffle, ganache and my text editor so far, and I'd like to keep it simple.
Running my tests on JavaScript only creates 4 blocks (4 transactions) on Ganache, and none of those 4, tested with truffle debug <tx-id> brings up any useful info - one of the txes returns the bytecode for deploying PassportManager.sol (which happens every time for some reason!) and the other 3 all have something to do with Migrations.sol.
Here's the tests and code just so you know what's up:
function addIDFileToPassport(address passport_id, bytes32 id_file) public returns (address, bytes32, uint) {
        Passport storage p = user_passports[passport_id]; //Passport is a struct I've declared earlier, like so:
        /* struct Passport {
                string flair_name;
                mapping(bytes32 => uint) identity_files;
                bytes32[] identity_files_LUT;

        }*/
        require(p.controller == msg.sender);
        p.identity_files_LUT.push(id_file);
        p.identity_files[id_file] = 1;
        return (p.controller, p.identity_files_LUT[p.identity_files_LUT.length - 1], p.identity_files[id_file]);
    }

And the failing test:
/* Other tests above */
it("should add an identity file sha256 hash to a controlled passport", () => {
        let this_address = accounts[0];
        let doc_hash = "0x21f3a9de43f07d855f49b946a10c30df432e8af95311435f77daf894216dcd41";
        //let hex_doc_hash = web3.utils.asciiToHex(doc_hash);
        //console.log(hex_doc_hash);
        //let hexArray_doc_hash = web3.utils.hexToBytes(doc_hash);
        //console.log(hexArray_doc_hash);
        //console.log(web3.utils.utf

    return PassportManager.deployed()
        .then(instance => {
            meta = instance;
            return meta.addIDFileToPassport.call(this_address, doc_hash);
        })
        .then(returned_tuple => {
            assert.equal(returned_tuple[0], this_address, "Passport controller, passed and returned by PassportManager.addIDFileToPassport(), should match!");
            assert.equal(returned_tuple[1], doc_hash, "Document hash (bytes32), passed and returned by PassportManager.addIDFileToPassport(), should match!");
            assert.equal(returned_tuple[2], 1, "Trust score of newly added doc_hash should be 1!");
        });
    });


texts: Pending transaction does not show on etherscan.io

texts: I had some ethereum on coinbase and I sent it to binance using the wallet address I got from there.  Even though it says pending in coinbase, it does not show up on etherscan.io.  Is that normal?  This is my first time.


texts: Converting an address type variable to payable address type throws me error

texts:
I am trying to convert an address to payable address but I'm not able to do it. please find my code below:

address a = destinationAddress;
address dest =  address(uint160(a));
dest.transfer(amount);


texts:
The EtherScan.io website provides a page for The DAO proposals.

This page does not provide the current voting status. How can I view The DAO proposals including the current voting status?


texts: How to unlock account in ethereum where Transaction are too higher?

texts:
While working on the ethereum , I come out with the issue of out of memory because of multiple transaction execution concurrently . The main reason was , i was unlocking account of that user every time which take too much of memory , if i do contract function execute (transaction) without unlocking the account in code and unlock account in geth by

  personal.unlockAccount("address","password")

and then run transaction it execute smoothly over 500 transaction / sec . How can i unlock account everytime or give me better solution how to unlock account so that i can overcome with out off memory problem ?


texts:
I read a research paper for verification and validation of solidity code
Here's a link:)!

The code is given below:

contract MyBank {
   mapping (address)uint) balances;

function Deposit() {
   balances[msg.sender] += msg.value;
}

function Withdraw(uint amount) {
   if(balances[msg.sender]  amount) {
     msg.sender.send(amount);
     balances[msg.sender] = amount;
   }
}

function Balance() constant returns(uint) {
   return balances[msg.sender];
}
}

It uses F* (F-star). However, it has to convert the solidity code into F-star. I cant find the converter. Can some body please guide me how to manually test the code?

The conversion of code into F* is given below:

 module MyBank
 open Solidity
 type state = { balances: mapping address uint; }
 val store : state = {balances = ref empty_map}

 let deposit () : Eth unit =
    update_map store.balances msg.sender
       (add (lookup store.balances msg.sender) msg.value)

 let withdraw (amount:uint) : Eth unit =
 if (ge (lookup store.balances msg.sender) amount) then
 send msg.sender amount;
 update_map store.balances msg.sender
 (sub (lookup store.balances msg.sender) amount)

 let balance () : Eth uint =
 lookup store.balances msg.sender

What I understand is that:
Initially balance is zero. Then store some value in the balance using msg.value : lets suppose 500. & in lets suppose Withdraw(700) it checks that balance is greater than amount so it sends the amount & deducts balance which seems fine. However paper says:

  Using the effect system of F*, we now show how to detect some
  vulnerable patterns such as unchecked send results in translated
  contracts. The base construction is a combined exception and state
  monad (see [9] for details) with the following signature:

  EST (a:Type) = h0:heap // input heap
  ->send_failed:bool // send failure flag
  ->Tot (option (a * heap) // result and new heap, or exception
  * bool) // new failure flag

  return (a:Type) (x:a) : EST a =
  fun h0 b0->Some (x, h0), b0

  bind (a:Type) (b:Type) (f:EST a) (g:a->EST b) : EST b =
  fun h0 b0->
  match f h0 b0 with
  | None, b1->None, b1 // exception in f: no output heap
  |Some (x, h1), b1->g x h1 b1 // run g, carry failure flag

Some body please guide me how to detect the error and what the above paragraph says.

Zulfi.


texts: How to interact with Smart Contract in private network with 3 nodes using Mist?

texts:
I'm looking for a method to interact with a smart contract deployed from the official Ethereum wallet.

My client is Geth,and I've synchronized 3 nodes. How is possible to recall a simple method of smart contract from any node?


texts: testrpc --account private key length is invalid even though its my account

texts:
I tried to initiate a testrpc account and passing my account with value to test the transactions but when I keyed in my key 0x94fd019eeb92780477b01ce5555513d3755b5193 it says that the key is invalid.

Why is it invalid even though its my key?

EDIT: full log of error down below

  C:\Users\user>testrpc --account="0x94fd019eeb92780477b01ce5555513d3755b5193,1000"
  C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:74143
  var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;if(Module["ENVIRONMENT"]){if(Module["ENVIRONMENT"]==="WEB"){ENVIRONMENT_IS_WEB=true}else if(Module["ENVIRONMENT"]==="WORKER"){ENVIRONMENT_IS_WORKER=true}else if(Module["ENVIRONMENT"]==="NODE"){ENVIRONMENT_IS_NODE=true}else if(Module["ENVIRONMENT"]==="SHELL"){ENVIRONMENT_IS_SHELL=true}else{throw new Error("The provided Module['ENVIRONMENT'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.")}}else{ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&"function"==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WOR

  RangeError: private key length is invalid
      at Object.exports.isBufferLength (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:60654:39)
      at Object.publicKeyCreate (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:60446:14)
      at Object.exports.privateToPublic (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:7065:20)
      at StateManager.createAccount (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:90434:25)
      at Array.map ()
      at StateManager.initialize (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:90342:33)
      at new GethApiDouble (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:89816:14)
      at new Provider (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:28446:23)
      at Object.create (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:105938:20)
      at Object.server (C:\Users\user\AppData\Roaming\npm\node_modules\ethereumjs-testrpc\build\cli.node.js:59272:19)


texts: Proof of authenticity without microchips?

texts:
If I was looking to "tag" items to prove uniqueness/authenticity, it'd be easiest to register them on the blockchain (public key) and then verify them through signing with the private key, right?

It seems the best way to do this would be to hide the private key behind a microchip so that it can never be duplicating, but that raises costs.  Are there any unique ways to do something like this without implementing a microchip to hide the private key for verification?


texts: How to keep the token price in uniswap the same with the centralized exchange

texts: Consider I have a custom Erc20 Token which already lists in CEX(centralized exchange like huobi). Then I add liquidity to Uniswap to make it tradable with initial exchange price. However this token is not popular and even no one trades it in Uniswap, while the price in CEX changes daily, then how can I keep the price same with CEX?


texts: I know I can get a number of confirmations one by one, but is there a easy way to monitor the number of confirmations of multiple transactions?


texts: What is a reasonable gas limit for a transaction to invest in an ICO?

texts:
IndaHash asks for a gas limit of 250 000.
Since it's $675 per ether, a gas is 675/100k,
the transaction could cost 250000*$675/100k = $1687.

Is my math wrong?


texts:
can someone help me with this ecrecover issue? The code below is a truffle test. The recoverSigner function just calls ecrecover, but the return is always '0x'. Recovering with ethereumjs-util works fine.

Geth v1.8.17 (clique private network)
Truffle v4.1.14
Solidity v0.4.24

//Front-end
const msg = new Buffer('hello')
const sig = web3.eth.sign(web3.eth.accounts[0], '0x' + msg.toString('hex'))

//Back-end
const res = ethUtil.fromRpcSig(sig)
const prefix = new Buffer("\x19Ethereum Signed Message:\n")
const prefixedMsg = ethUtil.keccak256(Buffer.concat([prefix, New Buffer(String(msg.length)), msg]))
const pubKey  = ethUtil.ecrecover(prefixedMsg, res.v, res.r, res.s)
const addrBuf = ethUtil.pubToAddress(pubKey)
const addrEthJS = ethUtil.bufferToHex(addrBuf)
assert.equal(accounts[0], addrEthJS) // Ok!

//Ethereum Network
let addrSolidity = await instance.recoverSigner(ethUtil.bufferToHex(prefixedMsg), res.v, ethUtil.bufferToHex(res.r), ethUtil.bufferToHex(res.s))
assert.equal(accounts[0], addrSolidity) // Fail! recoverSigner returns '0X'


texts: How do I set constant state variables in source code before migrating to a test network?

texts:
Is there a way to change the value of address literals in solidity source code before migrating to a local test chain using Truffle? Currently, if a contract A needs to know the address of another contract B, you must pass B's address to A's constructor, which means the address must be stored as a state variable in A's storage. This is very expensive, costing 20,000 gas for initialization plus 200 gas for every read. Ideally B's address could be stored in A as a constant state variable, but constant's cannot be set in a constructor, only hardcoded into the source code.

For example, here, creation of C uses 20,000 more gas than D. And D's get() can be pure rather than view. I'd like to be able to change D's value of a before compiling and migrating to a test network.

contract C {
    address a;
    constructor(address _a) public {
        a = _a;
    }

    function get() external view returns (address) {
        return a;
    }
}

contract D {
    address constant a = 0x1111111111111111111111111111111111111111;

    function get() external pure returns (address) {
        return a;
    }
}


texts: connection refused to Geth websocket port

texts:
I have installed Geth v.1.8.3-unstable on CentOS 7 / 64-bit with go version go1.8.3.

When trying to start geth with

$ nohup geth --datadir /home/bchain/Private_Chain/chaindata --mine --nodiscover --nat any --identity private_chain --networkid 1900 --port 30301 --verbosity 5 --rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpccorsdomain '*' --rpcapi personal,admin,db,eth,net,web3,miner,shh,txpool,debug --ipcpath /home/bchain/Private_Chain/get.ipc --ipcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3 --ws --wsaddr 0.0.0.0 --wsport 8546 --wsorigins '*' --wsapi personal,admin,db,eth,net,web3,miner,shh,txpool,debug --maxpeers 25 --etherbase 0 --gasprice 0 --targetgaslimit 9999999

Geth seems to be running successfully without error messages.

then..

$ geth attach ws://127.0.0.1:8546
Fatal: Unable to attach to remote geth: dial tcp :80: getsockopt: connection refused

$ geth attach ws://localhost:8546
Fatal: Unable to attach to remote geth: dial tcp :80: getsockopt: connection refused

I try $ ncat --listen 127.0.0.1 8546 and $ ncat 127.0.0.1 8546 and it catches all messages
(I think I have no problem of firewall)

Any idea ?


texts: I got " TypeError: Storage location can only .."

texts:
Here is my sample contract code, but I got an error,

TypeError: Storage location can only be given for array or struct types.

I just wannted to define some element of a structure in a function,

contract MyContract {
   PC[] public pcs;
   structure PC {
      string name,
      uint time
   }

   function checkTime(uint _pcid) public {
      uint memory a = pcs[_pcid];
      string memory b = pcs[_pcid];
      //do something with a and b...
   }
}

What am I doing wrong? do I have to define storage instead of memory??


texts:
Would like to deploy a smart contract that any Web2 user can communicate with -
 given my smart contract public functions accept a few parameters.

This essentially makes it "centralized" in a way, as my HTTP API gateway will be the funnel to the Ethereum network.

How can I solve such problem ? What is the best approach to this ?


texts:
I'm trying to test a token sale contract on the Ropsten test network but am having an issue. I am using Ethereum Wallet. I am following the guide at http://www.ethereum.org/crowdsale. I am getting this message:

The arguments for my crowdsale are the address of my test wallet, 25 minutes (arbitrary amount of minutes), and the address of my tokens.

Here is my crowdsale code:

pragma solidity ^0.4.18;

interface token {
    function transfer(address receiver, uint amount) public;
}

contract CoinCrowdsale {
    address public beneficiary;
    uint public amountRaised;
    uint public deadline;
    uint public price = 500 wei;
    uint public hardCap = 1000 wei;
    uint public softCap = 500 wei;
    token public tokenReward;

    mapping(address => uint256) public balanceOf;

    bool softCapReached = false;
    bool hardCapReached = false;
    bool crowdsaleClosed = false;

    event GoalReached(address recipient, uint totalAmountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);

    /**
     * Constrctor function
     *
     * Setup the owner
     */
    function CoinCrowdsale (
        address Address,
        address benAddress,
        uint durationInMinutes
    ) public {
        beneficiary = benAddress;
        deadline = now + durationInMinutes * 1 minutes;
        tokenReward = token(Address);
    }

    /**
     * Fallback function
     *
     * The function without name is the default function that is called whenever anyone sends funds to a contract
     */
    function () payable public {
      require(!crowdsaleClosed);
      require(msg.value > 0.1 ether);
      uint amount = msg.value;
      balanceOf[msg.sender] += amount;
      amountRaised += amount;
      tokenReward.transfer(msg.sender, amount / price);
      FundTransfer(msg.sender, amount, true);
      if (amountRaised >= hardCap){
        hardCapReached = true;
        crowdsaleClosed = true;
      }
    }

    modifier afterDeadline() {
      if (now >= deadline || hardCapReached == true) _;
    }

    /**
     * Check if goal was reached
     *
     * Checks if the goal or time limit has been reached and ends the campaign
     */
    function checkGoalReached() afterDeadline public {
      if (amountRaised >= softCap){
          softCapReached = true;
          GoalReached(beneficiary, amountRaised);
      }
      crowdsaleClosed = true;
    }

    /**
     * Withdraw the funds
     *
     * Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
     * sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
     * the amount they contributed.
     */
    function safeWithdrawal() afterDeadline public {
      if (!softCapReached) {
          uint amount = balanceOf[msg.sender];
          balanceOf[msg.sender] = 0;
          if (amount > 0) {
              if (msg.sender.send(amount)) {
                  FundTransfer(msg.sender, amount, false);
              } else {
                  balanceOf[msg.sender] = amount;
              }
          }
      }

      if (softCapReached && beneficiary == msg.sender) {
        if (beneficiary.send(amountRaised)) {
          FundTransfer(beneficiary, amountRaised, false);
        } else {
          //If we fail to send the funds to beneficiary, unlock funders balance
          softCapReached = false;
        }
      }
    }

}

I've tried putting it into remix and am getting a warning saying that it will require infinite gas - the same happens when I copy and paste the example crowdsale from the Ethereum site. How do I fix this / what is wrong?


texts: Tokens standards on go-ethereum and Quorum - ERC721

texts:
Someone just told me that Quorum does not implement EIP721, so it does not support ERC721 tokens.

I always though token standards are just standards you should follow in your smart contract code and not something natively programmed in the core of Quorum or go-ethereum.

So is that assumption true ? can I use ERC721 token standard on Quorum ? if not, any idea about ways to create non-fungible assets on Quorum ?

Thanks a lot for your help


texts: i have wallet's keystore file and private key. how can i find mnemonic words

texts:
I have keystore file and private key of my wallet. i need this wallet's mnemonic words.

How can i find mnemonic phrase from this json file and private key? I tried mycrypto and mew but i couldnt find a solution. I need these words.

Please help me.


texts: How to build and run dApps written in Solidity without ethers?

texts:
Is there a way to test build and run dApps with Solidity back-end that does not require downloading blockchains or ethers?

I have created an account in Ethereum Wallet, but have been unable to download the entire blockchain.

Are there any IDEs or some platform of the sort to build Solidity contracts, write the front end dApp and simulate a real world application?


texts: Using Oraclize to assign value to another contracts variable

texts:
I'm using oraclize to get the price feed using this code:

import "oraclizeAPI.sol";

contract PriceFeed is usingOraclize{
  uint public BTCUSD;

  function PriceFeed(){
    oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
    update(0); // first check at contract creation
  }

  function __callback(bytes32 myid, string result, bytes proof) {
    if (msg.sender != oraclize_cbAddress()) throw;
    BTCUSD = parseInt(result, 2); // save it as $ cents
    // The following line is what I do which ends up with the error message
   //MyContract.BTCUSD = BTCUSD;

    update(360); // schedule another check in 60 seconds
  }

  function update(uint delay){
    oraclize_query(delay, "URL",
      "json(https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD).USD");
  }
}

Now I have the second contract in the same file that has a variable called BTCUSD. I need to update that variable when I get callback from oraclize. I've tried multiple methods, writing a setter/getter method on both contracts, using MyContract.BTCUSD = BTCUSD style assignments but I get errors.

contract MyContract {
  uint public BTCUSD;
}

I'm using linter on atom and these are the errors I get depending on how I try to assign the value:

  Member "BTCUSD" not found or not visible after argument-dependent lookup in type(contract MyContract)


texts: Chainlink - on-chain contract functioning

texts:
The on-chain aggregation smart contract for ETH/USD on the mainnet (https://data.chain.link/eth-usd) is at this address https://etherscan.io/address/0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419#code.
If I create a smart contract and import the AggregatorV3Interface interface and instantiate AggregatorV3Interface internal priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419), how can
function getLatestPrice() public view returns (int) {
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }

be enough to obtain answers from the off-chain oracles? I thought that, to communicate with an oracle for its jobs, one had to inherit from ChainLinkClient.sol. So, I thought that the smart contract for ETH/USD inherited from ChainLinkClient.sol.
I cannot understand the logic on how this aggregator contract can fetch data from the outside from the decentralised network of oracles as shown in the picture (https://data.chain.link/eth-usd).


texts:
I'm new to ether mining.

Do I have to sync with the blockchain while mining?

Currently I'm using ethminer for solo mining with GPU and geth to sync with blockchain.


texts: What does geth need RAM for on a non-mining node?

texts:
I was running a private Ethereum chain on a couple of non-mining Raspberry Pis and encountered quite high and increasing RAM usage.

I understand that there was a memory leak with geth versions before 1.9 that made RAM usage increase excessively but I do not understand why geth would need any RAM at all if I am not mining. So the question:

What is RAM used for on non-mining nodes in a blockchain? Is the RAM usage generally meant to increase over time or should it be stable at a certain level?

Thank you very much in advance.


texts: Contract transaction ran out of gas, but the gas limit is much higher than the required amount

texts:
We have a smart contract which sends ETH to some address', but everytime we call that function, the function fails..

https://etherscan.io/tx/0xe430a3f57c01f4a1ea26dc94d4d16f0748d8d7a03e05187830c5bdf15826bdce

As you can see in the link we do however specify a much higher GAS limit that needed, but still it runs out of gas...

What is going wrong?


texts: "instance.at(addr) is not a function" in truffle console (access to non-migrated contracts)

texts:
I have a setup with one contract that is a singleton and is migrated to e.g. a testnet through the truffle console.
This contract "creates" new contracts, which I want to access in the truffle console. Since the new contracts are not migrated via the console I want to use instance.at(address) in a command I will execute in truffle. However, it's not recognising the instance...

Contracts:
Singleton.sol → migrated via truffle
ManyOfMe.sol → created via Singleton.sol

Error:

  TypeError: ManyOfMe.at is not a function

Code: run.js executed through truffle console: exec ./run.js

const artifacts = require('./build/contracts/Singleton.json')
const ManyOfMe = require('./build/contracts/ManyOfMe.json')
const contract = require('truffle-contract')
const MyContract = contract(artifacts)
MyContract.setProvider(web3.currentProvider)

let Singleton
MyContract.deployed()
.then(async function(instance) {
  Singleton = instance

  let tokenAddress
  await Singleton.tokens(0).then(_ => {
    tokenAddress = _
  })
  return ManyOfMe.at(tokenAddress)
})
.then(function(instance) {
  instance.doSomething().then(_ => console.log(_))
})
.catch(function(error) {
  console.error(error)
})

PS: If I just type ManyOfMe in the truffle console, I see the at function, so I'm not sure why it won't work.


texts:
I have an identical contract on the Mainnet and Ropsten. Both work fine in Remix. Using a python program on my Windows machine, I find that I get an error accessing the Ropsten contract, but not the mainnet version. All I changed in my Python program was the contract address and provider URL:
"https://mainnet.infura.io/v3/3e4616a1aed64da3b29e20c2970e23b7"
to
"https://ropsten.infura.io/v3/3e4616a1aed64da3b29e20c2970e23b7"
The flawed program generates an error on the first contract call
currDay = contract.functions.currentDay().call()

This generates a scalar output, type uint8. The error I get is:
web3.exceptions.BadFunctionCallOutput: Could not decode contract function call currentDay return data b'' for output_types ['uint8']

As mentioned, this works fine for the mainnet, and also works fine within Remix for both the Ropsten and Mainnet contracts.


texts: During truffle init - got error "something already exisits at the destination"

texts:
Error: Something already exists at the destination. Please unbox in an
  empty fol der. Stopping to prevent overwriting data.
      at C:\Users\lenovo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\~
  \truffle-box\lib\utils\unbox.js:22:1


texts: How does a contract find out if another address is a contract?

texts: Is it possible, from within a contract written in Solidity, to check if a contract is placed on a specific address or if this address does not contain any code?


texts: Send Custom ERC20 Tokens from one Address to another

texts:
How to send custom ERC20 tokens from one wallet to another, if i want to send EBTC/ECASH custom ERC20 tokens.

I wrote a method that can send the ether from one account to another, how could i do the same for non ether transactions?

public static void sendCustomToken(String privateKey,String toAccount, double amount) throws Exception{

Web3j web3 = Web3j.build(new HttpService("http://localhost:8180/"));
BigInteger key = new BigInteger(privateKey,16);
ECKeyPair ecKeyPair = ECKeyPair.create(key.toByteArray());
Credentials credentials = Credentials.create(ecKeyPair);
TransactionReceipt transactionReceipt = Transfer.sendFundsAsync( web3, credentials, toAccount, BigDecimal.valueOf(amount), Convert.Unit.ETHER).get();

System.out.println("Transaction Hash:"+transactionReceipt.getTransactionHash());
}

Custom Token: eBTC
Contract Address: 0x2fd41f516fac94ed08e156f489f56ca3a80b04d0
Token Decimals: 8

Any help or pointers?


texts: What economic incentive does anyone have to mine Ropsten and other networks?

texts:
Ethereum 1.0 has a basic limitation, as all global blockchains do: each block can only hold so many transactions. Due to this scarcity, every time even one application gets too popular on the main network, gas prices for transactions shoot up. At current prices of ETH, you might end up paying $5 or even $99.
However, developers use Ropsten network all the time. What if the volume of transactions there was the same as on the mainnet? Anyone can get unlimited amounts of ETH on it, so why do miners mine the next block at all? Is it basically a gift economy, that would come crashing down if someone actually deployed a popular app (say, voting on the blockchain) on Ropsten?
I am considering doing just this... meaning I want to build dapps which sidestep the high cost of ETH, and take advantage of the "good-enough" security of Ropsten etc. and also reward our own nodes and contracts in various ERC20 contract currency, rather than ETH. Presumably there are no faucets that just mint arbitrary amounts of arbitrary ERC20 contracts, since the mint methods are actual code deployed by someone. Like our own ERC20 contract... we can tell it to mint on Ropsten to those who send us wires, paypal, ETH on the mainnet, or whatever.


texts: Trying to write https://etherscan.io/writecontract/ transfer from

texts: I transferred link tokens to xdai network using trust wallet. But trust wallet come to find out doesn’t allow users to switch to poa network xdai. So I need to write within the contract to transfer the tokens to my MetaMask wallet address. Clearly I’m a noob,but I got this far Didnt I?


texts:
Canonical question about the public Ethereum testnets. What's the difference between Olympic, Morden and Ropsten?

What are their network IDs, which ones are still considered active?


texts: Cannot create a second account on my private chain from the Ethereum Wallet

texts:
Just playing around with Ethereum. I create my very first private-chain on a Windows machine..

First I'm starting up the node/miner:

  D:\ethereum\gethlatest>geth --dev --rpc --rpcport 8002  --datadir
  D:\ethereum\gethlatest\privatechain --ipcpath
  D:\ethereum\gethlatest\privatechain console

This is running without an issue. Then I am going to create the first address which I will use to collect the Ethers that the miner will mine:

personal.newAccount('myPassword')

Then, I will start the miner:

miner.start()

It starts mining, with every block the miner mines, 5 Ether is being credited to the address I just created. No problems here.

Now, I am going to start the wallet client:

C:\Users\xx\AppData\Local\EthereumWallet\app-0.8.7>"Ethereum Wallet.exe" --rpc http://localhost:8002

Ethereum wallet is looking for peers, can't seem to find one. I'm clicking Launch   When the wallet opens, I see the first address created with some Ethers in it. Good!

However, in the client terminal the first error appears:

  [2016-10-28 09:50:53.617] [WARN] (ui: wallet) - %cUnhandled rejection
  UnknownError: Internal error opening backing store for indexedDB.open.
  color: red

Meanwhile in the client:
I want to create another address/account. I want to send some ETH to it, just to play around. I choose "add account" and enter a password and the again for confirmation.

This doesn't work, in the client terminal:

  2016-10-28 09:55:38.648] [ERROR] ipcProviderBackend - Send request
  failed { code: -32601,   message: 'The method personal_newAccount does
  not exist/is not available' }

Any advice on how to fix this?

Thanks!


texts: Use ethereum address from ledger nano S for participating in ICO

texts:
I want to know if I can use the ethereum wallet addresses that come with the Nano S. I have eth on it and used this to participate in an ICO. Is that ok as it is first time using this address as it doesn't have a private key?
Thanks


texts: web3js recover returns different address than what signed message

texts:
Web3js as of version 1.0.0 beta supports an interface for verifying signed messages: https://github.com/ethereum/web3.js/issues/404

This is documented here: https://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html#recover

Following the documentation, i try to sign and verify a message, and notice the address I get from ecrecover is not the same as the one that created the message.

> let message = "this is a message"
> let account = '0x6eE80F4D7494E61b90c91a7175804018332d6e17'
> let privateKey = '82c290abc9dc56631a62ca9523dcb51b7c2beb6c941bd47ad0332a124eb822ce'
> let signature = '0x21ef296f199e079cae27abffc63389ffd910e91bd7196f389ca2b0177f116d020945a0dbed2ea62d4be17c09947ce33a7a183722e1fc2a75cd9dc9c6bd97d1501b'
> let signatureObject = we3.eth.accounts.sign(message, privateKey)

{ message: 'this is a message',
  messageHash:
   '0x29d8e880f198acda69a1cd82dd2c8e37edc6bb7e84da26527fb8a0cf7d482cda',
  v: '0x1b',
  r:
   '0x21ef296f199e079cae27abffc63389ffd910e91bd7196f389ca2b0177f116d02',
  s:
   '0x0945a0dbed2ea62d4be17c09947ce33a7a183722e1fc2a75cd9dc9c6bd97d150',
  signature:
   '0x21ef296f199e079cae27abffc63389ffd910e91bd7196f389ca2b0177f116d020945a0dbed2ea62d4be17c09947ce33a7a183722e1fc2a75cd9dc9c6bd97d1501b' }

> we3.eth.accounts.recover(signatureObject)

'0x1aB8B2a2BE93b08879b3b3e7eB1EF2D59A544B91'

Notice the address returned is not the same as the address used to sign the message ( the account variable).

I also tried hashing the message before signing using web3.utils.sha3() and web3.eth.accounts.hashMessage(), then passing that hash into sign. They all yield the same address as above.

I have already verified the address and private key I am using are correct.


texts: Transferring ETH from Coinbase to Etherdelta

texts:
I have an Ethereum wallet on Coinbase and want to transfer some ETH from Coinbase into my wallet on EtherDelta.  Can this be done and if so what is the procedure?

Thanks.


texts: Can I write and deploy smart contracts in Java language?

texts:
I am a Java developer. I want to write a smart contract using Java and deploy it to a private blockchain network.

Does Ethereum provide the facility to write smart contracts using Java language? If yes, how can I do this?


texts:
Lately, there's been some interest in sparse Merkle trees (SMTs).
I know Ethereum uses Patricia tries (PTs), but this thread seems to indicate that working with SMTs would yield similar performance, even better if constructed correctly.

I understand how generally SMTs work (one generates the hash of all possible inputs, and the tree is sparse because you don't actually store all empty keys and slots), but how is it going to work within the context of Ethereum and sharding?


texts: What's the difference between token tracker and address page in Etherscan?

texts:
As an example, let's use DAI.
DAI has these pages in Etherscan:

https://etherscan.io/token/0x6b175474e89094c44da98b954eedeac495271d0f
https://etherscan.io/address/0x6b175474e89094c44da98b954eedeac495271d0f

It seems like the first one will track all the transactions but what about the second page? I'm confused in trying to differentiate between those two.
Thanks in advance


texts: Transaction reverted by EVM when using transfer from method

texts:
I'm using a method in which transferfrom method of an ERC20 token is called.
In test enn I use my own ERC20 token and ganache and everything works fine.
but in Rinkeby testnet when I use interface of ERC20 and address of Deplyoed tokens in Rinkeby I get the error.
here is my deposite function :
function deposit(uint _value, IERC20 _currency) public {
        require(_currency.transferFrom(msg.sender , address(this), _value),  "transferFrom failed");
    }
}

in my web3 I call approve function first(and wait for get mined) and then call deposit, every thing works fine in Ganache, but in Rinkeby, I always get my deposit reverted.
web3 code:
ERCInstance.methods.approve('deposit contract address', token amount).send({from:
accounts[0]}).on('transactionHash', (hash) => {
        dipositeContractInstance.methods.deposit(amount, 'ERC address').
        send({from: accounts[0]}).on('receipt', function(receipt){

        });

note that I used pre created ERC20 tokens in rinkeby and even created my own one, but still get revert.
for example rinkeby dai address is :'0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735'


texts: Is there a way to generate multiple addresses at once?

texts:
I can use MyEtherWallet to generate a new Ethereum address. But using it I generate one address at a time. This takes a long time to generate, let's say, 100 private keys.

Is there a way to automate this process?

For example, I click one button and 100 (or any number) Ethereum private keys are generated.


texts: Could not Able to start my genesis block "Fatal: Account unlock with HTTP access is forbidden!"

texts: I am getting some problem while i am trying to mine for my genesis block on my Geth command prompt "Fatal: Account unlock with HTTP access is forbidden!" could anyone please provide me help in this, i have tried this many times but getting this same error each time.....


texts: How can I restrict a function to make it only callable by one contract?

texts:
Assume I have two contracts as follows

contract FirstContract{

function anyFunction(){}

}

contract SecondContract{

  FirstContract x = new FirstContract();

function anotherFunction(){
  x.anyFunction(); ///////
}

}

How can I restrict anyFunction() so that only SecondContract can call it and nothing else?


texts: Are the transaction parameters recorded on the blockchain?

texts: I'm trying to figure out if its safe to send a private key along with a transaction so that only people with the private key can execute the transaction. My concern is that the transaction record will contain the private key that was sent with the transaction. I reviewed the solidity docs and didnt see any mention of parameter values though, see here.


texts: Is it possible to fork ethereum so that only specified account(s) can deploy new contract?

texts:
Blockchains supporting smart contract are sometimes compared with smartphones in the sense that it is an infrastructure opened to host an indefinite number of Apps, any participant can create and deploy to make it available to the entire network.

In the case of a private blockchain, the administrating party might not wish to allow the participants to deploy new contract but only to call the methods of the smart contract it had deployed.

Is there a way to branch Etherum code to allow that?
If so, can the account(s) allowed for contract deployment be in the genesis block rather than hardcoded?


texts: Solidity assembly: why is the length of _bytes added to _bytes before mload()?

texts:
For example in BytesLib: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L348  (Edit: Note that the same pattern is used for lengths: 1, 2, 4, 8, 16, and 32)

    function toUint96(bytes memory _bytes, uint _start) internal  pure returns (uint96) {
        require(_bytes.length >= (_start + 12));
        uint96 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0xc), _start))
        }

        return tempUint;
    }


texts: Known cases of miners withholding blocks when used as randomness?

texts:
There are some applications that use the blockhash as a source of randomness, often with a payout similar to a lottery. I've heard of attacks where it would be more profitable for a miner to withhold blocks and lose the block reward, but increase the chances of them winning the lottery payout. I've heard this has actually happened, but have never seen details.

Are there any known instances of such a withholding? Are there numbers on what the payout would need to be relative to percentage of hash-power the miner controls?


texts: Is it possible to divide my crowdsale contract into multiple files in order to solve gas issue?

texts:
I'm trying to deploy a crowdsale contract, which is using open zeppelin, on ropsten network but I got gas related error. The error says "please check your gas amount". How can I solve it? I think this contract is very simple crowdsale contract. Thus, I believe I don't need to separate to multiple files. I did not try it on mainnet.

This is all what I did

$ mkdir /tmp/manatoken-infra
$ cd /tmp/manatoken-infra
$ truffle init
$ npm install ethereumjs-wallet bip39 web3-provider-engine@8.6.1 web3@0.18.4 zeppelin-solidity --save
$ vi ./truffle.js
$ vi ./contracts/GustavoCoin.sol
$ vi ./contracts/GustavoCoinCrowdsale.sol
$ vi ./migrations/2_deploy_contracts.js
$ truffle compile
$ truffle deploy --network ropsten

truffle.js

var bip39 = require("bip39");
var hdkey = require('ethereumjs-wallet/hdkey');
var ProviderEngine = require("web3-provider-engine");
var WalletSubprovider = require('web3-provider-engine/subproviders/wallet.js');
var Web3Subprovider = require("web3-provider-engine/subproviders/web3.js");
var Web3 = require("web3");
var FilterSubprovider = require('web3-provider-engine/subproviders/filters.js');

// Get our mnemonic and create an hdwallet
var mnemonic = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));

// Get the first account using the standard hd path.
var wallet_hdpath = "m/44'/60'/0'/0/";
var wallet = hdwallet.derivePath(wallet_hdpath + "0").getWallet();
var address = "0x" + wallet.getAddress().toString("hex");

var providerUrl = "https://testnet.infura.io";
var engine = new ProviderEngine();
engine.addProvider(new FilterSubprovider());
engine.addProvider(new WalletSubprovider(wallet, {}));
engine.addProvider(new Web3Subprovider(new Web3.providers.HttpProvider(providerUrl)));
engine.start(); // Required by the provider engine.

module.exports = {
  networks: {
    "ropsten": {
      network_id: 3,    // Official ropsten network id
      provider: engine, // Use our custom provider
      from: address    // Use the address we derived
    }
  },
  rpc: {
    // Use the default host and port when not using ropsten
    host: "localhost",
    port: 8545
  }

contracts/GustavoCoin.sol

pragma solidity ^0.4.11;

import 'zeppelin-solidity/contracts/token/MintableToken.sol';

contract GustavoCoin is MintableToken {
  string public name = "GUSTAVO COIN";
  string public symbol = "GUS";
  uint256 public decimals = 18;
}

contracts/GustavoCoinCrowdsale.sol

pragma solidity ^0.4.11;

import './GustavoCoin.sol';
import 'zeppelin-solidity/contracts/crowdsale/Crowdsale.sol';

contract GustavoCoinCrowdsale is Crowdsale {

  function GustavoCoinCrowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) Crowdsale(_startBlock, _endBlock, _rate, _wallet) {
  }

  function createTokenContract() internal returns (MintableToken) {
    return new GustavoCoin();
  }
}

migrations/2_deploy_contracts.js

var GustavoCoinCrowdsale = artifacts.require("./GustavoCoinCrowdsale.sol")

module.exports = function(deployer, network, accounts) {
  const startBlock = 1628404
  const endBlock = startBlock + 300
  const rate = new web3.BigNumber(1000)
  const wallet = "0x8005cEb675D2FF8c989CC95354438B9Fab568681"

  deployer.deploy(GustavoCoinCrowdsale, startBlock, endBlock, rate, wallet)
}

error

Running migration: 2_deploy_contracts.js
  Deploying GustavoCoinCrowdsale...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: The contract code couldn't be stored, please check your gas amount.


texts: How to send a transaction to myetherapi.com with Web3.py

texts:
I am having trouble interacting with myetherapi.com using web3.py. I am able to create a few functions that were working, like get_eth_balance() below. But to send transactions like send_eth(), I just keep getting this ValueError:

ValueError: {'code': -32601, 'message': '{eth_sendTransaction} Method not
found or unavailable', 'data': None}

Any help would be greatly appreciated, what am I missing here?

from web3 import Web3, HTTPProvider

class MyWallet():
    def __init__(self, addr=None, key=None):
        self.addr = addr
        self.key = key
        self.w3 = Web3(HTTPProvider('https://api.myetherapi.com/eth'))

    def get_eth_balance(self):
        return self.w3.eth.getBalance(self.addr)

    def send_eth(self, address, amt):
        transaction = {
            'from': self.addr,
            'to': address,
            'value': Web3.toWei(amt, 'ether')
        }
        return self.w3.eth.sendTransaction(transaction)


texts: Simple deposit and withdrawal contract, withdrawal not returning error but executing

texts:
I am attempting to write a contract that takes a two Ether deposit, has a function to check the balance of the contract, and also a function to remove the Ether from the contract and send it to the owner.
For example 0x17F deploys the contract and is the owner, 0xCA3 initialized the accept() function and two ETH is taken out of that address and appears as in the contract address 0xE2D. Now I would like to pay out the contract holdings to the owner by way of the collect() function.
When I try to run the collect() function, it seems to execute but no ether is removed from the contract and none is sent to the owner.
My code:
pragma solidity >=0.7.0 <0.9.0;

contract  AcceptEth {

    address public owner;
    uint public price = 2 ether;
    mapping (address => uint) balance;
    //uint256 contractBalance = address(this).balance;
    uint256 public val = 1;

    constructor() {
        owner = msg.sender;
    }

    function accept() payable public {
        // Error out if anything other than 2 ether is sent
        require(msg.value == price);

        //Remove the 2 ether from the initiator of the accept function, and add it to the contract address balance
        balance[address(this)] += msg.value;

    }

    function check() public returns(uint256) {
        //Error out if anyone other than owner tries to check the balance
        require(msg.sender == owner);

        //Show the balance on the contract address
        return address(this).balance;

    }

    function collect() payable public {
        //Error out if anyone other than the owner tries to collect
        require(msg.sender == owner);

        //Send the ether in the contract address, to the owner of the contract address
        balance[owner] += balance[address(this)];

    }

}

The last function appears to execute in remix, and renders a green check in the console. Besides that, nothing seems to happen. There may be something fundamental I am missing, so would appreciate if it appears I am doing something wrong in general with my contract if you could let me know.
So my question is, how can I retrieve the ETH from the contract and send it to the owner?
***Note that I am very new to Solidity and there may be lots of problems/misunderstandings I present here, so any commentary would be great.


texts: Why can I store over 32 characters in bytes32?

texts:
I have a Solidity contract with functions like this:

function SetMessage (bytes32 key, bytes32 message) returns (bool success) {
    publicStruct[key].message = message;
    return true;
    }

    function GetMessage (bytes32 key) public constant returns (bytes32) {
    var message = publicStruct[key].message;
    return message;
    }

Then I'll use web3 to execute SetMessage and then call GetMessage after that's done:

var mystringmessage = 'some string over 32 characters in length that can seem to be up to 128 characters in length to be stored in bytes32'
var key = 'message key'

MyContract.deployed().then(function (instance) {
          contractInstance = instance
          return contractInstance.SetMessage(key, mystringmessage, { gas: 200000, from: web3.eth.accounts[0] })
        }).then(function () {
          return contractInstance.GetMessage.call(key)
        }).then(function (messages) {
          console.log('MSG: ' + messages[0])
        })

It seems that any string up to 128 characters can be stored in one bytes32 object from this. I'm also not converting the ordinary javascript string into bytes32 before executing SetMessage, or using web3.toAscii to convert the bytes32 back into a human readable string (as I always thought was necessary). Why should a single bytes32 object be able to store more than 32 characters?


texts: testrpc security implications of opening mist with a custom RPC Port?

texts:
I am trying to use the testrpc, and one of the solutions I found was to run testrpc in one terminal window, and then run Mist --rpc localhost:8545 in another. When doing this, the following warning pops up:

What exactly does this mean? Since it is a localhost, does this matter at all? I am running a private-net, so would anyone benefit from abusing the less secure state? What 'passwords' will be sent ove rthe wire as plaintext?


texts: Error: invalid address in solidity constructor

texts:
I get a huge error message (~1MB) starting with

Error: invalid address (arg="_readAccess", coderType="address", value={"constructor":{"contractName":"SenderAccess","abi":[...

when executing a test written in TypeScript:

it("should be possible to create such an option", async () => {
    const accessControl = await SenderAccess.new(); // OK
    const validator = await NumberRangeValidation.new(1, 5); // OK
    // This will crash
    const option = await NumberConfigOptionDefinition.new('foo.bar.baz', accessControl, accessControl, validator);
});

The contract looks like this:

contract NumberConfigOptionDefinition is ConfigOptionDefinition {
    NumberValidation public validator;

    constructor(string memory _name, AccessControl _readAccess, AccessControl _writeAccess, NumberValidation _validator)
        ConfigOptionDefinition(_name, _readAccess, _writeAccess) public {
        validator = _validator;
    }
}

contract ConfigOptionDefinition {
    ... fields ...

    constructor(string memory _name, AccessControl _readAccess, AccessControl _writeAccess) internal {
        name = _name;
        readAccess = _readAccess;
        writeAccess = _writeAccess;
    }

What did I do wrong?


texts: Create token exchange by defining decimal values

texts:
I've just learned a lot about Solidity and decided to put it into practice.
Something I truly don't understand is how I can bypass the limitations of this programming language.

Assume the following scenario:

We have some sort of ICO where users exchange their altcoins for our own coin, for instance CoinA.

Today CoinA = $1

Tomorrow we set CoinA = $1.5

After-tomorrow we set CoinA = $1.75

Let's assume for now that altcoins have a stable value:

Altcoin1 = $0.222

Altcoin2 = $0.7

The problem I have is that solidity doesn't allow us to use decimals. Answers that I found say to use all of the 18 decimals that Ethereum offers however I'm truly confused about that. Nobody shows a way to implement in a practical scenario.

Consider the following code:

pragma solidity ^0.4.24;
contract Ballot {
  uint256 icotokenPrice;
  mapping(string => uint256) tokensPrice;

  function assignICOPrice(uint256 _tokenPrice) public returns(bool){
    icotokenPrice = _tokenPrice;
    return true;
  }

  function createTokenPrice(string symbol_, uint256 price_) public returns(bool){
    tokensPrice[symbol_] = icotokenPrice / price_;
    return true;
  }

  function returnPrice(string symbol_) public view returns(uint256){
    return(tokensPrice[symbol_]);
  }
}

Brief description

assignICOPrice function allows us to manually assign "CoinA" from $1 to $1.5, to $1.75. The problem we have is that we can't do anything after . since uint256 are integers. How do we solve this problem?

createTokenPrice allows us to define the AltcoinPrice. For example, for Altcoin1 = $0.222 and for Altcoin2 = $0.7

Any proper solution to bypass this issue? I also tried to read EtherDelta's smart contract but it doesn't seem to have anything like that.


texts: What is the most popular IDE/text editor for developing solidity contracts?

texts:
Just trying to get a feel for which IDE's are most used and why. I have seen and used many of the tools available (Mix, Ether.camp, Visual Studio), but am looking to see input from Dapp developers as to why they chose their IDE.

I've found Mix to be very buggy (haven't used it in a month or so), and Ether.camp was a little tough to get used to. Haven't tried VS myself...


texts: How can I use an account created on a webpage?

texts:
I am developing an API in javascript and one of the method calls is to register an account. I use web3.js to create an account and then I return the public and private key of this account.

Another method call is to store a number in a smart contract. The user will send their account's public key and/or private key (open for suggestion) and the number they want to store. Using this the API will make a transaction from their keys and store the number in a smart contract.

So far I am able to generate the account and return the keys however when I try to deploy a contract using their keys I get the message "account not recognised". I am using Ganache for the test net.

How can I make a transaction using their account keys?


texts: Does 0x0 have a balance, and if so is it always 0?

texts:
I have a condition in a contract that checks if msg.value > patron.balance. At the top of the contract, I declare patron with address patron;. However, it is not set in the constructor, so patron should be the default 0x0.

Can I even call patron.balance if I don't set it in the constructor? And if so, can I rely on the balance of 0x0 to always be 0?


texts:
When i try to use ethAccounts() method of web3j it returns some object ..
so the question is how to get the output same as eth.accounts geth command ?


texts:
i have about 4k$ and want to invest in mining. so far i read about both gpu mining and asic.
my current choices are antminer z15 vs about 10 Radeon RX 570.
it look like z15 is better choice because better profit but gpu are more flexible for future use.
i still new to this want to hear experts opinion's
tnx for help


texts: Sending ETH or Tokens from the command line to be integrated in a PHP script

texts: I'm relatively new to using ETH on the command line. Do I use Geth or Parity? All I want to do is be able to send some ETH or Tokens from my eth private key. Which way is the best way to do it? I plan to integrate this into my php application, so I don't want to download the entire Ethereum blockchain. What is the easiest way to do this?


texts: How do I specify the network ID in the config file when migrating/testing contracts on my local ganache?

texts:
So my issue is when I run the compile and then migrate commands everything goes smooth, then I try to test by running the truffle test command and it gives me an error saying 'Error: The network id specified in the truffle config (4447) does not match the one returned by the network (5777)'. This is what is in my config file at the moment:

module.exports = {
  localGanache: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      from: '0xFE50B4F7B2921454E9204596b295d2B3648CF421',
      network_id: "5777",
      gas: 6721975
    },

Do I need to have a separate config file set up for testing? If so what does it look like?
Thanks in advance for help and sorry my newbie skills