texts: How to find number of nodes in ethereum using web3?

texts:
Is there a way to find the number of nodes in the ethereum network using the web3 javascript console?

There is a command to find the number of peers, but couldn't find a query to get the total number of nodes in the network.


texts:
meanwhile i'm in despair and don't understand how some values are used for the calculation. I sincerely ask for support on how I can calculate the amount of ethereum mined per day from historical data based on my hashrate.
the formula:
(((hashrateMH/s x 1000000) x BlockReward) / BlockDifficulty) x 3600 x 24
Example for 01/26/2021 (https://www.coinwarz.com/mining/ethereum/calculator):
(((20800Mh/s x 1000000) x 2) / 4651150365111875.000000) x 3600 x 24 = 0.78659687 Eth per Day

This is also true as far as I refer to these values at https://www.coinwarz.com/mining/ethereum/calculator.
I get my historical data from https://etherscan.io/charts and export this as csv.
My big question and request is:
How the hell do these numbers correlate with each other?
Where does the 2 on coinwarz come from as a block reward where the etherscan source shows blockreward of, for example, 13544.3125 for 01/25/2021.
Likewise coinwarz calculator shows at 4651150365111875.00000000 Ethereum Difficulty but etherscan shows at 4429.988.
How is it possible to do an exact calculation? Which data do I have to add up to get realistic values? did i choose wrong data / numbers from etherscan? do i need more operands to complete the calculation?
I ask deeply for your support as it is very important to me.
Many, many thanks in advance...


texts: Warning! Error encountered during contract execution [Out of gas]

texts:
What is this ? I am trying to send a transaction from my Nano S Ledger to a Bittrex Account dont understand what is happening ? Do I need to purchase Gas as well ???

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


texts: What happens when you put an recursive schedule call with Ethereum Alarm Clock scheduler?

texts:
My goal is to schedule a call once every day.

[Q] Is it possible to use recursive function to schedule a call once every day using Ethereum Alarm Clock scheduler?

Example from following answer https://ethereum.stackexchange.com/a/87/4575 :

contract SchedulerAPI {
    function scheduleCall(address contractAddress,
                          bytes4 abiSignature,
                          uint targetBlock) public returns (address); }

contract CallMeLater {
    // The address of the v0.6.0 Alarm Clock scheduler contract.
    address constant Scheduler = SchedulerAPI(0xe109ecb193841af9da3110c80fdd365d1c23be2a);

    function CallMeLater() {
        // Schedule a call to the `callback` function
        Scheduler.value(2 ether).scheduleCall(
            address(this),               // the address that should be called.
            bytes4(sha3("callback()")),  // 4-byte abi signature of callback fn
            block.number + 5082,          // the block number to execute the call
        );               //As we know 1 day duration (1440 minutes): 5082 blocks.
    }

    function callback() public {
        // whatever code you want executed.
          CallMeLater(); //added: recursive call.
    } }

I added additional CallMeLater(); into end of callback() function, I assume, which will make new schedule (1 day ahead) in order to call callback().


texts:
bytes32 constant myHash = sha256("test");
 getting hash value like
 (0x4135aa9dc1b842a653dea846903ddb95bfb8c5a10c504a7fa16e10bc31d1fdf0)
 There is any function for decode it? or how to decode it?


texts: Does the latest version of geth does not create geth.ipc?

texts:
I have seen similar question about the geth.ipc file (I can't find my geth.ipc), I am on Windows 7.

I am not able to see geth.ipc file after running geth as said in the other question thread, tough I am able to connect to geth in other instance of command window using (>geth  attach) without passing the path for geth.ipc, my question is the new version of geth does not create geth.ipc?

  geth attach ipc:MyPvtBlockChain1/geth.ipc

Executing the above command says

  Fatal:Unable to attach to remote geth: Invalid pipe address MyPvtBlockChain/geth.ipc

The problem is that I have created two private blockchains on my machine now. It is a problem to connect these two separate blockchains without the geth.ipc file. Both my geth attach command connect to same geth node instance and not separate blockchains I have created, I have checked it using admin.nodeInfo command and both windows point to the same geth node.

When I try to run geth on the another private blockchain like this, the --ipcpath is requried here, but as I do not have access to geth.ipc file there is no way I can run geth on the my second blockchain instance which would require the command below, which takes details of my second blockchain and run it on a seperate port number.

Run Geth for first blockchain

  geth --datadir MyPvtBlockChainData1 --port 30303 --nodiscover --ipcpath MyPvtBlockChainData1/geth.ipc" --networkid 1234 console

Run Geth for second blockchain

  geth --datadir MyPvtBlockChainData2 --port 30304 --nodiscover --ipcpath MyPvtBlockChainData2/geth.ipc" --networkid 1234 console


texts: speed drops after "got new package" and then gets back to normal after few seconds

texts:
Please check the below image.

The mining speed drops after "got new package" and gets back to normal after some time. Can anyone tell me if it is a normal behavior? Or is there some problem?


texts: Should I use an average or median price for my oracle?

texts:
Excerpt from Compound's The Open Price Feed:

This is accomplished through a View Contract, which reads, parses, aggregates, transforms, etc from the storage contract. The determination of trustworthiness or quality of the data signed by reporters is a decision ultimately made in the View. Views may use a median price, an average, or whatever methodology they favor.

In what cases is an average oracle desirable? And a median one?


texts:
Is Metamask a web3 provider? I am aware it is a wallet. But is it also a web3 provider?
I have read from here that:

Web3 provider is a website running geth or parity node which talks to
Ethereum network.

Then I have read here that:

Web3Modal is an easy-to-use library to help developers add support for
multiple providers in their apps with a simple customizable
configuration.

What do you call Metamask, Dapper, Gnosis Safe, Frame and the rest? Are they web3Providers? Or what are they?
I am asking this line of code here:
const provider = await web3Modal.connect();

const web3 = new Web3(provider)

// what is provider and why should I pass it to a new instantiation of web3?

;


texts: Couldn't connect to node (Windows, Ethereum Wallet 0.8.8)


texts: geth v1.9.13 - web3.exceptions.BadFunctionCallOutput: Could not decode contract function call func return data b'' for output_types ['uint256']

texts:
For clearity I am using two different ubuntu machines as follows, please note that both machines are sync to my private black chain and working on the same smart-contract:

Contract call was working on 1.9.9 where it starts not to work on 1.9.13.

=> ubuntu-a uses:

- web3==5.7.0`, Python `3.6.8`, OS: `linux` on `venv`
- geth Version: 1.9.9-stable

Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic

=> ubuntu-b uses:

- On `web3==5.7.0`, Python `3.7.5` on `venv` I have also tried for Python `3.6.8`
- geth Version: 1.9.13-unstable

Ubuntu 19.10
Release:    19.10
Codename:   eoan

Following function call works using web3py on ubuntu-a which has (geth Version: 1.9.9-stable): but when I upgrade the geth version to geth Version: 1.9.13-unstable it starts not to work.

contract.functions.getReceivedStorageDeposit(b'97fc72c7b24e499b79cb9e2d42300ad1').call()

where the function has the following signature:

function getReceivedStorageDeposit(bytes32 sourceCodeHash)
    external
    view
    whenProviderRegistered returns (uint256)

On ubuntu-b, I get the following error message:

Traceback (most recent call last):
  File "/home/alper/venv/lib/python3.7/site-packages/web3/contract.py", line 1432, in call_contract_function
    output_data = web3.codec.decode_abi(output_types, return_data)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/codec.py", line 181, in decode_abi
    return decoder(stream)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/decoding.py", line 127, in __call__
    return self.decode(stream)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_utils/functional.py", line 45, in inner
    return callback(fn(*args, **kwargs))
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/decoding.py", line 173, in decode
    yield decoder(stream)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/decoding.py", line 127, in __call__
    return self.decode(stream)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/decoding.py", line 198, in decode
    raw_data = self.read_data_from_stream(stream)
  File "/home/alper/venv/lib/python3.7/site-packages/eth_abi/decoding.py", line 308, in read_data_from_stream
    len(data),
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "koo.py", line 5, in <module>
    eBlocBroker.functions.getReceivedStorageDeposit(b"").call()
  File "/home/alper/venv/lib/python3.7/site-packages/web3/contract.py", line 904, in call
    **self.kwargs
  File "/home/alper/venv/lib/python3.7/site-packages/web3/contract.py", line 1454, in call_contract_function
    raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not decode contract function call getReceivedStorageDeposit return data b'' for output_types ['uint256']

[Q] What may cause this error? How can I fix it?


texts: Retrieve price data from PancakeSwap [BSC]

texts:
Does PancakeSwap use the same constant product formula as Uniswap (x * y = k)? Because then I should be able to calculate a token pair exchange rate by just dividing the amount of token1 reserves by the amount of token2 reserves.

Is there an API that could deliver me the wanted token pair exchange rates?

Is there any other function in their contract to fetch price data from?


texts: Is there anything stopping me from using the ethereum blockchain as data storage?

texts: As I understand it, smart contracts are currently immortal by default. Does this mean that I could create a contract that happened to contain an encoded form of baby photos and have it stored forever? If not, what prevents it?


texts: Can someone explain Block 9193687: Why are there so many zero gas price transactions included?

texts:
Block 9193687 (Link: https://etherscan.io/txs?block=9193687&p=1) contains 79 transactions, of which 75 have a gas price of 0. These transactions are also not all from the same address.

How does something like this happen? Is someone mining his own 0 gas cost transactions? But then why include other 0 cost transactions? Is it a badly configured mining client? Was the tx pool completely empty (is there a way to check that?)?

I realize most of the tx minted GST2 tokens, which is very advantageous to do for a low gas price, but still, a gas price of 0 seems very odd to me.


texts: return array of struct with ABIEncoderV2

texts:
I have this error:

  UnimplementedFeatureError: Encoding type "struct Process.Process memory[] memory" not yet implemented.

when I try to return an array of Struct  I'm using:

  Truffle v5.0.10 (core: 5.0.10)
  Solidity - 0.5.2 (solc-js)

pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;

contract Process {
    struct Process {
        uint256[] tokens;
        bytes32 learning;
    }

    mapping(uint256 => Process[]) private processes;

    function _newProcess(uint256 _tokenId, uint256[] memory _tokens, bytes32 _learning) private {
        uint256 step = processes[_tokenId].length;
        Process memory process = Process({ tokens: _tokens, learning: _learning });

        processes[_tokenId].push(process);
        emit newProcessAdded(_tokenId, step, _tokens, _learning);
    }

    function getAllTokenProcess(uint256 _tokenId) public view returns (Process[] memory) {
        return processes[_tokenId];
    }

    function getTokenProcess(uint256 _tokenId, uint256 _step) public view returns (uint256[] memory, bytes32) {
        Process memory process = processes[_tokenId][_step];
        return (process.tokens, process.learning);
    }

}


texts: Why and how does the "low security" functions affect the biggest multi signature contract?

texts:
People use this contract everyday http://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol and it's also the contract with most ethereums right now.

Also you can create a multisig account on the official Ethereum Wallet using this contract source code.

But then when I go inside the site https://etherscan.io/address/0xab7c74abc0c4d48d1bdad5dcb26153fc8780f83e#code we have all these warnings stating that low security

  Warning: The compiled contract might be susceptible to ZeroFunctionSelector (very low-severity), DelegateCallReturnValue (low-severity), ECRecoverMalformedInput (medium-severity), SkipEmptyStringLiteral (low-severity), IdentityPrecompileReturnIgnored (low-severity), HighOrderByteCleanStorage (high-severity), SendFailsForZeroEther (low-severity), DynamicAllocationInfiniteLoop (low-severity), CleanBytesHigherOrderBits (medium/high-severity) Solidity compiler bugs.

How should I as a investor (and a programmer that has not fully learned Solidity) use this? Of course I have heard the Parity exploit which gave hackers freedom to just take 30 Milion USD.

My question is: Should I be worried? And what should I be careful with and pay attention to?

UPDATE:

I understand you but I can the basic solidity and I can't see any "internal" functions or "guards" which was put in action by parity after their exploit.

But here I have a more in depth analysis by the solidity remix simulator stating re-entrancy vulnerabilities: https://imgur.com/a/d3x8J

UPDATE 2:

You said higher compiler version is better well all of the contracts using that code (which I said is the one used in the Ethereum wallet) use version 0.3.2! 0.3.2! Which is from 2016!


texts: How to make Solidity Contracts Upgradable with a mapping and state variables?

texts:
While making a contract upgradable, I am facing issues with the approach where we split up the code implementation and storage.
As of this approach, I have created storage slots for every state variable that are either of type uint256 and address. These variables are static and don't extent with time, I define the slots as
For uint256 _totalSupply
bytes32 internal constant _TOTAL_SUPPLY_SLOT = 0x6cac11967c5738fe648c7b461acdbb3138d8619be340b9043646ca5ab64ec74b;

Getting the slot with eip1967
_TOTAL_SUPPLY_SLOT == bytes32(uint256(keccak256("eip1967.tokenGeyserStorage.totalSupply")) - 1)

And correspondingly
    function _totalSupply() internal view returns (uint256) {
    return getUint256(_TOTAL_SUPPLY_SLOT);
    }

    function _setTotalSupply(uint256 _value) internal {
        setUint256(_TOTAL_SUPPLY_SLOT, _value);
    }

where
    function setUint256(bytes32 slot, uint256 _value) private {
        // solhint-disable-next-line no-inline-assembly
            assembly {
                sstore(slot, _value)
            }
        }

and getter as

    function getUint256(bytes32 slot) private view returns (uint256 str) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            str := sload(slot)
        }
    }

What about data-types like
mapping(address => uint256) private _balances;

and

IERC20 public token;

As we know the mappings can grow, how to allot a slot for them, and what would be the setters and getters look like?
As IERC20 is also a data type that is different, how shall we go forward with those state variables while making the contract upgradable retaining these in states?
Any concepts like diamonds and facets that can help in better implementation of proxy?


texts: Always running out of gas when sending ETH to a contract

texts:
I'm trying to implement a Crowdsale contract using OpenZeppelin 4.x since this version has deleted the Crowdsale.sol from its repo.
My goal is to send ETH to the contract, receive "Gold" in exchange and redirect the received ETH to the pot wallet.
Gold is a simple ERC20 default Token.
Here is the code:
// SPDX-License-Identifier: BSD-Protection
pragma solidity ^0.8.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/math/SafeMath.sol";

import "./gold.sol";

contract Crowdsale {
    using SafeMath for uint256;
    ERC20 private token;
    address payable private wallet;
    uint256 private rate;
    uint256 public weiRaised;

    constructor( uint256 _rate, address payable _wallet, address _token )  {
        require(_rate > 0);
        require(_wallet != address(0));

        rate = _rate;
        wallet = _wallet;
        token = Gold(_token);
    }

    receive() external payable {
        require( msg.value > 0 );

        uint256 tokens = msg.value.mul( rate );
        weiRaised = weiRaised.add( msg.value );

        token.transfer( msg.sender, tokens );
        wallet.transfer( msg.value );
    }

}

I'm always running out of gas....


texts: Cannot call function in openzepplin ERC1155 contract via web3/metamask

texts:
I am trying to call the balanceOf function in a pretty barebones openzepplin ERC1155 contract through metamask.
I am using web3 only to generate the ABI, and metamask to actually send out the call.
Here is my code for the call,
const call = web3.eth.abi.encodeFunctionCall(
      {
        name: 'balanceOf',
        type: 'function',
        inputs: [
          {
            type: 'address',
            name: 'account',
          },
          {
            type: 'uint256',
            name: 'id',
          },
        ],
      },
      [account, 0]
    )
    console.log(call)
    // const from = account
    // /// 0x6c90b4eb
    return window.ethereum.request({
      method: 'eth_call',
      params: [
        {
          to: '0x7889d99522630E457cD522493eB7dE1C17e90a9D',
          data: call,
        },
      ],
    })

and my code for the contract is here
pragma solidity ^0.6.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant THORS_HAMMER = 1;

    constructor() public ERC1155("https://URL.XYZ/{id}.json") {
        _mint(msg.sender, GOLD, 100, "");
        _mint(msg.sender, THORS_HAMMER, 1, "");
    }
}

I am running it on ganache, which shows only one contract being made, which is this one. The address being passed in is not undefined and is the owner of the contract.


texts: sendTransaction returning “insufficient funds” when the account has enough ether

texts:
I am trying to send a transaction to the Ropsten network, using Infura as the Web3 provider. My transaction is being rejected ("insufficient funds for gas * price + value") and I suspect the reason is that the message is not being properly signed.

This is my code:

const Web3 = require('web3');

let endpoint = "https://ropsten.infura.io/v3/XXXXXXXXXXXXXXXXXXXXXX";
web3 = new Web3(new Web3.providers.HttpProvider(endpoint));

private_key = "0xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
address = "0xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
web3.eth.accounts.wallet.add(private_key);

recipient = "0xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

web3.eth.sendTransaction({
    from: address,
    to: recipient,
    value: '10',
    gas: 50000,
}).then(function(receipt){
    console.log(receipt);
});

Am I missing something?


texts: Specific to Geth the database used is LevelDB. But what is the database used for parity?


texts: call an api GET method in dapp - blocked by CORS policy

texts:
I am trying to create a dapp(web3js - truffle) where an API - GET method has to be implemented by setting 'x-api-key' on header.(OS - Linux) Here is the code :

app.js

//1st method
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", api);
xhr.setRequestHeader("x-api-key", key);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);

//2nd method

$.ajax({

      url: "api",
      type: "GET",
      beforeSend: function (xhr) {
         xhr.setRequestHeader('x-api-key', key);
      },
      success: function (resp) {
          console.log("Result :"+JSON.stringify(resp))
      },
      error: function(result){
        console.log("Error : "+JSON.stringify(result));
      }
  });

On chrome I get

  Blocked by CORS policy: The 'Access-Control-Allow-Origin'

I am able to get data using POSTMAN and on an executable js script. Tried by adding Allow-Control-Allow-Origin: * extension and enabling it on chrome. Then output was :

  Response to preflight request doesn't pass access control check: It
  does not have HTTP ok status

By trying above piece of code on meanstack - server side, it works. Do I have to write Nodejs backend for dapp? Is there other method to resolve it?


texts: Like other languages , Does solidity supports 'Null' keyword.


texts: Minimal contract testing setup using truffle

texts:
This question is a follow up onto this one. I have tried following the suggestion in the answer of adding a done() method that fires when an error occurs (an exception is raised) but it doesn't when I test the code.

Does anybody have a minimal setup that can test state changing contract method calls? (in my example, the call() method that read the blockchain works fine (an error is thrown if the expected strange and it passes if not)).


texts: Can miner himself add a transaction with a zero gas price?

texts:
In general it doesn't make any sense to send a transaction with zero gas price. Probably it will be pending forever. But what about miner - can he:

Send some transaction with zero gas price (so the total fee is also zero).
Include this transaction to the block and mine it.

If the miner wins the race - will this transaction be confirmed by the rest of the network? Or there's some protocol-defined bottom line for gas price?


texts:
Code :
git clone https://github.com/dappuniversity/election
https://github.com/dappuniversity/election/tree/2019_update

Errors faced :

Commands:

Compile:        truffle compile
  Migrate:        truffle migrate
  Test contracts: truffle test
  Run dev server: npm run dev

SANCBHAR-LW7947:election sanchitbhargava$ truffle migrate
Error parsing /Users/sanchitbhargava/Downloads/election/contracts/Election.sol: ParsedContract.sol:1:17: ParserError: Token incompatible with Solidity parser as part of pragma directive.
pragma solidity ˆ0.4.20;
                ^
Compilation failed. See above.
Truffle v5.0.3 (core: 5.0.3)
Node v10.15.0
SANCBHAR-LW7947:election sanchitbhargava$


texts: Web3 is injecting but stilling getting an invalid provider error

texts:
I'm injecting web3 with MetaMask, and everything works, but when I make a production build, I notice that it injects web3 alright, but when I try to call a web3 function, it throws `Please provide an valid Web3 provider'; specifically the error is being thrown when I try to make a contact instance.

Here's my code

if(typeof web3 !== 'undefined') {
  console.log("Using web3 detected from external source like Metamask");
  web3 = new Web3(web3.currentProvider);
} else {
  window.alert("No web3 detected. This site is a Web3 Dapp - to proceed you will need to get Metamask https://metamask.io/");
}

...

this.contract = new web3.eth.Contract(abi, address)

When I run the development build, everything works fine. But when I make a production build using npm react-scripts build and run it, then I get an error.

Edit:
Here is the error logged in the console


texts: The endpoint returned a different chain ID: 0x539 (Ganache)

texts:
I am trying to connect Metamask to ganache by creating a custom RPC with the following details:
New RPC URL: HTTP://127.0.0.1:7545
Chain Id: 5777
But I keep getting the error message The endpoint returned a different chain ID: 0x539


texts: Understanding private key handling with Parity Signer

texts:
I'm new to the world of crypto currency and need some explanations on how Parity Signer in particular handles private keys.
As far as I've understood, the private key is the most critical piece of information: lose it, and you cannot access your wallet any more. That's why I'm concerned about having backups.
Parity Signer does not seem to support showing/backing up your private keys (for example, for an Ethereum account). As far as I can tell, this is by design.
The list of words presented when I create an identity in Parity Signer can be used to "recover", so the private key can derived from this list. This is one part of having a backup.
But is this derivation following a documented approach that will let me regenerate the private key by other means? For example, what if, 10 years in the future, Parity Signer does not exist any more and I don't have access to its source: would there still be a way for me to derive the private key from the list of recovery words? Is there any information about this derivation that I should write down so I can always recover in the future?


texts: Can't migrate, ropsten randomly throws out of gas

texts:
I have the following migration files with 50 contracts' deployment and their setup (calling each other functions like privileges, access and so on):

On the development network everything works fine. When I change network to ropsten it cancels migration at totally random time. Once it's at "2", once at "13". It's totally randomness. To be clear: it's not the contracts' problem, because thair gas limit is below 4867350 limit. The message that comes with cancel is:

Returned values aren't valid, did it run Out of Gas?

If I continue migration it throws errors like contract not deployed or it won't call functions. It's weird, I know, but that happened to me moment ago. The only way is to perform migration over again with --reset param or deleted build folder. It's really lucky for me to finish the migration with success. I have already lost a lot of ropsten's ether (fortunately free), but I'm really afraid I could lose  ether on mainnet, because the whole migration costs over 2 ether.

Here is my truffle config for ropsten:

gas: 4867350,
gasPrice: 10000000000,
confirmations: 2,
timeoutBlocks: 200,
skipDryRun: true

What can I do to make ropsten working correctly?


texts: Can we create a token with some data inside it?

texts:
I wane to write some data (like a link to some file etc) in a token, and once someone sends it from one address to another, that data should be sent as well. Is there anyway we can do now? or you this its not feasible?

Thanks,


texts: Oraclize ethereum bridge : Notifying __callback tx error to frontend

texts:
I have called API dynamically using Oraclize with the delay of 10 minutes. The code is shown below and it works well.

  uint256 constant DELAY = 60*10;
  event Log(string result);

  function __callback(bytes32 _queryID,string memory result,bytes memory _proof)public
  {
    emit Log(result);
  }

  function update()public payable{
    oraclize_query(
        DELAY,
        "URL",
        "json(https://api.coinbase.com/v2/prices/ETH-USD/spot).data.amount"
    );

}

But if I got _callback transaction error while running the above code in ethereum-bridge and
How to notify that error to the front end?

Platform : Privatenet
solidity: 0.4.21
Truffle : 4.1.5


texts:
I have a contract deployed to the Rinkeby testnet. It includes the following function:

function deposit(uint amount) payable public {
    require(msg.value == amount);
}

If I try to send ETH to this contract by calling this deposit() function with an amount that does not satisfy the condition in require, it should fail -- and it does, in Rinkeby.

But if I switch my account to Mainnet and try calling the same function(via RemixIDE), the transaction completes and my ETH actually gets sent.

Why is this happening? Is it due to the fact that my contract was not deployed to Mainnet, and therefore a tx from Mainnet is no different than sending ETH to a random address?


texts: How to know which ERC20 tokens a wallet owns?

texts:
On Etherscan, when you view the details for a particular address, you can see a list of ERC20 tokens which are owned by that address:

How does Etherscan do this? It is my understanding that you have to call a function on each ERC20 contract to see the balance for a particular address. Is there some function in web3 that provides this information?


texts: I have an array that will be subject to lookup and insertion operations. It is likely that it will increase in size considerably. Does solidity offer any means of performing efficient lookup operations? or libraries for binary search, for example?


texts: Calling another smart contracts function which executes an event

texts:
I am trying to call another contracts function. When I test this in remix and inspect the transaction I don't see that the event is executed. No error is display either.

I execute check function in caller.sol passing the callee.sol contract address but the event never runs

caller.sol

contract Caller {
    function check(address callbackAddress) returns (string) {
           callbackAddress.call(bytes4(sha3("callMe")));
           return 'something';
    }
}

callee.sol

contract Callee {
    event EventTest(string value1);

    function callMe(string value) returns (string) {
            EventTest('testing')
    }
}


texts:
I get an error in the code below.
function test2(address _t) public { // Owned no deploy address => owned()
        if (!_t.call.value(msg.value)(bytes4(keccak256("test()")))){
            revert();
        }
    }

browser/AccessRestrictionsol.sol:49:39: TypeError: Invalid type for argument in function call. Invalid implicit conversion from bytes4 to bytes memory requested. This function requires a single bytes argument. If all your arguments are value types, you can use abi.encode(...) to properly generate it. if (!_t.call.value(msg.value)(bytes4(keccak256("test()")))){ ^-------------------------^
browser/AccessRestrictionsol.sol:49:13: TypeError: Unary operator ! cannot be applied to type tuple(bool,bytes memory) if (!_t.call.value(msg.value)(bytes4(keccak256("test()")))){ ^----------------------------------------------------^
browser/AccessRestrictionsol.sol:49:13: TypeError: Type tuple(bool,bytes memory) is not implicitly convertible to expected type bool. if (!_t.call.value(msg.value)(bytes4(keccak256("test()")))){ ^----------------------------------------------------^

I'm a beginner so I don't know,
Is there only two ways, the way using abi.encodeWithSelector () and the above way?
How many other ways are there to call a function of other contracts?
And which one works as the most generic way to call the contract method?
Using the above code as an example, please tell me the difference in the meaning of each way that generally works as a way of calling other functions.


texts: How to communicate with smart contract using python?

texts: I have developed a smart contract on remix IDE and now I want to communicate with it using python. What python libraries can I use ?


texts: Why is it considered a bad practice to burn tokens to 0x0 when creating an ERC20 token?

texts:
The Consensys Smart Contract Best Practices guide recommends to prevent transferring tokens to the 0x0 address.
I understand that 80M or more is locked at this address, but so what? Why is that bad, it's the burn address right?
Where should we burn the tokens if not at 0x0?


texts: Unable to call ERC20's balanceOf() from another (ERC20)contract

texts:
I was managed to use transfer() function of the token from my contract, however, the balanceOf() function will only return 0. (or it seems on MyEtherWallet)

I was testing a case where the smart contract receives a token from EOA(Bittrex account) and transfers to another EOA(MyEtherWallet account).

So I've deployed my smart contract below from MyEtherWallet and sent tokens (Golem in this case) to this contract.

Then, I have called transfer() function of the token(Golem) and successfully transferred the token to my MyEtherWallet account.

I have checked the balance by visiting the (Golem) token's contract on Etherscan which has been successfully transferred to my account(MyEtherWallet account).

However, whenever I try to read the balance of the token from my contract, it only shows 0.

I thought this was due to the decimals so I have tried multiplying, dividing the amount that would have returned from balanceOf() function. However, none of them works. It only shows 0.

I am so lost here and asking for more advanced solidity developer's help.
What can I do to make a contract that reads the balance of the token?

Thank you for listening.

Here's the smart contract code that I have made.

P.S. Thought the problem was constant, tried using view, did not work.
     Also, this code does not have a function that multiplies the returned balance.

pragma solidity ^0.4.24;

contract ERC20Basic{

function balanceOf(address _owner) external constant returns (uint256 balance);
function transfer(address to, uint256 value) public returns (bool);

}

library SafeMath {//SafeMath Code}

contract TokenTransferContract{

using SafeMath for uint256;

address _owner;
address _tokenAddress;
ERC20Basic erc20Instance;

constructor () public {

    _owner = msg.sender; //Contract distributor is the owner of this contract.

}

// Setting the instance to call functions from different contract (In this case ERC20 Token's function)

function setTokenInstance(address _tokenContractAddress) public {

    _tokenAddress = _tokenContractAddress;
    erc20Instance = ERC20Basic(_tokenContractAddress);

}

//transfer function works.

function transferContractTokenToOwner(uint256 _tokenAmount) public {
    require(_owner == msg.sender);

    erc20Instance.transfer(_owner, _tokenAmount); //Transfering the amount of token that was allocated with the address of this(UserTokenWalletContract) address to Owner(EOA).

}

function getAmountOfTokenOfOwner() view public returns (uint256 _amount){
    require(_owner == msg.sender);

    _amount = (erc20Instance.balanceOf(_owner)).div(1000000000000000000);

}

function getAmountOfTokenOfContract() view public returns (uint256 _amount){

    require(_owner == msg.sender);

    _amount = (erc20Instance.balanceOf(address(this))).div(1000000000000000000);

}

 function noneDecimalGetAmountOfTokenOfOwner() view public returns (uint256 _amount){
    require(_owner == msg.sender);

    _amount = erc20Instance.balanceOf(_owner);

}

function noneDecimalgetAmountOfTokenOfWalletContract() view public returns (uint256 _amount){
    require(_owner == msg.sender);

    _amount = erc20Instance.balanceOf(address(this));

}

function getOwnerAddress() view public returns (address _ownerAddress){
    _ownerAddress = _owner;

}

function getContractAddress() view public returns (address _contractAddress){
    _contractAddress = address(this);

}

function getContractInstanceAddress() view public returns (address _contractInstanceAddress){
    _contractInstanceAddress = _tokenAddress;

}

}


texts: Web3: constant get function - error: is not a function

texts:
I keep getting this error where my web3 throws an error saying that getCardByID is not a function, but it is clearly defined in my deployed smart contract. What am I missing here?

Smart contract code:

function getCardById(uint id) constant returns (uint idRet, string name, string email, string comment){

for (uint i = 0; i < count; i++) {

    if (cards[i].id == id) {

        idRet = cards[i].id;

        name = cards[i].name;

        email = cards[i].email;

        comment = cards[i].comment;

        return;

        }

    }

HTML/Jscript code:

 //pulls a record from the blockchain based on ID #
      function getCardByID() {
          web3.personal.unlockAccount(web3.eth.accounts[0], 'scrubbed');
          var vID = $("#id").val(); //pulls value from user input field
          var card = contract_instance.getCardByID(vID);
          console.log(card);
      }

Any help is greatly appreciated; thank you in advance.


texts:
I would like to know if this is possible to check in a simple way if a bytes32 value exists in an array of bytes32 value please?

contract Test {
    struct TestStruct {
        string name;
        bytes32 value;
    }

    struct ConfigStruct {
        bytes32[] valuesPossible;
    }

    TestStruct[] public structs;
    ConfigStruct[] configs;

    function constructor(bytes32[] _valuesToStore) public {
        configs.push(ConfigStruct(_valuesToStore));
    }

    function add(string _name, uint _idConfig, bytes32 _valueToStore) valueIsPossible(_idConfig, _valueToStore) public {
        structs.push(TestStruct("test", _valueToStore));
    }

    modifier valueIsPossible(uint _idConfig, bytes32 _valueToStore) {
        //require(configs[_idConfig].valuesPossible[_valueToStore]); // How to check that
        _;
    }
}

Thanks by advance

EDIT: Sorry my code was not very accurate, I updated it


texts: eth node is stuck on currentBlock, startingBlock > currentBlock

texts:
I recovered my SSD drive where I store my chaindata.  Geth has been running for a couple days, and yet currentBlock never increments:
> eth.syncing
{
  currentBlock: 11043159,
  highestBlock: 11091147,
  knownStates: 592880595,
  pulledStates: 592880595,
  startingBlock: 11065579
}

Shouldn't startingBlock < currentBlock?  I can't quite figure out what's going on, is there a way to set startingBlock?


texts: Strange popup window trying to send ether when I run aleth zero. What should I do?

texts:
I ran aleth zero and mined with aleth one a while back.  I had mined some ether from a mining pool.

Now when I run aleth zero (updated client for windows), I get an annoying and unstoppable pop up window that says:
Transaction

DApp is attempting to send 1.048 ether to a recipient ______, with additional network fees of up to 1.5 finney.  Maximum total cost is 1.05 ether.

I have never made a contract and I don't think I tried sending ether to anyone in the past.  How can I get rid of this popup and why exactly is it happening?


texts: How can i transfer ERC20 tokens from a contract to an user account?

texts:
I have deployed an ERC20 token (contract A) and the tokens are being used for a service in my other contract (Contract B). I can easily transfer tokens from an user owned account(EOA) to Contract B after i call approve on the token Contract A to allow Contract B. However, I am not able to transfer tokens from the Contract B back to the user account. Is there any way I can achieve that?

This works when transferring tokens from EOA to Contract B.

token.transferFrom(msg.sender, this, 100)

However, the other way round doesn't seem to work.

token.transferFrom(this,msg.sender, 100)

Do i need to call any other functions on the original token contract A ?


texts:
I am trying to listening to many events from infura but it is not working. Only one filter work, when I add the second filter, this message appear:
RuntimeError: cannot call recv while another coroutine is already waiting for the next message
Exception in thread Thread-15:

and after about 2 seconds, this error message appear:
raise ValueError(response["error"])
ValueError: {'code': -32000, 'message': 'filter not found'}

and The following is my python code:
import threading
import time
from web3 import Web3
import json

PROVIDER = "wss://ropsten.infura.io/ws/v3/f5000000000000"
web3 = Web3(Web3.WebsocketProvider(PROVIDER))

truffleFile = json.load(open('/Users/a/ropsten/build/contracts/a.json'))
abi = truffleFile['abi']
bytecode = truffleFile['bytecode']

contract = web3.eth.contract(abi= abi, address= '0x000000000000000')

 # ------------------------------------------------------------

def handle_event2(name,event):
     print('the event is from :%s'%name)
     print(event)

def log_loop2(name,event_filter, poll_interval):
     while True:
        for event in event_filter.get_new_entries():
            handle_event2(name,event)
        time.sleep(poll_interval)

def PS_listen():
     print(" I am in PS Listen ")
     block_filter = contract.events.PS.createFilter(fromBlock = 'latest')

     worker1 = threading.Thread(target=log_loop2, args=('Th-1',block_filter, 2,))
     worker1.start()

     print(" I am in PS Listen after start")

def handle_event2(name,event):
     print('the event is from :%s'%name)
     print(event)
# ---------------------------------------------

def log_loop2(name,event_filter, poll_interval):
      while True:
           for event in event_filter.get_new_entries():
               handle_event2(name,event)
      time.sleep(poll_interval)

def listen():
     print(" I am in Listen ")
     block_filter = contract.events.PS.createFilter(fromBlock = 'latest')

     print(block_filter)
     worker2 = threading.Thread(target=log_loop2, args=('Th-2',block_filter, 2,))
     worker2.start

     print(" I am in Listen after start")

 print(" This is the main function1")
 PS_listen()
 listen()
 print(" This is the main function2")

Note: I have added my Infura project ID correctly. The contract address is coped from the terminal after deploy it on Ropsten infura.
Is it threading problem which prevent me to create another filter for the next event while the error means a coroutine is running in another mission???
Any help please is much appreciated to solve this problem


texts:
As per this documentation, I'm trying to send a signed transaction.

Here's what I have

def send(web3, wallet_private_key, gas_price, transactionABI, value=0):
    options = {
        'to': units_address,
        'data': transactionABI,
        'gas': gas_price,
        'gasPrice': gas_price,
        'value': value
    }
    signed = web3.eth.signTransaction(options)
    receipt = web3.eth.sendRawTransaction(signed.rawTransaction)
    return receipt

send(web3, wallet_private_key, gas_price, transactionABI)

But I'm getting the following error

ValueError: {'code': -32601, 'message': 'The method eth_signTransaction does not exist/is not available'}

I'm using infura and it seems like this may be the issue but II'm having a hard time finding instructions for how to send a transaction otherwise.


texts: eth_estimateGas Error when balance of an account < the amount to send in a transaction

texts:
I have used the following request to estimate gas in an ETH transaction in Ropsten.
## JSON-RPC over HTTPS POST
curl https://ropsten.infura.io/v3/YOUR-PROJECT-ID \
    -X POST \
    -H "Content-Type: application/json" \
    -d '{"jsonrpc":"2.0","method":"eth_estimateGas","params": [{"from": "fromAddress","to": "toAddress","gas": null,"gasPrice": null,"value": "0x9184e72a","data": null}],"id":1}'

But when the balance of the account(toAddress) is less than the amount to be sent in a transaction(value), the response contains the following error message.
{
    "jsonrpc": "2.0",
    "id": 1,
    "error": {
        "code": -32000,
        "message": "err: insufficient funds for transfer: address 0x...DFCsbds807 (supplied gas 4010499)"
    }
}

The same request and condition in Kovan return the estimated gas.
{
    "jsonrpc": "2.0",
    "id": 1,
    "result": "0x5208"
}

Is it necessary to maintain this condition (balance of an account > the amount to send) to execute eth_estimateGas? Though this was not the case previously. Mainnet also behaves the same as Ropsten.
Is there a way to work this when the balance of an account < the amount to send?


texts: Any Detailed Documentation On The New Geth v1.4.0 JSON-RPC Protocol Revisions Yet?

texts:
I read that geth v1.4.0 had a complete overhaul related to the JSON-RPC protocol. Now that v1.4.0 is nearly a stable release, I am curious to find out if any of these latest revisions have been documented anywhere yet for developers to use in their applications?

I have resumed building an app which I started last summer (devoting to it full time 5 days per week starting May 2nd until a stable release), which relies almost completely on the geth JSON-RPC protocol...so I'm keen to understanding the latest / greatest features fully as soon as possible.


texts: How to deploy smart contract automatically in rinkeby network through web3.js?

texts:
I am deploying a DAPP in which after getting the inputs from the users I have to deploy a smart contract in Rinkeby test network.

After getting the inputs from a user I am writing the .sol file using Nodejs and storing it in Amazon EC2 instance. Now, how will I deploy this contract in Rinkeby network?


texts:
i am following a tutorial from here. And upon running truffle test. It produces following error.

2_HashnodeCrowdsale.js
    ======================

       Deploying 'HashnodeCrowdsale'
       -----------------------------
    Error:  *** Deployment Failed ***
    "HashnodeCrowdsale" -- invalid number value (arg="_goal", coderType="uint256", value=2000000000000000000).

        at /home/lubuntu/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/packages/truffle-deployer/src/deployment.js:364:1
        at process._tickCallback (internal/process/next_tick.js:68:7)
    Truffle v5.0.12 (core: 5.0.12)
    Node v10.15.3


texts: Why would you use promises over async when writing JS unit tests in truffle?

texts: I'm getting started with writing JS unit tests in the Truffle framework.  I'm curious to learn when to use promises over async?  On the surface, async seems a lot cleaner and easier to use for testing purposes.


texts:
I have a function in one contract that looks like this:

//Events
    event RequestReceived(bytes s);
    event WorldCreated(bytes32 indexed worldName, address indexed sender, address result );

function createWorld(bytes32 name) returns (World a){
        RequestReceived("createWorld fired");

        World w = new World(name);
        worldContracts.push(w);

        WorldCreated(name,msg.sender,w);
        return w;
    }

Its purpose is to instantiate and store a reference to a contract called 'World'
This is a POC game I am making where the gameworld, players and items etc exist purely within the blockchain.

I then invoke this from C# via Nethereum via:

public static string CreateWorld(string world)
        {

            var web3 = new Web3(Resources.Server);
             // Contract address
            var contract = web3.Eth.GetContract(Resources.ContractInterface2, address);

            var add = contract.GetFunction("createWorld");                         // Add method
            var worldCreatedEvent = contract.GetEvent("WorldCreated");
            var filterAll = worldCreatedEvent.CreateFilterAsync().Result;
            var totalGas = GenericUtil.GetGasPrice(add, world);
            UnlockAccountForTransaction();
            var callResult = add.SendTransactionAsync("0x13111c7C98dFb371A4dd6cD1B1D9E6285bE68d2e", totalGas, new HexBigInteger(0), world).Result;
            var theResult = GenericUtil.GetReceiptAsync(web3, callResult);
            var log = worldCreatedEvent.GetAllChanges<WorldCreatedEvent>(filterAll).Result;

            return log[0].Event.Result;
        }

However, when I watch the contract that fires these events  - I can see the RequestReceived and WorldCreated events appear in Mist/Ethereum Wallet - but when I run the C# code - it always detects 0 log entries.

I've tried changing filterAll to

var filterAll = worldCreatedEvent.CreateFilterAsync().Result;

and

var filterAll = worldCreatedEvent.CreateFilterAsync(world).Result;

Bot result in 0 log entries for the event

Note - Ether for gas shouldn't be a problem here- as I am on a private network and have plenty, I am actually supplying double the estimate from the GetGasPrice function.

I am also able to see in the WorldCreated Event in mist that the result is a valid contract address - so a World was created.
I am able to do

debug.traceTransaction("0x....");

in geth to see that the transaction ended on a return statement - presumably the return w;
(Granted, the debug.traceTransaction had about 516 operations being carried out, but it still ended with a good load of gas left in the engine.)

Does anyone have any idea why nethereum is unable to retrieve these events even though they are being fired in geth and visible in mist?


texts: Use other than default account in testrpc

texts:
I am using embark to deploy my contracts.What I need is to call a contract function from a different account rather than account[0] generated by testrpc.
i.e. msg.sender should contain the address of account[1] or account[2] or account[n] where n is less than the number of accounts generated. There should be a way to do so for manual testing purposes in embark console right?


texts:
I have tried a lot of combinations of the following code but nothing updates the students array.

pragma solidity ^0.4.18;

contract CA3 {

  uint public test=9;
  struct Student {
    uint age;
    uint income;
    uint score;
    uint attendance;
  }
  Student[] public students;
  uint public studentCount=0;

  function setStudent (uint _age, uint _income, uint _score, uint _attendance) public {
    test=19;
    students.push(Student({age: _age, income: _income, score: _score, attendance: _attendance}));
  }
}

It does not give an error but it does not ever modify students. Has anyone any idea about this?

I am testing in geth:

> con.setStudent(1,1,1,1)
"0x3bf6788c442a8495286cfccf7f8b18250cf1577a59b0d57e6a24b7e892dd2365"

 > con.students(0)
[0, 0, 0, 0]

> eth.getStorageAt(con.address,0)
"0x0000000000000000000000000000000000000000000000000000000000000009"
> eth.getStorageAt(con.address,1)
"0x0000000000000000000000000000000000000000000000000000000000000000"

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

I tried a lot of combinations of code but nothing updates students.


texts: Can a contract variable be referenced from the outside?

texts:
Is a value of the variable of the contract visible from the outside ?
For example,

contract Dummy {
  uint a = 0;
  function increment() {
    a = a + 1;
  }
}

This contract is on the ethereum blockchain. In this situation, can I look the current value of "a" ?


texts:
I am bit confused regarding NFT implementation usng ERC-1155 because of newbie in NFT, by defination, there can be one instance of one NFT, there is one uuid per artwork. But in ERC-1155, I can set X amount per ID, so

This NFT thing, having one instance or amount per UUID will be managed on App side or there can be multiple instances of one uuid?
If I mint a token by setting token ID  as uuid and path of actual image in metadata file. What if that image file replaced as that is not on Blockchain?
How can I setup commission while minting NFT using ERC-1155, or it is again to be managed on app side?
Is there a way if I want to prevent sale/purchase outside my app?


texts: Where can I learn to read a flow of opcodes and learn how to debug transactions?

texts:
There are many tools and visualizers to use to read through a transaction, but where can I go to learn how to understand this?

Fore example, that first link has a series of opcodes (and their associated gas and depth). If I had access to the contract, would I be able to compare the opcodes to different parts of the contract? Do solidity functions match up with opcode(s)? In order to read this, must I see a group of say 5 opcodes and know "oh this is adding two numbers"?


texts: How does solidity detect that Ether has been sent from one address to the other address?

texts:
I have learned solidity. And I have one question.

How does contract detect that Ether has been sent from one address to the other address?


texts: Automatic ERC20 Token Payment System - How to

texts:
Before starting to detail my problem, I must say that I am new to ERC20 Tokens and I write this question in ask for guidance.

Is it possible that I can forge a payment system on an ERC20 token?

What I want to do is somehow automatize the Send Ether & Tokens procedure from MyEtherWallet.

The scenario is the following : Let's say that I have a trading platform. User A is the producer of a random product and user B is the client that wants to buy the product. How can I make the users pay using an ERC20 token on a single click ( buy button ), and moreover, how can I do this automatically?

Any kind of help/guidance is really appreciated.

Thank you!


texts: Do the Keystore / json files the same across different wallets?

texts:
So I downloaded a version of MyEtherWallet.com onto my computer and generated a new wallet. It gave me a keystore which when decrypted contains my private and public keys.

I plan to buy some ethereum and have it for many years without touching it.

When I do want to access it, who knows whether MyEtherWallet.com will still exist.

So my question is, is this keystore file in some sort of common format that all ethereum wallets will understand or would I need to use MyEtherWallet to unencrypt it?

If so, I was thinking might be a good idea to put a version of the MyEtherWallet site on the USB drives where I will keep my keystore file.


texts: How to listen to the ether address for balance from my node?

texts: I am running ether node. I have to listen to the transactions continuously to check whether my address received any transaction or not. It is like listening to the address forever and update whenever my address is involved in any transaction, I should get a notification. In bitcoin blockchain, I can do this using 'ZMQ'. It pushes the confirmed and unconfirmed transactions to 'ZMQ'. I want to know how to do it using ether blockchain. Could anyone explain?


texts: Backslashes being removed and unable to set Solc in windows 10

texts:
I've installed Geth on win 10 and I'm trying to link solc but I'm not sure why the backslashes are being removed?  How can I get past this error?

> admin.setSolc("C:\Program Files\Ethereum\solc")
exec: "C:Program FilesEthereumsolc": file does not exist
    at InvalidResponse (<anonymous>:-81662:-48)
    at send (<anonymous>:-156322:-48)
    at setSolc (<anonymous>:-133322:-48)
    at <anonymous>:1:1

Thanks.


texts: Create login on website using blockchain

texts:
Im looking to make a small website with some different actions in a "company". This is based on a blockchain and at the moment you can enter an address and then do the action. I would like to do it such that you not only have to enter your address but also the secret key belonging to that address or something similar, is there a way to do that?
Thank you in advance


texts:
Towards the very beginning of the Ethereum release, a friend participated in a Ponzi scheme dapp by sending 1 ETH here. He was among the first!

For some reason, it seems he has not received any payout. Actually, the block explorers does not show any payouts, even though the contracts balance is much lower than what it received.

How can I see the payouts of this Ponzi scheme dapp?


texts: contract sendTransaction does not return transaction hash

texts:
I just started with truffle react box..
and i changed a little bit to :

const tx = await instance.set.sendTransaction(999,{from : accounts[0]});
console.log("tx is on the way : ",tx);
const txReceipt = await getMinnedTxPromise(tx);
console.log("tx minned !",txReceipt);
const response = await instance.get.call({from : accounts[0]});
console.log("the response is : ",response.toNumber());
this.setState({storageValue : response.toNumber()});

i added .sendTransaction() so that i could atleast see the transaction has begun. but when i ran this code, this line

   console.log("tx is on the way : ",tx);

it logged after the transaction was minned.
when i tried .sendTransaction() from trufle console, it did log the transaction hash right away.. only when i try to run this in browser, it doesnt work as expected..


texts: Are crypto-token holders disincentivized to spend their tokens?

texts:
Are holders of crypto-tokens that have real utility within a specific application disincentivized to spend their tokens because they fear that the value of the tokens will go up after they spend them?

If yes, are crypto-token powered applications running into issues since their users are afraid to actually spend their tokens to utilize their service?


texts: Cannot read property 'contract' of undefined. Node api interacting with smart contract

texts:
Hi I'm trying to interact with an Ethereum smart contract from my node js api.

My controller function is as follows:

var web3 = require('web3');

module.exports.getTokenBalance = function(req, res) {
var abi = //long ABI
var MyContract = web3.eth.contract(abi);

  // initiate contract for an address
  var myContractInstance = MyContract.at('...');
  myContractInstance.balanceOf.call('addr', function(err, data) {

  }
}

I'm using the web3@0.20 package. When I try to call this API function I get the following error :

  "Cannot read property 'contract' of undefined."

Am I missing something stupid?


texts: Is it a good practice to store a lot of keys in a string array in smart contracts?

texts:
I am working on a project where blockchain will be used on a supply chain. One can create and transfer assets to another in the same.

Whenever one is creating an asset or transferring any asset, that action is being stored in the smart contract's string array.

And the strings quite big, for eg.  "Token Tkn56fg2 is created by vendor with ID 4123" or "Tokens Tkn5rts2, Tkn67htf were transferred from vendor 5612 to vendor 4523" and so on...

All these actions are stored so that every action happened till date can be seen by anyone. In the dashboard section of my frontend, I'm taking this entire string array, and displaying these actions as individual actions taken place till date.

My question is, is this a good practice to store the actions in  a string array? Obviously this seems like it is not. But since I'm required to store all the actions till date, and also don't want anyone to make changes to these, I'm avoiding storing these in any other databases.
Pardon me if my question did not make sense. Also any suggestions to a different approach would be appreciated. Thank you.


texts: Why would Web3 return an empty array after calling the solidity function

texts:
So I want to interact with my Smart Contract from remix with python library called Web3.
The problem is when I try to call the function from the smart contract it runs successfully but it only returns an empty array instead of the actual data.
Solidity Code:
pragma solidity 0.5.1;

contract MyContract {
    Evidence[] public evidence;

    struct Evidence {
        string name;
        string location;
    }

    function addPerson(string memory name, string memory location) public {
        evidence.push(Evidence(name, location));
    }
}

Python Code:
import json
from web3 import Web3

url = 'HTTP://127.0.0.1:7545'
web3 = Web3(Web3.HTTPProvider(url))

web3.eth.defaultAccount = web3.eth.accounts[0]

abi = json.loads('my json')
bytecode = "my bytecode"

status = web3.isConnected()

if status == True:
    print("Connected")
    MyContract = web3.eth.contract(abi = abi, bytecode = bytecode)
    transaction = MyContract.constructor().transact()
    receipt = web3.eth.waitForTransactionReceipt(transaction)
    contract = web3.eth.contract(
        address = receipt.contractAddress,
        abi = abi
    )
    tx_hash = contract.functions.addPerson("Adam", "Near House").call()
    print(tx_hash)

else:
    print("Not Connected")


texts: What is GHOST and what is its relationship to Frontier and Casper?

texts: As high-level as possible without losing important meaning, what's the intuition behind GHOST?  How is it currently implemented in Frontier?  What will be different with GHOST in Casper?


texts:
I have this function and require the _price variable to be positive, But when I pass a negative int, it accepts the integer! How can I validate the input?
The Contract :
function createProduct(string memory _name, uint _price) public {
    require(bytes(_name).length > 0);
    require(_price > 0);
    //..... emit the product name & price
}

Test JS with moka & chai :
let createProductResult;
//before
createProductResult = await marketplace.createProduct('test', -1);

//it ...
const creationEvent = createProductResult.logs[0].args;
console.log(creationEvent.price.toString());

Not only the request is not rejected but also the console gives me 115792089237316195423570985008687907853269984665640564039457584007913129639935
for the price I just sent!


texts:
I'm thinking to create a server-less backbone for the wellness tracking app we are working on (https://sentimoto.com) with the following main principles:

every user generates his own blockchain of his data
this blockchain can be shared to a number of users (i.e. users may have access to multiple)

Basically it means that the distributed proof-of-work is not necessary as each user can write only to one (his own) blockchain, but other Ethereum technologies seem to be a good fit.

The questions are:

what do you think about the idea?
are ethereum technologies appropriate for this project (and state of maturity are they)?
is any other project better for this purpose?

Sincerely
Max


texts: Truffle does nothing and shows no output when running tests

texts:
I am switching machines and ran into a weird issue with truffle.  Truffle is set up properly on my old machine.  I can compile and run tests without any issues.  To my knowledge, I set up everything the same way on my new machine.  All tests and source files were pulled from a repo, so I at least know my project directory is identical on both machines.

When I attempt to run tests on my new machine via truffle test, the console hangs for about ten seconds, then the terminal prompt reappears:

benjamin@spectre-laptop:~/git/busd/ethereum$ truffle test
benjamin@spectre-laptop:~/git/busd/ethereum$

I do not receive any output or errors.  This also occurs with truffle deploy and truffle compile.

If I run truffle build, I see the following:

benjamin@spectre-laptop:~/git/busd/ethereum$ truffle build
No build configuration found. Preparing to compile contracts.
benjamin@spectre-laptop:~/git/busd/ethereum$

Does anyone know what the issue is?


texts: Making assertions (assert.equal) on two return values in Truffle

texts:
Appreciate any help I can get. I am trying to make an assertion on returned values from a smart contract, and I cannot figure out how to get it to work for a Truffle test. I cannot show all my code in raw format because it is sensitive in nature, but here is what you need from the test:

it("should accept a list of obj's and return a string & addr", async () => {
    let cInstance = await Contract.deployed("tester2");
    let cAddress = cInstance.address;
    let returnResult = await cInstance.submission.call("tester2","0xdade","type2","0xwizards",[1,"2","4",4]);
    assert.equal(returnResult.valueOf(), "0xdade", {contractaddress});

Here is the function I'm calling on contract:

function submission(string memory Id, string memory vId, string memory entryType, string memory hashSig, uint256[] memory list) public returns(string memory, address) {

    return(submittedObjStructs[vId].vId, address(this))
}

The contract function returns a string and the contract address, which comes back in an object format.

When I try to use assert.equal(result.valueOf(), string value, address value) it doesn't work and gives me an error that the values don't match for various reasons. And if I try array notation like assert.equal(result[0].valueOf(), string value) I get a vm error and the transaction reverts. Any way I can compare the value of the object that comes back from the function call: {0: '0xdade', 1: '0xcontractaddressexample'}


texts:
I want add and store more than 16 variables value in in my private blockchain, I am unable to define the variable in Struct {}, I got Error

  "InternalCompilerError: Stack too deep, try removing local variables".

Please tell any one how to store it, Also please see my code below.

pragma solidity ^0.4.0;

contract People {
    Person[] public people;
    struct Person {

        bytes32 referral_type;
        bytes32 student_name;
        bytes32 grade;
        bytes32 iep_status;
        bytes32 staff_name;
        bytes32 reff_date;
        bytes32 reff_time;
        bytes32 location;
        bytes32 problem_behavier;
        bytes32 perceived_motivation;
        bytes32 others_involved ;
        bytes32 action_token;
        bytes32 notes;
        uint lastID;

        bytes32 notes1;
        bytes32 notes2;
        bytes32 notes3;
        bytes32 notes4;

   }

    function addPerson(bytes32 _referral_type,bytes32 _student_name,bytes32 _grade,bytes32 _iep_status,bytes32 _staff_name,bytes32 _reff_date,bytes32 _reff_time,bytes32 _location,bytes32 _problem_behavier,bytes32 _perceived_motivation,bytes32 _others_involved,bytes32 _action_token,bytes32 _notes,uint _lastID) public returns (bool success) {

      Person memory newPerson;
      newPerson.referral_type = _referral_type;
      newPerson.student_name = _student_name;
      newPerson.grade = _grade;
      newPerson.iep_status = _iep_status;
      newPerson.staff_name = _staff_name;
      newPerson.reff_date = _reff_date;
      newPerson.reff_time = _reff_time;
      newPerson.location = _location;
      newPerson.problem_behavier = _problem_behavier;
      newPerson.perceived_motivation = _perceived_motivation;
      newPerson.others_involved = _others_involved;
      newPerson.action_token = _action_token;
      newPerson.notes = _notes;
      newPerson.lastID = _lastID;

      people.push(newPerson);
      return true;
    }

    function getPeoples() public view returns (bytes32[],bytes32[],bytes32[],bytes32[],bytes32[],bytes32[],bytes32[])
    {
        uint length = people.length;

        bytes32[] memory referral_types = new bytes32[](length);
        bytes32[] memory student_names  = new bytes32[](length);
        bytes32[] memory grades         = new bytes32[](length);
        bytes32[] memory iep_statuss    = new bytes32[](length);
        bytes32[] memory staff_names    = new bytes32[](length);
        bytes32[] memory reff_dates     = new bytes32[](length);
        bytes32[] memory reff_times     = new bytes32[](length);

        for(uint i=0;i<people.length;i++)
        {
            referral_types[i] = people[i].referral_type;
            student_names[i]  = people[i].student_name;
            grades[i]         = people[i].grade;
            iep_statuss[i]    = people[i].iep_status;
            staff_names[i]    = people[i].staff_name;
            reff_dates[i]     = people[i].reff_date;
            reff_times[i]     = people[i].reff_time;
        }
        return (referral_types,student_names,grades,iep_statuss,staff_names,reff_dates,reff_times);
    }
   }


texts: POA: Geth node (miner) automatically stops after 3-4 hours which results in primary node pausing and looking for peers

texts:
I have set up 2 Geth nodes with POA on different machines. After starting bootnode and starting Geth nodes, they sync well and starts mining alternately. If I manually stop a node, other node keeps looking for peer. If I restart both nodes, they start working well again. But after 3-4 hours, when they pause miner to " Writing cached state to disk" and "Persisted the clean trie cache", Node2 tries to restart mining and following errors occurs:
0|ethNode2 | ERROR[08-20|10:28:37.169] Etherbase account unavailable locally      err="unknown account"
0|ethNode2 | WARN [08-20|10:28:37.170] Served miner_start                         conn=84.147.159.252:62347 reqid=1134 t="323.102µs" err="signer missing: unknown   account"
0|ethNode2 | INFO [08-20|10:28:37.990] Submitted transaction                      fullhash=0x4336151b175d4d67f68a2760c995ff0c9cb14823c0ba11634cbac1dfb85bbd88 reci  pient=0x352828EF008Cf9f63Cc79ec002449E2d8B16370a
0|ethNode2 | INFO [08-20|10:54:28.648] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:55:31.673] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:55:54.716] Writing clean trie cache to disk           path=/home/pistis/ethereum/ethdata/geth/triecache threads=1
0|ethNode2 | INFO [08-20|10:55:54.717] Regenerated local transaction journal      transactions=1 accounts=1
0|ethNode2 | INFO [08-20|10:55:54.747] Persisted the clean trie cache             path=/home/pistis/ethereum/ethdata/geth/triecache elapsed=29.536ms
0|ethNode2 | INFO [08-20|10:55:55.682] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:56:06.703] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:56:16.724] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:56:26.746] Looking for peers                          peercount=1 tried=0 static=0
0|ethNode2 | INFO [08-20|10:56:36.766] Looking for peers                          peercount=1 tried=0 static=0 ```

Please note that in the error message `Served miner_start conn=84.147.159.252:62347` This is an unknown IP address so I think the miner tries to connect with an unknown node and is failing to find Etherbase account on that node?


texts: Self-test assessment for Ethereum vulnerabilities

texts: A while ago I found a wonderful website, where one is presented a series of smart contracts with vulnerabilities, and then has to fix these. However, I cannot find this application anywhere anymore, does anyone know this website or something similar?


texts: How is the 1GB dataset generated, which is used by the Ethash algorithm?

texts: I want to understand algorithmically how the 1GB dataset is generated and how it is updated based on block data in Ethash. I also would like to see, where in the code it is implemented in Go-Etherum. It would be appreciated if the link for that part of the code is attached with the answer.


texts: How is multiparty computation (MPC) possible using Ethereum?

texts:
MPC involves running calculations on numbers, perhaps from different parties, and sharing the result without anyone seeing the underlying data. Even the person operating the computer cannot access the information

How is this possible on ethereum?


texts: Creating a Geth Genesis File from Parity Chain Spec

texts:
I have a parity chain spec file that I'm running on several nodes in a private network.  I need to run a geth node and connect it to this private network.

How do I use this chain spec file to connect geth to the private network?


texts:
This is the code in my brownie.config.yaml file:
# exclude SafeMath when calculating test coverage
# https://eth-brownie.readthedocs.io/en/v1.10.3/config.html#exclude_paths
reports:
  exclude_contracts:
    - SafeMath
dependencies:
  - smartcontractkit/chainlink-brownie-contracts@1.0.2
  - OpenZeppelin/openzeppelin-contracts@3.4.0
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.0.2'
      - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@3.4.0'

 wallets:
  from_key: ${PRIVATE_KEY}
  from_mnemonic: ${MNEMONIC}

The error I receive when I try to run 'brownie run scripts/advanced_collectible/deploy_advanced.py":
brownie run scripts/advanced_collectible/deploy_advanced.py
Brownie v1.14.3 - Python development framework for Ethereum

  File "brownie/_cli/__main__.py", line 64, in main
    importlib.import_module(f"brownie._cli.{cmd}").main()
  File "brownie/_cli/run.py", line 38, in main
    if project.check_for_project():
  File "brownie/project/main.py", line 537, in check_for_project
    structure_config = _load_project_structure_config(folder)
  File "brownie/_config.py", line 243, in _load_project_structure_config
    data = _load_config(project_path).get("project_structure", {})
  File "brownie/_config.py", line 180, in _load_config
    return yaml.safe_load(fp)
  File "yaml/__init__.py", line 162, in safe_load
    return load(stream, SafeLoader)
  File "yaml/__init__.py", line 114, in load
    return loader.get_single_data()
  File "yaml/constructor.py", line 49, in get_single_data
    node = self.get_single_node()
  File "yaml/composer.py", line 36, in get_single_node
    document = self.compose_document()
  File "yaml/composer.py", line 55, in compose_document
    node = self.compose_node(None, None)
  File "yaml/composer.py", line 84, in compose_node
    node = self.compose_mapping_node(anchor)
  File "yaml/composer.py", line 127, in compose_mapping_node
    while not self.check_event(MappingEndEvent):
  File "yaml/parser.py", line 98, in check_event
    self.current_event = self.state()
  File "yaml/parser.py", line 438, in parse_block_mapping_key
    raise ParserError("while parsing a block mapping", self.marks[-1],
ParserError: while parsing a block mapping
  in "/Users/zeeshanbhatti/Desktop/nftDemo/brownie-config.yaml", line 3, column 1
expected <block end>, but found '<block mapping start>'
  in "/Users/zeeshanbhatti/Desktop/nftDemo/brownie-config.yaml", line 15, column 2

Any advice and background information on what this means would be much appreciated!


texts: Solidity Contract Invalid Opcode RPC Errors

texts:
I have a pretty straight-forward contract that let's you buy ERC721 Tokens.
My issue is that my "buyToken" function works half the time - and fails the other half of the time with the following error:
MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC
'{"value" :
    {"code" :-32603, "data":
       {"message" : "VM Exception while processing transaction: invalid opcode",
        "code" : -32000,
        "data":
        {"0xfd7b08996eb28759737deb2d695baaee53aaa0cea819d9f27a79181ccba021ae":
           {"error" : "invalid opcode",
            "program_counter" : 2687,
            "return" : "0x"},
            "stack" : "c: VM Exception while processing transaction: invalid opcode\n
                 at Function.c.fromResults (/usr/local/lib/node_modules/ganache-
                 cli/build/ganache-core.node.cli.js:4:194812)\n
                 at w.processBlock (/usr/local/lib/node_modules/ganache-cli/build/ganache-
                 core.node.cli.js:42:53376)\n    a
                 t processTicksAndRejections (internal/process/task_queues.js:93:5)",

            "name" : "c"
          }
       }
    }
}'

What I'd really like to know is how we are supposed to decipher these invalid opcode errors. Like what exactly does "code" :-32603 and "code" :-32000 actually mean?
What are the possible candidates of the issues I should be looking for?
To be clear: if my code failed 100% of the time and gave me this same error every single time, I would know with 100% certainly that it's my code that's bad. But it's working at least 50% of the time - and there's been absolutely no consistency in the failures.
I thought it might have to do with the PRICE of the Tokens - I have them ranging from 0.5 ETH to 15 ETH. But I could buy a Token for 1.5 ETH and have the Tx succeed, and then immediately try to buy another Token for the exact same 1.5 ETH amount - and that Tx would fail.
So this makes no sense.
Any tips on the sort of things I should be looking into with these invalid opcode errors?


texts: How to test if a TransactionHash is valid using web3?

texts:
Is there any way I can tell whether a transaction hash is valid or not?
For eg,

  0x2592cf699903e83bfd664aa4e339388fd044fe31643a85037be803a5d162729f is valid transaction Hash whereas 0x62720366ef403c9891e2bfbd5358ee3c8a57b113 is not.

How to test programmatically whether a transaction hash is valid or not using web3?

I wish to have a function like:

isValidTransactionHash(String txHash){
// if transaction hash is valid return true else false
}


texts: Is there a decentralized zk-SNARK (zero-knowledge Succinct Non-Interactive ARgument of Knowledge)?

texts:
Normally, in zk-SNARK, we need to generate two public keys: one for prover and one for verifier. However, the input parameter of this generator algorithm must be secret, meaning that it must be hidden for both prover and verifier.

And because of this, the process of those public generation is done by a trusted third party.

Since using a trusted third party is not desirable for decentralized blockchain, I am looking for a decentralized approach of those public key generation. Is there ? or it's impossible to have a decentralized zk-SNARK ?

P.S. More information about zk-SNARK is found here: https://media.consensys.net/introduction-to-zksnarks-with-examples-3283b554fc3b


texts: Augur: getShareToken returns error: invalid argument 0: json: cannot unmarshal hex string

texts:
I use the following code:

        augur.api.Market.getShareToken({
            _outcome: "0x1",
            tx: { to: _market },
        }, function (error, shareToken) {
            console.log(error, shareToken);
        });

This returns:

  Error: invalid argument 0: json: cannot unmarshal hex string of odd length into Go struct field CallArgs.to of type common.Address
      at parseEthereumResponse (/Users/jasperdegooijer/Documents/flux/initial-testing/augur-client/node_modules/ethrpc/src/decode-response/parse-ethereum-response.js:8:47)

This is the exact same code that's showed in the augur documentation: https://docs.augur.net/#market-call-api

I'm linking to a YesNoMarket address, maybe that's what causing the error? If so how'd I get the ShareToken addresses of a YesNoMarket?
I also tried adding from to the tx object but this didn't help.


texts: How to call function from child contract in parent contract?

texts:
I want to call function, which returns some value from child contract inside parent contract. Child contract will serve me as configuration, aka values from config contract can be reused in parent contract.

I tried to do something like this:

pragma solidity ^0.4.23;

import "./config.sol";

contract ParentContract{

    ConfigContract two;

    constructor() public{
        two = ConfigContract(msg.sender);
    }

    function getNameFromOtherContract() public view returns(string) {
        return two.getName();
    }
}

Config:

pragma solidity ^0.4.23;

contract ConfigContract{

    constructor() public{
    }

    function getName() external pure returns (string) {
        return "Amel";
    }
}

I use remix, I deploy ConfigContract first:

Then I deploy ParentContract:

When I then execute getNameFromOtherContract, I get error:

  call to ParentContract.getNameFromOtherContract errored: VM error:
  revert.


texts: atom-ethereum-interface returning different outputs from browser-solidity

texts:
I'm working on a proof-of-concept "email server" dapp and am getting different behavior in atom-ethereum-interface vs. browser-solidity

I'm running a private blockchain in a Docker container with my own nodes successfully mining all my transactions.

Here's my solidity code:

// EmailServer.sol

pragma solidity ^0.4.2;

contract EmailServer {
  address owner;
  bytes[] inbox;

  function EmailServer() {
    owner = msg.sender;
  }

  function addEmail(bytes x) constant {
    inbox.push(x);
  }

  function getInboxCount() returns (uint count) {
    return inbox.length;
  }

  function getEmails() returns (bytes email) {
    bytes emailsOutput;
    uint inboxCount = getInboxCount();
    uint emailLength;

    if (inboxCount == 0) {
      throw;
    }

    emailsOutput.push('[');
    for (uint i = 0; i < inboxCount; i++) {
      emailLength = inbox[i].length;
      emailsOutput.push('"');
      for (uint j = 0; j < emailLength; j++) {
        emailsOutput.push(inbox[i][j]);
      }
      emailsOutput.push('"');

      if (i < inboxCount - 1) {
        emailsOutput.push(',');
      }
    }
    emailsOutput.push(']');

    return emailsOutput;
  }

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

  // Kill contract and return funds to owner
  function kill() {
    if (msg.sender == owner) {
      suicide(owner);
    }
  }
}

This contract correctly compiles and deploys on both atom-ethereum-interface and browser-solidity.

In both places you can run addEmail("QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN") and it works fine.

But then in browser-solidity when you run getInboxCount() you get a result of: 0x0000000000000000000000000000000000000000000000000000000000000001 which decodes to a uint of 1.

When you run getInboxCount() in atom-ethereum-interface, the contract output is 0xab979d45598f6f3a548113f896a8d24681e9d231a5e3d614cae4b0dcee19e578 and is different every time you run the function. It doesn't seem to decode to anything.

Likewise with any of the other functions. In browser-solidity, it seems to work fine, but in atom-ethereum-interface it returns something I can't seem to decode to anything meaningful.


texts: Getting storage array data from contract

texts:
I have a solidity contract which stores an array of Proposal information:

contract Submissions {

    Proposal[] public proposals;

    struct Proposal {
        // ....
    }
}

In a test (using truffle framework), I am trying to access the proposal data:

const proposals = await Submissions.proposals();

But I get this exception:

  Invalid number of arguments to Solidity function

I don't understand this as it is not a function and therefore requires no arguments. Elsewhere in my tests I have successfully gathered contract data using this method (although not for arrays) - what am I missing?


texts: Connect local frontend with smart contract on ropsten

texts:
I'm new to DApp programming an I'm struggling with this problem since two days now.
Cloned this github example: https://github.com/dappuniversity/election
I deployed the smart contract to ropsten with remix.ethereum. The deployment works and I can interact with it in remix.
Now I want to interact with my local frontend with the smart contract on the testnet.
I can not get this to work.
I'm using the exact same frontend from the repo. In the chrome console I get the message "Error: Contract has not been deployed to detected network (network/artifact mismatch)"
I changed the contract address in the Election.json and in the Migration.json to the new correct one which I had deployed. Also copyd the abi from remix.ethereum and replaced it in Election.json and Migration.json
MetaMask is on the correct network.
What did I miss out? Do I need to rebuild something with truffle or change the network in truffle.js?
I hope someone can help me.


texts:
What have caused the recent default gas price

To go up (default was in some point near 100 GWei)
To come down (now it seems to be 20 GWei)

Specifically, was this because of

Actual demand for Ethereum transactions
Gas oracles, other gas price estimation mechanisms


texts: Anonymous function in Solidity example code

texts:
I'm following this link - https://ethereum.org/token to learn Solidity. The example contract implementation has the following line which I don't understand.

Can someone please explain what is this function intended to do? When would it be called? Is it an internal function or external function call?


texts: truffle and metacoin. How can I send a transaction?

texts:
I am trying to learn truffle, and I have compiled, migrated, and test the example contract.  I load the example Dapp in my browser from local host, and I have the lists of addresses created by testRPC, but I cannot send any tokens because I have no balance.  This is even though the Dapp put 1000 Metacoin in the first account.

The log, obviously says that I don't have enough funds.  I am just trying to get a hang of these very simple things so I can move on to more complicated examples and start to build things myself but I am getting stuck.


texts: Calculating data amount being mined. Server

texts:
Does anyone know how to calculate hardware being used by mining activity on a blockchain? I'm curious what the equivalent hardware usage is in a blockchain. I'm looking for a formula of blockchain activity= so much data transfer. Ideally I want to chart it as such.

Etherium blockchain data= data transfer rate
Maintaining blockchain would require= server info = amount of servers, cpu's, ram
Computing would require= (#AMD Cards by a type), (#Nvidia cards by a type)

I thought it would be a neat factoid for Bitcoin, Eth, Zcash. Litecoin with similar info.

On top of that how much data all block chains are using would be fun. It would be an interesting reference to the scope and volume of cryptocurrency world wide and I would be interested in seeing a reference like that somewhere.


texts: Is there an indexed database for ERC20 allowances?

texts:
For instance, I'd like to make the following query:

  Return all the addresses that have approved spender x on a particular token

It seems that I can only query for a specific (address, spender) pair on Etherscan.


texts: What is the definition of "gasLimit" in the chain spec files for Parity?  The wiki says it is "gas limit of the genesis" !  If I knew what that definition meant, I wouldn't need a definition.


texts: Why network hashrate fall when price go up?

texts: Its really strange for me, price for week is bull as hell and in this same time hashrate ethereum is decreasing, can anyone tell my why?


texts: What's Ethereum's mechanism for transitioning to new consensus rules?

texts:
In Bitcoin, historically, several ways to fork the network in have been used:

User Activated Soft Fork (UASF): on a certain hardcoded blockchain height the nodes simply start enforcing the new rules
Miner Activated Soft Fork (MASF): the new rule activation happens if a majority of miners signal readiness (and does not happen in case of a timeout)
The process specified by BIP 8 (combination of the previous two)

What is the corresponding process in Ethereum and is there an EIP that specifies it?


texts: Getting started: testnet or private? How to get testnet ether?

texts:
I have Ethereum Wallet v0.7.3, and was eager to try out my first contract on the testnet, but of course need ether.

Is it better to just create a private testnet? Is mining testnet ether feasible? Can I get enough to test a basic contract in a day? Are there testnet faucets?


texts: How can we implement a new opcode in the Ethereum Virtual Machine. For eg : I want to implement an opcode logic such that the opcode number of this operation is 0x21. The EVM-implementation I am using is in go-lang.


texts: How exactly is ERC721 tokens non-fungible?

texts: What makes them unique as compared to the ERC20? Is it the owner's address as  included in the form of token id? So what makes them unique is the historical chain of addresses attached to it?


texts: How can a contract can be notifying when his token balance has changed?

texts:
Let’s say that I have:

Token Contract (ERC20 token standard)

Dapp(Contract)

The Dapp account "have" some token.
Is there any way to know if the token balance of the Dapp changed?

In another words, I know that smart contract CAN NOT listen to Events
I don't want to use a 3rd party server

What are my options?


texts: Question on selfdestruct/suicide operation to a multi-sig address

texts:
I am writing a very simple contract that does the following:

accepts ETH
allows the transfer of ownerships
logs events
suicides when goal is met

I tested it successfully with a regular account and I do see the ETH transfer to the current account owner.

The steps I have tested are as follows:

Creator creates contract - creator becomes owner by default in the constructor
I transfer ownership to another account
The new owner suicides the smart contract when goal is met (1 ETH in Kovan testing environment)

When I transfer ownership between regular accounts and then suicide, it works fine.

When I transfer ownership to a multi-sig wallet (3 approvers required minimum) and then suicide it, it never sends the ETH to the multi-sig address.

Does it have anything to do with the fact that the multi-sig needs 3 approvers.

Any advice on how best to approach this?


texts: Can an NFT (e.g. ERC721) simultaneously belong to two different entities, say an user Owner, as well as a user Custodian?

texts:
For example, on the blockchain say you own a ERC721 Car token at your wallet address, but you want to park it in the ERC998ERC721 top down composable Garage owned by your friend, while still retaining ownership of the Car.
Can you retain ownership rights to your Car, while it is simultaneously in the custody of your friend/friend's Garage?

Edit: Is there a way to design a token / smartcontract that has this capability?


texts:
I have tried to verify my contract with my address and It's a ERC-20 Ropsten Test Network.
“0xee4ab34a3aa0b7d3e570df31da9f9afee9f5353b” and It just gave me a error.
Error! Unable to generate Contract ByteCode and ABI (General Exception, unable to get compiled [bytecode])
It’s a Ropsten Test Network Contract and the contract is “0xf08309b47cfc7b1e88a66a913660c57388ef2bab”
I would love for someone to help me verify my contract.
Here is the contract source code
https://pastebin.com/raw/AsSn59FN


texts: Usecase for approve and allowance functions of ERC20 token

texts: Could you please enlighten me on how approve and allowance functions work using a usecase? I dont understand the underlying operations of these functions. Especially, when a token owner delegates the right to spend his token by other user: how the ownership sign-off works, is this be done automatically?


texts: Can clique.propose be automated in a smart contract?

texts: I know that clique.propose can be manually entered into geth and then all other nodes to finally add a new node. Is there a way to automate this for example using a smart contract? Then the proposal could be made automatically. I assume function modifiers could be used so that users can only propose on their own nodes.


texts: Is Vitalik Buterin a real person or a pseudonymous name like Satoshi Nakamoto? I see videos and pictures of him.  But is he really the person behind Ethereum?


texts: Trying and failing to create my first Ethereum wallet

texts:
About 10 days ago, I created a desktop wallet on my Mac, downloading the wallet app from the Ethereum.org site.

I was told I'll have to "sync" the wallet and go through all of the blocks before my wallet is made. I transferred my first 10 Ether from Poloniex when I got the wallet address loaded, but nothing has shown up since all the blocks aren't synced yet.  It has been 10 days, on my fastest VPN server.

Now, IU've gone from 3,000,000 blocks to less than 100, but every time it gets to less than 100, it adds another couple of hundred blocks. This seems to be what it does, not try to complete the job, just getting new blocks for my computer to work on.

It is acting like a node, not like a wallet.  How do I get my 10 Ether back?  How many weeks will it take for my wallet to actually become a wallet, not a node?

I am a newbie and just want to get my investment back. I have seen my Ether in the blockchain so I know it is somewhere, just nowhere I can get it.  please advise.  Thank you.

Evander


texts:
Is the callback of a myContractMethod.sendTransaction(/* ... */) called as soon as the the transaction is sent to the network or once it is mined?

Related posts

Here are some related references I found about this but there seems to be some contradicting information and I also suspect some of it might be deprecated given how much ethereum changes month to month:

According to this post ,a .new() transaction is called twice (before and after mining) and other transactions are called once (but when?!)
According to this post, all callbacks are called twice (does not seem to be the case for me...)


texts: No longer have tokens after updating Nano S

texts: I recently updated my Nano S and was required to reset everything. After udpdating I went to MEW to swap my KIN & I had a ETH Ballance of 0.000 & a KIN ballance of 0.000. I have the address copied of my wallet that I've sent everything to which shows the ballance on Etheerscan. How do I retrieve the tokens/ get them back into my Nano?


texts: Web3j client is not detecting any transaction or blockchain from geth

texts:
I am using web3j to listen to transactions and blockchains through geth. It seems that none of the subscriptions that I have created to the blockchain or transaction are detecting changes.

I start geth like like the following.

./geth \
 --fast --cache=512 \
 --rpc --rpcapi personal,db,eth,net,web3 \
 --ws --wsapi personal,db,eth,net,web3 \
 --metrics --verbosity 5 --fakepow

My Java code looks like the following.

public class App {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    Web3j web3 = Web3j.build(new HttpService(), 100, Async.defaultExecutorService());  // defaults to http://localhost:8545/
    Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();
    String clientVersion = web3ClientVersion.getWeb3ClientVersion();
    System.out.println(clientVersion);
    System.out.println(web3ClientVersion.getJsonrpc());

    web3.blockObservable(false).subscribe(block -> {
      System.out.println(block.getBlock().getNumber());
    }, Throwable::printStackTrace, () -> System.out.println("block done"));

    web3.transactionObservable().subscribe(tx -> {
      System.out.println(tx.getHash() + ", " + tx.getGasPriceRaw());
    }, Throwable::printStackTrace, () -> System.out.println("tx done"));

    web3.pendingTransactionObservable().subscribe(tx -> {
      System.out.println(tx.getHash() + ", " + tx.getGasPriceRaw());
    }, Throwable::printStackTrace, () -> System.out.println("ptx done"));

    System.out.println("umm reached the end");
  }
}

All I see on the console of my Java app is the following.

Geth/v1.6.1-stable-021c3c28/linux-amd64/go1.8.1
2.0
umm reached the end

Any ideas what I am doing wrong?


texts: When creating a new contract I receive a "contract code couldn't be stored" error but the contract is still created

texts:
Sale.new({ from: state.account, value: value, gas: 4000000 }).then((instance) => {
  // do something with instance
}).catch((err) => {
  alert(err)
})

When the above code runs I sometimes receive this error: The contract code couldn't be stored, please check your gas amount.

The contract I am trying to create is almost exactly the same as the safe remote payment contract in the solidity docs with maybe just a few more lines.

The weird thing is that the contract actuallygets created and I can see the successful transaction in MetaMask and the Ether is subtracted from my account. I can even then use Sale.at(<new contract address>) to interact with the created contract. I've been testing in the Ropsten network.


texts:
I want to change etherbase in pyethapp, but couldn't find something like setEtherbase in geth.
How can I change etherbase (coinbase or eth.coinbase) in pyethapp?


texts: What determines the price of the ERC-20 token on a trading exchange?

texts: I know that ERC-20 tokens are traded in pairs on the trading exchanges, but what essentially determines the price in USD? I would like to know if there's a specific algorithm that does the calculation. Any help would be appreciated.


texts: Parity chain spec parameter: durationLimit

texts: What is the definition of the Parity chain spec parameter "durationLimit"?


texts: trying to find out but still didnt got how all this work ? How to create a wallet for the token you created on ERC20 contract ? what all things need to know and the flow of over all process can anyone ?


texts: Aren't all contracts that accept value and are deployed after the HF fatally vulnerable to replay attacks?

texts:
Let's say I deploy a contract with a simple function that accepts some value, and deploy this to the forked chain. The contract will end up on an unpredictable address U. Then people start sending some transactions carrying ETH value to the contract, calling the function at the same time. All fine.

But all these incoming transactions are replayable, and probably in fact replayed, on the ETC chain (provided there is ETC balance on the sender address, which can happen at any time in the future, eg. by some 3rd party accidentally sending funds there). The trouble here is that on the ETC chain, there is no contract at address U (even if I deploy the same contract on this chain it will end up on another address), so address U is treated as an externally controlled account so the value will be transferred and no function will be called (it seems the data field in the transaction is ignored for transactions to externally controlled accounts). So the ETC value went into the void and is not recoverable.

Is this true or am I getting something wrong? It seems this could happen very often.

I'm not saying this can lead to obvious ways of loss of value, but it could be a potential attack vector, or just create a mess.


texts: Would this make sense as a smart contract application? Trying to understand features and limitations

texts:
I'm starting to read up on Ethereum and smart contracts and some questions are popping up in my mind.

I can understand that smart contracts can be used, for example, to make a bet for/against the case that it'll be snowing in Cambridge on a specific day, and I can easily imagine how a smart contract like that would work.

However, let's imagine a more complex case.

Company has a bug bounty program.
User finds a bug and reports it to Company, and wants to make sure Company will pay him once the bug has been fixed.
Company pays User with a digital token on the Ethereum blockchain.

Does this mean that we need to code and create a new smart contract signed by both parties for every bug every user reports? If this was the case, would it be too onerous to publish a new contract on the blockchain for every bug report?

Or does it mean that we need to create a more generic smart contract that could get transaction sent to it, where each transaction has an attached bug report?

(I'm not trying to actually do this, just to understand. So let's imagine that we can code a generic function isBugFixed(bug) that returns true or false for every bug we pass to it)

Furthermore, it looks like that the user would have to pay to submit a new bug report, either to create a new contract or to send a new transaction. Am I correct to say that this cannot be avoided without a centralized figure that acts as a middle man and publishes reports on the blockchain, thus reducing decentralization (what if two users report the same bug at the same time? there would be no thing similar as "the consensus on the longest chain" but the middleman would make the decision).

Do you think that the best decision in such a case would be to rely on a central authority that verifies reports and bugs and use the blockchain only for token transfers or could the whole thing be built as a decentralized app?

Thank you