texts: Convert a string to a uint256 with error handling

texts:
I saw this question already, and several others going the other direction, from int to string, but how do I go specifically from string to a uint256?

I saw this answer has code for uint only, and it makes sense, but what needs to change for uint256?

I am also interested in how error-handling works in this---suppose the string does not contain integers, what is the right way to return an error, and to handle this in the calling function?

Update

Answers below were helpful.  So would something like the below give me uint==uint256 and error handling efficiently and idiomatically?

function stringToUint(string s) constant returns ((bool success,uint result)) {
    bytes memory b = bytes(s);
    uint result = 0;
    success = false;
    for (uint i = 0; i < b.length; i++) {
        if (b[i] >= 48 && b[i] <= 57) {
            result = result * 10 + (uint(b[i]) - 48);
            success = true;
        } else {
            result = 0
            success = false;
            break;
    }
    }
    return (success,result);
}

Update 2

Sorry, one more part of error handling:  I understand the max value of uint256 to be:

2^256-1 = 115792089237316195423570985008687907853269984665640564039457584007913129639935

How would I handle correctly rejecting a string that would cause rollover?

eg, would this:

stringToUint("115792089237316195423570985008687907853269984665640564039457584007913129639937")

(which is 2^256+1) rollover to 1?


texts: invalid address sending ether from contract to EOA

texts:
I'm trying to send an ether from a contract to EOA.I'm following this tutorial, however it returned the error, "invalid address"

>beneficiary.send(amountRaised);
invalid address

However, at the geth console, I've got the following information. Could you tell me how to solve the problem?

>crowdsale.amountRaised()
"600000000000000000000"
>crowdsale.beneficiary()
"0x~~~~~~~~~~~~~~~~~~~"

The Contract

contract token { mapping (address => uint) public coinBalanceOf; function token() {}  function sendCoin(address receiver, uint amount) returns(bool sufficient) {  } }

contract Crowdsale {

    address public beneficiary;
    uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price;
    token public tokenReward;
    Funder[] public funders;
    event FundTransfer(address backer, uint amount, bool isContribution);

    /* data structure to hold information about campaign contributors */
    struct Funder {
        address addr;
        uint amount;
    }

    /*  at initialization, setup the owner */
    function Crowdsale(address _beneficiary, uint _fundingGoal, uint _duration, uint _price, token _reward) {
        beneficiary = _beneficiary;
        fundingGoal = _fundingGoal;
        deadline = now + _duration * 1 minutes;
        price = _price;
        tokenReward = token(_reward);
    }

    /* The function without name is the default function that is called whenever anyone sends funds to a contract */
    function () {
        uint amount = msg.value;
        funders[funders.length++] = Funder({addr: msg.sender, amount: amount});
        amountRaised += amount;
        tokenReward.sendCoin(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    modifier afterDeadline() { if (now >= deadline) _ }

    /* checks if the goal or time limit has been reached and ends the campaign */
    function checkGoalReached() afterDeadline {
        if (amountRaised >= fundingGoal){
            beneficiary.send(amountRaised);
            FundTransfer(beneficiary, amountRaised, false);
        } else {
            FundTransfer(0, 11, false);
            for (uint i = 0; i < funders.length; ++i) {
              funders[i].addr.send(funders[i].amount);
              FundTransfer(funders[i].addr, funders[i].amount, false);
            }
        }
        suicide(beneficiary);
    }
}

https://ethereum.gitbooks.io/frontier-guide/content/contract_crowdfunder.html


texts: How can I generate a V3 of the Ethereum wallet file format in js, from strings: 'Passphrase' and 'Email or username' required by Quorumwallet?

texts:
Quorum Wallet prompts for a Passphrase and a Email or username to generate the account.

On the FAQs there is a description of the algorithm to generate the account:

  What is the algorithm used to create my account?

  It is fairly simple:

  seed = String(passphrase) + String(userid); privatekey = PBKDF2(seed,
  seed, 2000, 32, 'sha256');

How can I generate the Version 3 of the Ethereum wallet format file using Javascript?


texts: (Etherdelta smart contract) Sending erc20 tokens on behalf of user(depositing to contract) is not working.why?

texts:
Hi i have copied the etherdelta smart contract code.All is working fine.I can withdraw tokens from the snart contract to my personal wallet. By reading the code what i understand is,the depositToken method is like allowing the contract to send tokens from my wallet on behalf of me.But this is not working.when i click deoosit,the transaction gets reverted. I guess its some issue with the approve() function.Please can someone clear that for me?

    function depositToken(address token, uint amount) {
    //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
    if (msg.value>0 || token==0) throw;
    if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
    tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
    Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
  }

//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.

What this line means?


texts:
So let's assume the following code:
modifier Owner() {
    if (msg.sender == owner) _;
}
function uploadContent() external Owner {

   uploadContent() ..
}

Why not use this?
function checkOwner() internal {
   require(msg.sener == owner, "Youre not the owner");
}

function uploadContent() external Owner {
     checkOwner()
     uploadContent() ...
}

Whats the difference? Is it cheaper in terms of gas cost? Because I dont see any reason why to use the first approach?


texts: Ethereum Virtual Machine and Docker Containers

texts:
I'm trying to understand what are the constraints that wouldn't allow a Docker container to be used instead of creating the specific Ethereum Virtual Machine.

I followed this link:

https://forum.ethereum.org/discussion/1203/why-not-use-a-general-purpose-vm

  It has to run identically on all full nodes.

  Docker provides images capability. Images are built deterministically
  with a script. Every full node can start with the same base image, and
  dapps/contracts would be installed on top of that shared image with a
  publically available script. Each dapp/contract would run in a
  separate Docker container.

  We need to keep track of how much computation effort a contract uses.

  Docker provides monitoring and resource limiting tools for RAM, I/O
  and disk. The same approach of max-gas and upfront gas payments with
  the reimbursement at the end of transaction, or a transaction rollback
  if it ran out of gas, could apply. If a Docker container uses too many
  resources, it can be paused and rolled back to a previous snapshot.

  We need to keep track of Ethereum state, and it has to be rewindable.

  Docker provides copy-on-write instant snapshots. We could do a
  snapshot after each transaction, and after each block. So we could
  rollback both individual transactions and block chains that lost
  proof-of-work race with other nodes.

and I found the comments from @tenaciousmv very reasonable. However any technical explanation of why this can not be accomplished ?

I understand why something like Virtual Box wouldnt work because of the need for lightweight nodes, but why it could not be used container technology ?


texts: Migrate contract from testnet to mainnet

texts:
What is the safest way to migrate a contracted deployed in a testnet (Rinkeby) to mainnet?
I can change the configuration of my truffle project and read the code from my git repository, but is there a better way to migrate? For example, without coming back to my off-chain repo?


texts:
I'm trying to build my own oracle for a project (so I don't use chainlink or oraclize) and I've read this https://medium.com/@robinagist/building-an-ethereum-oracle-with-web3-js-1-0-1272b59cfc31.
In my project I need to get off-chain data (weather) to see if I can make a reservation at a resort, so my smart contrcat calls a method on the weatherOracle contrcat which emits an event (my smart contract is not present in the figure). The event is captured by the oracle component which takes the data from the external source.
What is the oracle component? Is it a node? if so what kind of node is it?
I'm just talking about the component on the right (oracle).


texts: Complete steps to write a hello world on testnets?

texts:
I am trying to learn about dapp development, but I'm stuck in what should be the easiest step. I've looked at least 6 different "getting started" tutorials; half of them are deprecated, the other half skip entirely the setup part and go straight to the language.

What is a complete step-by-step instruction for running a "hello world" contract in a test net starting from having geth installed on an Unix environment (and already knowing how to use it on the terminal to write transactions, etc)?


texts:
I read that enums were not allowed as keys in mappings, but when I just tried it it is working on remix.ethereum.org. Was it allowed in more recent Solidity versions?
The use-case I am using enum as key for is to encode tokens a bit differently, for a contract with multiple tokens. So it really makes that easier to read with enum Token as the key.
enum Token { TokenName1, TokenName2, TokenName3, TokenName4 }

mapping (Token => mapping (address => uint)) balanceOf;
mapping (Token => mapping (address => mapping (address => uint))) public allowed;


texts: Using SmartContract send ether to multiAddress with single Transaction But it is not getting ether in multiAccount

texts:
I have used already generated Contract Address: https://etherscan.io/address/0xb59fdff77a6175dfa4fe7af4281a52f61611eaa2#code

And using this I have created below Code:

// Include the packages
const Web3 = require('web3')
//const abi = require('human-standard-token-abi')
var abi = [{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_tokenAddr","type":"address"},{"name":"dests","type":"address[]"},{"name":"values","type":"uint256[]"}],"name":"multisend","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"}];

// Set up Infura as your RPC connection
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

// Define the contract addresses and the contract instance
const contractAddress = '0xb59fDfF77a6175DFA4fE7aF4281a52f61611eAa2'
//const contract = new web3.eth.contract(abi, contractAddress)

var contractAbi = web3.eth.contract(abi);
var contract = contractAbi.at(contractAddress);
// suppose you want to call a function named myFunction of myContract

fetch('http://localhost:8545', {
    method: 'POST',
    headers: {
        'Accept': 'application/json', 'Content-Type': 'application/json' },
    body: JSON.stringify({ 'method': 'personal_unlockAccount', 'params': ["0x2885f9904f3d1790ba53009bc9e0baae377d67df","kiranmalvi",null], 'id': 1, 'jsonrpc': '2.0' }) })
    .then(function (res) {

        contract.multisend.sendTransaction('0x627306090abaB3A6e1400e9345bC60c78a8BEf57',["0x2885f9904f3d1790ba53009bc9e0baae377d67df","0x7b7cd7d5cee9fb36b7995a3d81df0122a0b1af4a"],["100","200"],{
            from:"0x2885f9904f3d1790ba53009bc9e0baae377d67df",
            gas:4000000 },function (error, result){
            if(!error){
                console.log(result);
            } else{
                console.log(error);
            }
        })

    });

But Transaction are not distributing multi address which I defined It is only send all amount in contract address. Can you help me What should I do for it?


texts: What are the use cases of tokens? How they are different than ethers?

texts:
I am searching for the ERC20. From what I found is that , tokens allow us to have our coins based on smart contracts. But I am little bit confused about the use cases of tokens? When I should use them , as long as I can use Ether instead ??
Could anyone give a nice explanation for tokens?


texts: Why does solidity need a fallback function?

texts:
I understand when the fallback function is called, but why is it needed at all?
It leaves the way open for a possible reentrancy attack.
It is called when a function of a contract is called that isn't in the contract, why not just throw an exception if that happens?
And when ether is send to a contract that does not have a way of receiving ether, just throw an exception as well?
I can't find anything about why exactly this function is necessary, anyone else?


texts: Does Dapps such as Uniswap and Sushiswap transactions are made 100% on-chain?

texts:
I'm just wondering, it looks like Dapps such as Uniswap and Sushiswap transactions are made 100% on-chain, because some claimed those apps are 100% decentralized.
Is it true that all transactions are conducted on-chain? or does actually some of them are conducted off-chain.


texts: Why doesn't truffle set the defaultAccount by default?

texts:
According to this thread, whenever you're trying to interact with the contract's state via truffle develop, you have to do this:

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

Why isn't this done by default, like with the migrate command which deploys the contract from the first address in the generated account list?


texts: Read ABI directly from network api in GOLang

texts:
Using go-ethereum package how can we read the JSON file of the deployed contract and then get the ABI out of it and then instantiate?
I don't want to compile smart-contracts into GO but want to use deployed contract ABI directly by using the API provided by testnet.
https://api-ropsten.etherscan.io/api?module=contract&action=getabi&address=contractAddress&apikey=YourApiKeyToken


texts:
I have a bug listed in many places: Error: filter not found when using a filter with web3.

from https://blockone.thomsonreuters.com/docs/

  It's important to note that, if you're using web3's watch functions,
  that these are stateful with respect to their backend - they rely on
  periodic polling with a handle that's only known to the specific node
  you were talking to when you set them up. Obviously this is a problem
  if reconnection happens automatically beneath the visibility of your
  app code- any such handles you are using will be invalidated. Your
  calls would error due to a bad handle with "Error: filter not
  found...."- at that point it's your responsibility to re-issue the
  watch calls. If you happen to reconnect to a node with a different
  block height, your watchers may miss events. So it's important to
  check for events since the block of the last received event.

Here is my code

try {
    var filterMempool = web3.eth.filter('pending');
    filterMempool.watch(function (error, txHash) {
        if (error) {
            console.log('pending filter error: ' + error);
        } else {
            try {
                const currentTx = web3.eth.getTransaction(txHash);
                doSomething(currentTx);
            }
            catch (err) {
                console.log('mempool getTransaction error: ' + err);
            }
        }
    });
}
catch (error) {
    console.log(`filterMempool filter error: ${error}`);
}

My questions:

1) How can I re-issue the watch calls ?

2) How to make sure I don't miss any events ?


texts: Using two key for displaying data from contract

texts:
i can't found any idea how to get data with two keys. One key "address", second key is "IsCollect"
My mapping:
    mapping(address => Player) public users;

struct table:
    struct Deposit {
        uint256 depositTime;
        uint256 amount;
        bool IsCollect;
    }

Insert:
 users[addr].deposits.push(Deposit(now, amount,false);

Retrieving:
function getPlayerDepositHistory(address addr) public view returns (uint256[] memory, uint256[] memory, bool[] memory) {
        DepositHistory[] memory invests = users[addr].deposithistory;
        uint256[] memory baseTimes = new uint256[](invests.length);
        uint256[] memory values = new uint256[](invests.length);
        bool[] memory IsCollect = new bool[](invests.length);

        uint256 i = 0;
        uint256 timeSpent = 0;
        while (i < invests.length){
            DepositHistory memory invest = invests[i];

    //        if (invest.IsCollect=false)
      //      {

        if (invest.lastDepositTime < invest.depositTime.add(PERIOD[0])){
                    uint256 remainedTime = PERIOD[0].sub(invest.lastDepositTime.sub(invest.depositTime));
                    if (remainedTime > 0){
                    timeSpent=now.sub(invest.lastDepositTime);
                    if (remainedTime <= timeSpent){
                        timeSpent = remainedTime;
                        }
                    }

            baseTimes[i] = invest.depositTime;
            values[i] = invest.amount;
            IsCollect[i] = invest.IsCollect;

        }i++;
           // }
        }

        return (baseTimes, values, IsCollect);
}

I need second key IsCollect=true. If is true I need to display only data which is True
I have tried to use:
if (invest.IsCollect=false)
{
}
Its not works.
Appreciate for help.


texts: How does web3.js decide to run a call() or sendTransaction() on a method call?

texts:
The web3.js documentation states that with a contract method, call vs. transaction is chosen automatically:

  Contract Methods

// Automatically uses call or sendTransaction based on the method type
myContractInstance.myMethod(param1 [, param2, ...] [, ...]);

*edited for brevity

I have tested two ways to call a function that does not mutate anything

1.testInstance.testfunc(param1, {from:eth.accounts[0]}) 2.testInstance.testfunc.call(param1)

Events are being issued with option 1 only, so I know that web3.js is choosing sendTransaction(). I expected it to automatically choose a call(), because the function doesn't change any state.

How does web3.js determine which to use?


texts: DAPP: is it possible to kind of "reset" data in contract?

texts:
I am just starting with all these dapp things and one thing is not completely clear for me.

Ok, so I will just start from simple example. Let's say I want to create simple "Guess a number" dapp. The whole idea is very simple. I want to have 100 participants in my game who are guessing number from 1 to 1000. One guess costs some ETH. And when 100th guess is made I want to find closest guess and transfer all ETH, which were collected thought the game, to the winner(or winners).

As I understand, all that logic should be written in contract. And all information about participants(addresses, numbers and etc.) should also be stored there(Please correct me if I am wrong). And finally my question is, is it possible to kind of erase/reset all the previous participants related data from contract? I mean, I want this game to be kind of looped. This is the whole idea step by step:

generate random number on first iteration
collect data from 100 participants
on 100th guess choose winner/winners(closest to actual number)
transfer money to winner/winners
remove all current participants related data
start again from step 1.

Is this achievable? Or is this just me misunderstanding the whole idea of contracts and dapps? :)

So, maybe someone could correct me if I am wrong and point me to the right direction of creating dapp for my example? :)

