texts: Extremely slow geth mining and synchronization for private blockchain

texts:
I am constructing a very simple 2 nodes private Ethereum network to study the mining behaviour. The consensus algorithm is ethash. In order for the 2 nodes to discover each other, I also setup a bootnode. All these nodes are running on different IP addresses. Basically I created a docker network and ran 1 bootnode container and 2 geth containers.

I successfully initialized the block (via geth init...), created 10 accounts for each node. Then I initiated the 2 geth instances to start mining, it went through the usual DAG generation. While generating DAG for epoch 1, the mining also started and I can see node1 mined 2 blocks and node2 mined 1 block. After DAG generation is completed, the mining simply stopped.

Here is my genesis.json file, BTW I had lowered the difficulty to 0x000010

{
  "config": {
    "chainId": 5493,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "byzantiumBlock": 4,
    "ethash": {}
  },
  "nonce": "0x0",
  "timestamp": "0x5a9d2b4e",
  "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x47b760",
  "difficulty": "0x000010",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    "0000000000000000000000000000000000000000": {
      "balance": "0x1"
    }
  },
  "number": "0x0",
  "gasUsed": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

Here is the screenshots of my geth console. The top is node1 and bottom is node2. The geth instances are still busy working away - my CPU utilisation is max'ed out. But for the last 15 minutes, there is no activity reported on the geth consoles.

Somehow things started to move again but very slowly.
As you see in the below screenshot, node1 continues to mine new block and it also discarded a bad propagated block (from node2). It also has some lines that said "Regenerated local transaction journal"

For node2, it also mined 1 new block and synchronised other blocks from node1.
As shown on the screenshot, the duration between block is very long 7mins to 20 mins. There is also a sidefork on node2.

This experiment is done with plain vanilla geth, no externally triggered transferred or smartcontract call.

Is there anything I miss here? I simply want the private network to behave like the ethereum mainnet, i.e. mine new block roughly every 10 seconds.

The commands to launch the various nodes are

bootnode
file="/root/bootnode/enode"
if [ ! -f "$file" ]
  then
    echo "initialize bootnode"
    bootnode -genkey /root/bootnode/nodekeyfile
fi
bootnode -nodekey /root/bootnode/nodekeyfile

geth node
geth --networkid 5493 --bootnodes "$(echo -n 'enode://'; bootnode --writeaddress -nodekey /root/bootnode/nodekeyfile | tr -d '\n'; echo '@192.168.2.2:30301')" --mine --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal,net --etherbase 0 --unlock "$(cat /root/.ethereum/geth/security/coinbase)" --password /root/.ethereum/geth/security/password.sec

I basically shared the volume where bootnode nodekeyfile is stored among the 3 containers thus they can all construct the bootnode URL. Anyway, I don't think the bootnode is the issue as the 2 geth nodes are able to talk to each other.


texts: How to make a deployer in truffle tests?

texts:
For some reason, our app will only work with a forked instance of the mainnet. And hence, we want to run our test on the forked ganache. We are using truffle, so we have written all of our tests in the mocha format in test directory, we want to run these tests with the usual truffle test --network --fork command.
But, one of our contract is using a library which requires linking. Now, during migrations we have done this simply using:
await deployer.deploy(ScaledMath);
await deployer.link(ScaledMath, Comptroller);
await deployer.deploy(Comptroller);

But in tests we want to do the same thing, but we don't have the deployer object there. Can someone tell how to create one?


texts: Is there a solution to fees scaling with the size of the network?

texts:
I just read the whitepaper's section on fees. I like the idea that presenting a reward can avert a tragedy of the commons because miners can roughly predict the cost to them to process the transaction and the probability they will succeed in mining the next block so they can claim the reward fee. It is then advantageous to them to take up the task if

reward > cost / probability of successfully mining the next block

But this does not solve the scale problem: The probability anyone can successfully mine the next block is inversely proportional to the number of nodes in the network, so as the network scales, so will transaction fees!

Is there a solution to this? I have a hard time believing people will really use a cryptocurrency long-term if it gets more expensive to use it all the time. At least in a centralized star-graph network, like we have with credit cards and banks, the costs are flat no matter how many points the star has.

Aside: What about this related problem: Say I am a miner who controls a bigger part of the network than anyone else. Can't I now offer lower fees because my probability of successfully mining the next block is higher? Could I drive other miners out of business because they can't process those transactions cost-effectively and thus can't generate the next block? Could I slowly take over more and more of the network this way until I'm a monopoly? Or does the problem solve itself because other miners can still beat me to the punch by creating valid blocks that exclude those low-fee transactions/I would never take on low-fee transactions when there are higher ones around?

Note: My first question is not about basic blockchain scalability; it is specifically about how scaling the network will increase fees. The second question is less pressing.


texts: Invalid argument after upgrading geth from 1.5.9 to 1.6.1

texts:
Once upgraded the geth node to 1.6.1 it is not accepting queries anymore, throwing the following error:

Invalid argument 0: missing 0x prefix for hex data

That's weird for a query like this, where argument 0 seems to be a "from address" that starts with 0x.

eth_estimateGas([{ "from": "0x8c60d40a2e848251d139fc2b0b6b770bb3351ffd", "to": "0xe5f68950d479fab12797dabbe5a4b0d88ec7a722", "value": "1000000000000000000", "data": "0x4d61726b65745061792e696f202d204661756365743a2053656e642066756e647320746f203078653566363839353064343739666162313237393764616262653561346230643838656337613732322c2031206574686572" }])

Why this error? Why not in previous versions? Thx!


texts:
Here you can see that if the EVM stack gets larger than 1024, it results in an error:

Why is there this hard limit on the stack size?
What is the justification for this not being parametrizable?
Is 1024 particularly suitable? If so, why so?


texts: Distribution of tokens right away after ERC20.transferFrom

texts:
I would like to ask a question about token distribution with overriding ERC20 transferFrom function.

IERC20 Token;
  function buy(uint256 id)
        external
        onlyCardPayable(id, PaymentTypes.Buy)
    {
        uint256 amount;
        if (winners[id][msg.sender].amount == 0) {
            amount = collection[id].amount;
        }
        amount = winners[id][msg.sender].amount;

        distributeTokens(msg.sender, address(this), token, amount);
        transferFrom(address(this), msg.sender, id, 1, "");
        sold += 1;

        emit CardBought(msg.sender, id, PaymentTypes.Buy, amount);
    }

 function distributeTokens(
        address from,
        address to,
        IERC20 token,
        uint256 amount
    ) internal {
        uint256 totalShare =
                shares[_charityOne] +
                shares[_charityTwo] +
                shares[_toAddress];
        // Check if transfer reverts due to 2300 gas limit.
        // We should change to call than.
        token.transferFrom(from, to, amount);
        payable(_charityOne).transfer(amount * (shares[_charityOne] / 100));
        payable(_charityTwo).transfer(amount * (shares[_charityTwo] / 100));
        payable(_toAddress).transfer(amount * (shares[_toAddress] / 100));
    }

Question is this -> Is this possible? Getting token to contract and in next line distribute it.


texts: Is there an Ethereum wallet which provides the ability to annotate transactions like Electrum does for Bitcoin? It would be really useful. I can't find a way to do it in Mist. Thanks for any help on this.


texts:
I have installed parity and it runs for PoA. When I try to install geth it fails -

sudo apt-get install ethereum
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package ethereum is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'ethereum' has no installation candidate

I want to use web3 functions with parity and hence I want to use geth attach. Can geth be installed with parity?


texts: How to send ether using a wallet contract from the Parity Wallet?

texts:
How do you send ETH from a wallet contract using the Parity Wallet?

I tried selecting the wallet contract, and selected execute contract but I didn't see an option to send ETH to another address.


texts: Is address.call(abi.encodeWithSignature(.....)) the best function to call functions of other smart contracts for with least gas fee consumption?

