texts: Strange Ethconsole Output for getbalance typo

texts:
I came across this when I made a typo checking my ETH balance from the ethconsole. I had incorrectly typed web3.eth.coinbase. I poked around and anything after web3.eth. that is a typo brought up a balance of 7088.445913801793117574.

I asked on Redit with the example of web3.eth.wololo and Nick Johnson posted to following response:

  web3.eth.wololo evaluates to undefined, and web3.eth.getBalance
  apparently treats undefined the same as 0 - so you're seeing the
  balance of account 0.

So, back to the console.  I have only 1 account and this is account 0.  I will post my outputs below:

c:\>geth --cache=1204 -rpc --datadir "f:\Ethereum" account list

  Account #0: {dd289578d8915156de085df3d03062335238a293} f:\Ethereum\keystore\UTC--2016-06-21T17-26-40.480551500Z--dd289578d8915156de085df3d03062335238a293

c:\>geth --cache=1204 -rpc --datadir "f:\Ethereum" --unlock 0xDD289578D8915156De085DF3d03062335238a293

!! Truncated !!

  Unlocking account 0xDD289578D8915156De085DF3d03062335238a293 | Attempt 1/3
  Passphrase:

  I1010 00:30:37.012616 cmd/geth/accountcmd.go:189] Unlocked account dd289578d8915156de085df3d03062335238a293

!!! Eth Console !!!

web3.fromWei(web3.eth.getBalance(web3.eth.wololo), "ether")

  7088.445913801793117574

web3.fromWei(web3.eth.getBalance(web3.eth.coinbase), "ether")

  15.9387038629625851

web3.eth.sendTransaction({from: web3.eth.wololo, to: '0xDD289578D8915156De085DF3d03062335238a293', value: web3.toWei(1, "ether"), gas:22000});

  (shell):4334: Error: account is locked
          throw errors.InvalidResponse(result);
                       ^
  Error: account is locked
      at Object.module.exports.InvalidResponse ((shell):2103:16)
      at RequestManager.send ((shell):4334:22)
      at Method.send ((shell):4002:59)
      at (shell):1:10
  Error: Uncaught Error: account is locked


texts: Is there any way to find out what exchange a ETH wallet was created?

texts: I added a ETH wallet address to Genesis Mining back in 2017 for a 2 year contract. After the contract was finished it still took them a year to add the ETH to said Wallet. (long story but I did not add a wallet until the last day of the contract and they were adding ETH to a wallet i did not create, then provided me that wallet address) so I have 5 eth in a wallet i believe i did not create. But I would like to figure out where it was created. I have all the other info Etherchain can provide, date first seen, date of deposit, block number etc... Just wondering if Eth blockchain adds where it was created from, location or exchange wise.


texts: Can I use Metamask with promise async calls instead of nested callbacks?

texts:
I'm trying to use promises instead of nested callbacks for better readabilty.
When I use this code:

balanceUpdate: function() {

    MyWallet.deployed().then(function(instance) {
     return web3.eth.getBalance(instance.address);
    }).then(function(walletBalance) {
      document.getElementById("walletEther").innerHTML = web3.fromWei(walletBalance).toNumber();
      return web3.eth.getBalance(account);
    }).then(function(accountBalance) {
      document.getElementById("accountEther").innerHTML = web3.fromWei(accountBalance).toNumber();
    }).catch(function(error){
      console.error(error);
      throw "Can't get balances"
    })
}

I got this error when Metamask is active:

Error: The MetaMask Web3 object does not support synchronous methods like eth_getBalance without a callback parameter. See https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#dizzy-all-async---think-of-metamask-as-a-light-client for details.

It works fine if I use a nested callback but I find it much less readable:

balanceUpdate: function() {

    MyWallet.deployed().then(function(instance) {

      web3.eth.getBalance(instance.address, function(error, result) {
        if (error) {
          console.error(error);
        } else {
          document.getElementById("walletEther").innerHTML = web3.fromWei(result.toNumber());
          web3.eth.getBalance(account, function(error, result) {
            if (error) {
              console.error(error);
            } else {
              document.getElementById("accountEther").innerHTML = web3.fromWei(result.toNumber());
            }
          }); // getbalance account
        }
      }); // getBalance instance.address
    }); // MyWallet.deployed
  }, // balanceUpdate

I've found this issue ("Promisify TxManager") on Metamask's github. Not sure if it's related.

Any suggestion how to avoid nested callbacks and be able to use Metamask the same time?

Even the samples on truffle sites are using promises. Is it possible that those samples won't work with Metamask?


texts: How can I initalise a contract with an array?

texts:
Is there any way I can give a list of values (array or mapping) to the constructor of a contract?

In the style of the following code:

contract myContract {

    string[] public myArray;

    function myContract(string[] myArray) {
        myArray = myArray;
    }
}

I currently get the message from the online compiler:

  Error: Internal type is not allowed for public or external functions.


texts: Query returned more than 10000 results with getPastEvents

texts:
I am writing a function to sync all transactions on a particular contract from a particular account in my local database to build a dashboard for account owners. I need to fetch all the past transfer events from the blockchain but I am getting the error that the call returned more than 10000 results sync function
syncTransactions(contract_address, owner_address, max_block) {
  const contract = new web3.eth.Contract(abi, contract_address);
  const from_block = max_block - 1000 >= 0 ? max_block - 1000 : 0;
  contract.getPastEvents(
    "Transfer",
    {
      fromBlock: from_block,
      toBlock: max_block,
    },
    (err, events) => {
      if (err) {
        console.log(err);
      }
      for (let i = 0; i < events.length; i++) {
        // check if 'to' or 'from' is equal to owner_account, if yes, add it to local database
      }
      syncTransactions(contract_address, owner_address, from_block - 1);
    }
  );
}

I haven't gotten to the point of filtering transactions using the given owner account. How can I avoid this error? Is there a better way to do this?
P.S. I have tried using both https and web socket URLs provided by Infura but getting the same error.


texts: Gasless transaction and easy token Solidity receiver callbacks for ERC-20 tokens

texts:
I am planning a token swap for an old pre-ERC-20 token. The new token will have its ledger smart contract written from a scratch. While doing it, I would like to integrate new EIP features to the token core itself.

Some features I hope to add

Easier approve() for smart contract interaction - permit() as done by MDAI, but could not find official discussion for this
Gasless transactions or somebody else pays the gas for txs
Anything that would support microtransactionsn easily or making token transactions scale

Are there any EIP proposals or other proposals out there for microtransactions that would require active support from the token?

Are there wallet support (MetaMask / WalletConnect) and standardisation for layer 2 that I should look into when upgrading the token contract?


texts: The relation between GAS price & Confirmation number

texts:
i know that the lower the gas price you set the longer it takes your transaction to be validated by the miners,, sometimes they don't even validate it when the price is too low.

But is there a relation between gas price set to a transaction and the number of confirmation the transaction needs to be validated??


texts:
Mist is synchronizing extremely slowly on Linux Ubuntu 15.10. Any way to speed it up?

Current info:

  Downloading block 1,081,182 of 1,521,138.

It's downloading like a few blocks per minute, tops at the moment. So I suppose I have to wait for maybe 50-500 weeks or so if the speed does not increase somehow.

Any particular reason why it's so slow?
Any way to speed it up?


texts: How do I implement an internally populated blacklist?

texts:
I'm writing a token contract that accepts and and issues varying  ether/token amounts via conditional statements  like so:

function getAirdrop() public payable {
    if (msg.value < 0.005 ether) {
       balances[msg.sender] += 4000;
    } else if ( (msg.value >= 0.005 ether) && (msg.value < 0.008 ether)) {
          balances[msg.sender] += 9000;
    } else if ( (msg.value >= 0.008 ether) && (msg.value < 0.016 ether)) {
          balances[msg.sender] += 13000;
    } else balances[msg.sender] += 25000;
}

How do I implement a blacklist in the first conditional to limit access like so:

mapping (address => bool) public blacklist;

 //  TODO:  function to clear blacklist    -----

 if (msg.value < 0.005 ether) {
       require(firstPurchaceTierAllowed);

   //  TODO:   Check if msg.sender is not blacklisted

       balances[msg.sender] += 4000;

   //  TODO:   Add msg.sender to blacklist
 }


texts: Truffle Error: ContractName has no network configuration for its current network id (1575203139857)

texts:
Im doing the tutorial at https://github.com/ConsenSys-Academy/proof-of-existence-exercise and running into the following error:

$ truffle console
truffle(development)> var poe = await ProofOfExistence2.at(ProofOfExistence2.address)
Thrown:
Error: ProofOfExistence2 has no network configuration for its current network id (1575203139857).
    at evalmachine.<anonymous>:1:48
    at Function.getter (C:\Users\mrleo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.js:243:1)
    at Function.get (C:\Users\mrleo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\contract\properties.js:129:1)
    at Function.getter (C:\Users\mrleo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.js:246:1)
    at Function.network (C:\Users\mrleo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\contract\properties.js:108:1)
truffle(development)> truffle(development)>


texts: Why I need the genesis file to join a network?

texts:
I created a private ethereuem network using geth, and now I want other machine to join my network, I try this command :

geth --datadir node1/ --syncmode 'full' --port 30304 --rpc --rpcaddr 'localhost' --rpcport 8504 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://20c47b4a7bd6d8383f87c1c988e601c7aa27ba7177b25d57e00794d1917c0c992dc37b93dfdf54741633179fd9a96a34fc2687d606ad48e2015ef2d958f3f0fb@10.2.1.124:30310' --networkid 1515 -unlock '0x6747efc15a7209763e840c8bbf381b721aeababd' --password node1/password.txt

But it doesn't sync with others nodes,
and when I copy the genesis.json from connected machine and run:

geth --datadir node1/ init genesis.json

than I repeated the first command line it works!

so I want to know why I must have the genesis.json of a network to join it?


texts:
Two times ethminer logged that it found a solution, like the one in the screenshot. But my account is still empty.

I start geth with: geth --rpc --rpccorsdomain localhost 2

On other screens on the net, there is much more info when a solution is found, like several hash values. Why is mine just displaying the nonce?


texts: Can we add block reward contract in parity aura latter on

texts:
We know there is an option to add a block reward contract to incentivize authors of new block by using blockRewardContractAddress at chain engine specs.

  Is it possible to add this property in the chain specs?

Considering that the chain is running for a long time without any block reward contract or any kind of block reward.


texts:
I was curious, and well am not a developer.

However I was wondering if someone could provide the code to create the /ethereum sent to an ico contract addresss/ API from etherscan.