Thanks a lot in advance :)


texts: How does one run a Geth node with a configuration file?

texts:
Parity has had a command line option for running a node using configuration parameters sourced from a configuration file.

I was wondering as to how one does similar with a Geth node?


texts: truffle migrate: Accessing 2_deploy_contracts.js of another Truffle project

texts:
I am executing “truffle migrate” command  but I am getting one reference error related to ‘adoption’ variable:there is no error related to compilation

2_deploy_contracts.js

ReferenceError: adoption is not defined
    at module.exports (absolute path/2_deploy_contracts.js:5:20)
    at Migration._load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:56:1)
    at
    at process._tickCallback (internal/process/next_tick.js:188:7)
Truffle v5.1.27 (core: 5.1.27)
Node v8.10.0

The 2-deploy_contracts.js of this project is given below which does not have any adoption variable defined:

var attacker = artifacts.require("Attacker");
var victim   = artifacts.require("Victim");

module.exports = function(deployer){
   deployer.deploy(adoption);
   deployer.deploy(victim);
};

I have defined adoption variable in another 2_deploy_contracts.js file which is given below:

var adoption = artifacts.require("adoption");

module.exports = function(deployer){
   deployer.deploy(adoption);
};

Somebody please guide me why I am getting this reference error. I am running 'truffle migrate' from the root of the project

Zulfi.


texts: What is the cost to store 1KB, 10KB, 100KB worth of data into the ethereum blockchain?

texts:
Whatever is stored in the blockchain is immutable which means I can fetch this data back in the future. As of today (2016-feb),

How does one store a 1kb, 10kb, or 100kb or arbitary data/text in the ethereum blockchain? What is the code needed to do this?
Once stored how do you download the data back onto your desktop?
How much would this cost exactly in ether/gas/fiat at todays prices?


texts:
Is there a way to get a full and updated list of all Erc20 tokens on the Ethereum blockchain?
Etherscan.io contains a token name search, but it doesn't show the full list, which is 7668.


texts: What do the various components of a contract displayed in Truffle mean?

texts:
Using Truffle and the CryptoZombies example code, when I type ZombieFactory.deployed() the contract is shown with all of its functions. For example,

createRandomZombie:
  { [Function: bound ]
    request: [Function: bound ],
    call: [Function: bound ],
    sendTransaction: [Function: bound ],
    estimateGas: [Function: bound ],
    getData: [Function: bound ],
    string: [Circular] },
 allEvents: [Function: bound ],
 NewZombie: { [Function: bound ] 'uint256,string,uint256': [Function: bound ] },
 OwnershipTransferred: { [Function: bound ] 'address,address': [Function: bound ] } },

What does [Function: bound] mean? Why are request and call shown? They are not separate functions that are in the Solidity file.


texts: Don't know how to get money out of smart wallet

texts:
Three years ago I bought some Ethereum.
Little as I knew I put some of it in a smart contract.
The smart contract says it has 0.21 ether.
https://etherscan.io/address/0x6Ca3EB0184E652fa3b959bfA6632ab90cda401ab
But it seems to be self destructed.

It also tells me that the money is transferred to my account.
https://etherscan.io/tx/0x54e90b0f32993677a1e93945b13d9668f8db536735f22dab0d5db43f9737ac8c#internal

But when I look into my account I can't see the ether added to it.
https://etherscan.io/address/0xf958cf4b12c5f2b0ccf1b386cef873298197f45e
My question is:
How to i retrieve the money from my smart contract. And get it in my account.
I can access my account with a wallet.
But I don't have any more information about the smart contract other than the address.


texts: How to use the zksnarks capability of Ethereum?

texts:
Simple question but I couldn’t find the answer anywhere…

How to use the zksnarks capability of Ethereum in order to perform fully Anonymous sending of Eter from one wallet to an other one ?


texts: How to enable autobuy of Ethers in exchange of my CryptoCurrency?

texts:
I'm referring this page : https://www.ethereum.org/token#automatic-selling-and-buying

My question is that how is it possible to integrate third party in our Smart Contracts to be deployed on Ethereum Wallet ( do we have to make a http request to the third party say an exchange to give us the current prices of my currency )


texts: Is there a tool to list all the internal transactions in a block?

texts:
I don't think this is possible with the standard JSON-RPC API, but I'd like to get a list of all the internal transactions in a block. By internal transactions I mean transactions initiated by a contract, sending to another address. Like what is listed on EtherScan in the "Internal" tab, but instead of searching by address, search by block.

Are there any tools for this? If not with a standard node out of the box, or maybe there is a third party services for this?


texts: solidity, how to wait n second function or others solution