texts:
I am quite new to solidity coding. I am trying to find out the best way to call complex functions like swap from 1Inch exchange smart contract from my smart contract which can execute the function by consuming the least possible Eth Gas. I dont think I can use delegatecall() directly. So, does this mean, the next best possible solution is to use the call() function like - address.call((abi.encodeWithSignature(.....)) ?? I would like to know the best option out there which I can implement in my smart contract.
I will be executing a series of functions from different smart contracts such as 1Inch, Uniswap, Curve, etc. Whats the best way to execute these functions which can reduce the eth gas consumption?
Can anyone guide me on this?
Regards,
Harish


texts: Large contract (bytecode >= 45K) causes out-of-gas on deploy

texts:
I need some advice about handling a large contract. At a certain size it causes an out-of-gas error when I deploy to a local testrpc node. I experience this when the bytecode reaches approximately 45K. I have temporarily solved the issue by factoring out as much logic as possible into a library that is deployed separately. However, I'm running out of things that I can take out. The main contract has about 30 functions, many of which are now just forwarding to the library functions. Soon I will be unable to add even small features or improvements to the codebase, not to mention the undesirable effect of inducing refactoring for optimization reasons not architectural reasons.

How do you avoid the out-of-gas error for large contracts?


texts: How to get blocks from which an adress has taken coins&

texts: I need to undeerstand how to find out from which blocks come coins that are currently stored at somee adress.Will be pleased to hear any suggestions.


texts: How to centralize same ERC-20 token to one ETH address using SMART CONTRACT/SIGNED OFFLINE TRANSACTION

texts:
Suppose i have same ERC-20 Tokens in 100 ETH accounts. To sell those i have to send the token one by one to ONE mother ETH address. It takes lot of time. I heard there is a shortcut way to do that.

To maintain the security i always rely on OFFLINE TRANSFER from MEW. Is there any way to do this without compromising security. In case i could take out the Nonce one by one before doing. Please suggest the best way to do this automatically.


texts: Writing a function, where users are allowed to deposit their token

texts:
i want to create a smart-contract, where it is allowed for users to deposit their ether/tokens in.

As far i researched i found this function to get it happen.

address owner; // this is where you want the money to go

function getPayment() payable external{
    require(msg.value=='put here your minimal payment');
    owner.transfer(msg.value);
}

My plan is to create also a function, where the contract withdraws ether, when a special amount is reached du different option. How to withdraw ether to the users, which depositet their tokens to this contract?

Kind regards


texts: eth.getPastLogs() requires exact match 32 byte value, how to get bignumber to emit?

texts:
the API eth.getPastLogs() requires 4 topics to match the log indexing capabilities of the EVM.  It appears to require a full 32 byte number for the match to work.  i.e.

eth.getPastLogs((fromBlock:0, toBlock: 'latest', address '0xabc',
    topics: [ null, '0x25', null, null ] })

will not find a topic that has

`0x0000000000000000000000000000000000000000000000000000000000000025`

in it

but this will match said topic:

eth.getPastLogs((fromBlock:0, toBlock: 'latest', address '0xabc',
    topics: [ null,'0x0000000000000000000000000000000000000000000000000000000000000025', null, null ] })

So first question - is this a bug, and second question, how do I get bignumber.js to force an output of all 32 bytes?  toString(16) doesn't give me the leading zeros or the '0x'.   Do I have to write a special function or is there one there already in web3.js and I just can't find it?


texts: What are the advantage of verifying source code in Etherscan?

texts:
I deployed a smart contract in ropsten test network. Now when I try to verify the source code, I am getting some error.

What if I do not verify it?


texts: Managing multiple Ether addresses in one contract?

texts:
Although I have a background in Bitcoin (creating the WLOX exchange platform), I am completely new to Ethereum.

I am trying to find a way to manage multiple accounts/addresses as a pool to (1) be able to manage hot/cold storage for my application and (2) avoid having to manage every account/address in the wallet individually.

If there is a way to transfer funds between accounts internally (without the blockchain) it would work for me too.

I have read that smart contracts are potentially a way to do this, but I'm open to any solution.

Can anybody direct me to an existing example, or tell me how it can be done?

I realize this is a very general question, but I'm against the clock, so I might as well try my luck.


texts: When do we typecast an ethereum address to a contract name ? Also, what is the purpose of the same?

texts:
I have been learning and working on Solidity for quite a while now.
One thing that I have seen in many codes but did not understand was typecasting (looks like typecasting to me) of addresses to a contract type. When and why is this required ?
A few example use cases with explanation would be really helpful.
This is one of the codes that I found -

contract MyContract {
}

contract NewContract {
    MyContract a;

    function setMyContractAddress(address _contractAddress) {
        a = MyContract(_contractAddress);
    }
}

Please explain what is happening in the above code.
Thank You for your time.


texts: How to initialise a mapping variable of a struct?

texts:
I want to add elements in moneyLineData of a Bet instance.

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract Betting {

    struct Bet{
        uint betId;
        string question;
        mapping(uint => MoneyLineData) moneyLineData;
        uint lengthMoneyLineData;
    }

    struct MoneyLineData{
        string option;
        int value;
    }

    mapping(uint => Bet) public bets;
    uint public lengthBets = 0;

    constructor() public{
        MoneyLineData[2] memory moneyLineData = [MoneyLineData("Gator", 200), MoneyLineData("Miami", -100)];
        Bet memory bet;
        bet.betId = 1;
        bet.question = "Gator vs Miami";
        bet.lengthMoneyLineData = 0;
        bet.moneyLineData[bet.lengthMoneyLineData] = moneyLineData[0];
        bet.moneyLineData[bet.lengthMoneyLineData] = moneyLineData[1];
        bet.lengthMoneyLineData += moneyLineData.length;
        bets[lengthBets] = bet;
        lengthBets += 1;
    }
}

But I get this error.

Error: CompileError: /D/Workspace/Nodejs/ethereum-sports-betting/contracts/Betting.sol:32:3: TypeError: Member "moneyLineData" is not available in struct Betting.Bet memory outside of storage.
                bet.moneyLineData[bet.lengthMoneyLineData] = moneyLineData[0];
                ^---------------^

Any help would be greatly appreciated. Thank you!


texts: I have this ParserError: Expected pragma, import directive or contract/interface/library definition

texts:
I have another problem with my code and I don´t know how to solve it. This is a part of my code:
function countUsuarios() view public returns(uint){ //here is the error
      return usuariosAd.length;
    }

Also if I comment that order this is what happen:
pragma solidity ^0.6.5;
contract Contract_Alba{
....
....
//function countUsuarios() view public returns(uint){
      //return usuariosAd.length;
   // }

} //Now I have the error here.

What do I have to do?
Thanks!


texts: how to generate ethereum address from mnemonic and derivation path without using ethereumjs-wallet npm package?

texts:
Is there any way to generate ethereum address from mnemonic and derivation path without using  ethereumjs-wallet npm package?

I have generated mnemonic using bip39
and i can generate Ethereum address using ethereumjs-wallet/hdkey package  for any derivation path but i want any other way
I don't want to use ethereumjs-wallet/hdkey


texts:
I am trying to get a second mining rig setup and I have been having a lot of issues with the video cards that I have bought off ebay.

I get a lot of errors like this from nvidia-smi:

Failed to determine the device handle for GPU 0000:08:00.0: GPU is lost. Reboot the system to recover this GPU.

Should I return these gpus or is this just something that happens? I don't get these errors on my existing rig and this is with some light over clocking (about +1000 on nvidia-settings for memory. Normal overclocking on there is +1400)


texts:
Testing a small piece of code that gets information and the current block, as follows:

pragma solidity ^0.4.16;

contract BlockInvestigator {
    address public minerAddress;
    uint public gasPrice;
    uint public balance;
    uint public blockNum;

    function getMiner() payable {
        blockNum = block.number;
        minerAddress = block.coinbase;
        gasPrice = tx.gasprice;
        balance = minerAddress.balance;
    }
}

I'm trying to update the state variables of the contract everytime I call getMiner.  However, after deploying the contract and calling getMiner() through a transaction, the state variables do not change (they are all zero from initialization).

Am I doing something wrong, or this a bug?

EDIT: This code works when I remove the variables balance and blockNum and their assignments within getMiner().


texts: Why I can't mine eth in my private network?

texts:
Mist Version: 0.10.0 OS & Version: windows/64 Node version: geth 8.11.1

Screen shot : https://imgur.com/a/gRPeJz0

I've created a private network all fine but when I attache and miner.start(1); the kh/s show in Mist but I keep waiting and no ether got mine not a single one!!!

https://codeshare.io/GqxZ3Z this is the code of the first command line where I start geth

https://codeshare.io/2pgZYX this is the second terminal where I start mining command

I think the ERROR 'The pipe is being closed' it's the problem and that happen when opening Mist, see line 18 in the code in the first command line snippet, help! thanks guys


texts:
I'm using Angular 2, with TypeScript, Webpack and all that on my main projects, so every time I have to go back to a Truffle project using AngularJS 1.x, a kitten dies and my head hurts a little.

How would you integrate an Angular 2 CLI frontend project with a Truffle 2 project?


texts: Old contracts data not visible if pushed new contracts?

texts:
I created a contract campaign and deployed this contract in infura , then I called some functions of the contract which created the subsequent data(as in list of ongoing campaigns) in blockchain.
In these campaigns people can contribute some ether to these campaigns(this required  payable keyword). I was able to view these from my front end application created using react .
Now , I added some public view functions to the contract  , rebuilt and redeployed the same , when I tried accessing this , I was not able to view any of my old data (none of the old campaigns) ,
What might have happened to them?
And how can we persist data in these releases ?
I am new to blockchain , please help me in understanding the flow. Thanks


texts:
I'm trying to understand the specifics of privacy in quorum transactions, specially regarding the events.
Are the events raised in a private transaction in quorum also private? I can't find any specific information about this in the quorum docs.


texts: Why is it impossible to get return values of state-changing calls?

texts:
From reading I have surmised that it is impossible to get the return value of state changing calls. Consider this example.sol:

contract F {
  function createChildContract() public returns (address child) {
    child = address(new C());
  }
}

contract C { }

If I instantiate F, then call F.createChildContract() this will return the transaction receipt. This is reasonable, because the transaction will not have been mined yet. But is there not a way to wait on the transaction, then once it is mined get that child address that it returns?

Everywhere I look, I see people telling me it can't be done, and I should use Events:
How do I get the return value of a solidity function with web3?
How to get return values when function with argument is called?
https://github.com/ethereum/web3.js/issues/1207

Fine, I'll use events - but I would like to understand why this not possible? It seems like something that should be very much possible.

EDIT: Clearly I'm not asking what the difference between a transaction and a call is, because I make it clear that it is a call, specifically a state-changing call. The second dup - I can't even.


texts:
I am trying to list the various stable coin projects on Ethereum. So far I have:

Maker
StabL
Digix
EthereumDollar
String

Which did I miss? (I'll update the above as answer come in.)


texts: TypeError: gustavoCoinInstance.transferOwnership is not a function

texts:
I am getting the following error -

 GustavoCoin.sol

pragma solidity ^0.4.22;

import "../node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol";

contract GustavoCoin  {

    string public name = "GUSTAVO COIN";

    string public symbol = "GUS";

    uint8 public decimals = 18;
  constructor() {
  }
}

GustavoCoinCrowdsale.sol

pragma solidity ^0.4.22;

import './GustavoCoin.sol';

import '../node_modules/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol';

import '../node_modules/zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol';
contract GustavoCoinCrowdsale is TimedCrowdsale, MintedCrowdsale {

    function GustavoCoinCrowdsale

        (

            uint256 _openingTime,

            uint256 _closingTime,

            uint256 _rate,

            address _wallet,

            MintableToken _token

        )

        public

        Crowdsale(_rate, _wallet, _token)

        TimedCrowdsale(_openingTime, _closingTime) {

        }
}

 truffle.js

module.exports = {
  networks: {
      development: {
          host: "127.0.0.1",
          port: 8545,
          network_id: "*" // Match any network id
      }
  }
};

I am follwimg a tutorial from this link.


texts: How to execute contract functions from Remix

texts: How can I call functions on a contract? I'm using remix to deploys contract but I don't know where to call the functions.


texts:
a Consensys factory class has this method:

//verifies if a contract that has been deployed is a Human Standard Token.
    //NOTE: This is a very expensive function, and should only be used in an eth_call. ~800k gas

function verifyHumanStandardToken(address _tokenContract) constant returns (bool) ...

Do certain constant methods use gas? Don't they just query the blockchain on the local node?

Can somebody clarifies this? Thanks.


texts: A contract inherit from a token contract

texts:
I have a token contract(ERC20) A, then another contract B inherited from A (B is A). A contract C imported B.
questions are:

if I deployed B alone, is the address of this contract B represent the token A address?
if I deploy A first, then deploy B, are the tokens minted from A and the token minted from B the same?
if I deployed C alone, what's the address of Token A?
if I want to mint A token in C, what is the best way to do it?

Please please please help me. im so confused.


texts: Allow remote RPC to Ethereum parity node

texts:
I have a fully synchronized Parity Ethereum node running on Ubuntu 16
I tried to find a straight answer on how to enable the node to accepts remote RPC calls from a specific client but could not find any.
I use the following command:

parity --mode active --tracing off --pruning fast --db-compaction ssd --cache-size 1024

Also, I would really like to know how to run it in the background, as now I have to connect via SSH and keep the connection running.
Thanks everybody


texts: Geth v1.9.24 - POA - no sealing with period 0 - "Sealing paused, waiting for transactions"

texts:
I have a private clique network with geth v1.9.24.  1 sealer and 1 node.  With period=0 there is no sealing happening, all transactions go to txpool as pending, and logs show "Sealing paused, waiting for transactions".  With period=1 or period=5 sealing starts happening and all the transactions get sealed in blocks.  When I tried 3 sealers and 3 nodes, the same thing happens with period=0, no sealing.  I created the genesis file using puppeth.
I started the node as follows:
/usr/bin/geth --nousb --allow-insecure-unlock --identity "xxxx" --verbosity "3" --rpc --rpcaddr "0.0.0.0" --rpcport "8545" --rpccorsdomain "" --rpcvhosts "" --rpcapi "miner,eth,net,personal,web3" --port "30303" --nodiscover --gcmode "archive" --miner.gasprice "1" --miner.gastarget "8000000000" --miner.gaslimit "9000000000000000" --networkid "830" --ipcpath "/home/eth_user/gethipc/geth.ipc" --unlock "xxxxxxxxxxxx" --password "xxxxxxxxx" --mine --syncmode "full"
I called eth.sendTransaction({from: eth.accounts[1], to: eth.coinbase, value: web3.toWei(30, "ether")}) multiple times from the geth console, and each transaction ended up pending in txpool.  eth.accounts[1] was pre-funded, while eth.coinbase (sealer) was not.
I need period=0 to work so that the transactions are sealed very fast when they are submitted, and so that we don't have unnecessary bloat from empty blocks.
Am I missing setting up some parameter in Geth v1.9.24?  This doesn't happen with Geth v1.8.27.
Thanks in advance


texts:
Ethereum wallet does not work with version over geth 1.8.23
I have geth 1.9.1 installed, I am fully synchronized, but ethereum wallet requires you to download 1.8.23 and does not want to work with geth 1.9.1
How to make ethereum wallet work with geth 1.9.1?
windows 10.


texts: Unhandled Rejection (Error): invalid address web3.js

texts:
I got above error.
But I can't solve this problem.
I use web3.js 0.20.5 version;
Here's my web3.js code:
var web3js;

export function setupWeb3(){
    if (typeof web3 !== "undefined") {
        web3js = new Web3(web3.currentProvider);
        console.log("injecting web3js success");
        } else {
        console.log("Can NOT access to provider...");
        window.alert("can not access to provider");
        return;
    }
}

var test;
var userAccount;

export function CreateInstance() {
    var accountInterval = setInterval(function() {
        if (web3.eth.accounts[0] !== userAccount) {
          userAccount = web3.eth.accounts[0];
        }
      }, 100);
}

export function WriteMessage(message){
const contractAddress = 0xCf054a36e26b1Ce0e8E4Ab0DA831B259F3bf635F;
const contractABI = [
    {
        "constant": true,
        "inputs": [],
        "name": "getHoge",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "internalType": "uint256",
                "name": "_input",
                "type": "uint256"
            }
        ],
        "name": "setHoge",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    }
]
    web3.eth.getAccounts((error, accounts) => {
        if (error) {
          console.log(error)
          return
        }
        web3.eth.defaultAccount = web3.eth.accounts[0];
        alert(web3.eth.defaultAccount);
    });
    ethereum.enable();
    web3.eth.defaultAccount = web3.eth.accounts[0];
    alert(web3.eth.defaultAccount);
    test = web3.eth.contract(contractABI).at(contractAddress);
    test.setHoge(Number(message),{from: web3.eth.defaultAccount});  >>>Error invalid address

}