Dcorp and several other ico's have used it, to keep track or their ico's success.
https://www.dcorp.it/crowdsale

I figure in the coding I would be able to change the contract address so I could monitor ico's as sort of a precursor to see whats hot though.


texts: Getting a loan on my Ethereum using the MakerDAO to get DAI. What are the risks and safe zone collateral needed?

texts:
I have 10 Ethereum and I read one can take a loan against it and use it as collateral using the MakerDAO service to get DAI tokens. I've never done this and want to make sure I'm doing it correctly.

My ETH is currently worth pretty much $1000 now. I want to take a loan out for $500.

What is my liquidation price where I lose all my ETH?
What is the interest rate on borrowing?
Does my interest rate change after borrowing for 1 year?
Do I have to make monthly payments?
What else does one need to know before doing this? Any gotchas I should be aware of?


texts: transferFrom error. Exception thrown in smart contract transaction

texts:
I compiled smart contract in solidity on remix.ethereum.org. I made account via MetaMask and want to let other addresses send tokens to themselves using ropsten network. I mean - I am contract owner = A, transfer some tokens to B and let him transfer/withdraw his tokens to address C. There are two transfer functions:

transfer, send tokens from contract owner to receiver address and it's working properly
transferFrom, is causing problems, send tokens from B to C.
I tried to use it via remix, write contract on etherscan and with web3.py but all of them return error.

Firstly I deployed contract with 1000000 tokens (1000.000 with 3 decimals) and sent 1000 (1.000) tokens to B (balanceOf(B) returned 1000), then called approve function with 1000 tokens for B address (allowance returned 1000), and called transferFrom, which threw errors:

remix: "Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
gas required exceeds allowance (8000029) or always failing transaction"
MetaMask on etherscan: "ALERT: Transaction Error. Exception thrown in contract code."

Another weird thing is sending tokens via transferFrom function from contract owner's address works properly like normal transfer. Also transfer exaclty 0 tokens from B to C works normally.
I can not figure out what is wrong, below is contract code:

pragma solidity >=0.4.22 <0.7.0;

contract AnotherCoin {

    string public constant name = "AnotherCoin";
    string public constant symbol = "ATC";
    uint8 public constant decimals = 3;

    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
    event Transfer(address indexed from, address indexed to, uint tokens);

    mapping(address => uint256) balances;

    mapping(address => mapping (address => uint256)) allowed;

    uint256 totalSupply_;

    using SafeMath for uint256;

    constructor(uint256 total) public {
        totalSupply_ = total;
        balances[msg.sender] = totalSupply_;
    }

    function totalSupply() public view returns (uint256) {
        return totalSupply_;
    }

    function balanceOf(address tokenOwner) public view returns (uint) {
        return balances[tokenOwner];
    }

    function transfer(address receiver, uint numTokens) public returns (bool) {
        require(numTokens <= balances[msg.sender]);
        balances[msg.sender] = balances[msg.sender].sub(numTokens);
        balances[receiver] = balances[receiver].add(numTokens);
        emit Transfer(msg.sender, receiver, numTokens);
        return true;
    }

    function approve(address delegate, uint numTokens) public returns (bool) {
        allowed[msg.sender][delegate] = numTokens;
        emit Approval(msg.sender, delegate, numTokens);
        return true;
    }

    function allowance(address owner, address delegate) public view returns (uint) {
        return allowed[owner][delegate];
    }

    function transferFrom(address owner, address buyer, uint numTokens) public payable returns (bool) {
        require(numTokens <= balances[owner]);
        require(numTokens <= allowed[owner][msg.sender]);

        balances[owner] = balances[owner].sub(numTokens);
        allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
        balances[buyer] = balances[buyer].add(numTokens);
        emit Transfer(owner, buyer, numTokens);
        return true;
    }
}

library SafeMath {
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
      assert(b <= a);
      return a - b;
    }

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
      uint256 c = a + b;
      assert(c >= a);
      return c;
    }
}

I tried compile it on different compiler versions (4.x, 5.x, 6.x) and compilation was succesfull but this
single function throw errors. Similiar topics on stack didn't bring the solution.


texts: Is it safe to publicly host a parity node?

texts:
In the normal use case, Parity runs on localhost.  However, I'm building a demo web site that uses Web3JS to connect to a public parity node running on port 8545.

I am publicly serving a Node/VueJS site using nginx.  The client-side Web3 javascript is looking at localhost:8545 which implies that the users needs to run Parity on their local machine for the page to work.

It is a hassle for users to install parity and setup a config file just to view this web page.

One thought I had was to run a public parity node on port 8545 to circumvent these extra steps. However, I'm concerned about safety.

Is this safe, and what are the recommended best practices for accomplishing this?


texts: Error on Truffle console - "missing ) after argument list"

texts:
while declaring a variable in truffle console error popped up. Code:-

var ss
undefined
truffle(development)> ScoreStore.deployed().then(function(deployd){ss=deployed;});
SyntaxError: missing ) after argument list


texts: Use React Dev Tool in developing MetaMask

texts:
I am new to MetaMask, and learning how MetaMask works. I found MetaMask UI was implemented with React, so I tried to use React Dev Tool, but I am not able get it working. Please help.

I started stand alone react dev tool (https://github.com/facebook/react-devtools/blob/master/packages/react-devtools/README.md)
I added a line <script src="http://localhost:8097"></script> in app/home.html
I used npm start to have it built in dist directory
I used Chrome Extension (developer mode) to load that directory.
I am seeing in Chrome console: Refused to load the script 'http://localhost:8097/' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".

I tried to manipulate app/Manifest.json, but failed to make it work.
I tried dozens of time on different combinations of "content_security_policy", and some time the React Dev Tool worked, but the MetaMask stuck at initial loading screen.


texts: using indistinguishability obfuscation to ensure smartContract privacy

texts: we all know the probelm of the public aspect of smart contract that harness the code privacy, do you think that  APPLYING  indistinguishability obfuscation to secure  smart contract code resolve this problem ??


texts: What's the difference between 'type' and 'callType' in parity trace?


texts: How would one divide a decimal by a decimal in solidity?

texts:
To calculate with x == .5 y == .6 (n)x / (n)y = z and the store the result z in uint (precision n == 1000)  ... how would I go about that in solidity?

I've read this How to do Solidity percentage calculation? ... but it is not directly helpful to me in dividing two percentages, because

  (100)x * (100)y /100  ===  does not come close to the float result
  (.8333).

I'm totally lost here.

The units x or y are not ether in my case


texts: MetaMask 9.5.0 has bug when transferring on test network?

texts:
I cannot transfer from my Account1 to Account2 in MetaMask using Send
either choosing "Transfer between my acccounts"
or pasting address for Account2
(that is valid and starts with "0x", e.g. just copied from metamask)
(Transfering to other people account had the same bug)

gives me the same error (see below)
"HBT Test" is not address, not even network type, this is actually name of main currency (not ERC20 token)
MetaMask encountered an error
Try again by reloading the page, or contact support here.
Error Details
Message: This method only supports 0x-prefixed hex strings but input was: HBT Test

Code: Error

Stack:

Error: This method only supports 0x-prefixed hex strings but input was: HBT Test
  at Object.r.assertIsHexString (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui.js:72:210305)
  at Object.r.toChecksumAddress (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui.js:72:201511)
  at _ (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui.js:152:653574)
  at h.render (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui.js:152:478592)
  at Ya (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:70734)
  at Ka (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:70529)
  at jl (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:105704)
  at bu (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:90053)
  at pu (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:89978)
  at iu (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:87326)
  at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:45768
  at r.unstable_runWithPriority (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:172:3472)
  at Vo (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:45477)
  at Yo (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:45713)
  at Ko (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:45648)
  at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:114643
  at ue (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:114649)
  at fe (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:5411)
  at Rr (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:29682)
  at Cr (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:30610)
  at Tr (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:29898)
  at r.unstable_runWithPriority (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:172:3472)
  at Vo (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:45477)
  at le (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:114479)
  at Er (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/ui-libs.js:75:29321)
  at HTMLDocument.c (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/initSentry.js:1:10460)


texts: Why do we need to keep state trie? Only for the computation speed?

texts:
I'm studying solidity these days and came up with this silly question.
Is there any other reason why every node is maintaining state trie?


texts: How can I create a new account or address with web3.js?

texts: I'm trying to interact with geth, and I need to create a new deposit address (and be able to control it). How can I implement this with web3.js?


texts: geth console hangs after sendTransaction

texts:
So, first of all, I want to clarify that I'm doing the transaction without the blockchain updated in my computer (I've read you can send transactions without it being updated).

This is my code:

eth.sendTransaction({from: sender, to: receiver, value: ether_available - gas, gas:gas, nonce:2})

Where sender is my address, receiver is the receiver, value is my total amount of ethereum minus the gas, and the gas is basically 50gwei * 21000 (all converted). My account only have 2 outer transactions so I set the nonce to 2, as I've read in a reddit post.

After executing the command, the console hangs and nothing happens (waited for 15 minues) until I do ctrl+C, then it says Error: authentication needed: password or unlock, but I first did personal.unlockAccount(eth.coinbase) and got True as response.

Someone knows if this is normal? Should I re-download all the blockchain and try again? (I know from the past that downloading the whole blockchain is a pain in the ass).


texts:
Where is the information on the tx package build protocol? Bitcoin as an example, Bitcoin Wiki - Protocol Documentation: tx
Is there an example of serialization for python like this answer to How to redeem a basic Tx?

All that was found in Google, were using different libraries.


texts: In remix ide, we have UI designed in such a way that we can pass ether or Wei directly and execute the functions.  When we use truffle to deploy the contract, how can we pass ether?


texts: Sign message with web3 and verify with openzeppelin-solidity ECDSA.sol

texts:
I'm trying to get a little example working with ECDSA.sol here: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol

This contract:

Generate a random(ish) bytes32 (stub for a future message digest).
Morph it into an EthSignedHash with keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
Use ecrecover to work out who signed a message.

pragma solidity 0.5.8;

import "../../node_modules/openzeppelin-solidity/contracts/cryptography/ECDSA.sol";

contract Sigs {

    using ECDSA for bytes32;

    function rndHash() public view returns(bytes32) {
        return keccak256(abi.encodePacked(block.number));
    }

    function ethSignedHash(bytes32 messageHash) public pure returns(bytes32) {
        return messageHash.toEthSignedMessageHash();
    }

    function recover(bytes32 hash, bytes memory signature) public pure returns(address) {
        return hash.recover(signature);
    }
}