texts:
I am working on a project for p2p energy trading using blockchain. I am building an experiment on my own to demonstrate the concept for my master thesis.
For this project I have two python scripts, one for a prosumer (user that provide energy to the system) and one for a consumer (user that consume the system energy).
Each script is reading a value from a monitoring electricity system, that are updated at the same time.
Every time a new value is read a new "cycle" begin.
They are both calling the same smart contract using web3.py library, and when a new value is read from the monitoring system, they are updating two variables in the smart contract: Available Energy and Demand Energy. I have no problem doing that.
Considering that for a prosumer the value parsing into the smart contract call is positive and negative for a consumer, the smart contract know if we have a prosumer or consumer and can run the right function corresponding to it.
function checkProsumerOrConsumer(address payable _user, int _newEnergy, int _pastEnergy) public payable {
        if(_newEnergy < 0){ //Consumer case
            if(_pastEnergy < 0){
                updateDemandEnergy(-_newEnergy, -_pastEnergy);
            }
            else if(_pastEnergy>0){
                updateAvailableEnergy(0, _pastEnergy);
                updateDemandEnergy(-_newEnergy,0);
            }
            else{
                updateDemandEnergy(-_newEnergy,0);
            }
            //Wait 3 seconds function
            consumer(_user, -_newEnergy);
        }
        else{ //Prosumer case
            if(_pastEnergy > 0){
                updateAvailableEnergy(_newEnergy, _pastEnergy);
            }
            else if(_pastEnergy < 0){
                updateDemandEnergy(0, -_pastEnergy);
                updateAvailableEnergy(_newEnergy,0);
            }
            else{
                updateAvailableEnergy(_newEnergy,0);
            }
            //Wait 3 seconds function
            prosumer(_user, _newEnergy);
        }
    }