export function getMessage() {
    return test.getHoge().call();
}


texts: How to return address from newly created contract?

texts:
I am trying to create a factory contract that dynamically creates new instances of another contract. And I want the factory to return the newly created contract's address; however, when I test it in the Remix IDE, the function does not return anything. Here is my current code:

contract CreateTournament {
    Tournament public newTournament;
    address[] newTournaments;
    uint index = 0;

    function createNewTournament(string _title, uint32
_maxParticipants, uint _entryFee, uint _surcharge) public
returns(address) {
        newTournament = new Tournament(_title, _maxParticipants,
_entryFee, _surcharge);
        newTournaments.push(newTournament);
        return newTournament;
    }

    function checkAddress(address tournament) public view returns(bool)
{
        bool exists = false;

        for (uint i = 0; i < newTournaments.length; i++) {
            if (tournament == newTournaments[i]) {
                exists = true;
            }
        }

        return exists;
    }
}

Any help would be appreciated!


texts: Why 'Out of gas' error when there is still a lot of gas?

texts:
Gas limit was set to 6,000,000
Tx consumed just 1,943,125

Yet is still failed with Out of gas error.

If it makes any difference, this is my contract which calls other contracts with raw_call (in Vyper) and passes the full remaining gas to those calls.

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


texts:
My program is relaying raw transactions to a geth node from a mobile client.

I noticed that a transaction with the identical content will yield an identical hash. e.g. calling the same function with the same parameters.

If I send this raw transaction more than once in quick succession (before there was time to mine it) I get the known transaction error.

How can I check if my transaction is known? Or put it another way: How can I compute the transaction hash from the raw transaction string?

In the code below, I am looking for a solution to someWayToComputeHashFrom

This is how I create my transaction string with eth-lightwallet. The contract object is a web3 contract.

getCertificateContract().then((contract) => {
            let payloadData = undefined;
            let functionName = undefined;
            functionName = 'registerAuditReport';
            payloadData = contract.registerAuditReport.getData(result.hash, documentId);

            let gasEstimate = w3.toHex(w3.eth.estimateGas({
                    to: contract.address,
                    data: payloadData
                }) + 10000);

            let nonce = w3.toHex(w3.eth.getTransactionCount(profile.address) + 10000);

            var rawTx = {
                nonce: nonce,
                gasPrice: gasPrice,
                gasLimit: gasEstimate,
                to: contract.address,
                from: profile.address,
                value: '0x00',
                data: payloadData
            };

            let rawTxString = txutils.functionTx(contract.abi, functionName, [result.hash, documentId], rawTx);

            let signedTxString = signing.signTx(wallet.keystore, wallet.pwDerivedKey, rawTxString, '0x' + senderAddress);

            let txHash = someWayToComputeHashFrom('0x' + rawTxHexString);
            w3.eth.sendRawTransaction('0x' + rawTxHexString, function (err, hash) {
                console.log('transaction hash is', hash);
            })
        })


texts: Decentralized Exchanges with Market Orders

texts:
My goal is to make a market order (sell/buy) from a smart contract without a centralized app feeding in the order data. E.g. buy token X for 1 ETH at current market.

0x Project

So far I stumbled over the 0x-project which looks like a framework to build your own decentralized exchange.
https://0xproject.com/
https://blog.0xproject.com/a-beginners-guide-to-0x-81d30298a5e0

Idex

Idex sounds also promising but I don't find any information how to interact with their ABI

  Fill many orders at once, allowing for true market orders

https://medium.com/aurora-dao/idex-decentralized-exchange-state-channel-afca2e5809b1

Question

1) Is 0x only meant to build your own exchange on top? Or can I use the protocol to e.g. make a market order on any 0x exchange from a smart contract?

2) Is there any smart contract/decentralized exchange to make market sell/buy orders?


texts: How to see content of string in Remix in debugger? All I see is pointer address

texts:
for example I want to see the content of 'b', not just the address. How do I do that?

contract Test {

    function myTest(uint a) private returns (bytes32) {

        bytes32 a = bytes32(a);
        return a;
    }

    bytes32 b = myTest(1234);

}


texts:
Plan to use getEthToTokenInputPrice in a Dapp. I was going to just use a larger sample size spread out over a large time period to mitigate flash loan price manipulation. Someone said this was insufficient because miners could re-order things like so

1: miner dumps the price on Uniswap
2: miner lets the Dapp record the getEthToTokenInputPrice
3: miner reverses his transaction and only pays minor fees
4: The manipulated Uniswap price sticks in the Dapp even after the miner canceled the transaction

Was I given bad advice? This seems impossible how can a Dapp internalize data from a reversed transaction.


texts:
My initial aim was to return structure from the function.

After web search I ended up with serialization of data structure into bytes array.

Now I try to figure out how each type is represented in bytes and what is the dependency to properly convert it into bytes and backwards.

uint
address
bytes32

Can you provide docs which explains the dependency between data type and its representation in bytes?

Conversion uint to bytes
Conversion uint256 bytes


texts: Going from uint256 to uint8, is it possible?

texts:
I have a function that creates random numbers with a maximum value that you gives to it, the function was made to work with any uint256, and using % operator it returns a value between 0 and the maxValue that you gave to it. How could I cast from uint256 (the number that the function returns) to a uint8 for example... I now in this case the funtcion is giving a value that can be saved on a uint8, but looks like solidity doesn't.

Thank you


texts:
I am trying to understand what this means from the RLP white paper wiki "The only purpose of RLP is to encode structure; encoding specific data types (eg. strings, floats) is left up to higher-order protocols;"

reference: https://github.com/ethereum/wiki/wiki/RLP

My understanding from this is that RLP encodes just the structure and does not deal with the data, and the interpretation of the data type is left to a custom function?
can somebody give me an example of this input is the structure below using RLP encoding:

e:g: ["cat",[[]],"pig",[""],"sheep"]

Thanks in advance, also If there is any video reference just for RLP would be greatly helpful.


texts: Posted blocks on ethgasstation/Low gas price watchlist

texts:
Does anyone understand the posted blocks on ethgasstation/Low gas price watchlist?
I would guess that posted block < mined block is always true - but this is not what I see there.


texts:
What is the best way to 'harden' an infinite loop, if you are in a scenario where you would find it necessary to iterate over an array, would it be a best practice to put an assert condition in advance of the loop based on an length limit and if yes, what is the best way to calculate this limit? would that be to run the function and note the gas consumption and divide it by gas limit?
// Update rewards for all pools.
function updatePools() public {
    uint256 length = pools.length;
    for (uint256 p = 0; p < length; ++p) {
        update(p);
    }
}

Above, is attached an example.


texts: Metamask display for signing data with eth_signTypedData_v4