On the client side:

Conjure up a random(ish) message.
Make an ethHash of the message.
Sign it.
Send ethHash and the signature to ecRecover and get the signer address.

I'm not sure what I'm missing. I think the original message hash should be signed and EIP-712 does the "Ethereum Signing", so I should send the "Ethereum Hash" to ecrecover (as implemented in ECDSA.sol). In any case, no combination brings any joy.

var Sigs = artifacts.require("./Junk/Sigs");

contract("Sigs", accounts => {

  var signer;

  beforeEach(async () => {
    signer = accounts[0];
    sigs = await Sigs.new({from: signer});
  });

  it("should recover signer address.", async () =>  {

    console.log("SIGNER: ", signer);

    var random  = await sigs.rndHash({from: signer});
    var ethHash = await sigs.ethSignedHash(random);

    // four possible combinations tried for the next step :/
    var signature = await web3.eth.sign(random, signer);    // sign the random hash or the ethHash
    var recovered = await sigs.recover(ethHash, signature); // recover from the random hash or the ethHash

    console.log("random1: ", random);
    console.log("signature: ", signature);
    console.log("recovered: ", recovered);

    assert.strictEqual(recovered, signer, "The recovered signature does not match the signer.");

  });
});

I'd be very grateful if someone can sort me out.

Truffle v5.0.41 (core: 5.0.41)
Solidity - 0.5.8 (solc-js)
Node v8.10.0
Web3.js v1.2.1

Thanks!

Update

For anyone else who happens across this, this is the revised, passing test.

const Sigs = artifacts.require("./Junk/Sigs");
const EthCrypto = require("eth-crypto");

contract("Sigs", accounts => {

  var signer;

  beforeEach(async () => {
    signer = accounts[0];
    sigs = await Sigs.new({from: signer});
  });

  it("should recover signer address.", async () =>  {

    console.log("SIGNER: ", signer);

    var message = "0x1234";
    console.log("message: ", message);
    var msgHash    = await sigs.messageHash(message);
    var ethHash = await sigs.ethSignedHash(msgHash);

    var signature = await web3.eth.sign(msgHash, signer);    // sign the mesage hash
    signature = signature.substr(0, 130) + (signature.substr(130) == "00" ? "1b" : "1c"); // v: 0,1 => 27,28
    var recovered = await sigs.recover(ethHash, signature); // recover from the ethHash

    console.log("msgHash: ", msgHash);
    console.log("ethHash: ", ethHash);
    console.log("signature: ", signature);
    console.log("recovered: ", recovered);

    assert.strictEqual(recovered, signer, "The recovered signature does not match the signer.");

  });
});


texts: Problem with deploying contract on BSC Test net

texts:
I'm new here. I want to deploy a contract on the BSC test net thru remix. The code is below. I'm running into a problem "This contract may be abstract, not implement an abstract parent's methods completely or not invoke an inherited contract's constructor correctly."
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this;
        return msg.data;


texts: Function to Retrieve Tokens from Contract fails

texts:
In case people send ERC20 tokens to my contract, I want to be able to retrieve them. Hence the following function:

/**
   * @dev Allows owner to transfer ERC20 tokens to vault
   * @param _token the contract address of the ERC20 contract
   */
  function retrieveTokens(address _token) public onlyOwner {
    ERC20 erctoken = ERC20(_token);
    erctoken.transfer(Vault, erctoken.balanceOf(this));
  }

On Ropsten testnet, I successfully sent some tokens to the contract. Then I run the above, but it fails.  (It used very little gas and did not run out.  I entered a gas limit of 6000000, which was much more than needed.)

In remix.ethereum.org (with Injected Web3), I get the following error:

  transact to browser/Test.sol:TestSale.retrieveTokens errored: Gas
  required exceeds limit: 4000000.  An important gas estimation might
  also be the sign of a problem in the contract code.  Please check
  loops and be sure you did not sent value to a non payable function
  (that's also the reason of strong gas estimation).

In remix.ethereum.org (with Javascript VM), I'm getting the following error:

  from:0xca3...a733c,
  to:broswer/Test.sol:TestSale.retrieveTokens(address) 0x643...62e55,
  value:0 wei, data:0xac4...95963, 0 logs, hash:0xe76...c0094

  transact to browser/Test.sol:TestSale.retrieveTokens errored: VM
  error: invalid opcode.
       The constructor should be payable if you send value.
       The execution might have thrown.
       Debug the transaction to get more information.

How do I fix this?  I'm not sending any value when I call this transaction.

I copied the code from TenX and modified it for my Solidity smart contracts. You can see all of my code at https://gist.github.com/anonymous/3497e6b4e09953a009a4fdbacd11946a


texts: What is BlockApps and how can it be used with Ethereum?

texts:
BlockApps says:

  Customized, permissioned private Blockchain ledger to your
  specifications. Based on Turing-complete Ethereum standards, your
  Blockchain has full Smart Contract support built-in.

How can BlockApps be used with Ethereum?  How can these customized, private blockchains be used with Ethereum?  How can contracts in a private BlockApps chain invoke a contract on Ethereum?


texts: Receive Ethereum payments on eCommerce website

texts:
I am working on receiving ether on existing ecommerce site. For whatever reason, a decision has been made to run Ethereum node locally and not use any existing payment gateways.

I am relatively new to Ethereum. Based on what I read across forums, I can think of 2 possible approaches:

Approach 1:
For each eCommerce transaction on website, create a new contract and hand over its address to the customer to make payment to.
Periodically check balance on the contract address, if balance is > 0 - this implies that payment has been made.
Send payment from contract address to another main account address to consolidate payments.

Approach 2:
For each eCommerce transaction on website, create an account private key + address and hand over its address to the customer to make payment to.
Periodically check balance on the above address, if balance is > 0 - this implies that payment has been made.
Send payment from contract address to another main account address to consolidate payments.

I am wondering if approach 2 is even worth considering. I am looking for some expert guidance here on how best to do it, given the restriction that local Ethereum node is to be used.

Thanks for your help.


texts: Where is the function that rewards the miner address for mining the block?

texts:
I have recently been digging into go-ethereum and have 'plugged' my own consensus mechanism which requires a node to solve a simple equation (2+2) etc to seal a block.

However, even after letting it run to 4392 blocks the miner address still has not received any eth?

Can someone point me in the right direction such as documentation of where the reward is given in the codebase? I cannot seem to find it. Cheers!


texts:
I have 3 libraries, one exposes struct and 2 others expose method with same signature/return type (first one provides default method implementation and second - extended and customized one). When trying to compile it I got error TypeError: Member "transfer" not unique after argument-dependent lookup in struct TypesLib.MyToken storage ref.

Is it possible to override function from one library in another? usings order change doesn't affects anything in my case.

Here is examples:

TypesLib.sol:

library TypesLib {
    struct TokenStorage {
.....
    }
}

DefaultLib.sol

import "./TypesLib.sol"

library DefaultLib {
    function transfer(TypesLib.TokenStorage storage self, address to, uint256 amount) public returns (bool) {
        ... default implementation ...
    }
}

CustomizedLib.sol

import "./TypesLib.sol"

library CustomLib {
    function transfer(TypesLib.TokenStorage storage self, address to, uint256 amount) public returns (bool) {
        ... custom implementation ...
    }
}

Contract.sol

import "./TypesLib.sol"
import "./DefaultLib.sol"
import "./CustomizedLib.sol"

library CustomLib {
    using DefaultLib for TypesLib.TokenStorage;
    using CustomizedLib for TypesLib.TokenStorage;

    TypesLib.TokenStorage token;

    function transfer(address to, uint256 amount) public returns (bool success) {
        return token.transfer(to, amount)
}


texts: Calling public array of structs using web3

texts:
Good day.

I've got an array of structs such as:

User[] public users;

struct User{
    uint idNum;
    string name;
    address userAddress;
}

And I'm trying to get the array of users with web3.js using:

contract = web3.eth.contract([ABI]).at("0x0..");
var users = contract.users();

So far everything works fine, but when I'm trying to get the size of the array I always gets 3 - I assume it only counts how many fields each user have but what I want is to count how many users are there.

I understand the The variable "users" (in JS) is a function and not an array per se, but I just can't find any way to directly interact with the array.


texts: Unexpected behaviour. Huge size increase when adding new SubContract()

texts:
I have a contract similar to:

contract Contract01 {
  SubContract _refContract;
  ...
   constructor() public {
      refContract = new SubContract();
   }

   function setSubContractRef(SubContract refContract) {
      _refContract = refContract;
   }
}

When I add the new SubContract() the bytecode increase is "huge" since it looks like the byte code of the SubContract is also increased. This causes the max-contract size to be reached with easy.

I found it's possible to create a SubContract in a different TX and pass the reference to Contract01 in setSubContractRef, but I'm wondering whether there is a simpler way involving fewer steps.


texts:
Taking eth_getLogs as an example. Here's the original POST data:

{
    "id": 67,
    "jsonrpc": "2.0",
    "method": "eth_getLogs",
    "params": [{
        "fromBlock": 3138480,
        "toBlock": 3138482,
        "topics": ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]
    }]
}

If I do that I get:

"error": {
    "code": -32602,
    "message": "invalid argument 0: hex string without 0x prefix"
}

With:

"params": [{
    "fromBlock": "0x2fe3b0",
    "toBlock": "0x2fe3b2",
    "topics": ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]
}]

It works okay. 0x2fe3b0 is the hex representation of 3138480, while 0x2fe3b2 is for 3138482.

The question is if this is the case for all geth calls?


texts: Etherbase/Coinbase account of private net is changed automatically

texts:
I am testing on a privatenet, and as I started the chain I have set the etherbase using miner.setEtherbase. However after few hours I see that my etherbase is changed automatically.

  eth.coinbase
  "0xd9ee4d08a86b430544254ff95e32aa6fcc1d3163"

  eth.accounts
  ["0xc53f820bf0b95d0da114d0ca657dfa00fdf731df"]

I don't have any peers and do not have the culprit account even in my keystore.
Could someone help me on this. This happend in out test region and I need to make sure it will not happen in production.


texts:
Smart contracts in Ethereum must be deterministic so that nodes can achieve consensus.

There are implementations of smart contract based auctions where there is a fixed auction time.

But how do nodes achieve consensus when there is no shared clock, if the block is mined near the end of an auction: some nodes may process the block before the end of the auction, and others after the end of the auction?


texts: Updating data in ethereum Blockchain using Javascript