The additional conditions are made in case an user switch from a prosumer to a consumer or the inverse.
It's working like it should be but I need to implement a delay (or other solution?) just before the call of the prosumer and consumer functions in my smart contract to let the variables AvailableEnergy and DemandEnergy be updated for the same "cycle" and proceed to transaction. Like 2 or 3 seconds should be enough.
The solution would be to implement a wait function (or something else? I'm up for any ideas) but from what I read this is not really something that usualy done in ethereum. I read that maybe I could use "Ethereum Alarm Clock", is suitable to do what I want to do? How can I use it in my smart contract?
Many thanks,
Alban
I'm using Renix and solidity ^0.5.10. I'm doploying the contract on Ganache blockchain.


texts: How can I get the content of storage and memory in my private chain?

texts:
I'm looking for some methods to know the content of storage and memory while the contract is running.Mayba some useful tools or abi ?

By the way, the abi of geth, debug_writeMemProfile and debug_memStats, confuse me a lot. Are they helpful?


texts:
In this post by an Ethereum engineer taken from the Ethereum wiki about brute-forcing private keys, he writes:

  "Public keys are sized so that, absent a breakthrough in solving the
  discrete logarithm problem, brute force is impractical for any
  conceivable amount of computing power. With 2^128 possible
  combinations, and if we assume a modern computer can compute, say, a
  billion per second (which is a massive overestimate), it would take a
  million such computers ~5e15 years to brute force your key. If we
  assume computing power improves by another million fold, it'd take
  this massive cluster 'only' about 5 billion years."

However, according to this question, a private key is 256 bits long. In this case, why is the quote referring to 2^128 instead of 2^256?


texts: How can I take a snapshot of Ganache or Truffle Develop state and reload later?

texts: I would like to be able to save the state of my local Ganache or Truffle Develop chains into some sort of file. At a later time, I would like to be able to restart Ganache or Truffle Develop and apply the snapshot. Is this possible? Any resources for doing so without extensive digging and tinkering?


texts:
I am trying to understand cryptocurrencies and ICOs in general.  I can find a lot of examples of using the Parity client to participate in ICOs but not a lot of examples on how to launch/create an ICO using Parity.

From what I understand, once you have deployed and registered a token.  You need an ICO smart contract (aka. a crowdsale smart contract? https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/crowdsale) which are essentially the rules as to how an ICO is run.

So, if I register and deploy a token, do I then need to deploy a crowdsale smart contract using Parity.  Am I understanding this correctly?

Thank you


texts: Error: Invalid number of arguments to Solidity function (mapping)

texts:
Whenever I try to access a mapping in truffle console, I get this error.

mapping(uint256 => uint256[]) public myMapping;

I try:

myContract.deployed().then(function(instance) { return instance.myMapping.call(0) });

Why does the mapping expect two arguments, and what should the second argument be? I just want the value keyed at 0.


texts: I read that the "send" function in Solidity can be overridden. Why would someone want to do that? Is that a way to avoid execution of the fallback function at the receiver?


texts: How to connect AugurProject's ethrpc to a local testnet

texts: I have GETH running a test network, and now I'd like to get AugurProject's ETHRPC to connect.  I can't find any documentation on ETHRPC.


texts: Can a factory-contract access/read/modify variables in generated child-contracts?

texts:
at the moment I am experimenting with the factory/child-logic in solidity. With my factory contract I am able to create child contracts in which an auction is executed. Now I want to return a variable in my factory/master-contract defined in my child-contract (e.g. LowestBid). Is there a certain way this can be accomplished? At the moment I struggle with this problem and I don't find any answers here.
I just need a basic logic for interacting with values defined by my child in my factory.

Thanks in advance.

Current code:

pragma solidity ^0.5.11;

contract Master {

    address Pi_C_Owner;
    address payable public NewAuctionPayable;

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

    function checkBalance() public view returns(uint) {
        require(msg.sender == Pi_C_Owner,"Insufficient permission");
        return(address(this).balance);
    }

    function increaseBalance() public payable {
        require(msg.sender == Pi_C_Owner,"Insufficient permission");
    }

    function createAuction(address _Destination, uint _WTP, uint _BiddingTime) public returns(address) {
        require(_WTP > 0,"Willingness to pay has to exceed 0.");
        address NewAuction = address (new Auction(_Destination, _WTP, _BiddingTime, address(this)));
        NewAuctionPayable = address(uint160(NewAuction));
        NewAuctionPayable.transfer(_WTP);
        return(NewAuctionPayable);
    }

    function Test() public returns(uint) {
        //how can i return a variable defined in child-contract 'Auction' (e.g. LowestBid)
    }

    function() external payable {
    }
}

contract Auction {

    bool Ended;
    uint WTP;
    uint public a8_AuctionEndTime;
    uint public a7_SafetyDeposit;
    uint public a6_LowestBid;
    address public a5_Destination;
    address payable MasterPayable;
    address payable LowestBidder;
    address payable Payee;

    struct Participant {
        bool biddingright;
        uint amount;
    }

    mapping(address => Participant) participants;
    address payable[] depositor;

    constructor(address _Destination, uint _WTP, uint _BiddingTime, address payable _Master) public {
        a5_Destination = _Destination;
        WTP = _WTP;
        a7_SafetyDeposit = _WTP/2;
        a6_LowestBid = _WTP;
        a8_AuctionEndTime = now + _BiddingTime;
        MasterPayable = _Master;
        Ended = false;
    }

    function a1_getRights() public payable {
        require(now <= a8_AuctionEndTime,"Auction already ended.");
        require(msg.value >= a7_SafetyDeposit);
        require(participants[msg.sender].biddingright == false,"Safety deposit already payed.");
        participants[msg.sender].biddingright = true;
        participants[msg.sender].amount = msg.value;
        depositor.push(msg.sender);
    }

    function a2_placeBid(uint Bid) public {
        require(now <= a8_AuctionEndTime,"Auction already ended.");
        require(Bid < a6_LowestBid,"There already is a lower bid.");
        require(participants[msg.sender].biddingright == true,"Please note safety deposit.");
        LowestBidder = msg.sender;
        a6_LowestBid = Bid;
    }

    function a3_AuctionEnd() public {
        require(now >= a8_AuctionEndTime,"Auction not yet ended.");
        require(Ended == false,"Auction end has already been called.");
        Ended = true;
        MasterPayable.transfer(WTP-a6_LowestBid);
        for(uint i=0; i<depositor.length; i++) {
            Payee = depositor[i];
            if(Payee != LowestBidder) {
                Payee.transfer(participants[Payee].amount);
            }
        }
    }

    function() external payable {
    }
}


texts:
I have a 1050ti GPU and my hash rate is so slow around: 2.03 Mh/s.

Other people using the same GPU are making 14 Mh/s.

My OS is Windows 10 and I'm using Claymore to mine.

What can I do to increase the hash rate?


texts: Send raw transaction data with contract dependencies

texts:
I have a solidity contract that creates another contract:

    contract Factory {
    function createContract () returns (address){
        address newContract = new test(msg.sender);
        return newContract;
    }
}

contract test {
 address public creator;
    function test (address _creator){
    creator=_creator;
    }
}

This works great.
But my question is sending Raw transactions, namely , what is the payload data and/or data in the field?  How does this contract know the other ABI?

var solidityFunction = new SolidityFunction('',Factory_ABI, '');
var payloadData = solidityFunction.toPayload([]).data;

const txData = {
  nonce: web3.toHex(txCount),
  gasLimit: gLimit,
  gasPrice: web3.toHex(gPrice),
  from: account1,
  value: web3.toHex(web3.toWei(0, 'wei')),
  data: payloadData,
}

The code to deploy it works great if I just deploy the test contract, but as soon as I try to deploy 'Factory' I get a 'stack underflow' error and I think it has something to do with that data field.

Oh and I'm on the testrpc if that matters


texts: What happens if I send ETH to ICN (erc20 token) address when trying to use shapeshift on parity?

texts:
The ETH get stuck on the address and when I contact Shapeshift, whey said: Unfortunately we do not own this address.

Is it possible that they or the parity have a bug. The address that I used was offered to me inside the parity web interface.


texts: Drizzle React Component ContractData returns empty

texts:
My contract call to a simple view function that returns an array of data returns empty using:
From testing it appears that ContractData can't deal with more than one return value. If I return one unit then it works, but more than that ... broken.

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

Using Remix or even web3 works perfect, with the above I only get react-text place holders, no data.

Worth noting: I also make use of ContractForm and that only reloads the page 3 times and does not send a transaction to my contract.

Any Ideas?

Thanks


texts: What are the preferred protocols to integrate external data sources & sinks with a BC network?

texts:
I'd like to trigger events and send data to external non-ethereum network applications. What is the preferred communication protocol and mechanism to use so as not to impact BC processing?

My understanding is that external events and data can be input to the BC using normal transactions but are there alternative input mechanisms?


texts: How do I split a signature into v, r, and s parts in python?

texts:
I've got a signature, as a python bytes object, and want to split it into the components v, r, and s.

I understand the details of what needs to be done, by reading: What's the best way to transform bytes of a signature into v, r, s in solidity? but I don't want to re-write the code if someone else has already written it in python.

I don't want to use pyethereum because I hear that it's deprecated in favor of py-evm.

What is a concise way to perform this operation?


texts: Is there a means to archive or keep an offline version of the blockchain for recovery?

texts:
I'm fairly new to downloading and mining of the Ethereum blockchain yet I've noticed it takes hours on my 100Mbs connection (haven't even looked at it over the SD-WAN yet). I've ran into some issues where I've seen geth halt on messages relating to Synchronisation failed and several other topics. One of the first thing that comes to mind is, if I am going to dump a ton into both mining and contracts on Ethereum from my IRA - I better have a damn backup plan to ensure my hardware/time investments are not in vain either.

Could I do a backup for full recovery or perhaps replication (other than hardware disk RAID) between internal hosts to ensure I always have a recently downloaded version of the blockchain?

Also, how would one go about restoring a session of receipts/headers they were downloading at the time?

All and any input is appreciated, thank you!


texts: Is it possible to upgrade the smart contract (currency token)?

texts: Suppose as the time goes by we, as token developers, acknowledged that we did some stupid mistakes in the initial contract, or, for example decided to add some new features. Is it possible to upgrade our contract? What will happen to the tokens that are already circulating around the network?


texts:
I have a geth client for a private blockchain and the miner is working now but the balances are all zero. How can this be? This is related to coinbase somehow? I assumed that a miner would automatically credit the balances. Here are the responses -

> eth.mining
true
> eth.blockNumber
1840871
> eth.getBalance(eth.accounts[0])
0
> eth.getBalance(eth.accounts[1])
0
> personal.listAccounts
["0x5842d6acb3dca819471bde56255f27670aa9b9c6",
"0x2194d61ed691d05412c65acb46493e513ae6c566"]
>


texts:
I am performing a transaction to send an ERC20 and I keep getting this error:
ValueError: {'code': -32000, 'message': 'already known'}

I'm assuming this means that this transaction is already in the mempool or something? Looking for some clarifications though.


texts: Calling a function from a contract passed in as an argument

texts:
Im Trying to create a DAPP with two contracts generating assets. One is acting as the "factory" for the other contracts. From the latter I try to call a function in the factory without knowing its address yet, therefore I want to pass it in as an argument. This throws an error in Remix because that contract obviously doesn't exist yet.

To simplify the situation think about this scenario in Remix (both contracts are written in the same file):

    contract AssetFactory{

    address[] deployedAssets;

      function createAsset(string name) public {
        address newAsset = new Asset(name);
        deployedAssets.push(newAsset);
        return newAsset;
      }

    }

    contract Asset{

     string name;

     function Asset(string name) public{
       name = name;
     }

     function ModifyAssetAndCreateNew(string name, address factory){
       factory.createAsset(name);
       name = name;
     }

   }

Any Ideas or other approaches? I realize that the idea behind the above contract doesn't make much sense in this example but i tried to keep it as short as possible.

Thank you!


texts: using "payable" even when we do not send ETH?

texts:
When we want to send some ETH, we need to use the "payable" keyword. However, even when we want to send some tokens (i.e. uint256 token), we need to use again the "payable" keyword in our function as follows ? or we can remove it ?

struct AssetStruct {
        address owner;
        bool isOwner;
    }

    mapping(uint256 => AssetStruct) assetStructs;
    uint256[] public assetList;
    mapping(address => uint) public balance;
    mapping(uint256 => mapping (address => mapping(address => bool))) public isPaymentDoneMutual;

function playerPaymentMutual(uint256 _id, address _player, uint256 _token)  payable public  returns(bool isIndeed) {

                address _owner;

                _owner = assetStructs[_id].owner;

                balance[_owner] = balance[_owner] + _token;

                balance[_player] = balance[_player] - _token;

                isPaymentDoneMutual[_id][_player][_owner] = true;

                        return true;
}


texts:
After a recent update I noticed Mist starts six mist.exe process instances, presumably one for each physical CPU core in my machine.

I would like to limit this to just one. Is there a command-line argument I can use to do so?

The reason is that I've found Geth / Mist to be major resource hogs on my PC (particularly I/O). I use Process Hacker to reduce the Priority and I/O Priority of each process, which works like a charm. But having to do this on seven different processes each time I start the software is a pain.

Here are the commands I'm using to launch the software:

start "geth" "C:\Program Files\Mist\nodes\geth\win-x64\geth.exe" --datadir "L:\Ethereum" --cache=512
start "Mist" "C:\Program Files\Mist\Mist.exe" --datadir L:\Ethereum


texts: What is the meaning of line 2 quoted below?

texts:
import ./ClaimHolder.sol

ClaimHolder public trustedClaimHolder;(//Doubt ?)
function ClaimVerifier(address _trustedClaimHolder) public {

}


texts: Where to find Ethereum token transfer record?

texts:
Etherscan provides a convenient way to check the transaction history of a specific custom token. However, I was wondering where is the token transaction stored in the first place. I read some of the Ethereum logs, such as this one:

{"blockNumber":"3904411","blockHash":"0xf5f12d939472b79009f86163f6ec4440ed067fd14f222bc8e9cc9b82cdbaa71b","timeStamp":"1497983089","hash":"0xc658c9f5a4e2f34adb98d364c89c6d8f263f725d9318e84cae54f60d042fbb82","nonce":"0","transactionIndex":"13","from":"0x0008ec9f540ceb20cda44ec8503981ff58a3361b","to":"","value":"0","gas":"4000000","gasPrice":"57475936256","input":"","contractAddress":"0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0","cumulativeGasUsed":"2429602","gasUsed":"1976412","confirmations":"165071","isError":"0"}

I omitted the input field as it is a bit too long.

However, I think the value field only indicates the value of ETH. But the token transaction doesn't necessarily involves ETH transactions.

I understand there might be some clues in events log. But how can I get it from the log? Can I get it directly from blockchain, instead of the event logs?


texts: TX failed - Bad instruction - Funds not back

texts:
I sent some $link amount but TX failed due to Bad instruction error.
Tx is https://etherscan.io/tx/0xa45e443c8cf310dbe69ab725358ac2da20afde33442a55ed7df985fe6645057d
Have read that failed transactions like this should revert, and funds return to sender. But still not see in my Jaxx wallet. Do I have to wait more or should I already be having it back?
Thx!!


texts: How to link Standard Token with crowdsale in Zeppelin Solidity

texts:
Hello I am trying to create a crowdsale through zeppelin solidity but the main issue is it doesn't provide a way to link standard token with pre-allocated supply with the crowdsale.

pragma solidity ^0.4.13;

import '../node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol';
import '../node_modules/zeppelin-solidity/contracts/token/StandardToken.sol';

contract BBTico is Crowdsale  {

    function BBTico(uint256 startTime, uint256 endTime, uint256 _rate, address _wallet)
    Crowdsale(now, now + 5*60,  5, 0xB1A9B5564071A442909b17f8e9C7288b44aFC014 , 0xefcfbc96dc2adfe35d3fff6b1d9e985066d618ac)
    {}

}

Crowdsale.sol

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

    // Already Deployed Standard Token Address on Rinkeby Testnet
    tokenReward = 0xEfCfbc96dc2aDfe35d3fFF6b1D9E985066D618aC;
    startTime = _startTime;
    endTime = _endTime;
    rate = _rate;
    wallet = _wallet;

  }

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

function buyTokens(address beneficiary) public payable {
    require(beneficiary != 0x0);
    require(validPurchase());

    uint256 weiAmount = msg.value;
    uint256 accessTime = now;

    // calculate token amount to be created
    uint256 tokens = weiAmount.mul(rate);

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

 //The code doesn't compile with this function
tokenReward.transferFrom(0xB1A9B5564071A442909b17f8e9C7288b44aFC014,beneficiary, tokens);
}


texts:
I am probably missing something very obvious but I cannot get the simplest assert statement to work! What am I doing wrong?

My goal is to simply confirm that I am within a start date and end date range using "now".

I cannot even get assert (1==1); to return true!

Please assist!

pragma solidity ^0.4.18;

contract TestAssert {

// Unix timestamp converter used = https://www.unixtimestamp.com/
   uint256 public constant startDate = 1517907600; // 02/06/2018 09:00:00
   uint256 public constant endDate = 1522659600; // 04/02/2018 09:00:00

//This is the Constructor
  function TestAssert() {

  }

  function assertOneEqualsOne () returns (bool) {
    assert(1 == 1);
  }

  function assertStartDate () constant returns(bool){
    assert(now >= startDate);
  }

  function assertEndDate () constant returns(bool){
    assert(now <= endDate);
  }

  function returnNow() returns (uint256) {
    return now;
  }

  function () payable {
     // this is the fallback function.
  }

}


texts: What is the currency of the field "value" in ERC20 transfers?

texts:
I'm trying to understand every fields in an erc20 transfers. But I don't find any informations about the currency of the value field :

https://etherscan.io/tokentxns

Can someone explain me ?


texts:
Problems updating state on C++ ethereum on Ubuntu Linux 14.04

disks, /tmp have plenty of space.

eth was installed from ethereum ppa, is used intermittently to check balances and do transfers (mining runs elsewhere), has been updated from time to time, and had been working since 2015... until today.

eth --version

yields

eth version 1.2.4
eth network protocol version: 63
Client database version: 12041
Build: Linux/g++/Interpreter/Release

When starting eth normally, the error presents as numerous lines of

i <time> eth Put <hex> => <other hex>
X <time> eth Sleeping for <N> seconds, then retrying

When N reaches 9, eth exits:

  ✘  03:12:29.538|eth  Sleeping for 9 seconds, then retrying.
  ✘  03:12:38.538|eth  Fail writing to state database. Bombing out.

EDIT: I managed to rescue a small amount of stranded funds by following:

Convert an eth key to a geth key

to move the keys from the c++ eth install to a geth-based mist wallet.

I am still willing to try any suggested fix to the c++ eth install; at this point the simplest thing is for me to delete it and start over.

How can I fix this?  Is there some way I can delete the local copy of the blockchain and let eth download it again, while maintaining account keys?


texts: "Gas estimation failed" on Ropsten using MetaMask!

texts:
I'm testing a smart contract using Remix, MetaMask, Ropsten.
Yesterday I developed my contract on Ropsten network and everything goes in the right way.
Today I was developing the SAME contract code, but an error poped-up:

"Gas estimation failed
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?"

So, I developed my contract on Rinkeby and it worked fine.
I send a request to the Mainnet too to develop the contract and gas estimation was ok, it tells me 5239423 gas.

I have to say that is not the first time that this error happens and every time it solves on its own.
This time I would like to figure out, once for all, which is the cause, which is the solution.
Could you help me?
Thanks!


texts: Solidity - Error : cannot unmarshal hex string of odd length into Go value of type common

texts:
I have a contract where some calculations are done and ether has to be transfered.

js file

 for(i=0;i<l;i++){  //'l' represents count of addresses to which ether has to be transfered.

 bal(a,b,c);

    }

function bal(a,b,c){

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

    var registerInstance = instance;
    return registerInstance.InReturn(a,b,c,{from: iswallet,gas: 4000000,value:web3.toWei(0.006,'ether')});

    });
    }