texts:
I am using the latest implementation of EIP712 to ask for user to confirm some action:
        web3.currentProvider.sendAsync({
            method: "eth_signTypedData_v4",
            params: [account, dataToSign],
            from: account
        }

with:
        const metaTransactionType = [
            { name: "permission", type: "string" }
        ];
        ...
        let message = {
            permission: "Hello world"
        };
        ...
        const dataToSign = JSON.stringify({
            types: {
                EIP712Domain: domainType,
                MetaTransaction: metaTransactionType
            },
            domain: domainData,
            primaryType: "MetaTransaction",
            message: message
        });

And everything works fine, but the Metamask pop up shows the word "Message" twice:

Metamask version is 8.1.5 (the latest I believe).
Is this a bug or am I constructing the data to sign wrong?
Thanks!


texts: Can't get off the ground: solc: no build results found

texts:
Let's go step by step with my full trace and see if anyone can help. Basically, I can't even get the example to work in the documentation:

First, start geth on Windows 10, 64 bit on a private test network.

D:\archive\prog\ethereum\Geth-Win64-latest>geth --networkid 54321 --genesis genesis.json --datadir .ethereum_experiment console

Let it come up...

I0506 16:50:03.380287   13936 database.go:71] Alloted 16MB cache to .ethereum_experiment\chaindata
I0506 16:50:03.414806   13936 database.go:71] Alloted 16MB cache to .ethereum_experiment\dapp
I0506 16:50:03.431311   13936 backend.go:314] Protocol Versions: [63 62 61], Network Id: 54321
I0506 16:50:03.431812   13936 genesis.go:89] Genesis block already in chain. Writing canonical number
I0506 16:50:03.431812   13936 backend.go:326] Successfully wrote genesis block. New genesis hash = bb7de14b2509aeff30096e412ba22e8a9a86c2cd734ba8fd5a0d6f91e5e4d1bf
I0506 16:50:03.432312   13936 backend.go:362] Blockchain DB Version: 3
I0506 16:50:03.432312   13936 blockchain.go:214] Last header: #0 [bb7de14b…] TD=1048576
I0506 16:50:03.432812   13936 blockchain.go:215] Last block: #0 [bb7de14b…] TD=1048576
I0506 16:50:03.432812   13936 blockchain.go:216] Fast block: #0 [bb7de14b…] TD=1048576
I0506 16:50:03.435815   13936 cmd.go:115] Starting Geth/v1.3.6/windows/go1.5.1
I0506 16:50:03.436316   13936 server.go:311] Starting Server
I0506 16:50:05.495355   13936 nat.go:111] mapped network port udp:30303 -> 30303 (ethereum discovery) using UPNP IGDv1-IP1
I0506 16:50:05.589213   13936 udp.go:212] Listening, enode://caa503a9c083524e25149ce2363805c9fccddad96003466f8b77e039b0e594266c509811b4e1aa865948609520f72e29078adbdb7d4c003fde198d676068c9db@98.207.1.52:30303
I0506 16:50:05.589712   13936 server.go:552] Listening on [::]:30303
I0506 16:50:05.589712   13936 backend.go:526] Server started
I0506 16:50:05.590712   13936 ipc.go:112] IPC service started (\\.\pipe\geth.ipc)
I0506 16:50:05.591712   13936 nat.go:111] mapped network port tcp:30303 -> 30303 (ethereum p2p) using UPNP IGDv1-IP1
instance: Geth/v1.3.6/windows/go1.5.1
 datadir: .ethereum_experiment
coinbase: 0x4c6dfd596afe1ce8c01cec00e2042f04f159957e
at block: 0 (Wed, 31 Dec 1969 16:00:00 PST)
modules: admin:1.0 db:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 shh:1.0 txpool:1.0 web3:1.0

Cool... Let's see if there are any compilers installed. I put solc.exe in my path..

> web3.eth.getCompilers();
I0506 16:50:12.735747   13936 solidity.go:114] solc, the solidity compiler commandline interface
Version: 0.3.0-1f9578ce/Release-Windows/msvc/JIT linked to libethereum-

path: C:\Program Files\Ethereum\solc.exe
["Solidity"]

Nice... that seemed to work. Getting excited. Let's try the example.

> source = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"
"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"

Cool... so far so good. I feel I am close now!

> contract = eth.compile.solidity(source).test

solc: no build results found
    at InvalidResponse (<anonymous>:-81662:-45)
    at send (<anonymous>:-156322:-45)
    at solidity (<anonymous>:-133322:-45)
    at <anonymous>:1:12

....and BOOM. fail.

The previous trace shows my solidity version is 0.3.0.

This trace here shows my geth version is 1.3.6

D:\archive\prog\ethereum\Geth-Win64-latest>geth --help
NAME:
   geth - the go-ethereum command line interface

USAGE:
   geth [options] command [command options] [arguments...]

VERSION:
   1.3.6

I posted this question on the gitter chat room as well as the ethereum forum with no luck so far.

Any help or ideas appreciated. Apologies if I am doing something incredibly dumb.


texts: In Quorum, between Raft and Istanbul BFT (IBFT) consensus, which has a better (faster) block confirmation time? Assuming Ceteris Paribus

texts: In Quorum, to help decide between Raft and Istanbul BFT (IBFT) consensus, which has a better (faster) block confirmation time? Assuming Ceteris Paribus.


texts:
I want to make my smart contract, but I have some questions.

for example my new coin name is : Ghost and it's based on Eth.

how much ETH should I have in my wallet to create this smart contract?
After creation of my new coin "Ghost", and when someone want to send 10 Ghosts to another one, what about the fees of transaction, will it be in ETH or Ghost? and how I can control on it? the amount of fees and which address should got this fees?
after I deploy the smart contract on mist what the next ?

Regards


texts:
Where do penalties for being offline go? (for validators)
In POS when validator is being offline he loses part of its stake (depends on correlation with other validators being offline aka partial slashing)

So is that slashed stake will be burned or what?

Thx.


texts:
I am trying to call a fairly simple contract on a private blockchain:

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

And here is my running it from an interactive Python shell:

>>> e.unlock_account()

>>> instance.functions.getOwner().transact()
HexBytes('0x4f366ba7bb7ae0ef70e48c3ce7eb4f920d7079e90a10bfea36fc9fbbb48d52fe')

That works fine, but I need the function return value, not the transaction hash. So I believe I need to then call it right?

>>> e.unlock_account()

>>> instance.functions.getOwner().call({'from': e.account})

... error trace ...
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes
... more error traces ...
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

Has anyone any idea what I'm doing wrong?

Edit: I have tested it with another even more basic contract, and it seems to work fine. The contracts only differ in that the one that works returns an int..

function reveal() public view returns (int) {
    return number;
}

When I call() the function above, it returns the correct number.

Edit 2: I removed all of the functions from the contract related to setting an owner address, and now everything works. I have supplied the before and after versions of the contract, in case anyone else comes across the same issue. I still have no idea what is causing the contract not to work with addresses.. Is it something to do with the constructor? Any explanations are appreciated!

BEFORE EDIT (NOT WORKING)

pragma solidity ^0.4.0;

contract CryptoCert {

struct Award {
    bool isValid;
    string hash;
}

struct Authority {
    bool isValid;
    string hash;
    address[] representatives;
    Award[] awards;
}

address private owner;

mapping(address => Authority) authorities;

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

modifier onlyBy(address _address) {
    require(msg.sender == _address);
    _;
}

function CryptoCert() public {
    owner = msg.sender;
}

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

function createAuthority(address _address, string _hash) public onlyOwner {
    authorities[_address].hash = _hash;
    authorities[_address].isValid = true;
}

function addAuthorizedAddress(address _authAddress, address _repAddress) public onlyBy(_authAddress) {
    authorities[_authAddress].representatives.push(_repAddress);
}

function getAuthorityHash(address _address) public view returns (uint) {
    if (authorities[_address].isValid) {
        return 1;
    } else {
        return 0;
    }
}

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

function test() public pure returns (string) {
    return "nigchicken69";
}

}

And after...

AFTER EDIT (WORKING)

pragma solidity ^0.4.0;

contract CryptoCert2 {

    struct Award {
        bool isValid;
        string hash;
    }

    struct Authority {
        bool isValid;
        string hash;
        address[] representatives;
        Award[] awards;
    }

    mapping(address => Authority) authorities;

    function createAuthority(address _address, string _hash) public {
        authorities[_address].hash = _hash;
        authorities[_address].isValid = true;
    }

    function addAuthorizedAddress(address _authAddress, address _repAddress) public {
        authorities[_authAddress].representatives.push(_repAddress);
    }

    function getAuthorityHash(address _address) public view returns (uint) {
        if (authorities[_address].isValid) {
            return 1;
        } else {
            return 0;
        }
    }

}


texts: my smart contract always return empty when testing with rinkerby network

texts:
I am trying to implement the simple storage.

When calling set function, the contract will append a new Log object to logs array, and also return the related index to the caller for reference data.

The problem is I cannot get returned index, it is always empty.

How can I get the index from calling set function?

pragma solidity ^0.5.0;

contract Storage {
    struct Log {
        string fname;
        string lname;
        string dob;
    }
    mapping (uint => Log) logs;

    uint index = 0;

    function set(string memory fname, string memory lname, string memory dob) public returns (uint) {
        index++;
        logs[index] = Log(fname, lname, dob);
        return (index);
    }

    function get(uint idx) public view returns (string memory, string memory, string memory) {
        return (logs[idx].fname, logs[idx].lname, logs[idx].dob);
    }
}


texts: Cannot deploy contract in remix with my Metamask

texts: I'm following a token contract tutorial on Youtube and everytime I try to deploy the contract on the Kovan testnet (in the remix solidity editor), it sends it off but then fails later. I have sufficient KETH, wo why would this be? Would switching to Parity fix this problem, and what is the difference between Parity and Metamask? Sorry for the long question.


texts: How is Contract Address used with Balance in Geth?

texts:
I refer to -
http://solidity.readthedocs.io/en/develop/types.html?highlight=address

"It is possible to query the balance of an address using the property balance and to send Ether (in units of wei) to an address using the transfer function:"

Is this address a contract address?

I have con defined and I get this -

> eth.coinbase.balance
undefined

> con.address.balance
undefined

> con.address
"0x49b0bfa8e7fc7ac178d74b73dc92fa42cd7815e5"

> eth.coinbase
"0x46fb9a22689c4a4bfb494baeafbb8b2993725305"

How should balance be used with these addresses?


texts: Check if transaction is valid in blockchain

texts:
Can you receive invalid blocks/transactions when syncing via geth?
If so, how to make sure that received transaction is correct? Is checking status from eth.getTransactionReceipt() enough?


texts:
I'm getting the error:

  "Migrations" could not deploy due to insufficient funds.
  Sender doesn't have enough funds to send tx.
  The upfront cost is: 45000000000000000 and the sender's account only has: 0

as I'm migrating into Rinkeby test network. I have enough ether in Account #2 from faucet that I'm trying to use, but Truffle is persistently trying to use Account #1 that has 0 balance in it.  At which point does Truffle try to connect to MetaMask? Is it Node or Truffle that's not working properly? And how do I change the account that Truffle recognizes so that I can connect to Account #2, instead of Account #1?

So far, I've tried:

Uninstalling and re-installing Truffle
Logging out and re-logging into MetaMask and toggling between the accounts
Changing the gas/gasPrice to a higher value or commenting them out
Changing the node version