texts:
Suppose I'm having a form wherein I'm taking Name, Password and EmailID and I get the values. How will I be able to update/reflect the data in the ethereum blockchain?

In truffle console, it is
UserInfo.then(function(instance){return instance.addPeople("Name", "Password", "Email";}) which would essentially update the data.

Is it possible to write a JSX code exactly as this?


texts:
The question it's How store Ether in a smart contract.

In first step, I try transfer the transaction value to the smartcontract address  doing something y something like that:

function storeETH() payable public {
   address(this).transfer(msg.value);
}

I have the address but I think that isn't a wallet... I don't know how store ETH in my smart contract or if exist the possibility to do something like that.

Please, help me :D


texts: Strange transactions that get all balance from account on test network

texts:
I am writing smart contract and I test on rinkeby network. I have issued about 18 ethereums from faucet. But after a short time, there are 2 strange transactions: one getting 15eth and one getting 3eth from my account. Here is transaction detail:

https://rinkeby.etherscan.io/tx/0xc4829a6c8765a11c364abfe4370bfc5c42db8f4f30a750185249cd423a836242

https://rinkeby.etherscan.io/tx/0x6123a4af9dfd7eb06bab18bef5b0db729bfefe49df09710dcac8fab52127a08c

My address is: 0x627306090abab3a6e1400e9345bc60c78a8bef57. You can view my transaction detail here (from the time I issue 18eth):
https://rinkeby.etherscan.io/address/0x627306090abab3a6e1400e9345bc60c78a8bef57

So, what is my problem here ? I afraid if "something wrong" and I don't know, I will lost more money on main network.

Thanks


texts:
I'm in https://poocoin.app/ to follow some charts of a meme token and found this message in red "An unlocked wallet is holding 100% of  LP".
By following the link I ended in a PancakeSwap LP page of that pair with just 2 holders.
Is this token somehow vulnerable to any exploit until the owner lock it (whatever this means) ?


texts: I have some bytecode and would like to find the contract address that it belongs to. Is there an easy way to do this?


texts: Delegatecall Scope - Correct me if I'm wrong

texts:
When any contract function is called - delegatecall or otherwise - the EVM loads the requisite pointers & values into that call frame's volatile stack/memory.

Example:
Let's say we have contract A delegatecalling to contract Delegate.

Unless you explicitly:

a) align both the caller+delegate contract storage

b) explicitly pass in the caller contract's storage reference addresses
     as arguments to use in the function's call frame

your storage pointers are left up to the Delegate's standard function context.

Any correction/insight on this front is appreciated. Thank you.


texts: Error: CompileError: InternalCompilerError: Stack too deep, try removing local variables

texts:
Hello everyone please kindly help me out. I have researched on the error above associated with this block of code. But please is there a way to revise this code so that i can get all the data of a patient from a single struct. How would you advice I approach this

pragma solidity >=0.4.21 <0.7.0;

contract Patients {
    uint256 public count = 0;
    struct Patient {
        bytes16 patientID;
        bytes16 title;
        bytes16 fullName;
        bytes16 dob;
        bytes16 gender;
        bytes16 contact;
        bytes16 residentialAddress;
        bytes16 relativeNumber;
        uint256 NHIS;
        uint256 temperature;
        uint256 bloodPressure;
        uint256 pulse;
        uint256 respiration;
        uint256 weight;
        uint256 bmi;
        bool appointment;
    }

event created(string message);

mapping(uint256 => Patient) public patient;

  function setBio(bytes16  patientID, bytes16  title, bytes16  fullName, bytes16  dob, bytes16  gender, bytes16  contact, bytes16  residentialAddress, bytes16  relativeNumber, uint256 NHIS) public {
    count++;
    patient[count].patientID = patientID;
    patient[count].title = title;
    patient[count].fullName = fullName;
    patient[count].dob = dob;
    patient[count].gender = gender;
    patient[count].contact = contact;
    patient[count].residentialAddress = residentialAddress;
    patient[count].relativeNumber = relativeNumber;
    patient[count].NHIS = NHIS;
    emit created('New Patient folder created');
  }

  function getBio(uint256 index) public view returns(bytes16  patientID, bytes16  title, bytes16  fullName, bytes16  dob,bytes16  gender, bytes16  contact, bytes16  residentialAddress,bytes16  relativeNumber, uint256 NHIS){
    Patient memory p = patient[index];
    return(p.patientID, p.title, p.fullName, p.dob, p.gender, p.contact, p.residentialAddress, p.relativeNumber, p.NHIS);
  }

  function setVitalSigns(uint _id, uint256 temperature, uint256 bloodPressure, uint256 pulse, uint256 respiration, uint256 weight, uint256 bmi, bool)public {
    Patient memory _patient = patient[_id];
    _patient.temperature = temperature;
    _patient.bloodPressure = bloodPressure;
    _patient.pulse = pulse;
    _patient.respiration = respiration;
    _patient.weight = weight;
    _patient.bmi = bmi;
    _patient.appointment = !_patient.appointment;
    emit created('Vital Signs Checked');
  }

}


texts:
I have question
My geth show me like that "Deep froze chain segment" repeatedly

What mean??


texts: Accessing past values of Smart Contract variables

texts:
I would like to know if is possible to inquiry variable values using older blocks.

For example I have

contract Simple {
    string32 message public;

    function Simple() {
        message = msg.sender;
    }
}

Is it possible to retrieve the value of the message 1 month ago? Is there a method that let me inspect such variable on particular blockheight?

Is there a method that retrieves all different values that are found on the blockchain?

Thank you very much.


texts: How to convert plain text string variable to bytes32 variable? And how to store bytes32 in one variable after converting?

texts:
pragma solidity ^0.4.25;

contract Purchase {
    address public sellerAddress;

    constructor (address _sellerAddress) {
        sellerAddress = _sellerAddress;
    }
}

contract Buyer is Purchase {
    address public buyerAddress;
    string pass;
    bytes32 hashpass;

    modifier onlyBuyer() {
        require(msg.sender == buyerAddress);
        _;
    }

    constructor(string _pass) {
        buyerAddress = msg.sender;
        pass = _pass;
    }

    function stringToBytes32(string pass) returns (bytes32 hashpass) {
        hashpass = bytes32(pass);
    }

    function generateHashPass() public {

    }
}


texts:
Having trouble accessing Metamask's web3 object.

Following the recommended guidelines for using Metamask's injected web3 object
https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#partly_sunny-web3---ethereum-browser-environment-check

Shouldn't this avoid a possible race condition?

 componentDidMount() {
         window.addEventListener('load', function() {

         // Checking if Web3 has been injected by the browser (Mist/MetaMask)
            if (typeof web3 !== 'undefined') {
                 // Use Mist/MetaMask's provider
                 window.web3 = new Web3(web3.currentProvider);
             } else {
                 console.log('No web3? You should consider trying MetaMask!')
                 // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
                 window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
         }
         })
    }

Still...


texts: evaluation of execution speeds for various opcodes in EVM


texts: How to convert string to bytes32 properly?

texts:
In my solidity I'm using a mapping like this:

mapping(bytes32 => uint) items;

constructor() {
   items["test"] = 2;
}

function getItem(bytes32 key) returns(uint) {
   return items[key];
}

My question is now how to call the function in JS using web3 1.0? I have to convert the string to hex. Using web3.utils.stringToHex("test") gives me 0x74657374. Using that I'm getting invalid bytes32 value. The function web3.utils.asciiToHex returns 0x7465737400000000000000000000000000000000000000000000000000000000 which looks for me like a different value. The function call succeeds but I don't get the expected result value of 2.
I also tried web3Utils.padLeft(web3Utils.stringToHex(params[index]), 64); which gives 0x0000000000000000000000000000000000000000000000000000000074657374. Function call succeeded but result value is also 0 not 2.


texts: Solidity function gas requirement is infinite

texts:
struct userData{
     uint val;
     bool isvalue;
     string name;
}

mapping(uint => address) internal users;
mapping(address => userData) internal bidirectionalUsers;

function addMember(address newMember, string memberName) public{

        if (msg.sender != owner) return;

        if (bidirectionalUsers[newMember].isvalue) return;

        users[memberCount] = newMember;
        bidirectionalUsers[newMember] = userData(memberCount,true,memberName);

    }

Above code is throwing warning in addMember(), gas limit is high:infinite and it can not be executed.

I commented all the lines inside the function but still it throws this warning. What I'm doing wrong here? Can somebody help me in this. Thank you.


texts: Are regions a factor in downloading current Ethereum blocks?

texts:
We are currently having some problems syncing our nodes. Our server is located at the Asia Pacific region. Earlier our servers where in Azure and we don't have any troubles syncing. It has been 3 weeks that we are still behind for about an average of 70 to 100 blocks, in addition we are capped at 10mbps and our hard disk is SSD (1TB) but were not seeing any signs of completing the sync anytime soon. We are using geth's latest version 1.8.23. The parameters are:

geth.exe --syncmode "fast" --networkid 1 --datadir=<location> --rpc --rpcport "8545" --rpcaddr "127.0.0.1" --rpccorsdomain "*" --rpcapi "eth,web3,personal,net,miner,admin,debug,txpool" --cache=1024 --maxpeers 100

Have anyone encountered this issue specifically users in Asia Pacific? Is there anything that we can do to speed up the syncing?

Thanks in advance!


texts: How to create a token smart contract that sends tokens after recieving payment in ether?

texts: Hey everyone I am launching an ICO. I need to create a smart contract that holds a certain amount of tokens that I created. Then when ether is sent to the smart contract address for my token. It will send back my created tokens ether equivalent value to the sending address? I also need to set the value of the tokens to .5 usd or whatever the equivalent is in ether? The contract then should send the ether to my private address.  Can anyone help me or point me to some info. Thanks!


texts: erc20 and tokensale how to use interface

texts:
I have ERC20 interface copied from here link - zeppelin
Now, I have a contract called ERC20 which looks like this:
contract ERC20Token is IERC20 {

   uint8   public decimals = 18;

   // other part of the code.

}