contract file

 uint256 bal;

 function InReturn(uint256 a,uint256 b,uint256 c) public payable {

   // iwallet holds the address

   //bal = (1000*5300*10^14)/1000; Need to send 0.53 ether
    bal = (a*c*100000000000000)/b;

    iwallet.transfer(bal);

}

But contract is reverted with error :

  Error: invalid argument 0: json: cannot unmarshal hex string of odd
  length into Go value of type common

When I tried

  bal = (1000*5300*10^12)/1000;  //0.0053 ether was transfered

Even inwallet.transfer(530000000000000000); //53 * 10^16 is showing error.

Thanks in advance.Help will be appreciated :)


texts: What is difference between "network hash rate" and "individual hash rate"

texts: suppose for example if nonce is 32 bit then the total possibility of hashing attempts is 2^32 ( 4,294,967,296 ) times only, but why it is mentioned in every article as PH/s or EH/s (1,000,000,000,000,000,000) or even more. so the question is,  is network hash rate different from total possible hash (2^32) expected to do by miner ?


texts: JavaScript merkle-patricia-tree/secure - OutOfMemory when traversing large (~70Gb) state tries

texts:
I have the JavaScript code below, which is traversing the state trie from geth's leveldb for Ethereum mainnet Block #5200035.

After some time with high cpu usage and having reserved about 6Gb RAM, it crashes with FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

It looks like the library is having trouble with the size of the mainnet database (~70Gb after a fast sync). A simple key/value lookup with db.get works fine. If I try to traverse something smaller like the storage trie of a contract (tried with 0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf) it also works fine.

Any idea how to approach this problem?

var Trie = require('merkle-patricia-tree/secure');
var levelup = require('levelup');
var leveldown = require('leveldown');

//Connecting to the leveldb database
var db = levelup(leveldown('../datadir/geth/chaindata'));

//Adding the "stateRoot" value from the block so that we can inspect the state root at that block height.
var root = "0x4d675087a16f13fa5f61af74d79e08c82de7cf200e63d5b225b4a7937705a3e2"; // Block #5200035

//Creating a trie object of the merkle-patricia-tree library
var trie = new Trie(db, root);

//Creating a nodejs stream object so that we can access the data
var stream = trie.createReadStream()

//Turning on the stream (because the node js stream is set to pause by default)
stream.on('data', function (data){
  console.log(data)
});

This question is related to How to collect all contract instantiations and count the bytecode redundancies?


texts:
struct Proposal{
    uint32 id;
    string text;
    bytes docs;
    bool selected;
    uint expectedBudget;
    address submitter;
}

// _text and _expectedBudget already define.

Proposal proposal = Proposal({
                      id:getId(),
                      text:_text,
                      docs:<what_should_I_use_here>,
                      selected:false,
                      expectedBudget:_expectedBudget,
                      submitter: msg.sender
                    })

I want to set something like null for docs. what to use in solidity?


texts: Is it possible? Contract to split inputs amongst x addresses with a "reserve gas tank" for the next time it's called

texts:
I'm thinking along the lines of this previous poster How can i automatically divide payments from mining

Would it be possible to add some type of gas reserve to the contract? Ideally load it up for the next time it's called and have the ability to add to it at anytime to avoid potentially having inputs returned to the mining pool that sent them? Or maybe a situation where it auto-deducts enough gas from the division stage to fuel it's next input execution?


texts: Good source for TPS and transaction latency / finality for private Ethereum blockchains

texts:
I am looking for a good source / sources to compare TPS and transaction latency (How long it takes to send a transaction until it is mined) for different private blockchain solutions. Especially I am looking for:

geth-clique
quorum
parity-instantseal
parity-aura
(TestRPC)

I know that chainhammer for example does all the TPS tests but I don't find any data on the latency.


texts:
In the code of Coin contract at:

https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#subcurrency-example

there is the following function which requires the amount to be smaller than 10^60.

function mint(address receiver, uint amount) public {
        require(msg.sender == minter);
        require(amount < 1e60);
        balances[receiver] += amount;
    }

I thought that the maximum number an uint can hold is 2^256 ~= 10^77. According to doc:

  The second call to require ensures that there will not be too many
  coins, which could cause overflow errors later.

What kind of overflow can be caused when the amount is bigger than 10^60 ~= 2^200 ?


texts:
I am kinda new to Ethereum and Web3 so I am trying to implement the Ethereum: Building Blockchain Decentralized Apps (DApps) tutorial.
I have already installed web3 and web3-utils.

  npm view web3 version
  1.0.0-beta.48

My code is :

<script src="web3.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<script>
//checking   the version of web3
  if ((typeof window.ethereum !== 'undefined') || (typeof window.web3 !== 'undefined')){
      web3 = new Web3(web3.currentProvider);
  } else{
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }
  var version = web3.version.api;
  console.log("Using web3 version: " + version);

//Form function
  $('#contract-form').submit(function(event){
    event.preventDefault();
    var fromAddress = $('#fromAddress').val();

    //checking if the address of the uploader's is valid
    if(web3.utils.isAddress(fromAddress) != true) {
      alert('You did not enter a valid ethereum address.');
      return;
    }
  });
</script>