I'm using "@truffle/hdwallet-provider": "^1.0.35"

    rinkeby: {
      provider: () =>
        new HDWalletProvider(
          mnemonic,
          `https://rinkeby.infura.io/v3/${infuraKey}`
        ),
      network_id: 4, // rinkeby's id
      gas: 4500000, // rinkeby has a lower block limit than mainnet
      gasPrice: 10000000000,
      confirmations: 2,
      timeoutBlocks: 200,
      skipDryRun: false,
    },


texts: Is it cheaper overall to store a keccak hash or to store a ripemd(keccak) hash?

texts: As titled. I'm learning to build a DApp and I'm wondering if it's worth it to add the extra RIPEMD layer over keccak for a shorter hash to reduce storage costs.


texts: Why Should I use Ethereum in an Online-Election(Vote) System based on ZKP(Zero-Knowledge Proof)?

texts:
I am an undergraduate student studying Ethereum in South Korea.

Currently, I am developing an online election system that can be applied.

At first, I came up with this idea:

The system has an ETC that matches the number of voters.
Verify that the voter has the right to vote.
If a voter can vote, open a personal account; the system deposits 1ETC into the account.
After the election, count the results.
Voters can check where they deposited their money through their personal accounts (only themselves can check the address of the account).

And after studying the ZKP(Zero-Knowledge Proof), I found that voters could prove they voted for someone without opening their personal accounts to the system.

We also found that the system only needed to have encrypted remittance records, not personal account information.

This can help secure voter information(The system does not own personal information).

But if I develop an online election system using Zero-Knowledge Proof, I wonder why need to use Ethereum?

Without using Ethereum, I think the hash function allows us to implement the ZK-proof and create functions such as remittance and voting.

So I ask this question.

1. What is a rational reason why we must use Ethereum?

2. Without using Ethereum, can I create a safe election system? How can I prove that stability?

Even if you think I have a low understanding of Ethereum, please provide me with a chance to learn and grow.

Thank you.


texts: Can I use the Trezor hardware wallet for cold storage of ETH?


texts: Truffle: Contract transaction couldn't be found after 50 blocks

texts:
I'm trying to deploy a contract to the Ropsten testnet via the truffle console. In my truffle.js file, I set the gas parameter to gas: 4700000. When I run migrate --reset, I always get this error no matter how much gas I send during the deploy in 2_deploy_contracts.js:

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: Contract transaction couldn't be found after 50 blocks
    at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/contract.js:112:30
    at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/filter.js:120:21
    at Array.forEach (native)
    at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/filter.js:119:32
    at Array.forEach (native)
    at Object.onMessage [as callback] (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/filter.js:117:22)
    at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/requestmanager.js:259:20
    at Array.forEach (native)
    at /usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/requestmanager.js:258:12
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:118:13)

The contract works properly on testrpc and was successfully deployed via the Remix IDE. I could find it on Etherscan and it looks like the gas estimate was around 1700000.


texts: Get Private and Public Key from BIP44 Master Private Key

texts:
I am confused about getting the private key corresponding to the address for derivation path m/44'/60'/0'/0'/0'

Question 1: Is the following code correct in getting the address and private key? Why is the private key obtained a Buffer object?

<Buffer fd 5f 63 c0 6b 5a 99 c4 c6 9a 05 07 01 c7 fd 04 cd b5 39 b6 2e 58 4e 63 98 c4 7c 28 5e b8 31 fa>

If I understand correctly the various depth of the path:

44' means BIP44
60' means Ethereum
0' means wallet #0
0 means public, 1 means private?? What does public and private means?
0 means index 0

Question 2: Why is there a ' behind some of the numbers?

Code:

var bitcore = require('bitcore-lib');
var EthereumBip44 = require('ethereum-bip44');

var seed = 'xprv9s21ZrQH143K2uRcdeb2VJAEwhJQCtAjTCgx9JQt5NGhSkG4xGiuXvea8yN3tz3Q4LwPoP8j2cwERYNyw959ed9yqCrHGT1oDxJhNWoobqf'
var hdKey = new bitcore.HDPrivateKey(seed);
console.log('HD Key: ', hdKey.toString())

console.log('---')

var derivationPath = "m/44'/60'/0'/0'";
var derivedPrivKey = hdKey.derive(derivationPath)
var derivedPubKey = hdKey.derive(derivationPath).hdPublicKey

console.log('Derivation Path: ', derivationPath)
console.log('Extended Private Key: ', derivedPrivKey.toString())
console.log('Extended Public Key:  ', derivedPubKey.toString())

console.log('---')

var wallet = new EthereumBip44.fromPrivateSeed(derivedPrivKey)
console.log('Wallet (0) Address: ', wallet.getAddress(0))
// 0x10ea551752f7ba9fd73d19baa16b234585e2c45d

console.log('Wallet (0) Private Key: ', wallet.getPrivateKey(0))
// <Buffer fd 5f 63 c0 6b 5a 99 c4 c6 9a 05 07 01 c7 fd 04 cd b5 39 b6 2e 58 4e 63 98 c4 7c 28 5e b8 31 fa>

Output

HD Key:  xprv9s21ZrQH143K2uRcdeb2VJAEwhJQCtAjTCgx9JQt5NGhSkG4xGiuXvea8yN3tz3Q4LwPoP8j2cwERYNyw959ed9yqCrHGT1oDxJhNWoobqf
---
Derivation Path:  m/44'/60'/0'/0'
Extended Private Key:  xprvA1Q3FUbfXYKGzLiE9FgpgiBC4yrBkZm2eEQvBCtF95gvF6RQ1c1tWqeeemMDXczBwEi76wKrRR7oJPBQCsn9ghBSdigGdo5ZXE8WpX68t57
Extended Public Key:   xpub6EPPez8ZMusaCpnhFHDq3r7vd1ggA2Ut1TLWybHrhRDu7tkYZ9L94dy8VzvGNYjxiCFjpK4xbaBzaXkmWiU4Bj3q3SgwYrqJLKJP9SiQ2t1
---
Wallet (0) Address:  0x10ea551752f7ba9fd73d19baa16b234585e2c45d
Wallet (0) Private Key:  <Buffer fd 5f 63 c0 6b 5a 99 c4 c6 9a 05 07 01 c7 fd 04 cd b5 39 b6 2e 58 4e 63 98 c4 7c 28 5e b8 31 fa>


texts: Error: new BigNumber() not a base 16 number: when trying to retrieve a string from a mapping

texts:
I've created a fairly simple smart contract that has been deployed to the rinkeby testnet. You can see the code below:

pragma solidity ^0.4.18;

contract KVStore {

 mapping(address => mapping(string => string)) store;
 uint MAX_STR_LENGTH = 1000;

 function get(address _acct, string _key) public view returns(string) {
    return store[_acct][_key];
 }
 function set(string _key, string _value) public {
   if (bytes(_value).length <= MAX_STR_LENGTH) {
     store[msg.sender][_key] = _value;
   }
 }

}

I'm using geth to call the set function and then the get function. However, when I call kvstore.get(address, key) I get the following error:

Error: new BigNumber() not a base 16 number:

I'm not sure whats going on or how to fix. The set function works fine and writes to the rinkeby chain.

I first run this:

geth --verbosity 0 console --rinkeby

Then

var kvstoreContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_key","type":"string"},{"name":"_value","type":"string"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_acct","type":"address"},{"name":"_key","type":"string"}],"name":"get","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]).at("0xf8daca377691c8f52b07ef77dfc0e7ca287622c5");

Then

kvstoreContract.set("fly","star",{from:eth.accounts[1]});

Which works fine and sends a transaction to the contract address.

When I try to do

kvstoreContract.get(eth.accounts[1],"fly");

I get the bigNumber error. Any idea why? I'd really appreciate the help.


texts: Is there a way to pass custom parameters in truffle command line?

texts:
I am having 3 different environments:

dev
test
live

I have one contract deployed on three different addresses, that I want to use based on environment, since for every environment we will store different data into smart contract.

I am using teamcity for CI, but I am interested how to differentiate environment with Truffle migrations, so based on environment to pick different address from inside of migration?

Example:
Assume I have migration file:

    const test = artifacts.require("./test")

    module.exports = function(deployer, custom_argument_that_i_can_pass_via_teamcity) {

console.log(custom_argument_that_i_can_pass_via_teamcity);
        deployer
            .deploy(test);
    };


texts: How do I fix it? To be able to send eth from smartcontract to the address

texts:
Frontend

class App extends React.Component {
  state = {
    address: '',
  }

  async componentDidMount() {
    await window.ethereum.enable()
    this.w3 = new Web3(window.ethereum)
    const address = (await this.w3.eth.getAccounts())[0]
    this.setState({ address })
    this.contract =new this.w3.eth.Contract(ABI,"0x5888E695e574B6fd87E9552a50736875ec535773")
  }

  // address send to smart contract
  async sendToContract() {
    await this.contract.methods.invest().send({
      from: this.state.address,
      value: this.state.amount,
    })
  }

  onChange1(e) {
    this.setState({
      amount: e.target.value,
    })
  }

  // smart contract send to address
  async contractSendToAddress() {
    await this.contract.methods.sendEther(this.state.to).send({
      from: this.contract,
    })
  }

  onChange2(e) {
    this.setState({
      to: e.target.value,
    })
  }

  render() {
    return (

          <input placeholder="amount" onChange={this.onChange1.bind(this)}/>
          <button onClick={this.sendToContract.bind(this)}>sendToContract</button>

          <input placeholder="to address" onChange={this.onChange2.bind(this)}/>
          <button onClick={this.contractSendToAddress.bind(this)}>contractSend</button>

    );
  }
}

Smart Contract

contract sendEth {
  mapping(address => uint) balances;
  function invest() external payable {
    if(msg.value < 0.01 ether) {
      revert();
    }
    balances[msg.sender] += msg.value;
  }

  function balanceOf() external view returns(uint) {
    return address(this).balance;
  }

  function sendEther(address payable recipient) external {
    recipient.transfer(0.0001 ether);
  }
}

  Error: Provided address "[object Object]" is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can't be converted.


texts: When sending tokens from geth, how do I specify a different address to send gas from


texts: How to get total values in mapping and details of each transaction

texts:
I am trying to write a simple contract

contract students{
uint public totalTokens;
constructor() public {
    totalTokens = 800;
}
struct Students{
    uint amount;
    string givenFor;
}

mapping (string => Students) studentsMappig;

string[] private studentsArray;

function setStudents(string _name, uint _amt, string _reason) public{
    Students storage student = studentsMappig[_name];
    totalTokens -= _amt;
    student.amount += _amt;
    student.givenFor = _reason;
    studentsArray.push(_name);
}
function getDetails(string addr) public view returns(uint amount) {
    Students storage student = studentsMappig[addr];
    return amount = student.amount;
}
function getUsersCount() public view returns(uint) {
    return studentsArray.length;
}
}