Now, I have a tokenSale contract which actually has to sell tokens..
contract TokenSale {
    IERC20 public tokenContract;

   constructor(IERC20 _tokenContract, uint256 _price) public {
      tokenContract = _tokenContract;
      //some other code.
   }

   // now in one of the functions, I need to use tokenContract.decimals() . This is for the fact
   // that users can still pass the actual token amount, but the check is like this:

   uint256 scaledAmount = safeMultiply(numberOfTokens,
            uint256(10) ** tokenContract.decimals());

   // this scaledAmount is the value that I have to give to the buyer, since I am using decimals.

Okay.. The problem now is:

Member "decimals" not found or not visible after argument-dependent
lookup in contract IERC20.

That's understandable of course, but I want to find a better way to fix this. I don't want to change IERC20 interface, since it's standard and I am 100% following it.
One way would be that I create another interface which has decimals() in it and this interface inherits from the IERC20 , but of course, interfaces can't inherit in solidity.
What would the best way be to fix this?


texts: Compilation failed during instrumentation of solidity-coverage

texts:
Getting compilation failed error, while running solidity-coverage.  Truffle compile is working fine.
Here is my truffle config:
module.exports = {
  networks: {
    coverage: {
      host: '127.0.0.1',
      network_id: 5777,
      port: 8555,
      gas: 0xfffffffffff,
      gasPrice: 0x01
    },
  },
  compilers: {
    solc: {
      version: '0.5.10',
      settings: {
        optimizer: {
          enabled: true,
          runs: 200
        }
      }
    }
  },
  plugins: ["solidity-coverage"]
};

.solcover.js:
module.exports = {
  port: 8555,
  norpc: true,
  deepSkip: true,
  compileCommand: '../node_modules/.bin/truffle compile',
  testCommand: 'node --max-old-space-size=4096 ../node_modules/.bin/truffle test --network coverage',
  skipFiles: [
    'imports',
    'EventCaller.sol',
    'dummyDaiFeed.sol',
    'mocks'
  ],
  forceParse: [
    'imports/ERC1132',
    'mocks'
  ]
};

Command used to run coverage: node_modules/.bin/solidity-coverage
Getting this error only while running coverage:
* Line 1, Column 1
  Syntax error: value, object or array expected.
* Line 1, Column 2
  Extra non-whitespace after JSON value.
Compilation failed. See above.

Error occurred during the compilation after the instrumentation was completed.


texts: Usage of memory, storage and stack areas in EVM

texts:
In solidity contracts, I can understand that based on variable usage and expensiveness, I can determine that which one should use (memory, storage or stack). But I faced some situations where only memory can be used and like that.

So my question is:

Where only memory can be used?
Where only storage can be used?
Where only stack can be used?

I couldn't find any documentation that states specific area should be used in any specific situation.

Thanks


texts: Mist- Couldn't connect to node? See logs for more:

texts:
I was trying to launch Mist after a long time and I was hit bye error popup stating:

  Couldn't connect to node? See logs for more: Node Type: geth Network:
  main Platform: linux (Architecture x64)

  ..flag provided but not defined:-support-dao-fork

Have never faced the issue. I have been using the same wallet (v0.8.6).


texts: Truffle migrate Error Invalid number of arguments to Solidity function

texts:
Truffle 4.0.1

I've got a contract declared "is Pausable" (OpenZeppelin framework) and I want to pause it as part of the deployment logic.

I'm getting an error, however, when invoking pause()

Error: Invalid number of arguments to Solidity function
    at Object.InvalidNumberOfSolidityArgs (/Users/sofend/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/build/cli.bundled.js:43290:16)

The code seems straight-forward enough:

const MyContract = artifacts.require("./MyContract.sol");

module.exports = function (deployer, network, accounts) {

    const owner = accounts[0];

    return deployer.deploy(MyContract, {from: owner})
        .then(function () {

                  return MyContract.deployed().then((instance) => {
                      // pause the  contract
                      instance.pause(/*{from: owner}*/)    // I've tried it passing in the from: owner; tried it with call() etc.
                          .catch(function (error) {
                              console.error(error.stack);
                          })
                      ;
                  })
                      .catch(function (error) {
                          console.error(error.stack);
                      })
                      ;
              }.catch(function (error) {
                  console.error(error.stack);
              })
        );
};

And have tried variations of the call to pause():

.pause.call()

.pause({from: owner})

.pause.call({from: owner})

but all give the same error: Invalid number of arguments to Solidity function

The pause() function isn't declared to take any parameters.

What am I doing wrong?


texts: Access deployed smart contract using web3.js

texts:
I am new to Etherium smart contracts. I have created a smart contract and deployed it on https://kovan.etherscan.io. Now I am trying to access this contract from node js. below is my code but I am not getting how to set provider and further things. Can anybody help me with this?

const Web3 = require('web3');
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546', null, {});

module.exports = {
        tmp1: function (req, res, next){
                try{
                        Image(req,res)
                }
                catch(err){
                        console.error(err)
                }
        }
}
function Image (req,res){
        const abi =[{ my json of abi}];
        var contractInstance = web3.eth.contract(abi).at('0xB02542CF6C19B70813694EB9CFD60C10a796d83f');
        var result = contractInstance.buyCoordinator(req.query.coordinator,req.query.coimage).call();
        console.log(result);
        res.send(result);
}

I am totally confused about how to set provider https://kovan.etherscan.io and how exactly it will work or know that I have deployed contract here and my account address.


texts: Why borrow DAI from compound has lower rate than borrow USDT?

texts:
As shown in the figure, borrowing Tether from compound have 10.73% APY, while borrow DAI from compound only have 4.64%.
However, we can exchange DAI or USDC to Tether in any exchange very easily, so such an APY premium for USDT should not exist. A big difference in APY should be arbitraged until there is not much difference. For instance, one could borrow USDC, exchange it for USDT and deposit that USDT at a higher rate than the USDC borrow. After some time, the APY difference would subside. But this is not happening.
Why is the interest rate gap between the two currencies so big?


texts: What happened to eth.pendingTransactions ? Is there an equivalent?

texts:
I am just interested in the number of pending transactions which I usually get from Etherscan , I have seen references to eth.pendingTransactions online but I cannot find that or an equivalent in the api reference.

Is there any other place I can access that value programmatically?


texts: Quorum -- Is Raft more scalable in terms of TPS compared to Istanbul BFT (IBFT)?

texts:
This question is on Quorum, the enterprise flavour for Ethereum.

Understand that BFT algorithms are always prepared for the worst possible circumstances and pays a price for this in terms of speed.

Can one reasonably make the statement / assessment that Raft is more scalable in terms of TPS compared to Istanbul BFT (IBFT)?

Nathan Aw


texts: Transactions not going through(Rinkeby testnet)

texts:
I'm new to Ethereum development. I set up the mist Ethereum wallet with rinkeby testnet for contract deployment. All worked good I could send transactions and write to the smart contract but at some point my transactions stopped going thru. They are stuck at pending status.

Why are my transactions not going through?
How can I troubleshoot issues like this in the future?

Example of transactions that are not being accepted:executing a smart contract

My address https://rinkeby.etherscan.io/address/0x3b28b9547633ecebb76a6e3d47f5b2b6a22d85a9

Four days ago all transactions were accepted but none of my transacations since are going through.

edit: Seems like the transactions I have been doing for the past 3 days just went through. Does it mean my transactions were in the pool for 3 days?


texts: Truffle console: Accessing contract using an account other than owner

texts:
I have the following contract:
pragma solidity >= 0.5.0 < 0.7.0;

contract SimpleContract {
  string  public name;
  address private owner;
  constructor() public {
     name = 'abs';
     owner = msg.sender;
  }
  function getName() public view returns(string memory) {
      return (name);
   }
   modifier onlyOwner(){
      require(msg.sender == owner);
      _;
   }

   function changeName(string memory _name) public onlyOwner{
      name = _name;
   }
}

It works if I access through the owner's account:
truffle(development)> await SimpleContract.getName()
‘abs’

But I want to access the functions through a non-owner. I am trying the following:

truffle(development)> await SimpleContract.start({from: web3.acc1})
Thrown: TypeError: SimpleContract.start is not a function
at evalmachine.:1:24
truffle(development)> await
web3.eth.accounts[1].SimpleContract.getName(); Thrown: TypeError:
Cannot read property 'SimpleContract' of undefined
at evalmachine.:1:30 reentrancy:

Somebody please guide me how to access the contract using a non-owner.
Zulfi.


texts: What is wrong with the 'sell' and 'buy' token functions in my contract?

texts:
There is my solidity

function buyTokens(uint256 _numberOfTokens) public payable {

    // Require that value is equal
    require(msg.value == multiply(_numberOfTokens, tokenPrice));

    // Require token contract has enough tokens
    require(tokenContract.balanceOf(this) >= _numberOfTokens);

    // Require transfer is successfull
    require(tokenContract.transfer(msg.sender, _numberOfTokens));

    // Keep track tokensSold
    tokensSold += _numberOfTokens;

    // track Sell event
    emit Sell(msg.sender, _numberOfTokens);
}

function sellTokens(uint256 _numberOfTokens) public payable {

    // Reuqire that value is equal
    require(msg.value == multiply(_numberOfTokens, tokenPrice));

    require(tokenContract.transferFrom(msg.sender,this, _numberOfTokens));

    tokensSold -= _numberOfTokens;

    uint amountEther = multiply(_numberOfTokens, tokenPrice)/(10**18);

    uint amountEtherToSend = address(this).balance - amountEther;

    msg.sender.transfer(amountEtherToSend);

    emit Sell(msg.sender, amountEther);
}

For ex 1 ABC token = 0.01 ETH.
If I send 0.1 ETH I will send to sender 10 ABC token. It works fine
Now we have 0.1 ETH in our wallet.
That seller sells 5 tokens but seller receive all ETH from wallet.
Can you help me fix sellTokens Function ?


texts: Wrong estimation of gas while contract deployment

texts:
I have a smart contract:

pragma solidity 0.5.3;

import "./ERC20.sol";

contract Transfer {

  ERC20 private erc20iface;
  address private _owner;

  modifier validOwner() {
    require(msg.sender == _owner);
    _;
  }

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

  function () external payable {}

  function transferTo(address[] memory receivers, uint[] memory amounts, address token) {
    //Some code uses ERC20 methods/or simple transfers with .call()
    }
 }

When I try to deploy the contract in Remix
it shows the transaction cost = 424652 gas.
However when I try to estimate gas limit with web3 .estimateGas()

const contractData = {
      data: '0x123',
      arguments: []
    };

    const contract = new web3.eth.Contract(CONTRACT_ABI).deploy(
      contractData
    );
    const gasLimit = await contract.estimateGas();

I get gasLimit = 409652
And when I try to deploy, I receive an error: Out of gas

But if I use the amount of gas from Remix (424652) it works fine.

What can be the reason of such differences (15000 gas, like if .estimateGas is missing ERC20 import)? And how to estimate the gasLimit with .estimateGas() correctly?


texts:
How to add a node to the Ethereum Network Status page?

Does that not happen automatically? What is required to get listed on that page?


texts:
I'm trying to call a contract method from the web3 interface in node.js (via testrpc) which should return a Boolean value.

contract_instance.my_method()

This outputs an error:

  /node_modules/web3/lib/web3/requestmanager.js:61

  throw errors.InvalidResponse(result);

  Error: AssertionError: The field to must have byte length of 20

I also tried

contract_instance.my_method.call(function(error, result) {
  console.log(result);
});

That outputs the same error. Whenever I comment out the result log the error disappears. In the testrpc logs the call is registered.


texts: What does EtherScan's Transaction Visualizer do?

texts:
Go to this transaction https://etherscan.io/tx/0x832ae39d3848055a4ecaf70b036d53e6063c07ee97cfff504474fc1d1b703934. Then click on the 'Tools & Utilities' link. I am trying to figure out what this visualizer is showing. It shows what appears to be money coming out of one account (the from account) and into three different other accounts, but I can't figure out why it's showing that.

Does anyone know what is being shown in the transaction visualizer on EtherScan?


texts:
This article has a good description on how Ethereum calculates a difficulty level. And, this article mentions that the difficulty is adjusted such that, one block is generated every 12 seconds.

  The difficulty dynamically adjusts so that on average one block is produced by the entire network every 12 seconds (ie., 12 s block time).

What is the co-relation between this difficulty adjustment and the value of difficulty in a genesis.json document?
In a private Ethereum network, once set in the genesis.json, does the difficulty level adjust automatically similar to the main network?

genesis.json parameters explained


texts: TruffleSuite contract class or Web3^1.0 contract class for production code?

texts:
Starting out with blockchain development and I'm coming across many sources/courses that recommend the Truffle/Contract class for interacting with deployed contracts because of "ease of use". But Web3^1.0.0 seems straightforward and easy to work with (PromiEvents enable async/await, etc).

Any reason not to use Web3 1.0.0-beta for simple contracts? And if not, is the Truffle Contract class still relevant in 2019? Hope this isn't too open-ended of a question...


texts: Best way to list all tokens of user in Solidity

texts:
I am using openzeppelin erc721 library to create an NFT and need to list all the tokens of a user. The most obvious way is to iterate through all the tokens in the contract and check if the owner of the token is same as the address I have sent.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
    uint256 tokenCount = balanceOf(_owner);

    if (tokenCount == 0) {
        // Return an empty array
        return new uint256[](0);
    } else {
        uint256[] memory result = new uint256[](tokenCount);
        uint256 totalCats = totalSupply();
        uint256 resultIndex = 0;

        // We count on the fact that all cats have IDs starting at 1 and increasing
        // sequentially up to the totalCat count.
        uint256 catId;

        for (catId = 1; catId <= totalCats; catId++) {
            if (kittyIndexToOwner[catId] == _owner) {
                result[resultIndex] = catId;
                resultIndex++;
            }
        }

        return result;
    }
}