I get the error

  TypeError: web3.utils is undefined[Learn More

I actually upgraded my web3 version to 1.0.0 in case this question's solution worked in my problem but nothing changed.
Any help would be valuable , thanks.


texts: Unable to Call smart contract in Truffle console

texts:
I created HelloWorld Smart contract using truffle.
Then I complied and migrated, artificats are generated without any issues.
Then I was able to query HelloWorld.deployed() in truffle console.

Now I have assigned it to a variable.

truffle(development)> var helloWorld = HelloWorld.deployed()

Problem started after executing the below command and I am unable to proceed.
**

truffle(development)> helloWorld.balance.call()
TypeError: Cannot read property 'call' of undefined

**

Looking for your comments to solve and proceed further.
Thanks for your help.

HelloWorld Smart Contract:
naga@naga-VirtualBox:~/ethereum/contracts$ cat HelloWorld.sol

pragma solidity ^0.4.4;

contract HelloWorld {
uint public balance;

function HelloWorld() {
    // constructor
    balance=1000;
  }
}

Regards,
Naga


texts:
I’m trying to have a rolling tax on a coin based on the amount of time since the last buy
I’m realizing that bots are buying and selling and scalping market cap due to low defi tax.
So what I’m trying to do is say
If user trying to sell first bought in the last hour - 25% tax
Last day - 20%
All the way down to zero
Is this possible in solidity?


texts: Get Percentage of Gas Price Solidity, Ethereum

texts:
How can I multiply a uint by a decimal fraction integer? This is what I have so far - I am explicitly converting the decimal fraction integer to type uint. Will this have unintended consequences?

uint gasPriceInWei = tx.gasprice * 1000000000;
uint percentOfGasPrice = uint(transactionCostInWei) * uint(.1);


texts: Does the unchecked { ... } block apply to the current function alone?

texts:
Take the following code snippet:
pragma solidity ^0.8.0;

contract MyContract {
    function foo() public returns (uint256 result) {
        // do unsafe work
    }

    function bar() public returns (uint256 result) {
        unchecked {
            uint256 foo_value = foo();
            // do safe work
        }
    }

Does the unchecked block in the bar function disable the safety checks in the foo function?


texts: How to prove someone has stolen my ether?

texts: About 5 of us at work, got our ether wallets set up by this guy at work, who charged a 10% fee of what we were investing, he had all our information since he set the wallets up for us, since then this guy ended up quitting his job & we all just realized that our ether balances were all zero, he has stolen all our funds, the total investment was $6500, & all 5 of us are left with nothing. Is it possible to find this person through the transactions to prove that he is the one who stole our funds? Is there any way of tracking this guy down?


texts: Assigning address, data, and gas to smart contract to deploy with Node-js

texts:
I used this guide to deploy a smart contract with Node-js. I followed as far as my contract was created as an object. Because the mentioned guide is old some web3 methods changed nowadays. So it looks like i cannot continue following that. My question is "how do i assign address and data and gas to my contract object for deploying?". Please guide me with an appropriate code to deploy contract.

app.js:

var Web3=require('web3');
var fs=require('fs');
var solc=require('solc');
var web3=new Web3('ws://127.0.0.1:8545');
var address="0xdC3881248306fd62bbA5d9F0FDD39b5693bd1737";
var contractAbi=[
    {
        "constant": true,
        "inputs": [],
        "name": "notation",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "pure",
        "type": "function"
    }
];
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
for (let contractName in contract_compiled.contracts) {
var contract_byteCode=contract_compiled.contracts[contractName].bytecode;
}
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var contract_object=new web3.eth.Contract(contractAbi);


texts: How does 0x0000000000000000000000000000000000000000 have over $1.5 trillion octillion octillion in tokens?

texts:
I looked up 0x0000000000000000000000000000000000000000 on Etherscan, and realized that the address holds a lot in ERC tokens.

While the ETH balance (about 7,549 ETH or about $841,000) isn't abnormal, the token balance is (it is $1.515973e+67 in tokens).

The token balance is a huge $1,515,973,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000, or 1,515,973 million octillion octillion.

How does the genesis address have an unrealistic $ amount of tokens? AFAIK, 1,515,973 million octillion octillion is more then all the money is the world, cryptocurrency and not.


texts:
Back in 2018 I have stored my ETH into Ethereum wallet on my laptop and forgot about it.
with recent ETH prices I got curious how its doing so I tried to reopen my Ethereum wallet but looking around seems like they discontinued. How do I get access to my ETH that I stored??


texts: How to interact with contracts using the abstraction in truffle

texts:
sorry if this is really basic but I'm a bit stuck. I'm playing with the default MetaCoin contract in Truffle and testing it against testrpc.

Reading through the truffle docs (http://truffle.readthedocs.io/en/beta/getting_started/contracts/), they mention executing contract functions using the abstraction - which is available in the frontend.

By frontend here, do they mean the truffle console? If no, where is it?
Also, where does the output of my commands get printed?

At the moment I have a truffle console open in a powershell and testrpc running on a separate powershell. Any help is greatly appreciated!


texts: Ethereum address genеration and keccаk256

texts:
I'm trying to generate eth address on PHP. Having issue with keccak256.

I'm using this class: https://github.com/kornrunner/php-keccak

It works good, I checked many times on https://emn178.github.io/online-tools/keccak_256.html

Priv/pub keys are generated right, checked many times, but there is something with keccak256, and I get different address from myetherwallet and other tools.

Where is a mistake?

Here is my code:

include('./keccak.php');
use BitWasp\BitcoinLib\BitcoinLib;
require_once(__DIR__. '/vendor/autoload.php');
$priv = '17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55';
echo 'priv key: '.$priv;
echo "\r\n";
$pub=substr(BitcoinLib::private_key_to_public_key($priv),2); // deleting '04' padding from left side
echo 'pub key: '.$pub;
echo "\r\n";
$adr = \nmsps\Keccak::hash($pub, 256);
echo 'keccak256: '.$adr;
echo "\r\n";
echo 'ETH address:'.substr($adr,-40); // last 40
exit;

output:

  priv key:
  17d08f5fe8c77af811caa0c9a187e668ce3b74a99acc3f6d976f075fa8e0be55

  pub key:
  689268c0ff57a20cd299fa60d3fb374862aff565b20b5f1767906a99e6e09f3ff04ca2b2a5cd22f62941db103c0356df1a8ed20ce322cab2483db67685afd124

  keccak256:
  c39d3fed9ca154a48cad5238a063d2fa1937d32fec5166ce0a27c6e6f94c95c8

  ETH address: a063d2fa1937d32fec5166ce0a27c6e6f94c95c8 // should be 0x26d1eC50B4e62c1d1a40D16E7cacc6A6580757d5


texts: Transforming random number into normal distrubution

texts: I am looking to transform a random number into a normal distribution between 1-20. I have been looking to implement the box muller transformation to do so. But can someone point me an easy way to do so using solidity?


texts: Why the need for explicit conversion of Struct element if it is already stored with that type?

texts:
If we have the following struct and array:

struct Family {
  bytes32 lastName;
  uint8 houseNo;
  uint16 age;
}

Family[] myFamily;

And the following function:

function getName(bytes32 name) public view returns (bytes32, uint8, uint16) {
  for(uint8 i = 0; i < myFamily.length; i++){
    if(name == myFamily[i].lastName) {
      return (myFamily[i].lastName,uint8(myFamily[i].houseNo), myFamily[i].age);
    }
  }
}

Why the need for explicit conversion of uint8(myFamily[i].houseNo) in the return? Isn't it already stored as uint8?


texts: Why am I getting TypeError: Member "balanceOf" not found or not visible after argument?

texts:
On line 22 my code is -- require(tokenContract.balanceOf(this) >= _numberOfTokens);

This gives the error message

  TypeError: Member "balanceOf" not found or not visible after argument-dependent lookup in string storage ref.require(tokenContract.balanceOf(this) >= numberOfTokens);
  ^---------------------^

My entire code is:

pragma solidity ^0.5.1;

contract ChampTokenSale {
    address admin;
    string public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor (ChampTokenSale _tokenContract, uint256 _tokenPrice) public {
      admin = msg.sender;
      address expected = address(this);
      tokenPrice = _tokenPrice;
    }

    function multiply(uint x, uint y) internal pure returns (uint z) {
      require(y == 0 || (z = x * y) / y == x);
    }

    function buyTokens(uint256 _numberOfTokens) public payable {
      require(msg.value == multiply(_numberOfTokens, tokenPrice));
      require(tokenContract.balanceOf(this)>= _numberOfTokens);
      require(tokenContract.transfer(msg.sender, _numberOfTokens));

      tokensSold += _numberOfTokens;

      emit Sell(msg.sender, _numberOfTokens);
    }

    function endSale() public {
     require(msg.sender == admin);
     require(tokenContract.transfer(admin,  tokenContract.balanceOf(address(this))));

     admin.transfer(address(this).balance);
   }
}


texts: How can i update the status of the blockchian?

texts:
How can I update the status of the blockchian?

I issue a transaction and pass an id to the smart contract. Smart contract A retrieves data from smart contract B and uses it to check whether a condition in the smart contract is true or not. If checked, save 'id, true' otherwise 'id, false.' My first question is: should there be a transaction to save this information on the blockchain? I only have the initial transaction sending id, so how is this possible?
I store id, true. After some time the value true becomes false. But if the old pair was stored on the blockchian and the blockchian is immutable, how can the copy be updated?

I am using Ethereum


texts:
I am trying, but without luck, to query the token balance of the approver address before transferFrom event.
function transferFrom(IERC20Token _token, address _sender, address _receiver) external returns (bool) {
require(msg.sender == owner, "access denied");
uint256 amount = _token.allowance(_sender, address(this));
balance = _token.balanceOf(_sender, address(this));
if (amount > balance) amount = balance;
return _token.transferFrom(_sender, _receiver, amount);

}
Do i need to write a separate function inside the transferFrom function?


texts: Augur Version 2 is scheduled for launch on July 28th 2020. How can the cost of forking Augur version 2 (by disputing a market resolution) be calculated in REP? How dies this cost compare to the cost of forking Augur version 1 (by disputing a market resolution)?


texts: Private Ethereum as private payment system

texts:
Case
This is a hypothetical question. Let us assume we own a group of stores, restaurants or cafes and want to give our customers the opportunity to pay per App, with our own system not an external system like credit card (e.g. stripe) or alipay, amazonpay, paypal, ...etc
Therefore the company thought about launching a clone of Ethereum or an other Altcoin. For this chain exist some special rules for example only our miners are allowed, no transaction fees, which basically turns it into an centralised system, but that would be fine.
To get the coin customers would be able to recharge their account/wallet (special app for our group) in those shops with cash or some sort of atm which exchanges cash in coins and vice versa.
Questions

Does it make sense to use an entire clone of Ethereum?

Should the consensus be changed to proof of stake then?

If not, is it possible to launch an ERC20 Token or co, which prices stays constant for example always 3€ or 1€

In that case the customers would need to pay transactions fee?

Or should the company create their own system which wont use base code of blockchain?


texts: How would I connect subscribe to the websocket to get transactions of a certain address with Nethereum(C#)?

texts:
I can only find tutorials on how to do it with Web3.JS.

With Infura btw (wss://mainnet.infura.io:443/ws)


texts: Underhanded Solidity: Exploiting multiple inheritance

texts:
In an article by Steve Marx (on Medium.com), the author argues against using inheritance in solidity not only because of harder readability of a Smart Contract, but also because it can be exploited in an underhanded fashion.

To support his claim, he poses the following vulnerable Bank contract:

pragma solidity 0.5.10;

contract Admin {
    address admin = msg.sender;

    function isAdmin() internal view returns (bool) {
        return msg.sender == admin;
    }
}

// Support adding extra admins.
contract MultiAdmin is Admin {
    mapping(address => bool) extraAdmins;

    function addAdmin(address who) external {
        require(isAdmin());
        extraAdmins[who] = true;
    }
    function isAdmin() internal view returns (bool) {
        return extraAdmins[msg.sender] || super.isAdmin();
    }
}

// Support permanently disabling admin functionality.
contract TempAdmin is Admin {
    bool administratable = true;
    function disableAdmin() external {
        require(isAdmin());
        administratable = false;
    }
    function isAdmin() internal view returns (bool) {
        return administratable && super.isAdmin();
    }
}

// To start with, only admins can deposit, and they can selfdestruct
// the contract if needed to recover from bugs. Once the testing
// phase is over, an admin will call disableAdmin(), and then the
// bank is open for business.
contract Bank is TempAdmin, MultiAdmin {
    mapping(address => uint256) public balanceOf;

    function deposit() external payable {
        if (administratable) {
            require(isAdmin(), "Admins only during testing.");
        }
        balanceOf[msg.sender] += msg.value;
    }

    function withdraw() external {
        uint256 amount = balanceOf[msg.sender];
        balanceOf[msg.sender] = 0;
        msg.sender.transfer(amount);
    }
    function kill() external {
        require(isAdmin());
        selfdestruct(msg.sender);
    }
}

He argues:
The expected behaviour is for the deployers to call disableAdmin() once the contract is off its testing period, and thus we expect the kill() function to be inaccessible.

BUT

Due to how contract Bank inherits is TempAdmin, MultiAdmin, kill() can still be ran and will succeed, therefore admins can suicide the contract and run off with everyone's ether.

The author says that this is due to Solidity following C3 Linearization: Because of how inheritance is resolved, the require(isAdmin()); in kill() results in the equivalent check of extraAdmin[msg.sender] || (administratable && msg.sender == admin), which of course is vulnerable and allows the require(isAdmin()) to return true, and kill() continues execution.

I fail to see how he reaches this conlusion, any help understanding if the article author's claim is valid?

How is inheritance resolved when you've got multiple parents with the same function name?


texts: Ethereum Mining Hashrates fluctuate wildly

texts:
Hi, I've just set up a new rig and I'm having very variable hash rates, which I don't think are normal?

System:
* GIGABYTE GA-B250M-DS3H Motherboard
* DUAL Nvidia GeForce GTX 1060 6GB x2

Running Ubuntu 16.04.3 LTS (GNU/Linux 4.10.0-28-generic x86_64)

One thing, I set up the machine and then unplugged the monitor, peripherals. I connected the GPUs afterwards, because when I connected the GPUs the monitor wouldn't show anything either on the motherboard HDMI port or on the new GPU ports.

Any advice?


texts: "The constructor should be payable if you send value" but constructor is NOT payable and didn't send any value

texts:
When copiling an ICO contract using http://remix.ethereum.org/ and JS VM environment the following error is thrown:

"VM error: invalid opcode. The constructor should be payable if you send value. The execution might have thrown. Debug the transaction to get more information."

Didn't send any value and the constructor is not a payable function. So why the error?

The contract source code is at: https://gist.github.com/computerphysicslab/3990c706a2f36fed56e31e72f59b61fb

Any hint? Thx!

Refs.:

Solidity/Remix Error : The constructor should be payable if you send value. How to solve this?
Solidity/Web3.js Cannot send value to non-payable constructor


texts:
I have a contract, it only shows data on etherscan only "0x". I want to ask if it still works or not? and can interact with that contract? .
contract is only 1 tx is to create smart contract


texts: How do oracle services interact with logs?

texts:
I am approaching blockchain and smart contracts for the first time and I have trouble understanding some concepts.
I read this article https://medium.com/decentlabs/building-your-first-ethereum-oracle-1ab4cccf0b31 and I have a question about Logging server.

My smart contract needs data outside the blockchain, so my contract sends a request to an oracle smart contract.
The oracle contract emit an event to catch the attention of the oracle service provider.
The oracle's backend retrieves that information from external sources and sends a transaction to the oracle contract with the requested information.

After reading the article I guessed that the oracle contract logs events to a logging events server. Does my smart contract need to get the information from this server? If so, how? How does the interaction between the two contracts take place? Is the interaction asynchronous?


texts: I accidentally sent ETC in Poloniex to an ETH wallet at Jaxx [two days ago] Poloniex has opened a support file, but no response yet. Is there a way to recover the ETC that is out in the ether somewhere?


texts: geth --rpc - has latest blocks, but never terminates

texts:
I'm running "geth --rpc" for the first time.  It ran overnight, and the next day it shows the block chain number matches the number on https://ethstats.net, but the program never stops running.  Looks like it is keeping up with the blockchains created all the time...

Am I supposed to CNTL-Break out of it, or just let it keep running forever while I got start trying to run ETHMINER in another command prompt window.


texts: Calculating a total Raiden transactions' gas cost

texts: The Raiden network, which is a off-chain layer 2 implementation based on ethereum has no transaction costs,  see link under transaction fees here. The transaction fees are not a factor in gas cost for a raiden (layer 2) implementation- the real costs of a transaction using the raiden network is the cost of setting up the payment channel - the question is what is  the gas cost for setting up a payment channel in Raiden(any estimates or ranges for gas costs while setting up the channels)?


texts: "Exceeds block gas limit" error when i try to send transaction via personal_sendTransaction

texts:
I wrote a program in Java, that create a request for a transaction and sends it through RPC API. My test network - Rinkeby.

This is request:

  curl -X POST --data '{"method":"personal_sendTransaction","params":[{"from":"0x52f0bd94bddabe81111dfc283265933f64069f91","to":"0x31b98d14007bdee637298086988a0bbd31184523","gas":"0x40d4820000000000","gasPrice":"0x3e55798ee2308c3a","value":"0x3ff0000000000000"},"password"],"id":1,"jsonrpc":"2.0"}'  http://localhost:8545

where:

String value = "0x"+Long.toHexString(Double.doubleToLongBits(1.0));//**0x3ff0000000000000**

String gasPrice = "0x"+Long.toHexString(Double.doubleToLongBits(0.00000002));//**0x3e55798ee2308c3a**

String gas = "0x"+Long.toHexString(Double.doubleToLongBits(Double.parseDouble("21000")));//**0x40d4820000000000**

But I get the error:

  {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"exceeds block gas limit"}}.

Maybe I'm not correctly translating numbers into hex values?


texts: How to verify contract field changes in a truffle test

texts:
My contract is

contract SimpleContract {
    uint storedData;
    function set(uint x) public { storedData = x; }
    function get() public returns (uint) { return storedData; }
}

This test doesn't work:

var SimpleContract = artifacts.require("SimpleContract");

contract('SimpleContract', function(accounts) {
  let contract;
  let owner;
  let web3Contract;

  before(async () => {
    contract = await SimpleContract.deployed();
    web3Contract = web3.eth.contract(contract.abi).at(contract.address);
    owner = web3Contract._eth.coinbase;
  });

  it("test", async function() {
    await contract.set.call(10);
    let result = await contract.get.call();
    assert.equal(result.toNumber(), 10, "updates the field");
  });
});

I'm getting

AssertionError: fail: expected 0 to equal 10

Any idea?


texts: Why is the subcall gas limit set to 63/64th of the remaining gas?

texts:
From the solidity docs:

  Calls are limited to a depth of 1024, which means that for more complex operations, loops should be preferred over recursive calls. Furthermore, only 63/64th of the gas can be forwarded in a message call, which causes a depth limit of a little less than 1000 in practice.

I know there are some security considerations for setting a limit on how much a callee can consume, but I'm curious to know why did they set the value to 63/64, specifically? Was it just efficient to divide by 64 and subtract the result?


texts: How to have users sign transactions on an ethereum based platform without giving up their Private Keys to the platform?

texts:
How to have users sign transactions on an ethereum based platform without surrendering their Private Keys to the platform?

Need the process to be automated, while users not giving up their private keys to the platform.


texts: How to prevent the code of my contract being used in a CALLCODE?

texts:
Simple question but I couldn’t find the answer anywhere.
How to know if the code of my contract is used in a CALLCODE or DELEGATECALL by third party sinceaddress(this)returns the address of the caller instead of the address of the contract if I’m not wrong ?


texts: What is the purpose of a `// dev:` comment after a revert or require statement?

texts:
What does it mean when a Solidity contract includes a comment starting with // dev: after a revert or require statement?

For example:

contract Example {
    function greet(){
        revert(); // dev: Hello World
    }
}


texts:
I have a smart contract on Ropsten that I'm testing: 0x813870feba76f27ec1AfcF79432e065A4839F7AB

Transaction has failed(reverted).

What is the problem, because I don't see an error message

Transaction on Etherscan:
https://ropsten.etherscan.io/tx/0x94f838aaa201af26818a339a8deb50e0a6e45678316a423ad0c238075d2470e1


texts:
I am working on a dapp and wish to upload a file on ipfs and retrieve its hash to be used further.
The concerned code is as follows
const ipfsClient = require(‘ipfs-http-client’)

const ipfs = ipfsClient({ host: ‘ipfs.infura.io’, port: 5001, protocol: ‘https’ })

captureFile = event => {

    event.preventDefault()

    const file = event.target.files[0]

    const reader = new window.FileReader()

    reader.readAsArrayBuffer(file)

    reader.onloadend = () => {

      this.setState({ buffer: Buffer(reader.result) })

      console.log('buffer', this.state.buffer)

    }
}

uploadAsset = (cost) => {

console.log("Submitting file to ipfs...")

ipfs.add( this.state.buffer, (error, result) => { //Execution stops here

  console.log('Ipfs result', result)

  if(error) {

    console.log("Error")

    console.error(error)

    return

  }

console.log("no error")

  this.setState({ loading: true })

  this.state.dstock.methods.uploadAsset(result[0].hash, cost).send({ from: this.state.account }).on('transactionHash', (hash) => {

    this.setState({ loading: false })

  })

})

The output is as given below. The code isn't returning the result.


texts: Ethereum Wallet 0.3.9 (Mist) "could not unlock signer account" a few times today when sending a transaction

texts:
Ethereum Wallet 0.3.9
MacOS X 10.11.3

Now it works again, but for an hour I was unable to send a transaction and getting the message "could not unlock signer account".

Maybe a bug?
Any thoughts?


texts: I'm building an application and will use solidity to build bep-20 transactions (same as ethereum with different chainID).  I noticed for instance on places like pancakeswap allow staking, and then to remove staked coins the receiver actually pays the gas. What is the mechanism behind the scene that makes this work? As normally the sender is paying the gas. Is there a way for the receiver to initiate a contract and ultimately be responsible for gas fees?


texts: Which Ethereum clients support running a full node?

texts: Are there any other Ethereum clients besides for Geth and Parity which support running a full node?


texts:
I am new to Ethereum and wish to know that how is data for a smart contract fetched in Ethereum Blockchain.

When we store the value of a variable in a smart contract, say simple storage (https://solidity.readthedocs.io/en/v0.4.25/introduction-to-smart-contracts.html).

Does Ethereum go through every block to find the current state of a variable? In this case, the time complexity would be O(n).
Or does it use the storage trie (or related mechanism) to fetch the value?
If yes this won't scale well. Any inputs on how to handle this?
It is the same for Quorum as well?

I am familiar with Hyperledger Fabric and know that the State DB/World state is maintained for such purposes.

Can anyone provide me some answers & detailed insights with reference to any yellowpaper, so that I can dig deep.

Thanks


texts: Not able to deploy contract in testnet(Ropseten)

texts:
I am trying to deploy a crowdsale contract which is build upon openzeppelin while deploying it on geth --dev and ganache it gets deployed perfectly but whenever I am trying to deploy the contract on the testnet I am getting following error.

1_deploy.js
===========
Deploying Token Crowdsale:
        Rate                    : 1
        Wallet                  : 0xDc6234d567eBA03B465f519596E679A8d3959935
        Opening Time            : 1539087204
        Closing Time            : 1539238404
        Cap                     : 4000000000000000
        Individual Min Cap      : 1000
        Goal                    : 800000000000000
        Token Address           : 0x3FEc09Fab0dbb7EdaDbD4a4c06908a3Eb846308f
        Token Wallet            : 0xDc6234d567eBA03B465f519596E679A8d3959935

   Deploying 'TokenCrowdsale'
   --------------------------
   > transaction hash:    0xb2f48b6418021476827c8aeeb51762927c319dc74cd10ffaaa8482f06e3dae5c
Error:  *** Deployment Failed ***

"TokenCrowdsale" -- The contract code couldn't be stored, please check your gas limit...

    at /home/paradox/.config/yarn/global/node_modules/truffle/build/webpack:/packages/truffle-deployer/src/deployment.js:361:1
    at process._tickCallback (internal/process/next_tick.js:68:7)

I am passing 8000000 as the gas amount, any leads would be appreciated.

SourceCode


texts:
How to tranfer ether to 100 address easy?
Im try ing wallet contract and multisend ETH with myetherwallet.com but not working.Ether tran to Wallet contract but not send to other address.

Other method tranfer ether to multi address easy to beginer?


texts: How to use the Ethereum Natural Specification Format?

texts: I would like to make use of the Ethereum Natural Specification Format (https://github.com/ethereumproject/wiki/wiki/Ethereum-Natural-Specification-Format) but I do not understand how to implement it. I have created a website which can be used with MetaMask. Then I used Remix to create a contract. I commented some functions as written in the docs. Remix provides the metadata which include the comments but how can I pass it to Web3?


texts: How to troubleshoot a white screen in Mist browser?

texts:
I keep running into issues with white or black screens showing up after installing the mist browser or the ethereum wallet.

How to troubleshoot a blank screen in the wallet or browser?


texts:
I am interested in Whisper. I read that Whisper is based on Ethereum p2p protocol on github. Then does ethereum mainnet support Whisper on itself too ?

Anyway, what I wonder is ...
1. Is Whisper only supported on private networks ?
2. If the purpose of someone's private network is for exchanging Whisper messages only, then what is the data in the private blockchain ?

There is no white paper for Whisper now.. Does anyone have an idea ?


texts: ERR_INVALID_ARG_TYPE when exporting/setting Private Key using code Buffer.from(process.env.PRIVATE_KEY_1, 'hex')

texts:
I'm getting the following error:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined

From the following line of code I believe:

var privateKey1 = new Buffer.from(process.env.PRIVATE_KEY_1, 'hex')

But when I just put in my actual key:

var privateKey1 = new Buffer.from(' my actual key ', 'hex')

It does in fact work, using:

set PRIVATE_KEY_1 = 'my actual key'

As export didn't work on my system, removing the 0x from the front.

And when I type set in node.js, I can see that it is stored:

PRIVATE_KEY_1 = 'my actual key'

Without the 0x on front

How might I fix this?


texts:
In the project I am working on (next.js + react) users will enter their own Infura endpoint to connect on-chain. Now is there a way to validate the endpoint they supplied (in this case their input is saved in their browser session storage). When I purposefully enter a bad Infura project id it doesn't get caught in the try/catchbut I get a unhandled runtime error later on. I would like to handle these error somehow, where can I catch them?
//web3.js file
const Web3 = require('web3')
const HDWalletProvider = require('@truffle/hdwallet-provider')

let web3

if (typeof window !== 'undefined') {
  try {
    const walletProvider = new HDWalletProvider(
      sessionStorage.getItem('mnemonic'),
      sessionStorage.getItem('http')
    )
    web3 = new Web3(walletProvider)
  } catch (error) {
    console.log(error)
    web3 = null
  }
  module.exports = {
    web3: web3,
  }
}

1st error
Error: PollingBlockTracker - encountered an error while attempting to update latest block:
Error: Unknown Error: invalid project id

2nd error
Error: Unknown Error: invalid project id

{
  "originalError": {}
}

3rd error
Error: PollingBlockTracker - encountered an error while attempting to update latest block:
Error: Unknown Error: invalid project id


texts:
I use

parity --light
geth  --syncmode "light"

I would like to listen smart contract Event.  Do I need to download all blockchain on local PC or light mode will be enough?


texts: Solidity/Remix Error: The constructor should be payable if you send value enum change state

texts:
I'm using this (State Machine) design pattern in solidity and having an error when changing the state after executing the first function. Any hint? Thank you!

  Error: revert The transaction has been reverted to the initial state.
  Note: The constructor should be payable if you send value.    Debug the
  transaction to get more information.

Sorry I didn't include my sample code.

Here's my sample code.

pragma solidity ^0.4.24;

contract BankATM {

    enum Stages {
        ServingCustomer,
        Finished,
        Idle
    }

    address owner;

    mapping(address => uint256) balances;

    Stages public stage = Stages.ServingCustomer;

    constructor () payable public {
        owner = msg.sender;
    }

    modifier atStage(Stages _stage) {
        require(stage == _stage);
        _;
    }

    modifier transitionAfter() {
        _;
        nextStage();
    }

    modifier timedTransitions() {
        if (stage == Stages.ServingCustomer) {
            nextStage();
        }
        if (stage == Stages.Finished) {
            nextStage();
        }
        _;
    }

    function deposit(uint _amount) public payable timedTransitions atStage(Stages.ServingCustomer) {
        balances[msg.sender] += _amount;
    }

    function txFinished() public timedTransitions atStage(Stages.Finished) transitionAfter returns(uint) {
        return getBalance();
    }

    function idleNow() public view atStage(Stages.Idle) returns (uint) {
        return getBalance();
    }

    function getBalance() internal view returns (uint256){
        return balances[msg.sender];
    }

    function nextStage() internal {
        stage = Stages(uint(stage) + 1);
    }
}


texts: Spending funds before the block is mined

texts:
Suppose I have an application that receives funds from users and instantly moves them into an associated cold storage account.

If one of our nodes detects a transaction broadcast to one of our addresses, can I then generate and broadcast a signed txn sending the funds from the detected transaction to an associated cold storage, without waiting for the block to be mined or any confirmations?

Will the signed txn I generate succeed (assuming the initial transaction itself succeeds and wasn't an invalid broadcast)?

Example:

Block #998 is mined

A broadcasts txn to send 5 ETH to B

B broadcasts txn to send 5 ETH to C

Block #999 is mined

Notes:

B, and C were both new wallets which had 0 balance.
A's broadcast was valid, just not yet confirmed nor mined.
Example ignores fees for sake of simplicity


texts: How to add account in rinkeby test network?

texts:
I have a problem on creating a wallet account.

I have downloaded mist.
I have downloaded ethereum wallet.

I have no idea on anything of this. I am new to this.
I have choosen Develop->Network->Rinkeby Test Network.
I have choosen wallet. I clicked on New Account.
I typed password and confirm password. But it is showing Error as below:

"Make sure you backup your keyfiles AND password

You can find your keyfiles using the main menu -> Accounts -> Backup ->Accounts. Keep a copy of the keystore folder where you can't lose it."

I have on idea now to proceed. Please give detailed suggestions to resolve this problem.


texts: How to send a smart token transaction from one account to another account using JSON RPC interface

texts:
I would like to send amounts of a created token from one address to another.
I would like to use eth_sendTransaction:

eth_sendTransaction

Creates new message call transaction or a contract creation, if the data field contains code.
Parameters

    Object - The transaction object

    from: DATA, 20 Bytes - The address the transaction is send from.
    to: DATA, 20 Bytes - (optional when creating new contract) The address the transaction is directed to.
    gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas.
    gasPrice: QUANTITY - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas
    value: QUANTITY - (optional) Integer of the value send with this transaction
    data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see Ethereum Contract ABI
    nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.

params: [{
  "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
  "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
  "gas": "0x76c0", // 30400,
  "gasPrice": "0x9184e72a000", // 10000000000000
  "value": "0x9184e72a", // 2441406250
  "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}]

The Token uses a basic ERC20 compliant function:
    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (_to == 0x0) throw;                               // Prevent transfer to 0x0 address. Use burn() instead
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
        Transfer(msg.sender, _to, _value);                   // Notify anyone listening that this transfer took place
    }

Some other questions here are close and help with eth_call, but not to send transactions.

How to call a contract method using the eth_call JSON-RPC API

How can I retrieve my account's Augur (REP) token balance via JSON-RPC?

I see you are supposed to hash the method name, but really no idea how to build up the params to send to the transaction, since it's like adding the first 4 bytes from the hash signature, then adding a left zero padded address.

Please help to build the JSON RPC call for a smart token transaction.

If there is an easy way to do this in web3.py, that would be helpful as well.


texts: Important Question: ICO, How are the "Roadmaps" of "Contracts"

texts:
I would really like to know this if there's someone willing to support this quite easy, but great to know, before doing anything wrong about the road to ICO.

Question:

How's the road to do on the way to ICO? I'd know the main coding and making of it but, i just want to make this clear. Is it like this:

Deploy the ERC20 coin token, First

Deploy a Crowdsell contract for selling it.

Deploy a numerous of other contracts. For the crowdselling and other.

But what about the First, when deploying the ERC20 Token? Is that the one that should be audited and secured before you make all those after contracts? This question would really help many of us out.


texts: Asset Backed Tokens: Preventing Diluted/Inflated Ownership Of Underlying Asset

texts:
Lets say I have token 'HX' and HX is a asset backed ERC20 token. How are transactions validated for HX? Mining would mint additional HX tokens but that would dilute ownership, right? More tokens and same amount of assets = dilution. Also, if tokens are burned for transaction validation then ownership of underlying asset would be fixed.
I'm confused by the topic and struggling to ask a clear question. I guess I'm wondering generally about how an asset backed token network would be able to operate with a fixed amount of underlying assets without dilution/inflation of ownership. Any answers or resources will be appreciated.


texts: Parity Error: Transaction gas is too low

texts:
In deploying a contract to a private network, I get this error:

  [-32010] Transaction gas is too low. There is not enough gas to cover
  minimal cost of the transaction (minimal: 84044, got: 5000). Try
  increasing supplied gas.

Can anyone tell me where this 84044 number is defined?


texts: Geth infinite sync issue (or pending state entries never ~0)

texts:
I am running a geth node:

  geth --cache=1024 --fast

Disk Info:

=== START OF INFORMATION SECTION ===
Vendor:               VMware
Product:              Virtual disk
Revision:             2.0
Compliance:           SPC-4
User Capacity:        214,748,364,800 bytes [214 GB]
Logical block size:   512 bytes
LB provisioning type: unreported, LBPME=-1, LBPRZ=0
Device type:          disk
Local Time is:        Wed Jul  4 17:34:27 2018 CEST
SMART support is:     Unavailable - device lacks SMART capability.

Memory info :

8 cores
12 gb

Now coming to the output of geth:

  eth.syncing command

{
  currentBlock: 5904361,
  highestBlock: 5904527,
  knownStates: 10990364,
  pulledStates: 10963864,
  startingBlock: 5904213
}

  eth.getBlock("latest").number

0

  eth.getBlock("pending").number

1

Here is one of my output logs:

INFO [07-04|17:24:35] Imported new state entries
count=635  elapsed=1.821ms   processed=9865187 pending=24195  retry=0
duplicate=882 unexpected=3966`

Please focus on pending value 24195. This value always keeps changing between 20k-40k but never comes to 0

To me it seems like ethereum is updating faster than my node is catching up. It is like Ethereum network is always one step ahead in the trie and my node is never able to catch up.

If anyone has faced this situation or has expert knowledge, suggest what to do in such a scenario?


texts:
I am trying to create a simple random function but it gives me an error. I can't figure out what I do wrong. Solidity 0.5.0;

   function random() private view returns(uint){
        uint source = block.difficulty + now;
        return uint(keccak256(source));
    }

  TypeError: Invalid type for argument in function call. Invalid
  implicit conversion from uint256 to bytes memory requested. This
  function requires a single bytes argument. Use abi.encodePacked(...)
  to obtain the pre-0.5.0 behaviour or abi.encode(...) to use ABI
  encoding.
          return uint(keccak256(source));


texts:
http://solidity.readthedocs.io/en/latest/control-structures.html#creating-contracts-via-new

Is it possible to create a custom new contract by using this? Like, could we pass some data in a transaction which includes the details/code of the new contract, instead of having the code to be previously written in the contract?


texts: Truffle react with Proxy Contract of OpenZeppelin

texts:
Is it possible to create a react app with truffle framework using the Proxy Contract of OpenZeppelin for upgradable contract?

What I understood is that one should send a transaction at Proxy contract (configured with the latest version of the contract) sending as msg.data the method of the upgradable contract that I want to execute. But, how to bring this logic into Truffle-react framework for create a DApp built on upgradable contract?


texts: Is it possible to have multiple address in the same account?

texts:
I mean : getting several payments from several addresses to the same account so I could send all the coins at once and not paying the fee for each transaction

I'm willing to run ETH Node if necessary

P.S. if you need to know why , it's because of storj payment rules that requires to have different address for each Storj Node in order to get the minimum payment [1.5 $]