My issue are 2

I want to get how many total users which have tokens for which i tried getUsersCount() but it is giving every user mean not unique users
I want to get list of transactions done mean what was paid,to whom was paid and why was paid

thanks a lot for the help to understand me this and complete it


texts: How to solve ImportError: No module named web3?

texts: I already installed web3 using pip install, but I get the error "ImportError: No module named web3" when I try to use it.


texts: Truffle develop get new contract instance from contract address

texts:
From a truffle develop console, is there a way I can get the contract instance from the contract's address?

I have a remote ec2 with truffle/geth installed and truffle develop instance running. From a local truffle develop console, I have deployed my contracts to that remote network (using the truffle migrate --compile-all --reset --network remote_network_name). The contracts deployed successfully, and I have an address for where the contract is stored.

In a truffle develop console on the remote server, I have tried Contract_Name.deployed().then(function(instance) {app = instance; }) to get the instance, but I get a Contract_Name is undefined error.

From a truffle develop console on the remote server, is there a way I can get the contract instance from the contract's address?

Maybe something like MyContract = new Contract.at("ContractAddress")?


texts: Trying to connect Mist/Ethereum wallet with testrpc

texts:
I need someone who can explain to me, step by step, in simple terms how can I connect the ethereum wallet with the local blockchain.
I found the following link: Connect Mist to ethereum-js testrpc

The problem is I'm still learning how to code and setting up test environments.So this is all new stuff to me.

Can somebody explain to me how and where do I have to put the following lines so that the Ethereum wallet connects with my local blockchain and not with the live testnet?!

web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));

Some basic step by step instruction would be nice.

Thanks in regards


texts: Need help in setting up ethereum blockchain

texts:
Sorry for a newbie question. I am learning etheream and would like to know if it's possible to setup ethereum blockchain where tokens represent database records and not currrency for e.g. user information ?
I think storing data on blockchain is not safe and expensive.


texts: What is the size (bytes) of a simple Ethereum transaction versus a Bitcoin transaction?

texts:
Alice owns an empty Ethereum wallet. Receives 1 ETH then sends 1 ETH to Bob.

Alice owns an empty Bitcoin wallet. Receives 1 BTC then sends 1 BTC to Bob.

What are the transaction sizes in bytes (Alice->Bob) in both cases? If Ethereum is lower, is that the main reason why Ethereum can do more tx/sec than bitcoin?


texts:
I just installed IPFS version 0.4.22 on my Mac.

When I try to upload/add a file in TERMINAL - using the following command:

ipfs add myLogo.jpg

I get this error:

Error: ipfs repo needs migration

Note: my repo version is ipfs repo version fs-repo@7

Additionally, when I try to run:

ipfs daemon

I get this error:

Initializing daemon...
go-ipfs version: 0.4.22-
Repo version: 7
System version: amd64/darwin
Golang version: go1.12.7
Found outdated fs-repo, migrations need to be run.
Run migrations now? [y/N]

So I tap on “y” to run these migrations, and I get another error message which boils down to this:

The migrations of fs-repo failed:
    migration failed: exit status 1

Here's the full error message:

=> Looking for suitable fs-repo-migrations binary.
=> None found, downloading.
=> Running: /var/folders/l_/793j9l1j7fx4n6pb0zd2tww40000gn/T/go-ipfs-migrate464045646/fs-repo-migrations -to 7 -y
Found fs-repo version 2 at /Users/johnSmith/.ipfs
===> Running migration 2 to 3...
applying 2-to-3 repo migration
locking repo at "/Users/johnSmith/.ipfs"
- verifying version is '2'
beginning pin transfer
- opening datastore at "/Users/johnSmith/.ipfs"
- created version 3 pinner
- loading recursive pins
ipfs migration: migration 2 to 3 failed: datastore: key not found
=> Failed: /var/folders/l_/793j9l1j7fx4n6pb0zd2tww40000gn/T/go-ipfs-migrate464045646/fs-repo-migrations -to 7 -y
The migrations of fs-repo failed:
migration failed: exit status 1
If you think this is a bug, please file an issue and include this whole log output.
https://github.com/ipfs/fs-repo-migrations

Obviously there's some migrations issue - I’ve already spent a few hours trying to troubleshoot this, but no luck.

So, what in the world is going on - and what do I need to do to fix this?


texts: Why can't we do bitwise operations on Bools?

texts:
So I'm running an if/then comparator function with bools.  It's essentially and xor function but when I tried a ^ b i get operator not compatible with types bool and bool.

Given that bools (in general) are logic primitives, I'm wondering why we cannot bitwise them in solidity?

Can this be done in inline assembly instead?


texts:
I'm trying to create a contract which calls boolean method on another contract. However, for some reason it doesn't work.

Here is an example:

pragma solidity ^0.4.23;

contract Season {
    address[] public requests;

    constructor() public {
        requests.push(new Request());
    }

    function getRequestsByFilter() public view returns(bool) {
        Request r = Request(requests[0]);
        bool ret = r.isMatch();
        return ret;
    }
}

contract Request {
    function isMatch() public pure returns(bool) {
        return true;
    }
}

It compiles fine but if you call R.foo from web3.js you get false instead of true.

Here is what I see in UI:

I don't understand why it happens and how can I call this method.

Here is smaller example:

pragma solidity ^0.4.23;

contract Season {
    function getRequestsByFilter() public returns(bool) {
        Request r = new Request();
        bool ret = r.isMatch();
        return ret;
    }
}

contract Request {
    function isMatch() public pure returns(bool) {
        return true;
    }
}


texts: How to make node address a bootndoe address?

texts: when I add node enode address to bootnode other node only connect to node assigned in bootnode


texts: TypeError: Cannot set property 'method' of undefined when using WebsocketProvider

texts:
I'm using:

web3 v0.20.6
web3-providers-ws v1.0.0-beta.34

First question - can web3-providers-ws be used with web3 v0.20.*?

Second question (problem) - I get an error when probably trying to send transaction (reading and watching events through this provider is totally fine).

Pull request: https://github.com/ethereum-alarm-clock/timenode-core/pull/146

Working HTTP provider E2E tests:

https://travis-ci.org/ethereum-alarm-clock/timenode-core/jobs/406823597

Failing WS provider E2E tests:

https://travis-ci.org/ethereum-alarm-clock/timenode-core/jobs/406823603

Actual error:

5 passing (4s)
  3 failing
  1) ScheduleTx
       schedules a basic transaction:
     TypeError: Cannot set property 'method' of undefined
      at WebsocketProvider._addResponseCallback (node_modules/web3-providers-ws/src/index.js:197:39)
      at WebsocketProvider.send (node_modules/web3-providers-ws/src/index.js:252:10)
      at RequestManager.send (node_modules/web3/lib/web3/requestmanager.js:58:32)
      at Eth.get [as accounts] (node_modules/web3/lib/web3/property.js:107:62)
      at Object.<anonymous> (test/e2e/TestScheduleTx.ts:75:34)
      at Generator.next (<anonymous>)
      at fulfilled (test/e2e/TestScheduleTx.ts:4:58)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

The only difference between HTTP provider and WS provider is using ws://localhost:5454 instead of http://localhost:8545. RPC I'm talking to is ganache-cli 6.1.6.


texts: How to get only past 2 days events using getPastEvents everytime?

texts:
How can the following query be modified to only fetch the past two days worth of events:

const events= await MyContract.getPastEvents("eventName", {
  fromBlock: 0,
  toBlock: "latest"
});


texts: How do I define my token to pass truffle test?

texts:
After running truffle test i get the following error:

Zanes-iMac:xyztoken zanemassey$ truffle test
Using network 'development'.

Compiling ./contracts/Migrations.sol...
Compiling ./contracts/xyzToken.sol...

Compilation warnings encountered:

/Users/zanemassey/Desktop/xyztoken/contracts/Migrations.sol:11:3: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.
  function Migrations() public {
  ^ (Relevant source part starts here and spans across multiple lines).
,/Users/zanemassey/Desktop/xyztoken/contracts/xyzToken.sol:8:2: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.
    function xyzToken (uint256 _initialSupply) public {
 ^ (Relevant source part starts here and spans across multiple lines).

  Contract: xyzToken
    1) sets the total supply upon deployment
    > No events were emitted

  0 passing (36ms)
  1 failing

  1) Contract: xyzToken
       sets the total supply upon deployment:
     ReferenceError: xyzToken is not defined
      at Context.<anonymous> (test/xyzToken.js:7:3)
      at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-core/lib/testing/testrunner.js:135:1
      at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/property.js:119:1
      at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:89:1
      at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
      at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
      at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
      at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
      at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
      at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
      at endReadableNT (_stream_readable.js:1081:12)
      at process._tickCallback (internal/process/next_tick.js:63:19)

If no events were emitted then what exactly is it failing?

this is my js:

var DappToken = artifacts.require("./xyzToken.sol");

contract('xyzToken', function(accounts) {
    var tokenInstance;

    it('sets the total supply upon deployment', function() {
        return xyzToken.deployed().then(function(instance) {
          tokenInstance = instance;
          return tokenInstance.totalSupply();
        }).then(function(totalSupply) {
          assert.equal(totalSupply.toNumber(), 600000000, 'sets the total supply to 600,000,000');
          return tokenInstance.balanceOf(accounts[0]);
        }).then(function(adminBalance) {
          assert.equal(adminBalance.toNumber(), 600000000, 'it allocates the inital supply to the admin account');
        });
    });
});

and solidity:

pragma solidity ^0.4.23;

contract xyzToken {
    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    function xyzToken (uint256 _initialSupply) public {
        balanceOf[msg.sender] = _initialSupply;
        totalSupply = _initialSupply;
    }
}

I have asserted total supply for number and admin balance and i have configured ganache accounts with an associative array. What exactly isn't defined about my token?

any help would be appreciated


texts: Problem starting BSC Full Node - GraphQLPort is not defined in node.config

texts:
Trying to start running a full node as per the steps here: https://docs.binance.org/smart-chain/developer/fullnode.html
Upon running the last step, "Start your full node"
## start a full node
geth --config ./config.toml --datadir ./node

I get this error, and the node fails to start.
INFO [05-10|01:29:48.318] Starting Geth on Ethereum mainnet...
INFO [05-10|01:29:48.318] Bumping default cache on mainnet         provided=1024 updated=4096
Fatal: ./config.toml, line 43: field 'GraphQLPort' is not defined in node.Config, see https://godoc.org/github.com/ethereum/go-ethereum/node#Config for available fields

How can I fix this, and get the node running? Any help is much appreciated!


texts: How to convert string to type defined by an abi.Type for payload construction?