Link to this solution
Another solution that I am thinking of implementing is to have a mapping where I map the user address to an array or another mapping which includes all the tokens the user owns. Upon transferring the token to another address, I would need to remove the token from seller list and add it to buyers list. This solution sounds more reasonable but I dont know how cost efficient it will be. What are the disadvantages of this method?


texts: How to update Geth on Ubuntu without using the PPA

texts:
I originally downloaded Geth using the instructions on the original (read: old) Ethereum homepage, using a curl command in a Bash one-liner. I now want to update to a version that will support Homestead.

The current Ubuntu installation instructions are based on apt-get, which pulls things from the official repository.

Is there any way I can update without moving to using the repository method? If I do now have to use the repository method, how do I remove the old version of Geth without losing my account data?


texts: What to enter for NODE_ENDPOINT on blk.io explorer

texts:
blk-io/blk-explorer: https://github.com/blk-io/blk-explorer-free

Hi,

I'm relatively new to ethereum, and I am having difficulty implementing the blk.io block explorer (for my private ethereum network).

I was wondering what to enter for 'NODE_ENDPOINT' ? I have no idea what a node endpoint is

Any help appreciated


texts:
Am trying to add few hashes into an array and retrieve those but the getHash() is returning an empty array. My smart contract is :

pragma solidity ^0.5.0;
contract simpleexample{

bytes32 public inputHash;
bytes32[] inputHashArray;

function addNewHash(bytes32 input) public {
  inputHash = input;
  inputHashArray.push(inputHash)-1;
  return;
}

function getHash() view public returns (bytes32[] memory){
  return inputHashArray;
}

function getLength() view public returns (uint) {
  return inputHashArray.length;
}

function blockTime() view public returns (uint blkTime) {
  return block.number;
}
}

Am sending the transaction as :

var simpleContract = web3.eth.contract(abi);
var simple =    simpleContract.new(0x37cfa6a8721ac72e8472dbcc55ec7bc773730de36217504c3addc9e93480443e, {from:web3.eth.accounts[0], data: bytecode, gas: 0x47b760, privateFor: ["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc="]}, function(e, contract) {
    if (e) {
            console.log("err creating contract", e);
    } else {
            if (!contract.address) {
                    console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");
            } else {
                    console.log("Contract mined! Address: " + contract.address);
                    console.log(contract);
            }
    }
    });

Any clue as to what am missing?


texts: How to buy GNT tokens using myetherwallet

texts:
this is my first time buying Ethereum tokens on mainnet. Probably I am doing something wrong, so I am willing to hear any comments or hints about this process. My ethereum address on mainnet is https://etherscan.io/address/0x919ae3010329decba980259d1e624be6028d16c7

Through https://www.myetherwallet.com/#contracts I tried to call TokenSeller contract https://github.com/bokkypoobah/TokenTrader/wiki/TokenSeller-And-TokenSellerFactory as described at https://cryptoderivatives.market/token/GNT

I am just interested in buying a few Golem Network Tokens (GNT), basically spending 0.1 ethers just to test around. So I executed the method createSaleContract() on contractAddress 0xb1eb96f752c624dc784d80961a1accfaf348c923 and ABI:

[{"constant":false,"inputs":[{"name":"tokenAddress","type":"address"},{"name":"tokens","type":"uint256"}],"name":"ownerWithdrawERC20Token","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"tradeContract","type":"address"}],"name":"verify","outputs":[{"name":"valid","type":"bool"},{"name":"owner","type":"address"},{"name":"asset","type":"address"},{"name":"sellPrice","type":"uint256"},{"name":"units","type":"uint256"},{"name":"sellsTokens","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"asset","type":"address"},{"name":"sellPrice","type":"uint256"},{"name":"units","type":"uint256"},{"name":"sellsTokens","type":"bool"}],"name":"createSaleContract","outputs":[{"name":"seller","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"payable":false,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"ownerAddress","type":"address"},{"indexed":true,"name":"tokenSellerAddress","type":"address"},{"indexed":true,"name":"asset","type":"address"},{"indexed":false,"name":"sellPrice","type":"uint256"},{"indexed":false,"name":"units","type":"uint256"},{"indexed":false,"name":"sellsTokens","type":"bool"}],"name":"TradeListing","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"tokenAddress","type":"address"},{"indexed":false,"name":"tokens","type":"uint256"}],"name":"OwnerWithdrewERC20Token","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"}],"name":"OwnershipTransferred","type":"event"}]

the call parameters are:

asset Golem => 0xa74476443119a942de498590fe1f2454d7d4ac0d
sellPrice .1
units 40 => rate .0025
sellsTokens true

the resulting transaction is:

tx:

amount 0
gas limit 29091

raw tx:

{"nonce":"0x00","gasPrice":"0x098bca5a00","gasLimit":"0x71a3","to":"0xb1eb96f752c624dc784d80961a1accfaf348c923","value":"0x00","data":"0xc5e412e5000000000000000000000000a74476443119a942de498590fe1f2454d7d4ac0d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000001","chainId":1}

Transaction submitted: https://etherscan.io/tx/0x6f739b16584e8e9d24ee34c79efbd60463da8cb6c3f05fdca74c6e400d5b0867

But got this error:

     Warning! Error encountered during contract execution [Bad jump destination]

Any ideas? Thx!


texts: What does the keyword "memory" do exactly?

texts:
I've been looking through the code of Etherdice and noticed that some variables are declared like

ParserResult memory result;

and I haven't found the keyword "memory" in any documentation.
What I found on here was this explanation:

  They are analogous to memory and hard drive storage in a computer. The
  contract can use any amount of memory (as long as it can pay for it of
  course) during executing its code, but when execution stops, the
  entire content of the memory is wiped, and the next execution will
  start fresh. The storage on the other hand is persisted into the
  blockchain itself, so the next time the contract executes some code,
  it has access too all the data it previously stored into its storage
  area.

Does the "memory" declaration actually make the value be stored in "memory"? Aren't all local variables inside a function stored just in memory and global variables always stored in the blockchain? And what is the relation to this explanation of "Memory" here?


texts: I need some clarification about cloning Ethereum

texts:
I would like, just for learning purpose how to create a new crypto by cloning the Ethereum.

I know how to make a clone of BTC and LTC, basically with that chains is enough modify some strings (such as name and other params) and compile a new wallet that generates a new blockchain.

I would like to do the same with Ethereum, but I'm not sure of what I've understand.
I've read this article:

https://medium.facilelogin.com/build-your-own-blockchain-b8eaeea2f891

So what I need is the “geth” program and the json genesis file, then this is enough to build the blockchain, right?

If yes (and so now I have my own crypto) the step that is not clear for me is: after create genesis block how can I start mining my own crypto (how can I pick a unique network id?)? Where I set the maxium amount of cloned-eth? Is a really new crypto? Can I build a UI for my wallet in any language (maybe Java)? Are there some guide to do that?

Sorry for so many questions, I hope that someone could point me the right direction, thanks.


texts: Using the Parity or Geth light client, how can I monitor an address for transactions?

texts:
I'd like to use Parity or Geth, in light client mode, to monitor an address for transactions.  Essentially, I should be able to check each block for transactions involving a certain address.

In the end, the goal is to have devices linked to wallet addresses.  Payments can be made to these addresses to launch software containers or other software on the devices.

Thanks so much for any help, tips, or pointers in the right direction.


texts:
address[] child;

function createChildContract() onlyOwner public{
    address newChild = new Child(msg.sender);
    child.push(newChild);
    emit ChildCreated(newChild);
}