texts:
I am writing a CLI in Go that should faciliate users to be able to make contract function calls from it. This entails generating contract ABIs and providing input parameters to the function arguments but requires knowledge of the argument type to be able to construct a transaction payload correctly. This payload becomes the data component of an Ethereum transaction to make a function call.

My CLI prompts for input which then needs to be converted to a specific type for that parameter as defined by its ABI.

// Compile solidity contract given a path to file
contract, err := compiler.CompileSolidity("", contractPath)
if err != nil {
    log.Fatal("ERROR failed to compile contract:", err)
}

path := strings.Split(contractPath, "/")
contractName := path[len(path)-1]

// Resulting compiled contract instance
compiledContract = contract[contractPath+":"+strings.Replace(contractName, ".sol", "", -1)]

// Retrieve the ABI definition as a JSON string from the compiled contract
abiStr, err := json.Marshal(compiledContract.Info.AbiDefinition)
if err != nil {
    log.Fatal("ERROR marshalling abi to string", err)
}

// Go format ABI from JSON
abiContract, err := abi.JSON(strings.NewReader(string(abiStr)))
if err != nil {
    log.Fatal("ERROR reading contract ABI ", err)
}

inputParameters := abi.Methods[methodName].Inputs
// Gets input parameters to named method as strings
args := getArguments(inputParameters)

payload, err := abiContract.Pack(methodName, args...)
if err != nil {
    log.Fatal("ERROR packing the method name for the contract call: ", err)
}

As shown above, a contract instance is compiled and its generated ABI used to discern the method metadata. For a given methodName, a Method contains Inputs as type Arguments which contain information for each input argument including parameter name and type. This code is here.

Above, args is an array of string that have been input as parameters to the methodName function call but need to be casted to the correct type before abiContract.Pack where it panics due to type mismatch of provided parameters vs the expected type as defined by the ABI.

Given a variable of type string and another variable of type abi.Type how can I perform a type conversion to convert the string variable into the type defined by the abi.Type variable?


texts: solidity - where the token goes if creator balance is less than total supply

texts:
When I create my token with Token-Factory , I made a mistake, I set the balance far less than the total supply, the construction is

function TOToken() {
    balances[msg.sender] = 100000000;
    totalSupply = 10000000000;
    name = "TEST OF TOKEN";
    decimals = 2;
    symbol = "TOT";
}

Although it is just a test token but it confuses me that where is the left token that does not come into my wallet and may I retrieve them back?


texts: Where's Submit button to register .ETH domain?

texts:
When I attempt to register a .ETH domain at https://registrar.ens.domains, there is no button for me to submit my request. Right below the message "I understand how the process works and my risks and responsibilities involved", there is a button that reads "LOADING DICTIONARY", but this button is not highlighted in order for me to click it for domain submission.

Am I on the correct website to purchase an ETH domain?
Is there another way to submit my auction request?
Or what can be done to fix this problem?


texts: When to stop importing new chain segments from Rinkeby testnet?

texts: I am using geth to sync up with the Rinkeby testnet using the command: geth --rinkeby --syncmode "fast". First it downloaded the blocks, then account states, and now new chain segments are being imported. Can I stop the processes now and continue with creating account and start developing? Or I would have to wait until a specific message gets printed on the screen?


texts:
What are the schema and data stored in geth's chaindata directory?
There are blockchain data under datadir/chaindata in geth. What is kind of data is stored in LevelDB? What are the actual key and value in the database?


texts: what is the difference between payable and view in a smart contract in solidity?

texts: I don't quite understand the concept of payable in a function in the smart contract and the difference between payable ,view and pure.


texts: Input byte array must be in range 0 < M <= 32 and length must match type-web3j

texts:
I have created an api to addCandidates. But when i run the api i get error:

Input byte array must be in range 0 < M <= 32 and length must match type

My codesnippet for addCandidates is:

 @RequestMapping("/addCandidate")
    public String addCandidateDetails(@RequestParam("candidateName") String candidateName, @RequestParam("elecName") String elecName) {
        try{

        String contractAddress = contract.getContractAddress();
        System.out.println(contractAddress);
        contract.addCandidate(candidateName.getBytes(), elecName.getBytes());
        }
        catch (Exception e) {
            String error = e.getMessage();
            return error;
        }
        return "Success";
    }

Code for contract in java is:

public RemoteCall<TransactionReceipt> addCandidate(byte[] candidateName, byte[] election) {
    final Function function = new Function(
            FUNC_ADDCANDIDATE,
            Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Bytes32(candidateName),
            new org.web3j.abi.datatypes.generated.Bytes32(election)),
            Collections.<TypeReference<?>>emptyList());
    return executeRemoteCallTransaction(function);
}

Can any one tell me what I am doing wrong here?? Is getBytes() the right way to convert string to bytearray??
Any leads would be appreciated. Thank you!!


texts:
is it possible to get the information about the actual amount of gas that was used for a transaction? I have the transaction hash and I'd like to know the gas that was used by this transaction after the block has been mined. The estimate Gas won't be helpful for me.
I'm using web3.py and Ganache


texts: Why gas usage differ on mapping(int32 => Struct) vs Struct[]?

texts:
My goal is to iterate around 100 items or even more inside a mapped data stuct per a function call by using minimum gas. In order to achieve it I have used two different approaches.

In my case only empty function call costs 23499 Gas.

I have observed that to read a single mapped items costs around 303 gas<= (23802 - 23499) and a single push costs 25979 Gas <= (49478 - 23499)  for the following code:

  struct Interval {
    uint32 num;
    int32  core;
    uint32 next;
  }

  Interval[] list;
  function createList(){
      for(int i; i < 100; i++)
         list.push(Interval( { num: 10, core: 10, next: 10 }) );//some dummy push
  //to push a item costs 25979 gas. So 100 items => 100 x 25979 = 2597900 gas.
      }
  }

  function iterateList(){
     for(int i; i < 100; i++){
         list[i];
  //to read the list per item costs 303 gas. So 100 items => 100 x 303 = 30300 gas.
     }
  }

  function singlePush(){ //costs 49478 Gas
      list.push(Interval( { num: 30, core: 10, next: 10 }) );
  }

  function singleRead(){ //costs 25979 Gas
      list[0];
  }

  function emptyCall(){ //costs 23524 Gas
  }

[Q] Why reading data is expensive? If I use assembly code to access to data would gas cost be cheaper?

When I update the code as follows(changing Interval[] list; with mapping(int32 => Interval) list;)... gas amount for reading and pushing data decreases dramatically. Now I have observed that to read a single mapped items costs around 25 gas <= (23524 - 23499) and single push costs 20545 Gas <= (44044 - 23499).

  struct Interval {
    uint32 num;
    int32  core;
    uint32 next;
  }

  mapping(int32 => Interval) list;
  function createList(){
      for(int i; i < 100; i++)
          list[i] = Interval( { num: 10, core: 10, next: 10 });
   //to push a item costs 20545 gas. So 100 items => 100 x 25979 = 2054500 gas.
      }
  }

  function iterateList(){
     for(int i; i < 100; i++){
         list[i];
  //to access into list per item costs around 25 gas. So 100 items => 100 x 25 = 2500 gas.
     }
  }

  function singlePush(){ //costs 23524 Gas.
      list[0] = Interval( { num: 10, core: 10, next: 10 });
  }

  function emptyCall(){ //costs 23499 Gas
  }

[Q] What may cause to have dramatic change on gas to read and push data based on the definition differ as follows: mapping(int32 => Interval) list vs Interval[] list.

I did ask multiple questions all in once but I believe that they all linked to each other.


texts: Security - Locking/Unlocking geth wallet

texts:
If you're running geth on localhost and use a web page I provided to interact with the ethereum network, is it not possible for me to just unlock the account and transfer the funds to a different account using web3js and javascript? I am a little confused as to how locking and unlocking of wallets work and how I can build a self contained web app without using geth/infura?

Also, is it possible to connect a web dapp to a web wallet and use the web wallet somehow to interact with the contract?


texts: Sending Tether USDT via RPC JSON API call

texts:
I'm trying to send Tether using JSON RPC API via 0xdac17f958d2ee523a2206206994597c13d831ec7 contract.
I've tried to cases:

From simple ETH wallet
From ETH wallet, which has only USDT

This is what I am sending from my ETH wallet:

{
"jsonrpc":"2.0",
"id":"personal_sendTransaction_1562573686",
"method":"personal_sendTransaction",
"params":[{
    "from":"0x1653d4669bab423cab7593260bc373d5d57d7f8d",
    "to":"0xdac17f958d2ee523a2206206994597c13d831ec7",
    "value":"0x0",
    "data":"0xa9059cbb000000000000000000000000CfCB8f60D94827381b4BDa53f052aAFEC246D72e00000000000000000000000000000000000000000000000000000000000dbba0"
  },
  "password"
 ]
}

This is what I've got as a result

Transaction result

ERC-20 Token Transfer Error (Unable to locate Corresponding Transfer Event Logs)

Missing opcode 0xfe

UPD Seems like you can not send USDT without having them on ETH wallet, like no chance to convert ETH to USDT. You should have both ETH and USDT on your wallet

And the second case, when I have only Tether on my ETH wallet

{
"jsonrpc":"2.0",
"id":"personal_sendTransaction_1562579177",
"method":"personal_sendTransaction",
"params":[{
    "from":"0xbe9027e5d76df40e51300a49aea6152e0c885eb1",
    "to":"0xdac17f958d2ee523a2206206994597c13d831ec7",
    "value":"0x0",
    "data":"0xa9059cbb000000000000000000000000CfCB8f60D94827381b4BDa53f052aAFEC246D72e00000000000000000000000000000000000000000000000000000000000dbba0"
  },
  "password"
 ]
}

and I've got this

{"code":-32000, "message":"insufficient funds for gas * price + value"}

like there are no funds at all on my wallet.
But I definitely have USDT there

What should I do to fix at least, the second case? Is it possible?


texts: What should gas prices be for sending out tokens?

texts: I constantly get failed transactions when sending out tokens like USDT using metamask. I have my gwei set at 10 and the gas limit at 21000. I even tried gas limit set to 51000 and it still fails. Where can I go to easily calculate what numbers to put to send out my tokens? Obviously metamask isn't calculating this correctly.


texts:
Once I do cancel some data from a struct, how do I remove the empty cells that I then create? Sorry for the silly question but I am just new :)

Below you will see "function removeAppointment" where, given a year, it cancels al the appointments that contain that year. I then remain with empty spaces in my struct that I would like to remove.

pragma solidity ^0.5.14;

contract Calendario_Appuntamenti {

    mapping (uint => calendar) public appointment;
    address owner;
    uint256 public _counter = 0;

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

    modifier only0wner(){
        require (msg.sender == owner);
        _;
    }

    struct calendar{

        uint256 _id;
        uint256 _day;
        string _month;
        uint256 _year;
    }

    function addAppointment (uint256 _day, string memory _month, uint256 _year) public{
        _counter +=1;
        appointment [_counter] = calendar (_counter,_day,_month,_year);
    }

    function removeAppointment (uint256 _yeartoremove) public only0wner {
        uint256 _i;
         _i = _counter;

        while (_i > 0){

            if(_yeartoremove == appointment [_i]._year){

                delete (appointment [_i]);
            }
            _i -=1;

        }
    }
}


texts: How to get all historic changes of a state variable in a smart contract?

texts: Blockchains are known to be immutable because all transactions of cryptocurrencies and state (data) changes.  However, looking at ethscan does not provide any information on the output of a smart contract function that results in a state change.  Is there a way to monitor the historic values of a state and if so how to do so?


texts:
I have just finished installing Swarm and I managed to follow the documentation. I created a new account using

  geth account new

and I connected using said account using the below line

  swarm -bzzaccount accountno

This left me a bit clueless as to the next steps

1) Is the Account I created a wallet on the main Ethereum network?

2) Can I set up swarm on a private chain using my chain ID?

3) My understanding of swarm is that it will be like Ethereum, only you dont store transacations, but you store literally anything. So a ledger can be a mass repository of any file of any kind? Are there principles of consensus involved, immutability and nonrepudation?


texts: How to find the block, when contract was deployed

texts: I have contract address, and I want to find the block number, when it was deployed, to use it for loading events for this contract. Is it possible?


texts: Encryption of keystore, keys and cryptographic library usage locations

texts:
I understand that another question posted has mentioned that the keystore has
 aes-128-ctr encryption: What is the strength of Mist wallet encryption?

Key Derivation Function uses scrypt (where the underlying function uses SHA256?), then we have ECDSA for creating private keys. Where does secp256k1 come in?

I don't have a lot of knowledge in the cryptography or which libraries are used for hash/encryption but looking through the source code for the keystore and keys, can anyone explain the steps on how the keys & the keystores are being generated for Ethereum?


texts: What are the risks associated with using Ethereum?

texts:
Knowing the risks associated with a system, their probability and their severity is the first step towards good risk management. There is little details and analysis that has been published about the risks associated with Ethereum so far.
From the Wikipedia risk management article:

Risks can come from various sources: e.g., uncertainty in financial markets, threats from project failures (at any phase in design, development, production, or sustainment life-cycles), legal liabilities, credit risk, accidents, natural causes and disasters as well as deliberate attack from an adversary, or events of uncertain or unpredictable root-cause. [...]
Risk sources are more often identified and located not only in infrastructural or technological assets and tangible variables, but also in human factor variables, mental states and decision making. The interaction between human factors and tangible aspects of risk highlights the need to focus closely on human factors as one of the main drivers for risk management, a "change driver" that comes first of all from the need to know how humans perform in challenging environments and in face of risks [...].

In December 2014, Mariam Kiran from the University of Bradford and Mike Stannett from the University of Sheffield published a document called Bitcoin Risk Analysis which include an in depth analysis of the various different risks associated with Bitcoin. Is there any similar document for Ethereum?
Ethereum is most likely going to share a good amount of the same risks that Bitcoin does. What are the additional risks that Ethereum has and that Bitcoin does not have? Is there any risk that Bitcoin has and that Ethereum does not have?


texts:
Is there any way in the Web3 Javascript API to retrieve the latest, let's say five, transactions that were done on the blockchain?

The only option I can think of, is by using web3.eth.getBlock(web3.eth.blockNumber, true) in a for loop and subtracting the blockNumber till you find an object in the transactionsproperty.

However, this can take a very long time, because in our case, we have our blockchain on an Azure server and a lot of empty blocks are created by nodes.

EDIT: Not a duplicate of this. I want to know how to find the latest transactions in an efficient way, without using a for loop that takes ages to complete.


texts:
Anyone know an (easy way) to import a pre sale wallet onto Kraken?
They used to have this tool but it doesn't seem to work anymore?

Thanks


texts: I AM Trying to connect my Website with Remix Ethereum IDE and getting Error { (index):85 Uncaught TypeError: CoursetroContract.at is not a function}

texts:
'''

    Document
<link rel="stylesheet" type="text/css" href="main.css">

Coursetro Instructor

    Instructor Name
    <input id="name" type="text">

    Instructor Age
    <input id="age" type="text">

    <button id="button">Update Instructor</button>

'''


texts: Can you input a variable into a contract call?

texts:
In ETH could you call a contract by inputting a variable parameter? As in the value of that parameter is unknown at call and must be evaluated at run-time?

Something like "someFunction( current_time_at_run_time );" - is this allowed?

Thanks.


texts:
ERC-1155:
    function approve(address _spender, uint256 _id, uint256 _currentValue, uint256 _value) external;

    /**
        @dev Allow other accounts/contracts to spend tokens on behalf of msg.sender
        Also, to minimize the risk of the approve/transferFrom attack vector
        (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), this function will throw if the current approved allowance does not equal the expected _currentValue, unless _value is 0
        @param _spender        Address to approve
        @param _ids            IDs of the CryptoItems
        @param _currentValues  Expected current values of allowances per item type
        @param _values         Allowance amounts per item type
    */
    function batchApprove(address _spender, uint256[] calldata _ids, uint256[] calldata _currentValues, uint256[] calldata _values) external;

Which events (and with which arguments) should these two functions emit?


texts: Contract Using An Interface Is Not Compiling

texts:
I am learning Solidity and I am using Remix to experiment and enhance my learning. I am currently trying to create a simple contract that uses an Interface.

pragma solidity ^0.4.19;

contract InterfaceWithMe {

    function call() returns (string);

}

contract Interfacing {

    address ckAddress = 0x9fe1c58215407d67719ba680360940056e5eceb7;
    InterfaceWithMe daContract = InterfaceWithMe(ckAddress);

    function call() returns (string) {
        return daContract.call();
    }

When I try an compile this on Remix, I get the following type error on line 14:

TypeError:Return argument type inaccessible dynamic type is not implicitely convertibel to expected type (type of first return variable) string memory.

Here is the other contract that I use to interface with this contract:

pragma solidity ^0.4.19;

contract InterfaceWithMe {

    function call() returns (string) {
        return "Hello";
    }
}

Thanks for the help.


texts: variable declared as uint but accepting negative values instead of throwing errors

texts:
pragma solidity ^0.4.24;

contract setget{
    uint x;
    function setnumber(uint _x) public {
        x=_x;
    }
    function getnumber() public view returns(uint){
        return x;
    }
}


texts: I am trying to view values stored on my ethereum contract using ethereum wallet. Currently the values are being placed onto the contract in hex format. Is there a way to decode them on the contract so that Ethereum wallet can read back words rather than hex values?


texts: Problem with understanding contract containing array of structure

texts:
I got the following code for a contract from a Solidity tutorial website:
pragma solidity 0.5.1;
contract MyContractPersonStruct {
    Person[] public people;

    uint256 public peopleCount;

    struct Person {
        string _firstName;
        string _lastName;
    }

    function addPerson(string memory _firstName, string memory _lastName) public {
        people.push(Person(_firstName, _lastName));
        peopleCount += 1;
    }
}

I have got 3 questions:

Person is declared as an array of structure having a variable people. But with ‘people’ we are not using square brackets. Is this not required in Solidity? When can we use square brackets with 'people'?

I have tried to execute the contract on Remix. I got the above scenario:
I can’t understand what values I have give to text box associated with people.

What is the purpose of call in the image above?

Somebody please guide me.
Zulfi.


texts: Can you neglect profitable transactions to increase mining profits?

texts:
As far as I understood, each miner can access a pool of pending transactions, select those that he likes, put them together in a block minding that they don't exceed the block's gas limit, and then tries to mine this block. Of course, the miner would pick those transactions with the highest transaction fees as it seems most profitable to mine them. This is the behavior implemented in the available geth/pygeth/cpp-ethereum implementations.

Now imagine the miner would only pick the transactions with the lowest fees and put them into a block. Would he not greatly reduce the overall competition in the network and end up more profitable due to the block rewards? If this was possible, a miner could even create low-fee transactions himself to guarantee there are always enough "unprofitable" transactions around. This would harm the network as the miner would get paid block rewards for verifying bogus transactions.

At the time of writing this, the gas price on ethstats.net is 146 gwei, so it is indeed a realistic scenario that 21-gwei-transactions are neglected by the majority of miners for a pretty long time.

Is this possible or what mechanisms prevent this? Is it possible to continue mining a block if another block in the network has been mined in the meantime, if they share no common transactions? If noone ever picked any of the transactions you chose, could you try mining your block for hours/days and then append it to the block chain? And would you even need to fill your block with bogus transactions until the gas limit for the block is reached, or could you also mine (almost) empty blocks? I suspect this is not possible since I assume that otherwise, this would have been exploited by now.


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

Is it the datacopy precompile? and if yes, what it does?


texts: How can I setup a fixed price (in USD) in a smart-contract?

texts:
I would like to sell tokens at a fixed price in dollars and to do the conversion in ETH by default at the coinmarketcap price.
E.g. Would like to sell 1 "mytoken" every day at 1 USD. 1 USD = 0.12 ETH (because the ETH today is quoted at 8.1 USD).

How could I code that?


texts: contract state variable does not change after call the function

texts:
I have deployed the contract, the code is here, very easy. Then get the instance

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

call the function

ballot1.giveRightToVote.sendTransaction(eth.accounts[1], 'xiaoB', {from:eth.accounts[0]})

continue minned after confirmed

  ballot1.voters()
  ["0x0000000000000000000000000000000000000000000000000000000000000000", false, 0, 0, 0]

the state variable was still empty


texts:
I want to make code coverage for my project. I installed the solidity-coverage from this page: https://github.com/sc-forks/solidity-coverage

and then ran this command in truffle : truffle run coverage

and then truffle give me an error : Error: solidity-coverage listed as a plugin, but not found in global or local node modules!

why am I getting this error?

thank you.


texts: How long does it take to "save artifacts" to Ropsten?

texts:
Migrating contracts with Truffle I get stuck at

Saving artifacts...

Sometimes for 10 minutes or more.

I also get:

Error: Transaction 0x123...123 wasn't processed in 240 seconds!

Is it normal that test network is so slow?


texts: Where is the location to login to access to infura links

texts:
In https://infura.io/ I see the "Get Started" button that leads me to the sign up page, like this, https://infura.io/signup.

The problem is I already signed up before. How do I sign in now?

Last time I signed up to use the ropsten link. Now I want to use the mainnet link. Apparantly I did not write it down last time. I do not want to use a different email address every time to see the links.