contract Child {
   address public owner;

constructor(address _owner) public{
    owner = _owner;
}

function getOwner() external view returns(address){
    return owner;
}

I can make child contracts with this code in testnet but in mainnet it dosen't work.

Does mainnet just impossible to create child contract? or my code is wrong?


texts:
I used Truffle to setup a basic example dapp, which includes a frontend javascript file in which I see the following lines:

window.onload = function() {
  web3.eth.getAccounts(function(err, accs) {
    if (err != null) {
      alert("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];

    refreshBalance();
    refreshBalances();
  });
}

What I don't understand is; where does web3 come from in this context? In the index.html file, only this javascript file is imported, and I don't see any mentioning of web3 anywhere else.

Can anyone shed some light on this for me?


texts: Blockchain. Using sub-wallets through the main wallet without any restrictions or commissions

texts:
What I mean:
Alleged example:
I have a wallet "A". This is the main wallet. I want to creat 5 sub-wallets (in real case it will be more than 10.000 sub-wallets) from the main wallet - "AB", "AC", "AD", "AE" and "AF". So i give one sub-wallet address to each of five payers  ("AB" to first payers, "AC" to second payers, "AD" to third payers end so on). They transfer coins to it. And i can see all this transfered coins on my main wallet "A" a single sum. So i can manage them from my main wallet "A" without any restrictions or commissions.
Can i do this ? Is there such a possibility? Share info or links to documentation, please. I need it with Ethereum and Bitcoin wallets.
If it possible i need algorithm how to do it in Python 3.7 with Web3 lib.
I have no same code because i don't know is it possible in general for Ethereum and Bitcoin wallets.
I need any info about it and will be appreciate all the help i can get.


texts:
I cannot figure out how to buy Digix gold tokens using Ethereum.  I download Ethereum's wallet on my computer and it disappeared.  Something about "unpacking." I use Coinbase, but they limit purchases to less than $2500 without uploading your drivers license.  That completely eliminates all privacy and anonymity.

How do I buy Digix gold tokens?

Thx


texts: Transaction propagation and acceptance on forks

texts:
Assuming the scenario where a fork occurs shortly after I have sent a transaction out, and it gets mined in my side of the fork, could it also be mined in the other side of the fork?
In other words, if we had a fork, is it reasonable to assume that both forks would process the same transaction?

If it was a contract creation transaction, I understand that each of the two instances of that creation would yield a different contract address. However, with a transaction that runs a contract method to alter state, both forks would process them the same way.


texts: uint overflow problem:why not solve this problem in evm?

texts:
Solidity's uint256 can cause overflow.

Why not resolve this problem in the EVM?


texts: How to get all the contracts deployed by a specific ethereum address?

texts:
It is anyhow possible to get all the contracts deployed by a specific ethereum address in lifetime?

If yes, is it possible to get ABI details of the contract by their address?


texts:
Wouldn't it be possible for a government seeking to destroy the blockchain just "print out" the money for getting 51%? if they plan to bring the network down then the printing wont effect the fiat economy since they will "burn" the money right after printing it?
Also If proof of stake give the most reward to the biggest coin holder won't it just make the rich richer thus centralizing most of the coins to a handful of people?


texts: How to get only latest log from my event?

texts:
I currently am using Oraclize in my contract and I make a call to a contract function from my front-end and don't want to continue onto the next call until the Oraclize function has returned.  So I decided to use an event with a filter, and it works perfectly the first time, then on the next calls it doesn't actually wait for the Oraclize function to return again, it just takes the return value from the previous Oraclize function and uses that because its using the old logged event, and not waiting for the newest one.

This leads me to question why my filter is listening/uses the event emitted from the smart contract in the last call, instead of waiting on the new event to be called.  It later returns the new Oraclize value if I don't use myEvent.stopListening() so I know Oraclize is still working after the first call.

My question is how do you only listen/react to the last event?  Right now it's taking whatever event was fired before and being triggered off that.

Here's my front-end code watching the event:

I've tried also using various combinations for the filter such as:
{fromBlock: 'latest', toBlock:'latest} or {fromBlock: 'latest'}

neither actually work at all, they don't ever fire the first time, then if I call the function again they have the same problem and instantly fire on the previous logged event.

Can someone explain to me what 'latest' does, for I seem to have a bad understanding.  Also if this makes any difference my Event call in my smart contract takes place in the __callback() from Oraclize, and my front-end watching code is placed in a callback where the user clicks a button and enters a number and sends the transaction.  Is the placement inside a callback function causing this weird error?

Thanks for any help or understanding, I have gone through the documentation on both contract events and web3.eth.filters but have been unable to figure this out.  Sorry for the massive wall of text.

TL:DR How do you get your watch() to only look for new event logs, not react to past event logs that were triggered? Thank you!


texts: What happens when you send transaction with higher nonce that conflicts with previous transaction balance?

texts:
As an example:

  Current ETH balance: 10 ETH

  TrxA  nonce: 88, amount: 7 ETH

  TrxB nonce:89, amount: 5 ETH

From what i understand, as long as TrxA is still pending, TrxB can be created by increasing the nonce value. However, TrxA has to be confirmed first before TrxB can be processed.

If i'm right, does that mean that TrxB can be successfully submitted to pool but will be rejected once TrxA is confirmed?


texts: There is a missing currency sent to the account, please be sure to confirm it

texts:
Missing Ethereum Transaction! From Poloniex to my ETH wallet
this process
Address: 0x9434903Dc1a16872EF1F80920CC71EE8d70d8Cf4
Txid: 0x1d5a31b99a16971c010e4c9fb2f16e2ee8a9540b1a18f4d3e505e304f76e49ad


texts: How can i get confirmed transactions from an address?

texts:
I'm looking for some way to listen to transactions happening on this address. Basically, whenever a new transaction is confirmed, i would like to receive it. How can i do that? I just got started to web3 and Infura so i don't really know where to go from here.
I tried the Infura websocket, with very little results:
import asyncio
import websockets

async def connect():
    uri = "wss://mainnet.infura.io/ws/v3/<MY-PROJECT>"
    async with websockets.connect(uri) as ws:
        await ws.send('{"jsonrpc":"2.0", "id": 1, "method": "eth_subscribe", "params": ["logs", {"address": "0x7a250d5630b4cf539739df2c5dacb4c659f2488d"}]}')

        while True:
            msg = await ws.recv()
            message = json.loads(msg)
            print(message)

asyncio.get_event_loop().run_until_complete(connect())

This should subscribe to all the events happening on the smart contract, but i'm receiving nothing. Any kind of help is appreciated


texts:
When I run the code in remix, The state variable requesting is overwritten after a call to addSimpleStruct(), which makes it impossible to add another struct because of the require statement. Why would this be and how can I make it so the address in requesting persists throughout the contracts entire lifetime.

pragma solidity ^0.4.21;

contract test {
  address public requesting;

  struct simpleStruct {
    bytes32 desc;
    uint256 startTime;
  }

  struct itmap
  {
    mapping(bytes32 => IndexValue) data;
    KeyFlag[] keys;
    uint size;
  }

  struct IndexValue { uint keyIndex; simpleStruct value; }
  struct KeyFlag { bytes32 key; bool deleted; }

  itmap data;

  function test() public {
      requesting = msg.sender;
  }

  function addSimpleStruct(bytes32 key, bytes32 _desc) public {

    require(msg.sender == requesting);

    simpleStruct storage newStruct;
    newStruct.desc = _desc;
    newStruct.startTime = now;
    insert(data, key, newStruct);
  }

  function insert(itmap storage self, bytes32 key, simpleStruct storage value) internal returns (bool replaced)
  {
    uint keyIndex = self.data[key].keyIndex;
    self.data[key].value = value;
    if (keyIndex > 0)
      return true;
    else
    {
      keyIndex = self.keys.length++;
      self.data[key].keyIndex = keyIndex + 1;
      self.keys[keyIndex].key = key;
      self.size++;
      return false;
    }
  }
}


texts: Using web3.js, how can I get a TX hash before sending?

texts: I'm using web3.eth.accounts.signTransaction() to obtain a rawTransaction, but I also need the transaction hash. calling web3.eth.sendSignedTransaction() will give me the hash, but I need to get it BEFORE sending the transaction. I tried using web3.eth.accounts.hashMessage(rawTransaction) but the result wasn't correct.


texts: How to loop through a array of addresses?

texts:
I have a mapping and an array that contains a list of addresses of students. When I loop over that array, the method .length is not working.

How can I loop through the array Student_list shown below?

 mapping(address => Student) Students;
 address [] public Student_list;

  function Studentgrade() public{

for (uint i=0; i<Student_list.length; i++) {
if (Students[Student_list[uint(i)]].grade <= Maxvalue) {
     Students[Student_list[uint(i)]].grade=  90;

}
}
}


texts:
Is any way to get a summary balance of ethereum hd wallet?

For example, I generated hd wallet and a lot of derived addresses (bip44). Made few transactions on these addresses and wanna know summary balance of these addreses.

Or give me advice how to receive payments on my site without 3rd parties.


texts: I have created a windows server EC2/GPU instance, downloaded the proper version of ethermine and tried to start mining. It says that it won't work thanks to no OpenCL or CUDa. This is confirmed by documentation which states that Elastic GPUs only support OpenGL and not OpenCL or Cuda. There are EC2 GPU Compute instances that I can confirm work, however, they are expensive. Is there a version of an ethereum mining that will work on an OpenGL only machine?


texts:
I am a beginner studying how to use Solidity in writing smart contract.

As I read the Solidity documentation, I would like to have a feel of how smart contract works using the Remix IDE.

I am trying with the contract Ballot given in the voting example.

According to my understanding, after I have created the contract, I would be the the chairperson with address msg.sender

And I can give right to other voters using the giveRightToVote function by entering their address.

What I am not sure here is how I can create another voter with different address in Remix IDE. If I click create, another contract would be generated voting for different proposals.

Can someone please teach me what I should do in order to create a new voter or point out if I have misunderstanding in concepts. Thank you very much.


texts:
I want to get all transaction associated with a contract in ethereum.
I tried to found the solution with Web3, or etherscan API ,but i didn't found anything.

Thanks for your help :)


texts: It seems like oraclized takes way more than $0.05

texts:
When a TX for a random number like such: https://ropsten.etherscan.io/tx/0x54fa389796fea546ac6562bec7cfe4b0daca1b744920a38a0e85036b07a1e0ee

It says that 0.004 ehter was send to oraclized and it is not put back in my contract, this is worth way more that the $0.05 that is in Oraclized price tables.. How/when does the ETH come back?


texts: I would like to use gas from a different ETH address to spend an ERC20 token - is it possible?

texts: I have ERC20 tokens (on addresses with no ETH ) and will require first funding the address with ETH and then sending the ERC20 tokens (2 total tx fees to be paid). I would like to cut this down to one transaction fee by publishing my ERC20 tx using gas paid from a different address with existing eth on it, is it possible?


texts: Started getting EventStructWrongData warning in my ERC20 Token Code

texts:
I suddenly started getting  EventStructWrongData (very low-severity) warning in my Ethereum code in Etherscan. It was not there before, so how come it started showing up all of a sudden?

This is the code: https://rinkeby.etherscan.io/address/0x42a5740f1e7efd2337171db355d8bf4a6e232e15#code

This is the error:

The funny thing is that I have not used Struct anywhere in the contract. So, how come it says Struct used in event will have some problem?


texts: how is GET https://solc-bin.ethereum.org/bin/list.json net::ERR_CERT_DATE_INVALID corrected?

texts:
I am trying to load Remix via the website in Chrome.

Reported here -

https://github.com/ethereum/remix/issues/1167

I get

  mock compiler: source not found

and in the console -

  GET https://solc-bin.ethereum.org/bin/list.json
  net::ERR_CERT_DATE_INVALID

Any help appreciated.


texts:
Does Ethereum have a standard contract for "dumb" assets that most common wallets understand? Mainly so that one can

Issue new assets (one time issue)
Distribute these assets to the accounts of shareholders
Accounts then can freely move assets between them


texts: Is it faster to use "geth --unlock" than "personal.unlockAccount"?

texts:
I have a script that I run with geth attach, and then I use:

primary = eth.accounts[0];
personal.unlockAccount(primary, "password");

like I saw in the example script.

Doing this in geth usually takes about one or two seconds. I learned there was another way to unlock accounts. I was wondering if it was faster to unlock directly with geth --unlock "0xaddress" --password "password" attach. What does it do differently ?

How can I know if it unlocked successfully ? If I use a random address or password instead of the correct ones, attach still opens correctly.

EDIT: I found in the answer of a duplicate question that you can't use --unlock with attach, which wasn't in the original answer (or at least not clearly).

Geth attach "opens correctly" because it ignores those flags. You can run geth --unlock "0xaddress" --password "password" attach or geth --password --testnet --testnet attach and it will open like geth attach (flag order seems to be important sometimes though, you can't use password after testnet or it ignores attach).


texts: Execute from truffle dev to python language

texts:
I successfully execute smart contract function in the truffle development console, for example:

let instance = await MetaCoin.deployed()
let accounts = await web3.eth.getAccounts()
instance.sendCoin(accounts[1], 10, {from: accounts[0]})

I get the "Coin" in my accounts[1]. But the problem is when I try to use python, it gives an error.

contractAddress = '0x...'
abi = '...'
contract = w3.eth.contract(contractAddress, abi=abi)
contract.functions.sendCoin(accounts[1], 10, {from: accounts[0]})

Error:

contract.functions.sendCoin(accounts[1], 10, {from: accounts[0]})
                                              ^
SyntaxError: invalid syntax

This is my sendCoin function:

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

function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    emit Transfer(msg.sender, receiver, amount);
    return true;
}


texts: Invalid sender error in MetaMask with private network in Azure ethereum BaaS

texts:
I had implemented Ethereum Blockchain as a service from Microsot azure. The client i am using is from Metamask. I am not able to send ether from one wallet to other and i get an error Invalid sender .
Sending ether from Network to the wallet works fine.
Can you please help.
Thanks,
Phani


texts: What happens if two different states of smart contract conflict?

texts:
I'm newbie studying blockchain and Ethereum. While I'm studying, I've got a question.
What will happen in the case of conflict of two different states on smart contract, e.g. from the network partitioning attack such as eclipse?
From the network partitioning attack, the Ethereum network will be separated into two groups, and the states of smart contract would be proceeded into two different states. And I wonder, after the end of attack, to make consensus, what will happen to resolve the conflict in Ethereum?


texts:
I have a major problem/ I've got a simple smart contract that stores data (a text in blockchain and it works well, but when I pass keccak256, it stores only the string passed in as an argument but not the hashed value.

I have tried a lot of code from the internet but I haven't found a solution.

pragma solidity ^0.5.7;
contract store {
    bytes32 data;
    function set(string memory _word) public {
        data = keccak256(abi.encodePacked(_word));
    }
}


texts: Estimate the cost of gas in Truffle Console?

texts:
Is there a way in the Truffle console to estimate the cost of gas for deploying a contract to mainnet?
I'm attempting to truffle migrate --network main a contract, and it's running out of gas.
I've been tweaking the gas and gasPrice in truffle-config.
// truffle-config.js
main: {
      network_id: 1, // Main's id
      gas: <gas limit>,
      gasPrice: <gas price>

But it would be very helpful to know what the gas would be to deploy a specific contract.


texts: I tried to deploy a contract on Ropsten, but always get the following error

texts:
PS D:\nodejs\rff\metacoin> truffle --network ropsten migrate
Using network 'ropsten'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
undefined

I then unbox the Metacoin and do truffle --network ropsten again. same error happened.
My truffle.js as following:

var HDWalletProvider = require("truffle-hdwallet-provider");

var mnemonic = "<My Mneomonic>";

module.exports = {
  networks: {
    rinkeby: {
      host: "127.0.0.1", // Connect to geth on the specified
      port: 8545,
      from: "0xec14efb50fd9108a567b007479bd3345300d8374", // default address to use for any transaction Truffle makes during migrations
      network_id: 4,
      gas: 4612388 // Gas limit used for deploys
    },

    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    },

    test: {
      gas: 6721975,
      gasPrice: 0,
      host: '127.0.0.1',
      port: 8545,
      network_id: '*' // Match any network id
    },

    ropsten: {
      from: "0x5FBC4Dde3019f7d93AA9c2b59E5537F3Fb1210df",
      gas: 6721975,
      gasPrice: 2,
      provider: new HDWalletProvider(mnemonic, "https://ropsten.infura.io/<My token>"),
      network_id: 3
    }
  }
}

I also tried Rinkeby and testnet. everthing goes well. then I try Rinkeby with provider:'https://rinkeby.infura.io/, got the same error. Can anyone help?


texts: Two calls to a contract: input of the first can only be revealed after the second call

texts:
I see that there are no parallel execution in EVM. The problem I am trying to solve is the following: I have a contract which takes the input of two parties -- say users A and B. The result of the contract depends on both inputs, but if A calls the contract first, then I would this input to not be public until B calls the contract as well. The point is, both parties should not know each other's input before both have called the contract. Imagine a card game, where both players have to choose a card simultaneously and put them on the table face down, to be revealed at the same time.

Is this possible?


texts: How to apply EthFilter to specific address?

texts:
In web3.js, we can apply event filter something like below:

 this.event = this.Contract.events.MyEvent({
     filter: { address: "0xAccountAddress" },
 })

In Web3J, it is translated to

EthFilter eventFilter = new EthFilter(
    DefaultBlockParameterName.LATEST,
    DefaultBlockParameterName.LATEST,
    mContract.getContractAddress()
);
eventFilter.addSingleTopic(EventEncoder.encode(Contract.MY_EVENT));

But, how to pass specific address in the event like filter in above web3.js example?


texts:
Dears,

I am getting the below error while trying to compile the contract.

~/Desktop/TstToken$ truffle compile
TypeError: Cannot read property 'kdf' of undefined
    at Function.Wallet.fromV3 (/home/fkp/Desktop/TstToken/node_modules/ethereumjs-wallet/index.js:237:19)
    at Object.<anonymous> (/home/fkp/Desktop/TstToken/truffle.js:5:43)
    at Module._compile (module.js:649:30)
    at Object.Module._extensions..js (module.js:660:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Module.require (module.js:593:17)
    at require (internal/module.js:11:18)
    at Function.Config.load (/usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-config/index.js:259:1)

I am using the key file from Ethereumjs-wallet.

It will be great if there is a workaround for the same.


texts:
I'm wanting to create a smart contract that sends an amount of ether to an address when the weather is above 30 degrees for 3 or more consecutive days, using the OpenWeatherMap API.

How can I use data from an API in a smart contract?

Thanks in advance..


texts: How to modify the base fee 21000 gas for a simple transaction?

texts:
I found that for a simple transaction, the UsedGas is constant value(i.e. 21000).
Can it be modified when sending a transaction or configured somewhere?
Thanks.


texts: Difference between a.add(b) and a+=b as well as a=a+b?

texts:
For example, if I have:

balances[from] -= tokens;
balances[from] = balances[from]-tokens;
balances[from] = balances[from].sub(tokens);

What is a difference and why should I use one rather than the other, and when ?

Edit: I am aware of differences in languages such as C, but I don't know about the Solidity.


texts: Testnet password, the same as the real Ethereum wallet?

texts: I want to deploy a smart contract, but I don't know which password to use. Is it the same as my main account on the real Ethereum network? And can I change the Testnet password? I forgot it, but I really want to see my smart contract in testnet ethereum.


texts: Please help! I don't know how to access the BLX I sent to MyEtherWallet - it says 0 balance but it shows on blockchain

texts:
I bought some BLX on EtherDelta, withdrew from contract to my EtherDelta wallet, then clicked "Transfer" and transferred all of my BLX to a MyEtherWallet address.

Later I got confirmation that it went through and I found the successful transaction on etherscan.io.

It was at the following:

 Block Height:
 4235569 (2265 block confirmations)

 TimeStamp:
 15 hrs 16 mins ago (Sep-03-2017 11:30:53 PM +UTC)

It gave the correct sending and receiving addresses, though the address it said received it was a Contract, not the MEW address I had specified.

It contains 0 Ether, Gas LImit 250000, Gas Used by Txn 37524, etc. etc.

I also found the whole transaction accurately recorded on ethplorer.io.

HOWEVER, MyEtherWallet shows 0 BLX tokens in my account when I look under Token Balances.

QUESTION: Are my BLX tokens still there? If so, where are they? How do I access them? What if I want to send them somewhere? MEW claims they don't exist, so how do I send them off of MEW? If they're not on MEW where are they and how do I access them?

Thanks in advance for your help. I am in full freak out mode right now!


texts: What is the difference between 'Deployed data' and 'Send data' in a contract creation transaction?

texts: I'm following the 'Create your own cryptocurrency contract' on ethereum.org. I deployed the contract but I don't understand what does 'Deployed Data' and 'Send Data' represent. Is any of them the bytecode for the contract?