texts:
I would like to know how can i exchange my ether in my MEW wallet for flat currencies like USD, INR etc. It would be highly appreciable if anyone can guide me with this.

Thanks in Advance!!!


texts:
I have a crowd sensing system where user after checking the task I provide for a location x, sends temperature values to the contract of that location.

I've been trying to a way to implement data integrity and privacy however, so far with no luck.

I'd like ensure the integrity of the data sent in the sense that the user is actually in that location and not just faking the location or values to get a reward, second issue is when the user sends a completed task we could know that he should have been in the location x which is a privacy concern for the user. In-other words can I ensure location privacy in the sense that location is always kept private.

Any ideas on how to implement this, or documents I could read to assist.


texts: Consolidate Batch of ETH Wallets w/ERC20 Tokens?

texts: I have a large number of Ethereum wallets with small amounts of ERC-20 tokens in each.  How can I send all of these tokens to a single ethereum wallet without doing this process manually? (it would take a long time)


texts: How to modify geth node configuration after launch

texts:
Is it possible to modify geth configuration when the node is running?
For instance, open a port, add more parameter flag to control geth node functions.

I think maybe there are two ways:
One is stop the node and re-launch with new parameters. but not sure it's feasible.
the other one is use command api, if it permits, which command can be used to re-configure?

Thanks for you help.


texts: web3 js. How to get list of all tokens being in an given address

texts:
I want to write a function that has 1 input and 1 output. Input is an address and output is the number of tokens that being in that address

I am very new in web3. is there any one help me write a simple bunch of web3 code to solve this function


texts: How to tell if an NFT jpg is stored on a legitimate IPFS domain?

texts:
usually URLs of NFTs point to well-known IPFS servers like ipfs.io and some gateway that bridges from the web to IPFS,
but what about cases where an NFT is pointed towards something like
https://f8n-ipfs-production.imgix.net/[NFT_contract_name_here].
This looks just like any other web URL, i have no idea what company "imgix" is, and the inclusion of ipfs in the sub-domain could be nothing but a trick.


texts:
Anyone knows what happened to Go Ethereum Disasm (disassembler) ?
The repo used to be here: https://github.com/eris-ltd/go-ethereum/cmd/disasm
and apparently the latest version available was 1.3.3 on Jan 2016.
In recent ethereum documentations it mentions that it is included in the packages

For all archives we provide separate ones containing only Geth, and separate ones containing Geth along with all the developer tools from our repository (abigen, bootnode, disasm, evm, rlpdump). Please see our README for more information about these executables.
To download these bundles, please head the Go Ethereum Downloads page.
source: https://geth.ethereum.org/install/

However after installing the package (e.g Geth & Tools 1.5.8) it only includes these fils:

COPYING
abigen
evm
geth
rlpdump
swarm

anyone with a linux or Mac os x link would save me


texts: Help using and reading Arrays[] and mappings

texts:
I'm trying to do something very simple. I want to make a structure that holds the data for a player.

Within that data, I want an array to store things like its inventory, and its current eggs/monsters.

Yet I cannot interact with arrays at all, I'm constantly getting issues. Can someone tell me what I'm doing wrong and why it won't let me read and return arrays?

contract EtherMon{
    uint public starterEgg;
    address public owner;

    struct player{
        uint256 goldAmount;
      uint[10] listOfEggs;
        bool eggCoolDown;
        uint eggTime;
        uint eggID;
        bool battleCoolDown;
        bool breedingCoolDown;
        uint[] ownedEthermon;
    }

      mapping (address => player) public listOfPlayers;

    function EtherMon(){
        owner = msg.sender;

    }

    function createAccount(){

     starterEgg = block.timestamp % 10;

     listOfPlayers[msg.sender].goldAmount  = 100;
     listOfPlayers[msg.sender].listOfEggs[0] = starterEgg;

        }

  function getCurrentEggs() returns (uint[]) {
 uint length =  listOfPlayers[msg.sender].listOfEggs.length;
 uint[] eggArray;
            for(uint i = 0; i < length; i++){
               eggArray[i] =  listOfPlayers[msg.sender].listOfEggs[i];
            }
            return eggArray;
        }

    }

Basically I just want to be able to...

Call CreateAccount and it stores a random uint into the array that stores the eggs a player holds
Pull that egg data from the mapping and see it/change it

Can someone give me an example of a structure that holds an array (and mapping because it seems I can use a mapping within a struct but have issues with dynamic arrays) and has getter and setter functions?


texts: My parity node constantly gets requests from 0x0

texts:
I ran my parity node (stable version) with this command on a docker:

/bin/parity
--chain=kovan \
--jsonrpc-interface all \
--jsonrpc-hosts all \
--light \
--force-sealing \
--auto-update=all \
--min-gas-price 1000000000 \
--gas-floor-target 8000000 \
--jsonrpc-apis web3,eth,net,parity,traces,rpc,personal \
rpc=trace \
--jsonrpc-cors=all

It is working fine, although I keep getting these requests all the time from author 0x0. Can anyone explain why are these requests taking place?


texts: How does knowing the root hash of a past world state help me to revert to this world state?

texts:
In section 4.1 of the Ethereum yellow-paper (http://gavwood.com/Paper.pdf) the following is written:

  The world state (state), is a mapping between addresses (160-bit
  identifiers) and account states (a data structure serialised as RLP,
  see Appendix B). Though not stored on the blockchain, it is assumed
  that the implementation will maintain this mapping in a modified
  Merkle Patricia tree (trie, see Appendix D). The trie requires a
  simple database backend that maintains a mapping of bytearrays to
  bytearrays; we name this underlying database the state database. This
  has a number of benefits; firstly the root node of this structure is
  cryptographically dependent on all internal data and as such its hash
  can be used as a secure identity for the entire system state.
  Secondly, being an immutable data structure, it allows any previous
  state (whose root hash is known) to be recalled by simply altering the
  root hash accordingly. Since we store all such root hashes in the
  blockchain, we are able to trivially revert to old states.

I understand Merkle trees and that the root node is a digital fingerprint of the tree leafs ... but how does this fact make it possible to "trivially revert to old states"??

Let's say I am at block/state N. Now I want to revert to state N-1. I know the root hash of state N-1. How does this knowledge help me to reconstruct the state of the tree leafs (tree leafs == Ethereum Accounts) in state N-1? The root hash in state N-1 could result from many different combinations of tree leaf-values ... I can easily compute the root hash given the tree leafs ... but the whole point of a hash is to make it impossible to get from a hash back to its input ...

So why does knowing the root hash of a past world state help me to reconstruct this world states?


texts: Can I transfer ether from a wallet to smart contract directly without invoking a payable function?

texts:
hey I was trying to pass some ether from my account to smart contract through metamask. Ive already given some ether from my contract to metamask account so it should be possible to do the same even without a payable function.transferring ether to contract through wallet is as easy as transferring ether to any usual account right? But when i send ether it gives me following error-

Any help would be appreciated thanks. :)


texts:
I want to create ethereum account using golang. I am following this guide but I am stuck with errors just at the beginning of code.

accountManager:=accounts.NewManager(".ethereum/rinkeby/keystore",accounts.StandardScryptN, accounts.StandardScryptP))

Error : Unresolved Reference "accounts.StandardScryptN" & "accounts.StandardScryptP"


texts: What's the point of sending a value in a contract deployment transaction?

texts:
When deploying contracts, to what end can/is the ether value associated to the deployment transaction be used? In the documentation, it's stated that:

  The value field is used the same as in ether transfer transactions
  between normal accounts. In other words transferring funds is
  available between any two accounts, either normal (i.e. externally
  controlled) or contract.

but who receives this value? or is it the value of the product between gasPrice and gas deducted from the creating account upon deployment (and received by miners)?


texts: Can we deploy a private blockchain on ethereum without using smart contract

texts: I'm recently trying to investigate whether we can deploy a private blockchain without using the functionality of the smart contract, or in that case can we deploy it on quorum without the functionality of smart contract


texts: Resetting storage slot increases gas usage although should decrease it

texts:
I have a simple contract that deletes the last element of the array:

pragma solidity^0.4.11;

contract GasRefundTest {

    uint[] myArray = [1, 2];

    function deleteLastElem() public returns(bytes32) {
        myArray.length--;
    }
}

Transaction cost for calling deleteLastElem() is 17182 gas.

When I change it to:

pragma solidity^0.4.11;

contract GasRefundTest {

    uint[] myArray = [1, 2];

    function deleteLastElem() public returns(bytes32) {
        delete myArray[1];
        myArray.length--;
    }
}

the transaction cost becomes 22480 gas.

I thought deleting storage slots should result in gas refund, instead I see gas increase.

Can anyone explain what's going on here.


texts: Are there any currently successful use cases for smart contracts?

texts:
I was reading this article "Why Many Smart Contract Use Cases Are Simply Impossible" (here at coindesk.com) about how many ideas for smart contracts are impossible to implement in practice.

The author does not say that smart contracts are not useful for anything at all, but just that many of the ideas are not well suited for smart contracts.

He writes that

  The problem with smart contracts isn’t just that people’s expectations
  are overblown, it's that these expectations are leading many to spend
  time and money on ideas that cannot possibly be implemented.

  ...

  Over the past nine months, we've been pitched many smart contract use
  cases, and have found ourselves responding, time and again, that they
  simply cannot be done.

This made me think, are there any examples of successful implementations of smart contracts in use by any industry?

(I mean outside of the work smart contracts may do in the standard Ethereum network.)


texts: Best way to see a real-time list of pending transactions that have not yet been mined

texts:
I've spent all day trying to figure this out, to no avail.

I'm trying to find a way to analyze the ongoing pending transactions at certain times in the day/week, to ascertain ideal times for processing transactions based on network load, at least based on averages. Specifically, I would like to be able to easily view and ideally download the list of pending transactions currently being broadcast to the network that have not yet been mined, in JSON format for instance, so that I can then analyze that data.

A great example of this would be this page.

However, it does not give me all of the data I am looking for on that initial screen/list, unlike some of the other API calls that they support. Unfortunately there does not seem to be an API call yet for the pending transactions list, otherwise that would be exactly what I need.

This is an example of a supported API call that DOES give me what I need, except I need the same thing for pending transactions.

I am pretty desperate to get this to work for my small project at this point, and will donate/contribute what feeble fraction of ETH I can to anyone who can help me solve this.


texts: I'm getting "Cross-Origin Request Blocked" error

texts:
I'm getting this error:

  Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at http://localhost:8545/. (Reason: CORS request
  did not succeed).

I'm aware of this GitHub issue: https://github.com/ethereum/web3.js/issues/1802
But my web3 version is 1.2.6. So I think this bug was already fixed, because this GitHub issue is 2 years old.

I'm trying to connect to MetaMask like this:

 var web3;
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
            console.log("web3 was not undefined");
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
            console.log("We are not in the first 'if' statment.");
        }

        //long part with ABI

        EthereumSession.methods.BuyTicket().send({ from: web3.eth.defaultAccount })
        .then(receipt => { console.log("We are in the 'then'"); });

This will give error No "from" address specified, if I set an address with web3.eth.defaultAccount = '0x...'; I will get error about Cross-Origin Request

~~This is a simple HTML file with < script> tags, web3 is installed with npm install web3.~~

UPDATE:

(not running as file anymore)
Now I'm hosting it in localhost.
I removed node_modules folder with web3, now I see the MetaMask injected Web3.
This changed some errors, now I need to use different version of EthereumSession.at

Now I'm getting a TypeError: this._eth.sendTransaction is not a function error for this line:

ethereumSessionInstance.BuyTicket({
            from: web3.eth.defaultAccount,
            gas: 100000,
            value: web3.toWei(0, 'ether')
        });

BuyTicket() is a Solidity function that has no arguments.

I'm also getting 'Source Map Error' warnings.


texts:
Question:

How many (or up to how many) characters does a Ethereum address have?

Elaborating:

I have been looking online for an answer but it seemed harder to find than I expected.

I am working on storing a list of Ethereum addresses with web3.js in a MySQL database, and need to know the limit of characters I should put for the VARCHAR. I could ofcourse put a very high value like 100 and be safe from not having enough space, however that would cost some speed.


texts:
Q:- While sending only Ether One wallet to another wallet(NO SMART CONTRACT),
do we need to define the default gas limit and price?

i.e. 21000 * 3 OR 21000 * 4 OR 21000 * 5 etc

Or

I've need to use estimate gas function web3.eth.estimateGas(callObject [, callback])?

because the web3.eth.estimateGas function always return 21000 gas in all the case when I'm giving two params "value" and "to_address" to this function


texts: Does Solidity pre-compute the powers of two defined in the body of functions?

texts:
I'm using the powers of two in only one my contract functions, but I defined them at the top-level thinking that this way I would save gas at runtime.
Is that necessary though? Can I do the following and incur the same gas cost when using the Solidity optimizer?
function foo(uint256 x) external returns (uint256 result) {
    if (x >= 2**128) {
        // ...
    }

    if (x >= 2**64) {
        // ...
    }

    // ...
}


texts: Consequences of 'VM Exception while processing transaction: invalid opcode'

texts:
The question
Hello everyone, could anyone explain to me the consequences of:
VM Exception while processing transaction: invalid opcode.
The context
I'm passing in an integer in web3js that is not mapped to an enum in my solidity contract - I have 2 elements in the enum and I'm intentionally passing in an index of 2, expecting the transaction to fail. The transaction does fail , however I expected a revert and not an invalid opcode. Should I handle parameter sanitisaton in some way?


texts: copying bytes32 values from map to array

texts:
I am trying to copy stored values from a map to an array. I have the following code:

pragma solidity ^0.4.21;

contract test {

event LogTest(
    bytes32[5] a
);

bytes32[5]  arr;
mapping (uint=>bytes32) attr;

//function that stores values and copies them to array which is returned
function attributes() internal returns(bytes32[5]){
    bytes32[5] x;
    attr[0] = "0x0"; attr[1] = "0x1"; attr[2] = "0x2"; attr[3] = "0x3"; attr[4] = "0x4";

    for(uint i=0;i<5;i++){
        x[i] = attr[i];
    }
    return(x);
}

//function that retrieves stored values and prints them in log
function copy() public {
    arr = attributes();
    LogTest(arr);
}

}

For some reason I am not getting the correct values copied. I am getting something that looks like this:

"event": "LogTest",
        "args": {
            "0": [
                "0x3078300000000000000000000000000000000000000000000000000000000000",
                "0x3078310000000000000000000000000000000000000000000000000000000000",
                "0x3078320000000000000000000000000000000000000000000000000000000000",
                "0x3078330000000000000000000000000000000000000000000000000000000000",
                "0x3078340000000000000000000000000000000000000000000000000000000000"]

What am I doing wrong? Are the values not even permanently stored in the attributes() function?
Is there a better way to do this than store in a map and copy into an array?


texts: Is it possible to launch the C++ eth client without unlocking the accounts?

texts:
Each time I run eth it requests my master password. I don't feel comforatble with permanently running a node with unlocked accounts.

Is it possible to launch the C++ eth (or alethzero) client without unlocking the accounts?


texts: Automatically test who can withdraw Ether from a smart contract

texts:
Is there any way I can automatically test who can withdraw ether from a smart contract? I need to perform this test automatically. So I cannot manually inspect the instructions.

Can I design a smart contract in such a way that it becomes easy to test? I want to ensure that only the creator of the smart contract can withdraw ether through one specific function.
I can easily test that this function exists, but how do I automatically test that no other function exists through which the creator (or any other person) of the smart contract can withdraw ether?

Update:

I am aware how to design a smart contract such that only the creator can withdraw ether. However, I need to automatically test who can withdraw ether from a smart contract that is given to me.


texts: How to register USER in my Smart Contract using Solidity?

texts: I can't figure out how do we register user in smart contract and get the userdata when he/she tries to login after register through our website..I didn't see any article regarding this..Kindly enlightened me..


texts:
When i deploy a smartcontract with remix, i can call functions in order to test it.
I do not really know if this is remix or metamask which is doing this job: Before validating the transaction, i have a popup which tells me if the execution of the function will cause an error. And i know how much gas the function will consume.
So i suppose there is a kind of "pre-execution" of the smartcontract's code, before sending the transaction.
What i want to know if it is possible to do the same thing inside a solidity smartcontract.
Is it possible to know how much gas is necessary before calling an external contract inside a solidity function ? And is it possible to pre-execute it in order to see if it will fails ?
Thanks


texts: Error: VM Exception while processing transaction: out of gas

texts:
I am running into out of gas exception while calling this function : contractInstance.createProposal("ADHD", "Foo", 2, {from: web3.eth.accounts[1]}) . I'm super new to ethereum and I would really appreciate some help!

Here's my super simple contract

pragma solidity ^0.4.2;

contract DataProvider {

struct Proposal {
    address owner;
    uint id;
    bytes16 name;
    bytes32 desc;
    uint pool_size;
    address[] consents;
    bool initialized;
}

address public admin;
Proposal[] public proposals;

function DataProvider() {
    admin = msg.sender;
}

function createProposal(bytes16 nm, bytes32 ds, uint n) {
    address[] memory cons;
    proposals.push(Proposal({ owner: msg.sender, id: proposals.length, name: nm, desc: ds, consents: cons, pool_size: n, initialized: true }));
}

}


texts: Declare an string array inside a int array in Solidity

texts:
I am using truffle and I am trying to pass during the deployment execution script a double array of prices inside my contract's constructor.
ie
In the migration file I have a 2 dimensional array. It's nested array contains a pair of prices.
var prices = [
  ['1223.456', '1223.456'],
  ['123.46', '12.1']
];

contract A {

   struct Price {
        string Price0;
        string Price1;
    }

    mapping (uint => Price) prices;

    constructor (int[][] memory _prices) public
    {

        for(uint i=0; i< _prices.length; i++)
        {

          prices[i] = Price(
              _prices[i][0],
              _prices[i][1]
          );

        }
    }
}

How can I declare this inside my contract's constructor so that I can parse it right after?
What I saw so far is that I can declare a 2 dimensional array with the same type
ie
uint[][] prices;
// or
string[][] prices;

but these are not working since in my double array the 1-level key is of type integer and the value of the 2-level is of type string.


texts: truffle compile with solc 5.0.0 error: solc.compileStandard is not a function

texts:
Trying to use Solidity v0.5.0 with Truffle. Starting v5.0.0 Truffle allows setting solc version in truffle.js, as per its docs

I tried both native

    compilers: {
        solc: {
            version: "native"
        }
    }

with

$ solc --version
solc, the solidity compiler commandline interface
Version: 0.5.0+commit.1d4f565a.Linux.g++

and solc-js v0.5.0

    compilers: {
        solc: {
            version: "0.5.0"
        }
    }

all that with Truffle v5:

$ truffle version
Truffle v5.0.0-beta.1 (core: 5.0.0-beta.1)
Solidity v0.4.25 (solc-js)

v0.4.25 here is its default packed solc-js version, not what I use in the project.

But even an empty sample contract

pragma solidity ^0.5.0;

contract Sample {
    constructor() internal {}
}

fails to compile:

$ truffle compile
TypeError: Error parsing /path/to/project/contracts/Sample.sol: solc.compileStandard is not a function
    at Object.parseImports (/home/etsvigun/.nvm/versions/node/v10.13.0/lib/node_modules/truffle/build/webpack:/packages/truffle-compile/parser.js:49:1)
    at Object.getImports (/home/etsvigun/.nvm/versions/node/v10.13.0/lib/node_modules/truffle/build/webpack:/packages/truffle-compile/profiler.js:332:1)
    at Promise.all.then.results (/home/etsvigun/.nvm/versions/node/v10.13.0/lib/node_modules/truffle/build/webpack:/packages/truffle-compile/profiler.js:305:1)

Is there a way to use Solidity v0.5.0 with Truffle already, or doesn't that work yet?


texts: Rerendering causes results to display twice (possibly caused by async event emission)

texts:
This may seem like a web developer problem at first but i think it pertains to how function calls are done in solidity.
So basically i have a voting application which triggers an event every time a vote is cast, and a function listens for events and asks the site to rerender.
In the render function i always empty the already displayed content and append new content from the blockchain and then render it.
But after adding a console log i see sometimes when i refresh the event is triggered before and then there are 2 console logs (after 1 vote is cast obviously).
(FYI the 2 in the console log is the number of candidates)

sometimes it works fine

PART OF RENDER FUNCTION RESPONSIBLE FOR PRINTING CANDIDATE LIST
App.contracts.Election.deployed()
      .then(function (instance) {
        electionInstance = instance;
        return electionInstance.candidatesCount();
      })
      .then(function (candidatesCount) {
        var candidatesResults = $("#candidatesResults");
        candidatesResults.empty();

        var candidatesSelect = $("#candidatesSelect");
        candidatesSelect.empty();

        for (var i = 1; i <= candidatesCount; i++) {
          electionInstance.candidates(i).then(function (candidate) {
            var id = candidate[0];
            var name = candidate[1];
            var voteCount = candidate[2];

            // Render candidate Result
            var candidateTemplate =
              "
" +
              id +
              "	" +
              name +
              "	" +
              voteCount +
              "
";
            candidatesResults.append(candidateTemplate);

            // Render candidate ballot option
            var candidateOption =
              "<option value='" + id + "' >" + name + "</ option>";
            candidatesSelect.append(candidateOption);
          });
        }
        console.log(candidatesCount.toString());
        return electionInstance.voters(App.account);
      })

FUNCTION LISTENING FOR EVENTS
    App.contracts.Election.deployed().then(function (instance) {
      // Restart Chrome if you are unable to receive this event
      // This is a known issue with Metamask
      // https://github.com/MetaMask/metamask-extension/issues/2393
      instance
        .votedEvent(
          {},
          {
            fromBlock: 0,
            toBlock: "latest",
          }
        )
        .watch(function (error, event) {
          console.log("event triggered", event);
          // Reload when a new vote is recorded
          App.render();
        });
    });
  },


texts: Error calling a function from another contract: Member "*" not found or not visible after argument-dependent lookup in type

texts:
I'm having trouble compiling a contract that calls a function of an imported contract.

SilverCoin.sol:

pragma solidity ^0.4.11;

contract SilverCoin {
    function abc() constant returns (uint) {
        return 0;
    }
}

Banker.sol:

pragma solidity ^0.4.11;

import "./SilverCoin.sol";

contract Banker {
    function abc_1() constant returns (uint) {
        return SilverCoin.abc();
    }
}

Migration script for truffle:

var SilverCoin = artifacts.require("./SilverCoin.sol");
var Banker = artifacts.require("./Banker.sol");

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

Error:

$ truffle compile
Compiling ./contracts/Banker.sol...
Compiling ./contracts/SilverCoin.sol...

/path/to/file/contracts/Banker.sol:7:16: : Member "abc" not found or not visible after argument-dependent lookup in type(contract SilverCoin)
        return SilverCoin.abc();
               ^------------^
Compiliation failed. See above.

How do I fix this?


texts: Why are PoS (e.g. BSC) transactions costly?

texts:
How much may cost PoS transactions in such networks as future Ethereum mainnet or already existing BSC?
Why do BSC transfers cost $0.05?
Why doesn't gas cost about the cost of electricity used for the transaction by one node? There is only one validator per transaction in PoS. So the amount of electricity used is negligible. $0.05 seems very high and this confuses me.


texts: Proxy function clashing - what kind of danger comes exactly with it?

texts:
I read that if I am using proxy, there is a chance of function clashing. Let's say in my contract there is a function with a signature:

proxyOwner()
025313a28d329398d78fa09178ac78e400c933630f1766058a2d7e26bb05d8ea

Now, as I understand correctly, a hacker can perform a loop on his computer and create a special function with signature:

clash550254402()
025313a2bba9fda619061d44004df81011846caa708c8d9abf09d256021e23ee

Both signatures are same: 025313a2

What exactly can a hacker do with this? He can call the function directly anyway. What kind of danger comes with function clash? If my function isn't view, what unexpected can be happened?

In my contract in the proxy's update proxy address I'm checking if sender exist in the registry contract as an allowed to make any changes. Still, do I need to implement zeppelin's transparent proxy to prevent clashing? Why?


texts:
On a locally hosted instance of Ethererum I am trying to replay and understand the Bad Parity hack. I have a Wallet and a Wallet Library Contract.

Wallet.sol

constructor(address lib) public payable {
    walletLibrary = lib;
    walletLibrary.delegatecall(bytes4(keccak256("initWallet(address)")), msg.sender);
}

function () public payable {
    emit LogValue(301,msg.value);
    walletLibrary.delegatecall(msg.data);
}

I want to fetch all the coins by resetting the owner with the fallback Method.

WalletLibrary

function initWallet(address _owner) public payable {
   owner = _owner;
}

My idea is to call the fallback method with Remix with the following parameters:

bytes4(keccak256("initWallet(address)")), msg.sender);

I manually computed bytes4 and keccak with the web3 console, is this approach correct?


texts:
I'm trying to fetch the first account using web3.eth.accounts[0] using Truffle, but couldn't seem to make it work.

I'm using version 0.5.0. I read that the command is deprecated and have to use web3.eth.getAccounts() for asynchronous execution. The latter only displays an array of accounts connected to the local network.

How do I get a single account in this case? I wanted to pass { from: web3.eth.accounts[0] } metadata to a public function in my contract.


texts: Calculating AAVE intereset rate belonging to different users that transferred into a smart contract

texts:
I have a smart contract that accepts user funds and adds them to an AAVE lending pool (DAI for example). Something like this:
lendingPool.deposit(stableCoinAddress, amount, address(this), 0);

As you can see, smart contract receives minted aTokens. The above code can be called by many users with different deposit amounts at different times.
Later on, somewhere else in the same contract, users can redeem their funds at any arbitrary time with any amount up to their original deposit:
lendingPool.withdraw(stableCoinAddress, amount + interest, userAddress);

I need to calculate and add each user's interest in AAVE pool and add it to the original deposited value, but it sounds kind of complicated. Can anybody give me a hint? (or better than that, a usable piece of code!)


texts:
I created a private network using go-ethereum with 2 clien which are VMs(ubuntu 14.04).

On VM1, I created a contract:

N1greeterSource ='contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function changeMessage(string myMsg) returns (string){ greeting = myMsg; return myMsg; } function greet() returns (string) { return greeting; } }'
N1greeterCompiled = web3.eth.compile.solidity(N1greeterSource);
_greeting = "Hello world !";
N1greeterContract = web3.eth.contract(N1greeterCompiled.greeter.info.abiDefinition);
N1greeter = N1greeterContract.new(_greeting,{from:web3.eth.accounts[0], data: N1greeterCompiled.greeter.code, gas: 310000}, function(e, contract){
    if(!e) {

      if(!contract.address) {
        console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");

      } else {
        console.log("Contract mined! Address: " + contract.address);
        console.log(contract);
      }

    }
    else{
    console.log("Error:>>>>>>>>>>>>>");
    console.log(e);
    }

})

On VM2, I see contract by:

N1greeter = eth.contract([{ constant: false, inputs: [], name: "kill", outputs: [], type: "function" }, { constant: false, inputs: [{ name: "myMsg", type: "string" }], name: "changeMessage", outputs: [{ name: "", type: "string" }], type: "function" }, { constant: false, inputs: [], name: "greet", outputs: [{ name: "", type: "string" }], type: "function" }, { inputs: [{ name: "_greeting", type: "string" }], type: "constructor" }] ).at("0x526e636021fbfef1584097690798145ff32be21a");

Everything is OK.

But, I don't know how to VM2 can automaticlly find the contract? (find address and abi in VM1 to add this code: N1greeter = eth.contract(abi).at(address))

Thanks.


texts: Mist Wallet vs Account - How do I send ether from Wallet to exchange?

texts: I am on a mac using Mist. I have 1 ether in my account and a few more in my wallet. How do I send ether from my wallet to an exchange? I see that I can deposit bitcoin but I can't withdraw ether... Do I need to do this via the command line? When I hover over my wallet it reads "watch only" and in the top right hand corner it shows my account balance not my wallet balance. Any guidance is appreciated.


texts: What are the other 2 mnemonics represent for when I launch ganache?

texts: I download the Ganache on Windows, it gives me 10 accounts and 12 mnemonics when I launch it, I think that the first 10 mnemonics are represent for 10 accounts, but what are the other 2 mnemonics "subway" and "mouse" represent for? I cant catch that...so can anybody help me about this? Thanks!


texts: Gap in the block chain synchronization when interrupted

texts:
I was synchronizing the block chain with geth --fast --cache=1024. Then I got the message synchronization failed and I pressed CTRL+C because I had for some reasons to shutdown the VM [I am running several VMs on XenServer 6.5].

I noticed the last number: 558'400.

Then, after the same VM restarted I ran the synchronization command again and expected it will continue from the last number: ~558'400.
Surprisingly the first number which appeared was ~1'800'500.

My question:

Why this gap and am I wrong when I expected the starting number ~558'400?

Here a screenshot from the displayed information:

INFO .. Imported new state entries               count=500  elapsed=1ms        processed=7689495 pending=13579 retry=61  duplicate=284 unexpected=589
INFO .. Imported new block headers               count=2048 elapsed=6.299s     number=4891636 hash=23772e.3c586a ignored=0
INFO .. Imported new block receipts              count=26   elapsed=253ms      number=4854528 hash=0e47c8.c9be5a size=3.81mB   ignored=0
INFO .. Generating ethash verification cache     epoch=164 percentage=36 elapsed=6.418s
INFO .. Imported new block receipts              count=29   elapsed=234ms      number=4854557 hash=fe2e2a.fd00be size=3.86mB   ignored=0
INFO .. Imported new state entries               count=1195 elapsed=5ms        processed=7690690 pending=13169 retry=52  duplicate=284 unexpected=589
INFO .. Imported new block receipts              count=28   elapsed=292ms      number=4854585 hash=c50bbc.644e26 size=3.91mB   ignored=0
INFO .. Imported new block receipts              count=27   elapsed=186ms      number=4854612 hash=865a2f.e51e61 size=3.86mB   ignored=0
INFO .. Imported new state entries               count=1050 elapsed=5ms        processed=7691740 pending=12696 retry=0   duplicate=284 unexpected=589
INFO .. Imported new block receipts              count=26   elapsed=379ms      number=4854638 hash=65f38b.f2ae16 size=3.80mB   ignored=0
INFO .. Generating ethash verification cache     epoch=164 percentage=89 elapsed=9.463s
INFO .. Generated ethash verification cache      epoch=164 elapsed=10.146s
INFO .. Imported new block receipts              count=98   elapsed=869ms      number=4854736 hash=90e80c.2647ba size=13.99mB  ignored=0
INFO .. Imported new state entries               count=1041 elapsed=5ms        processed=7692781 pending=12391 retry=0   duplicate=284 unexpected=589


texts: Will existing smart contracts stop working if Solidity language changes?

texts:
In this article there is a claim that "if you change something in Solidity, existing smart contracts might stop working". With references to here and here.

It doesn't make much sense to me -- how changing the language could possibly affect EVM code on the net?


texts: How to fetch values from double mapping?

texts:
I have a structure data with double mapping for storing and fetching details. Here is the code :

struct data {
    uint a;
    uint b;
}
mapping(address => mapping(bytes11 => data[])) testidmapping;

Used storevalues() function to store and getvalues() to fetch the values

function storevalues(address owner,bytes11 id,uint a,uint b) public{
testidmapping[owner][id].push(data(a,b));
}

function getvalues(address owner,bytes11 id) view returns (uint a){
  data storage k = testidmapping[owner][id];
  return (k.a);

}

Is this the possible way of double mapping for fetching and storing details?
But I am getting this error:

  BigNumber() is not a number: (id is printing)

Help will be appreciated...


texts: How do dapps connect to blockchain network?

texts: Once the simple blockchain web applications runs on the web browser it uses the metamask to connect to the blockchain network, when it comes to mobile applications how the application connects to blockchain network ?


texts: Data location must be "memory" for parameter in function, but none was given

texts:
I code my solidity contracts and I test in Remix Web IDE. When I test and I not get errors I copy to my project folder in my local machine. And all this errors appear in Visual Studio Code.

I can migrate and compile with truffle and use. Without errors.

Who know´s what happening??


texts:
I'm trying to get the balance of a set of accounts using Parity RPC and web3.eth.getBalance.

The problem is that, some accounts are returning 0 even though they have balance.

For instance:
https://etherscan.io/address/0x5a87acb36e55da34fed0d7d3dcac9f5a3514b212 and
https://etherscan.io/address/0x3127c4157a1822934e76b47417127fcb3abc5958

If I do:

curl --data '{"method":"eth_getBalance","params":["0x5A87AcB36E55Da34fed0D7d3DCAC9f5A3514B212"],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:[port]

I get:

{"jsonrpc":"2.0","result":"0x0","id":1}

But if I do:

curl --data '{"method":"eth_getBalance","params":["0x3127c4157a1822934e76b47417127fcb3abc5958"],"id":1,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:[port]

I get:

{"jsonrpc":"2.0","result":"0x1a14b71b6fd3e5f","id":1}

Why could this be happening?
Do you have any insight about how to correct it?

I have the same problem with other accounts:
https://etherscan.io/address/0x9d3f63e177b488effdb86e27ffa57a93488fd249
https://etherscan.io/address/0xef345babf5639c2d5658bb2cce2f3361c1ed5063

Thanks!


texts: How to get transaction details from filter in web3.py

texts:
I am developing a software that listens for pending transactions.

...
web3 = Web3(HTTPProvider(cfg.eth_node_url))
web3_pending_filter = web3.eth.filter('pending')
transaction_list = web3.eth.getFilterChanges(web3_filter.filter_id)
...

In documentation of web3.py here is written that filter's getFilterChanges method should return transaction objects (list of dictionaries), but I am receiving list of hashes only. How can I get list of 'full' transactions from filter?


texts: Parity configuration for maximum throughput

texts:
What’s the recommended approach for configuring a private ethereum network using Parity to achieve the highest possible transaction throughput? Which is theoretically around 1000 TPS.

Let’s say my use case involves only one organization (one authority) and i have a single ERC20 contract for token transfer.

I need answers for the following:

Consensus/engine used
Number of nodes
Node/server specs
Chain specs file


texts: "Out of Gas" while transferring ethereum from account to contract

texts:
I am using ganache to create 10 ethereum accounts. I want to transfer ethereum from one account to a smart contract. I am doing this by writing two following smart contracts in solidity;

pragma solidity >=0.4.0 <0.6.0;
contract Ether_Transfer_To{
    function () external payable { //fallback function

    }
    function get_balance() public returns(uint){
        return address(this).balance;
    }
}
contract Ether_Transfer_From{
    Ether_Transfer_To private the_instance;
    constructor() public{
        //the_instance=Ether_Transfer_To(address(this));
        the_instance=new Ether_Transfer_To();
    }
    function get_balance() public returns(uint){
        return address(this).balance;
    }
    function get_balance_of_instance() public returns(uint){
        //return address(the_instance).balance;
        return the_instance.get_balance();
    }
    function () external payable {
        // msg.sender.send(msg.value)
        address(the_instance).send(msg.value);
    }
}

When I deploy the contract Ether_Transfer_From smart contract then I get its three-member functions as follows in remix;

But when I sent one 1 Wei from account to smart contract by writing 1 in the text box and clicking on a (fallback) button, then I get the following error;

  transact to Ether_Transfer_From. (fallback) errored: VM Exception while
  processing transaction: out of gas

I followed the answer of the same question by installing Ganache-cli 7.0.0 beta.0 by using following command;

  npm install -g ganache-cli@7.0.0-beta.0

But I still get the same error. I think I am using older Ganache cli instead of Ganache-cli 7.0.0 beta.0 as it goes to C drive and I installed ganache 2.1.1 in D drive previously.

I just want to send ethereum from one account to other but I am really stuck in this out of gas Error. If there is any way to remove this error or transfer ethereum from one account to another then please let me know.


texts: Nano S Ethereum Public Key and Chain Code

texts:
I'm trying to figure out how to get this repository (https://www.npmjs.com/package/@ledgerhq/hw-app-eth) to interact with the Nano S ledger, the hardware wallet.

I can't figure out what tools or technologies I need to call methods like:

import Eth from "@ledgerhq/hw-app-eth";
const eth = new Eth(transport)

eth.getAddress("44'/60'/0'/0/0").then(o => o.address)

So I can get a public key and chain code from the hardware wallet.


texts: How to use a contract after it has been deployed in migrations

texts:
I'm trying to us a contract in a truffle project.
This is part of a migration.js file.

deployer.deploy(token,companyID).then(function(){
    var starttime = web3.eth.getBlock(web3.eth.blockNumber).timestamp + 300000000;
    var endtime = starttime + 1000000;
    GG = token;
    return deployer.deploy(tokenICO, token.address, tokenwallet, rate, goal, tokenwallet, starttime, endtime).then(function()
    {

        console.log("token object: " + token);
        GG.approve(tokenICO.address,16000000);
    });
});

In this case I want to use the approve function of the token contract but
I get the following error:

TypeError: GG.approve is not a function
at (location)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)

Is there an alternative way of going about this?


texts: EIP150 testBlockchain RangeError: Maximum call stack size exceeded

texts:
ethereumjs-vm > npm run testBlockchain

TAP version 13
# BlockchainTests
# file: ContractCreationSpam test: ContractCreationSpam_d0g0v0_EIP150
ok 1 correct pre stateRoot
ok 2 correct genesis RLP

functional-red-black-tree/rbtree.js:904
  get: function() {
           ^

RangeError: Maximum call stack size exceeded
    at RedBlackTreeIterator.get

https://github.com/ethereumjs/ethereumjs-vm/pull/139/commits/20ae83596266bb240103f81d9115fca8137aa4ab

[Ran to completion with node --stack-size=XXXX] Please refer the commit to package.json in the link above by jwasinger to proceed with npm run testBlockchain with node v8.1.2


texts: IPFS Integration with dapp developed using Embark Framework

texts:
This is the contract code.

      pragma solidity ^0.4.2;

     contract SimpleStorage {
           uint storedData;
           function set(uint x) {
                          storedData = x;
           }
           function get() constant returns (uint retVal) {
                          return storedData;
           }
    }

This is the javascript code used (index.js)

        var addToLog = function(txt) {
              $(".logs").append("
" + txt);
        };

        $(document).ready(function() {

              $("button.set").click(function() {
              var value = parseInt($("input.text").val(), 10);
              SimpleStorage.set(value);
              addToLog("SimpleStorage.set(" + value + ")");
       });

       $("button.get").click(function() {
              SimpleStorage.get().then(function(value) {
                 $(".value").html(value.toNumber());
             });
             addToLog("SimpleStorage.get()");
     });

   });

This is the code for html file(index.html)

                <title>Embark - SimpleStorage Demo</title>
                <link rel="stylesheet" href="css/app.css">

Embark - SimpleStorage Demo

 1. Set the value in the blockchain

                         <input type="text" class="text form-control" >
                         <input type="text" class="text form-control">
                         <button class="set btn btn-primary">Set Value</button>

 2. Get the current value

                        current value is

               <button class="get btn btn-primary">Get Value</button>

 3. Contract Calls

Javascript call being made:

I am trying to integrate ipfs for storing 'x' in ipfs.I am using embark framework for developing the dapp.

I have installed ipfs-api using npm as follows.

         npm install --save ipfs-api

Then i have updated the above index.js with following lines

           var ipfsAPI = require('ipfs-api')

           // connect to ipfs daemon API server
           var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'})

what are the further modifications required in index.js and index.html files for storing and retrieving the value using ipfs?


texts:
For Ganache, there are several solutions.
What about Hardhat? They implemented their own local blockchain, Hardhat Network, which is different to Ganache.


texts:
i am new to this site and i am glad i found it, hopefully someone can help me.
So this morning i tries to swap some usdt to etherium, but i didnt go through, i got to error messages and four different fees, my wallet it's showing 0 balance so I don't know where it went. Here is the transaction and hope someone can help me.
Thanks!!!
transaction hash: 0x4634a153793b58d270233b7e80b75e3ff96d2ba39b80e56e6fb8df71e166ed89
Contract: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D


texts: Are there Ethereum Level 2 Rollup scaling solutions that support ERC-1155?

texts:
I've been doing my research on Level 2 Scaling solutions in general and docs are generally pretty lacking in detail. Usually, they just state general ideas and I'm looking for examples and concrete integration guides.
Basically, I'm looking for a Zk-rollup scaling solution that can process ERC-1155 transactions when the ERC-1155 itself would be deployed on Level 1. I've looked at StarkEx, Aztec 2.0, zkSync, and a couple of others but they either have little documentation on this or their allowed tokens list only includes some ERC-20 tokens.
Do you know about such a scaling solution? If yes, I would appreciate if you link me a website and docs, please.


texts:
I am trying to work through the https://ethereum.org/token#improved-coin tutorial. I deployed the contract to testnet. Initialized tokens, set the buy and sell price. Now, one of my accounts has 50 tokens. I am trying to sell some tokens by calling

  >contractInstance.sell(10)
  '0x936906cddd13155cf3a5be090363aa4b1a6f909ebd556e80cbb8e01234c52e80'

This results in a [Bad jump destination] error. You can see the transaction here: https://testnet.etherscan.io/tx/0x936906cddd13155cf3a5be090363aa4b1a6f909ebd556e80cbb8e01234c52e80

Here is the entire source code: https://gist.github.com/anonymous/e40d6a7433431776c7c0ff330eaee126

How do I debug this issue?


texts: Kinda stuck, seeking guidance, can't see/find ETH

texts:
Series of events:

Got excited about Ethereum and began to download Ethereum Wallet (7/14/2016)
When prompted (before blockchain synched), I transferred about 2 BTC to my "Master Account" in three separate transfers (within about a 4 hour period)
Blockchain continued to synch (at about 6000 blocks per minute)
Flipped back and forth between menus talking about recipes for crowdfunding/DAO/currency... Then went to far "back" and reached the "create account" page at the front...
The only way to proceed was to create another account, so I did. (I later learn that this public key is now a secondary account after my Master Account)
Because I created 2 accounts (on accident, really), the blockchain began synching A SECOND TIME, and has been MUCH MUCH SLOWER (60 blocks a minute).  At this rate, it will take over 10 days to synch if running continuously
When I launch the Wallet (after a break from synching), then "skip" to the application, I can see that there are 2 accounts... The Master Account and the second account I accidentally created.  Both accounts show 0 ETH

Question:

Where are my ETH?  Do I need to wait for blockchain to finish synching before the ETH will be visible in the Ethereum Wallet?  If so, what can I do to speed up the synching process?


texts: How to get same prices with Uniswap SDK & interacting directly with contract?

texts:
I am having difficulty understanding getting the price within the contract. So I created 2 different methods (one using SDK and other one using ethers.js)

When I try the SDK, I get 3839.62
When I try with ethers.js, I get 55561073443426097 so it's not just decimal difference :/

let chainId = ChainId.MAINNET;
const dai = await Fetcher.fetchTokenData(chainId, '0x6B175474E89094C44Da98b954EedeAC495271d0F')
const weth = WETH[chainId]

const pair = await Fetcher.fetchPairData(dai, weth);
const route = new Route([pair], weth)
const trade = new Trade(route, new TokenAmount(weth, '100000000000000000'), TradeType.EXACT_INPUT);

console.log(trade.executionPrice.toSignificant(6)); // 3839.62

const provider = new ethers.providers.getDefaultProvider();
const weth = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
const dai = '0x6B175474E89094C44Da98b954EedeAC495271d0F'

let uniswapRouter = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';

const routerABI = [
'function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB)',
'function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut)'
]

let factoryContract = new ethers.Contract(uniswapRouter, routerABI, provider);
let price = await factoryContract.getAmountOut('100000000000000000', weth, dai)
console.log(price.toString()); // 55561073443426097

By integrating the contract, how can I get the price? Is there a method in contracts like: getPrice(tokenAAmount, tokenA, tokenB) returns (tokenBAmount)

Update: I can get the midprice using
let pairAddress = '';

const pairABI = [
'function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast)'
]

let pairContract = new ethers.Contract(pairAddress, pairABI, provider);
let reserves = await pairContract.getReserves();
let price = Number(reserves._reserve0) / Number(reserves._reserve1)

console.log(price.toPrecision(6)); // mid price


texts:
Is there any trace or possibility to understand who executed the attack?
What do we know? Heres some:

The attacker had at least 25,805.6141471 DAO tokens. All on one address?
The attacker executed the attack between time x and time y? What does this imply?
...


texts:
contract Vuln {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        // Increment their balance with whatever they pay
        balances[msg.sender] += msg.value;
    }

    function withdraw() public {
        // Refund their balance
        msg.sender.call.value(balances[msg.sender])("");

        // Set their balance to 0
        balances[msg.sender] = 0;
    }
}


texts: How can i know my smart contract , compilar version.I cant verify my contract properly

texts: I want to know compilar version of my smart contract.(https://i.stack.imgur.com/6K5sM.png)


texts: Can an Ethereum token be bound or pegged to the value of the gold?

texts: Could a token be built in ethereum that its price would be bound or pegged to lets say .00006 times the price of an once of gold?


texts: Solidity test: Contract calling another Contract and addresses are different

texts:
I have a wrapper contract that instantiates and calls another contract, and my test cases say the owners (msg.sender)s don't match. Why?

contract A

pragma solidity ^0.4.4;

contract A {

    function A() {
    }

    function createB(string name) {
        return new B(msg.sender, name);
    }
}

contract B

pragma solidity ^0.4.4;

contract B {
    address owner
    string public name;

    function B(address _owner, string _name) {
        owner = _owner;
        name = _name;
    }
}

test case

pragma solidity ^0.4.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";

contract TestB {
    B testB;
    A testA;

    function beforeEach() {
        A = A(DeployedAddresses.A());
        B = testA.createB("test");
    }

    function testOwnerIsSet() {
        Assert.equal(address(A), address(B), "Owner's address does not match");
    }
}

Test Results

 1) TestB testOwnerIsSet:
     Error: Owner's address does not match
      at /Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214233:17
      at Array.forEach (native)
      at processResult (/Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:214231:19)
      at process._tickCallback (internal/process/next_tick.js:109:7)

EDIT

I have added the address public owner to contract A. And made owner public in contract B.

And now my TestB contract looks like this:

pragma solidity ^0.4.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/B.sol";

contract TestB {
    B testB;
    A testA;

    function beforeEach() {
        A = A(DeployedAddresses.A());
        B = testA.createB("test");
    }

    function testOwnerIsSet() {
        address aOwner = A.owner();
        address bOwner = B.owner();
        Assert.equal(aOwner, bOwner, "Owner's address does not match");
    }
}


texts: what is the difference between Swarm and BigchainDB?

texts: Are both Swarm and BigchainDB complementary to ethereum or do they function independently? What are their applications?


texts:
I have a very beginner level question. Suppose I have a list containing the IP address of different machines and I want to share them via ethereum blockchain and suppose that the list is very large as the time passes, how much time it will take to share with other nodes and add into the block?
Does it take 14 seconds irrespective of list size or what?
If any reference available that would be great. Please help.


texts:
Intro
Basically I have a contract that overrides the transfer function in IERC20.
Contract TokenA is IERC20{
   function transfer(address recipient, uint256 amount) public override returns (bool) {
       (uint256 _majority, uint256 _minority) = _getUValues(amount);
       _transfer(_msgSender(), recipient, _majority); // sends the majority of tokens (80%) to the recipient
       _transfer(_msgSender(), _addressB, _minority); // sends the minority of tokens (20%) to address B
   }
}

This transfer function sends 80 percent of the tokens to person A, and sends the remaining 20 percent of the tokens to person B.
Current Dependencies:
Hardhat
hardhat-waffle
hardhat-ethers
mocha
chai
tokenA.test.ts
import { ethers, waffle } from "hardhat";
import { expect, use } from "chai"
import { BigNumber, Contract, Wallet, EventFilter } from "ethers"
import { TransactionResponse, TransactionReceipt } from "@ethersproject/abstract-provider"
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"
import TOKENA from "../artifacts/contracts/TOKENA.sol/TOKENA.json"
import IERC20 from "../artifacts/contracts/TOKENA.sol/IERC20.json"

const { deployContract, deployMockContract } = waffle

describe("Owner to Wallet (No VIP)", async () => {

    const provider = waffle.provider
    const wallets: Wallet[] = provider.getWallets()
    let tokenA: Contract
    let mockERC20: Contract

    let amountSent: BigNumber

    let transferEvent: EventFilter

    let receipt: TransactionReceipt
    let receipt_2: TransactionReceipt
    let response: Promise<TransactionResponse>

    const wallet1 = wallets[0] // owner (from)
    const wallet2 = wallets[1] // transfer 20% (to)
    const wallet3 = wallets[3] // transfer 80% (to)
    const wallet4 = wallets[4] // random guy

    beforeEach("transfer", async () => {
       response = await tokenA.transfer(wallet3.address, 1000000)
       receipt = await (await response).wait()
    })

    describe("emits two Transaction events", async () => {
       it("owner(sender) to wallet3 (No VIP) | 80% transfer", async () => {
          await expect(receipt).to.emit(tokenA, "Transfer").withArgs(wallet1.address, wallet3.address, 800000)  // the 800000 value is not the exact amount sent so the test fails
       })
       it("owner(sender) to wallet2(receiver) | 20% fee", async () => {
          await expect(receipt).to.emit(tokenA, "Transfer").withArgs(wallet1.address, wallet2.address, 200000)
       })  // the 200000 value is not the exact amount sent so the test fails
    })
})

Question:
How do I write a unit test with Mocha/Waffle to see if the transaction sends the correct amount of tokens to each person? Verifying that the sender sent the proper amount of tokens to each user, and/or that the users received the proper amount of tokens.


texts: How to calculate Estimated Confirmation Duration of a pending transaction?

texts:
How I can calculate Estimated Confirmation Duration

or

Can someone give me a formula to calculate Estimated Confirmation Duration of a pending transaction like etherscan.io do?


texts: How to check if a pending transaction nonce has duplicate?

texts: Is there a web3 function or other workaround to check if the pending tx has duplicate nonce?


texts: Truffle Error: VM Exception while processing transaction: revert

texts:
Issue:Not able to return the input string(ofcourse it works in remix). Below is the contract.

pragma solidity ^0.4.17;
    contract samplecontract {
    function viewuserName(string name) public returns(string){
    return (name);
}
}

index.html:

<input id="txtdummyName" type="text" placeholder="Enter  sometext" />
<button id="btnViewUserName" onclick="App.viewUserName()">View userName</button>

when i click on the "View userName" button, ie., when i try to call the viewUserName in app.js in truffle it logs Error: VM Exception while processing transaction: revert. I tried the following commented ways too.! Also tried console.log(v.toString()) How to identify the issue?

app.js:

viewUserName:function(){
var sometext=document.getElementById("txtdummyName").value;
sampleinstance.deployed().then(function (instance) {
  console.log(sometext);
  // return instance.viewuserName.call(sometext).then(function(v){
  //   console.log(v);
  // })
  // return instance.viewuserName.call(sometext,{gas: 540000, from: web3.eth.accounts[0]}).then(function(v){
  //   console.log(v);
  // })
  // return instance.viewuserName(sometext,{gas: 540000, from: web3.eth.accounts[0]}).then(function(v){
  //     console.log(v);
  // })
  // return instance.viewuserName(sometext).then(function(v){
  //   console.log(v);
  // })
  return instance.viewuserName(sometext,{from: web3.eth.accounts[0],gas: 1540000}).then(function(v){
    console.log(v);
  })
})

Any help would be appreciated.

Thanks.


texts: How to include constructor arguments in bytecode for smart contract deployment in genesis block?

texts:
Please excuse if the title is not perfectly accurate but I had a hard time fitting my problem into 1 question. If you have a better title please feel free to suggest it and i will edit it.

I want to "deploy" a smart contract in the genesis file of my blockchain so that the contract is available when creating the chain.

Problem: The smart contract requires a constructor argument that I have to include in the bytecode.
When I compile the smart contract in Remix with the arguments set, it works perfectly fine.

Unfortunately, I'm working on a Ubuntu VM so using Remix to compile the contract is not an option.

Any suggestions?


texts: How long does it take for the ethereum blockchain to synchronize?

texts: For the past few days I've been synchronizing my mist wallet with the blockchain (using geth). My laptop has been working all day and all night. I've already synced more than 880000 blocks. How many more blocks do I need to download?


texts: When are “pending” transactions dropped from the blockchain?

texts:
When are transactions dropped from the blockchain?

Suppose I broadcast a transaction to the blockchain, then it is a pending transaction waiting to be mined.

But when are pending transactions dropped from the blockchain, e.g., if the gas price is too low? Can someone think of other reasons for miners not willing to include the transaction?

If transactions are not discarded at some point, then an enormous amount of pending transactions could result.


texts:
I started with geth wallet the first time. Got to near the finish and it started itself over at the beginning. The last four times have been with parity, which seems to queue forevever and then crashes with a fatal memory error.
have tried parity with geth option and without.
Have installed latest versions of wallet and parity. Ubuntu 16.04
Started Oct 1. last crash today 10/15

trying now with docker/win10


texts: Best way to record document hash and address (mapping vs transaction input data)

texts:
First of all, sorry if the question is too open, is not a coding problem but a design decision.
I'm doing a bit of research about storing a proof of a document existence (a hash of the document) in Blockchain, and I want to ask you which of these 2 options is better to store a hash of a document, related to an address (to show property of the document at the time of).
My main objective is to let users to record proof of ownership of their Ethereum address over documents, without depending of my Dapp to verify it.
I think there are 2 main alternatives:

Store the hash as a message to be available in the input data field of an Ethereum transaction:
fallback() external

Store the hash in a mapping of an Smart Contract
mapping(dochash => address) documents;

The first option provides a quick way to see the hash of the document and relate it to the "from"  address field (in Etherscan with transaction ID, for example).
I know that it would be a more elegant way to store the document hash and the sender address in a Solidity mapping, but someone would need a Dapp connected with the Smart Contract ABI to verify the hash, and if the Smart Contract logic allow it, the mapping value could be updated (it should require an Smart Contract audit to be sure).
Maybe the most interesting solution would be to combine both? Store hash in message, while also in Smart Contract mapping, for a Dapp to manage the verification?


texts:
When withdrawing funds from a smart contract send returns a boolean

function withdrawFromContract(uint amount) onlyOwner returns(bool success) {
    if(amount > this.balance) throw; // not enough money
    if(msg.sender.send(amount)) {
        LogWithdrawal(amount);
        return true;
    } else {
        throw;
    }
}

under what circumstances would send return false?


texts: How could I measure the total delay (time) to confirm the transaction?

texts:
First of all, I'm new to the Erthereum world, I need some help in measuring the total delay (time) require for confirming the transaction.
I have a decentralized application over a Rinkeby network, and I want to know, how long the process will take until confirming the transaction?

I have been read in many papers that a total delay is 10 seconds, 15 seconds, 5.5 sec...etc
My question:

How they measure these numbers "10 sec,15 sec..etc"?
Is it manually, or there is a specific tool or way for measuring the total delay (time).


texts: Build failed SyntaxError: Unexpected token: name (length)

texts:
I setup truffle unbox react-auth and add few libraries as shown in my package.json below.

I have no problem running npm run start but failed to compile npm run build with the following error:

SyntaxError: Unexpected token: name (length) [./~/idna-uts46-hx/~/punycode/punycode.js:55,0]

 {
  "name": "react-auth-box",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "autoprefixer": "6.5.1",
    "babel-core": "6.17.0",
    "babel-eslint": "7.1.1",
    "babel-jest": "17.0.2",
    "babel-loader": "6.2.7",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react-app": "^2.0.1",
    "babel-preset-stage-2": "^6.24.1",
    "babel-register": "^6.26.0",
    "case-sensitive-paths-webpack-plugin": "1.1.4",
    "chalk": "1.1.3",
    "connect-history-api-fallback": "1.3.0",
    "cross-spawn": "4.0.2",
    "css-loader": "0.26.0",
    "detect-port": "1.0.1",
    "dotenv": "2.0.0",
    "eslint": "3.8.1",
    "eslint-config-react-app": "^0.5.0",
    "eslint-loader": "1.6.0",
    "eslint-plugin-flowtype": "2.21.0",
    "eslint-plugin-import": "2.0.1",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "6.4.1",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.9.0",
    "filesize": "3.3.0",
    "fs-extra": "0.30.0",
    "gzip-size": "3.0.0",
    "html-webpack-plugin": "2.24.0",
    "http-proxy-middleware": "0.17.2",
    "jest": "18.1.0",
    "json-loader": "0.5.4",
    "object-assign": "4.1.0",
    "path-exists": "2.1.0",
    "postcss-loader": "1.0.0",
    "promise": "7.1.1",
    "react-dev-utils": "^0.4.2",
    "recursive-readdir": "2.1.0",
    "strip-ansi": "3.0.1",
    "style-loader": "0.13.1",
    "truffle-contract": "^1.1.8",
    "url-loader": "0.5.7",
    "webpack": "1.14.0",
    "webpack-dev-server": "1.16.2",
    "webpack-manifest-plugin": "1.1.0",
    "whatwg-fetch": "1.0.0"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.6",
    "@fortawesome/free-solid-svg-icons": "^5.4.1",
    "@fortawesome/react-fontawesome": "^0.1.3",
    "babel-preset-env": "^1.7.0",
    "bootstrap": "^4.1.3",
    "history": "^4.7.2",
    "immutable": "^4.0.0-rc.12",
    "ipfs-mini": "^1.1.2",
    "moment": "^2.23.0",
    "openzeppelin-solidity": "2.1.1",
    "papaparse": "^4.6.1",
    "prop-types": "^15.6.2",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.2",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^4.0.7",
    "react-toasts": "^2.0.14",
    "reactstrap": "^6.5.0",
    "redux": "^3.6.0",
    "redux-auth-wrapper": "^1.0.0",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0",
    "web3": "^1.0.0-beta.37"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom"
  },
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.js?(x)",
      "<rootDir>/src/**/?(*.)(spec|test).js?(x)"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx"
    ]
  },
  "babel": {
    "presets": [
      "react-app",
      "es2015",
      "stage-2",
      "stage-3"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}


texts:
I have a function that iterate through an array, which could cost a lot of gas. But I still want to test out the estimate gas cost, then decide if I should maintain the design or not.

function giveAwayDividend(uint amount) onlyOwner payable {
for(uint i=0;i<size();i++){
    customerAddress[i].call.value((balances[customerAddress[i]] * amount * 100) / totalSupply)();
}}

If I test out on testnet, I have to manually create over 1 thousand user account and send each of them some token, which seems stupid. Is there a better way to calculate the gas cost?
For example, if the cost is linear, I could calculate the cost for one customer then multiple by the number of customers. Question is, I dont think its linear, can someone shed some light on this?


texts: How to estimate gas in an address with no ETH at all

texts:
Say I have received an ERC20 token in my address. Such address has no ETH and no other tokens except the one I just received. If I try to estimate the gas cost of sending the token from that address, the mocked transaction fails because there's not enough gas to run the simulation.

I need the gas estimation in order to know approximately how much ETH I have to send from another address in order to collect the ERC20 funds, but I cannot run the estimation because I have no ETH... so it's a cyclic problem.

Any known solution for this problem?


texts: Why do we have to put 'hex' at the end of this function? Buffer.from('key' , 'hex')

texts: I know that this line of code: Buffer.from('key', 'hex') Converts a string into its binary representation. My question is: what does adding the 'hex' at the end do? I am confused, since the key is already in hexa-decimal, why would we want to specify that if the function can work on any string?


texts:
I/ve downloaded Atom.

Regardless of which solidity package I download, install and enable, it doesn't seem to work ie. I don't see any syntax checking, highlighting, correcting etc...

Do I need to pre-install something aside from the Atom editor? I'm only interested in local correct solidity syntax editing

tx/tony


texts:
What is the difference between this two? I understand that Ganache is like a fake blockchain, but Truffle has that too ?

What are the limitations of each and under which circumstance we use either of them ?


texts: Easiest Framework to build a quick POC Daap

texts:
So I'm trying to build the most simple Daap to make a POC. I just want to register messages/strings on a block so that any given duplicate messages are ignored.

I've done a lot of research but I'm overwhelmed by the information there's available. The problem I'm having is to have a decent test net/private net to test my application.

I've tried Hyperledger Fabric but there are some broken issues and it requires a lot of stuff that I don't yet fully understand (like docker and vagrant for instance)

I made a lot of progress working with Go-Ethereum framework which I can use the Web3j API to send my requests. But for some reason, I'm having difficulty now connecting to a ROPSTEN network or even creating a private network to test(using $geth --testnet or $geth --rpc and every possible combination). It just won't start or it will take too long and then it connects to Ethereum Blockchain which is not what I want(for now).

So does anyone know some framework or even a simple way to create our private network without geth?

I just need to initialize a private-net that I can use with web3j, then everything will fall into place.

Thank you in advanced.


texts:
I recently installed ethminer from the new active repository: https://github.com/ethereum-mining/ethminer

ethminer --version returns:

ethminer version 0.11.0.dev0
Build: Linux/g++/Release

My OS version is ubuntu 16.04 with kernel version 4.4.0-83-generic.
I have an Intel Skylake graphic card, and OpenCL 1.2 installed with beignet 1.1.1. llvm 3.8-33 is also installed

When running ethminer in benchmarking mode (-M option), I faced this issue:

> ethminer -M -G
[OPENCL]:Found suitable OpenCL device [Intel(R) HD Graphics Skylake ULT GT2] with 2147483648 bytes of GPU memory
Benchmarking on platform: CL
Preparing DAG for block #0
Warming up...
  ℹ  14:14:09|openclminer0  set work; seed: #00000000, target:  #000000000000
  ℹ  14:14:09|openclminer0  Initialising miner...
[OPENCL]:Using platform: Intel Gen OCL Driver
[OPENCL]:Using device: Intel(R) HD Graphics Skylake ULT GT2(OpenCL 1.2 beignet 1.1.1)
ASSERTION FAILED: Not implemented
  at file /build/beignet-5qGeBM/beignet-1.1.1/backend/src/llvm/llvm_scalarize.cpp, function bool gbe::Scalarize::scalarizeExtract(llvm::ExtractElementInst*), line 722
[1]    2772 trace trap (core dumped)  ethminer -M -G

How can I fix this?


texts: get address of contract which called other contract

texts:
What are some ways to get address of contract which called a contract ?

For example, does msg.sender pass the address of the account which invoked callCanOnlyBeCalledByB(), or the address of B ?

contract A {
    address B; //set by other mechanism
    function canOnlyBeCalledByB() external {
        if(msg.sender == B) { do thing }
    }
}

contract B {
    address owner; //set by other mechanism
    address A; //set by other mechanism

    function callCanOnlyBeCalledByB() {
        if(msg.sender != owner) throw;
        bytes4 functionSig = bytes4(sha3("canOnlyBeCalledByB()"));
        A.call(functionSig);
    }
}


texts: how to configure the listening interface or IP address for geth?

texts:
I have multiple network adapters (with virtual IP addresses on each) on my box and I want to run geth on a certain network interface with a certain IP address. How do I do this? Can't find the parameter.

--port is for port only, but where is the --ip option ? (or --device)


texts: How can fix in smart contract written in solidity?

texts:
TypeError: Invalid type for argument in function call. Invalid implicit conversion from address to address payable requested.
          selfdestruct(admin);

pragma solidity >=0.4.21 <0.6.0;
import "./DappToken.sol";
contract DappTokenSale{
    address admin;
    DappToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor(DappToken _tokenContract, uint256 _tokenPrice) public {
        //Assign an admin
        admin = msg.sender;
        //token Contract
        tokenContract = _tokenContract;
        //Token Price
        tokenPrice = _tokenPrice;
    }
    // multiply function
    function multiply(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x);
    }
    // Buy Token
    function buyTokens(uint256 _numberOfTokens) public payable{
        // Reqiured that value is equal to tokens
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        // Required that the contract has enough token
        require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        // Required that a trnasfer is successfuly
        require(tokenContract.transfer(msg.sender,_numberOfTokens));
        // keep track of number of token sold
        tokensSold += _numberOfTokens;

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

    // Ending Token DappTokenSale
    function endSale() public {
        // Require admin
        require(msg.sender == admin);
        // Transfer remaining dapp token to admin
        require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
        // UPDATE: Let's not destroy the contract here
        // Just transfer the balance to the admin
        // admin.transfer(address payable(this).balance);
        // selfdestruct(address payable admin);
        // selfdestruct(address payable admin);
        //address payable adminAddress = address(uint160(admin));
        selfdestruct(admin);
    }
}


texts:
Looking at the code of OpenZeppelin's Ownable, I see this public field:

contract Ownable {
  address public owner;
  :
}

Can owner be changed from web3 or other contracts? I would guess no, since it would be a security hole.

Does it means that public fields can be accessed only by the contract itself? (something like a public getter and an internal setter)

Can I define something like:

contract MyContract {
  Person[3] public persons;
  :
  struct Person {...}
}

And be sure that the array can be read and cannot be written by any client?


texts:
Does ethereum node supports SSL (https) JSON-RPC connections like in Bitcoin? is there any work on control access over ethereum rpc nodes?
Thank you


texts: How can I set my custom gas Price and gas Limit?

texts:
I want to set my custom gas and gas Price in sendTransaction method.Currently I set it but when i send the transaction gas fee is showing 0.21 ETH in metamask. How can I solve this?

web3.eth.sendTransaction({
   from: currentAccount,
   to: toAddress,
   value: web3.toWei(value, 'ether'),
   gasPrice: web3.toWei("0.00001" , 'ether'),
   gasLimit: '21000',
   chainId: '0x1'
}

Above is my code. How can I solve it?


texts: Installation of pyethapp fails on Raspberry Pi

texts:
I'm trying to install pyethapp on Raspberry PI B+

sudo pip install  pyethapp getting error

Complete output from command python setup.py egg_info:
Couldn't find index page for 'pytest-runner' (maybe misspelled?)
No local packages or download links found for pytest-runner>2.0,<3
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-U_2TGJ/devp2p/setup.py", line 56, in <module>
    tests_require=test_requirements
  File "/usr/lib/python2.7/distutils/core.py", line 112, in setup
    _setup_distribution = dist = klass(attrs)
  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 221, in __init__
    self.fetch_build_eggs(attrs.pop('setup_requires'))
  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 245, in fetch_build_eggs
    parse_requirements(requires), installer=self.fetch_build_egg
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 576, in resolve
    dist = best[req.key] = env.best_match(req, self, installer)
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 821, in best_match
    return self.obtain(req, installer) # try and download/install
  File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 833, in obtain
    return installer(requirement)
  File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 294, in fetch_build_egg
    return cmd.easy_install(req)
  File "/usr/lib/python2.7/dist-packages/setuptools/command/easy_install.py", line 602, in easy_install
    raise DistutilsError(msg)
distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('pytest-runner>2.0,<3')

I already have pytest-runner installed :

$sudo pip install  pytest-runner==2.12.1
Successfully installed pytest-runner-2.12.1
$ls -l /usr/local/lib/python2.7/dist-packages/
drwxr-sr-x  2 root staff 4096 Jan 15 20:33 pytest_runner-2.12.1.dist-info
$ sudo python --version
Python 2.7.3
$ sudo pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)


texts: ethereum-go how to get the latest block?

texts:
I've set up a private local Ethereum node with just a genesis block I made, and I have this Go code I want to run on the private local network:

package main

    import (
        "fmt"
        "math/big"

        "github.com/ethereum/go-ethereum/rpc"
    )

    type Block struct {
        Number *big.Int
    }

    func main() {
        // Connect the client
        client, err := rpc.Dial("http://localhost:8000")
        if err != nil {
            panic(err)
        }

        var lastBlock Block
        if err := client.Call(&lastBlock,
            "eth_getBlockByNumber",
            "latest"); err != nil {
            fmt.Println("can't get latest block:", err)
            return
        }

        // Print events from the subscription as they arrive.
        fmt.Println("latest block:", lastBlock.Number)
    }

It compiles fine, but when I run it I get this error: can't get latest block: missing value for required argument 1

I'm passing in "latest", which is a valid argument for the RPC call according to the docs.

I tracked down the error output to this file and it seems the string is getting converted to nil and the RPC call is failing. Does anyone know what's going on here or how to fix this weird issue?


texts: Is there a limit to the length of dynamic arrays that can be returned by Solidity?


texts: Send ether reentrancy attack in reality - how could fallback function make a message call back into current contract?

texts:
Below is quoted from solidity docs:

pragma solidity ^0.4.0;

// THIS CONTRACT CONTAINS A BUG - DO NOT USE
contract Fund {
    /// Mapping of ether shares of the contract.
    mapping(address => uint) shares;
    /// Withdraw your share.
    function withdraw() {
        if (msg.sender.send(shares[msg.sender]))
            shares[msg.sender] = 0;
    }
}

The problem is: Ether transfer always includes code execution, so the recipient could be a contract that calls back into withdraw. This would let it get multiple refunds and basically retrieve all the Ether in the contract.

To avoid re-entrancy, you can use the Checks-Effects-Interactions pattern as outlined further below:

pragma solidity ^0.4.11;

contract Fund {
    /// Mapping of ether shares of the contract.
    mapping(address => uint) shares;
    /// Withdraw your share.
    function withdraw() {
        var share = shares[msg.sender];
        shares[msg.sender] = 0;
        msg.sender.transfer(share);
    }
}

The highlighted part is where I have question: I do understand that in theory reentrancy attack exists, but given the fact that fallback function has 2300 gas limitation (link),  which is not enough to make a message call back into current contract.  So in reality, how could the reentrancy attack work? Can some expert give an live example? Thanks!


texts: What is the difference between transaction cost and execution cost in remix?

texts:
What is the difference between transaction cost and execution cost as seen after contract instantiation in remix?

I don't think it matters, but here is my contract:

contract DepositCounter {
    uint deposits = 0;
    function() {
        deposits++;
    }
}


texts: How to pull data from DeFi Liquidity Pools

texts:
I am relatively new to decentralised development, and apologies in advance if a bit of a dumb question.
I am doing a project where I am looking to download the following data. I am trying to figure out what is the best way to do it and a bit lost with available options.

Current yield on ETH deposits
Reward token mechanism for providing
USDC/USDT pair liquidity
Size of liquidity pool for USDC/USDT pair
Historical daily closing price data for ETH

I am using Golang and looking to pool data from Uniswap, Curve, Balancer, and Aave to compare it.
Options I have considered are:

TheGraph + Golang through JSON: all of these pools have a subgraph. Disadvantage is data is in different format for each pool and availability is different. For example I can pull size of liquidity pools from Uniswap, but not from Balancer
Custom API: Uniswap has a full on Javascript API which is very good. Disadvantage is that Curve doesn't have a comparable API and this presents an integration issue using several different languages for pulling data
Straight from the blockchain using Solidity: I've not really been able to figure out how to pull this data since some of it is not specific to an exact smart contract.

Would really appreciate any help, if you could point me in the right direction on where to look.
Thank you very much!


texts: Correctly deploying contracts with web3 1.0 and testrpc (invalid opcode error)

texts:
I followed the following tutorial:
https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2

Now this tutorial is not using the recent version of web3 but I tried to solve this with the web3 documentation.

This is how far I got:

>byteCode = compiledCode.contracts[':Voting'].bytecode
>deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data:   byteCode, from: web3.eth.accounts[0], gas: 4700000})
>deployedContract.address
>contractInstance = VotingContract.at(deployedContract.address)

I successfully compiled the byteCode and deployed the contract in the following way:

> VotingContract.deploy({ data: byteCode, arguments: [[web3.utils.asciiToHex("name1"),web3.utils.asciiToHex("name2"),web3.utils.asciiToHex("name3")]] }).send({ from: acc1, gas: 4700000, gasPrice: '3000000' }).on('confirmation', function(confirmationNumber, receipt){console.log(confirmationNumber + ' ' + receipt) }).then(function(instance) {contractInstance = instance});

Now I should have a contract instance, shouldn't I? Or is this something else? The author goes on to do the following:

>contractInstance = VotingContract.at(deployedContract.address)

I did this instead:

  var contract3 = new web3.eth.Contract(byteCode, contractInstance.options.address, {from: acc1, gasPrice:'3000000'});

Now if I try to call methods on this contract like:

  contract3.methods.totalVotesFor(web3.utils.toHex('name1')).call(acc1).then(function(returned, err) {console.log(returned + ' ' + err)});

I receive the following response:

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> Unhandled rejection Error: Returned error: Error: VM Exception while executing eth_call: invalid opcode
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:59368:17
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:69306:5
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:11335:9
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:7895:16
    at replenish (C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:8415:25)
    at iterateeCallback (C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:8405:17)
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:8380:16
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:11332:13
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:69302:9
    at C:\Path\node_modules\ethereumjs-testrpc\build\cli.node.js:63982:7
    at Object.ErrorResponse (C:\Path\node_modules\web3-core-helpers\src\errors.js:29:16)
    at C:\Path\node_modules\web3-core-requestmanager\src\index.js:137:36
    at XMLHttpRequest.request.onreadystatechange (C:\Path\node_modules\web3-providers-http\src\index.js:64:13)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Path\node_modules\xhr2\lib\xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (C:\Path\node_modules\xhr2\lib\xhr2.js:354:12)

What might I be doing wrong?

Thanks for your help!


texts: Who pays for the gas in Plasma contracts

texts:
I've been looking at the OmiseGo Plasma-MVP,

And the finalizeExits() looks like this :

    // @dev Loops through the priority queue of exits, settling the ones whose challenge
    // @dev challenge period has ended
    function finalizeExits()
        public
    {
        uint256 utxoPos;
        uint256 exitable_at;
        (utxoPos, exitable_at) = getNextExit();
        exit memory currentExit = exits[utxoPos];
        while (exitable_at < block.timestamp && exitsQueue.currentSize() > 0) {
            currentExit = exits[utxoPos];
            currentExit.owner.transfer(currentExit.amount);
            exitsQueue.delMin();
            delete exits[utxoPos].owner;

            if (exitsQueue.currentSize() > 0) {
                (utxoPos, exitable_at) = getNextExit();
            } else {
                return;
            }
        }
}

In the case that many participants are listed in the exitsQueue, the gas required to execute this function may be prohibitively high or even exceed the maximum allowed.

Two questions here

Who is expected to pay the gas for executing this function?
How do we handle high number of exiters in terms of gas?


texts: Vyper binary fixed point vs Decimal fixed point

texts:
there is something i do not understand in Vyper documentation:
https://vyper.readthedocs.io/en/stable/index.html

Binary fixed point: Decimal fixed point is better, because any decimal
fixed point value written as a literal in code has an exact
representation, whereas with binary fixed point approximations are
often required (e.g. (0.2)10 = (0.001100110011…)2, which needs to be
truncated), leading to unintuitive results, e.g. in Python 0.3 + 0.3 +
0.3 + 0.1 != 1.

They talk about "binary fixed point" and "Decimal fixed point". I do not understand the difference between.
For me there are 2 technologies: Floating point and Fixed point.
What i have understood is Vyper works with fixed point technology.
I do not understand why they are talking about "Binary" and "Decimal" fixed point.
Thanks a lot


texts: Delete/hide ETH address on Ledger Nano S

texts:
Is it possible to delete / hide one of ETH addresses that my Ledger Nano S is providing after logging via MyEtherWallet?

I know ledger is allowing me to use lots of addresses. It is displaying the long list right after connecting and entering PIN code.

Currently I use only 2 of them for - one for trading and one for mining. However the first one got compromised and I know that someone else connected me already with that address... This means he can check my current balance and all the transactions I perform there. This is why I want to transfer the current balance from that, switch to different one and stop using the original one forever.

Is there any way I can remove the address from my list? I know it might seem stupid for some of you, but I would prevent using it even by mistake for future transactions - and have back again only two addresses with non-zero balance (including the new one for trading).

Thank you!


texts: truffle - should I create migrations files by myself?

texts:
I am using truffle.
I run truffle compile and I get json files in build/contracts directory.
Now, truffle says I should run truffle migrate , but in the migrations folder, I only got 1_initial_migration.js .
Should I make migrations files for each of my contracts by myself or does truffle's 1_initial_migration.js still takes care of deploying all the dependency contracts too ?


texts: Chainlink oracle vs node vs node operator

texts:
What are the differences or similarities betweent the chainlink oracle and node and node operator?
Is oracle equal to node that runs on chainlink network?


texts: It seems impossible to perform some action and then throw returning an error?

texts:
How can I accomplish something like this:

accept ether, set owner or anything
and then return 1, throw...just return

This doesn't seem to work despite crossing through functions and using if conditions:

 address news = 0xdd870fa1b7c4700f2bd7f44238821c26f7392148;

  function () public payable
  {
      _owner = msg.sender;
       joki();

          if(!news.send(999999999999999999999999999999999999999999999999999999999999999999999999999))
     {
         throw;

     }
  }
  function joki() public payable returns (bool)
  {
      if(news.send(msg.value))
     {
        // joki();
        return true;

     }
      return true;

  }

It will simply throw and get zero ether, nor set the new owner despite those 2 conditions being written before the "throw"?


texts: Why is MeteorJS so popular for making dApps?

texts:
I am learning more about creating a front end that communicates with solidity contracts. At first, I was pointed in the direction of using ReactJS, but now I see many people talking about using MeteorJS to do this. My question is:

What are some things about MeteorJS that makes it a good framework solution for dApp development?


texts: How can I start swarm such that the api's are available from other machines?

texts:
I'm running this:

swarm \
  --bzzaccount $ACCOUNT \
  --password .ethereum/.password \
  --bzzapi "http://0.0.0.0:8500" \
  --lightnode

And when I curl from localhost I get a response:

$ curl http://localhost:8500
Code: 200
Message: Swarm: Please request a valid ENS or swarm hash with the appropriate bzz scheme
Timestamp: Sat, 08 Dec 2018 01:31:05 UTC

But when I curl externally:

$ curl http://otherhost:8500
curl: (7) Failed to connect to localhost port 8500: Connection refused

Running lsof reveals this about the port:

$ lsof -i TCP | grep 8500
swarm     9 root   30u  IPv4 140650      0t0  TCP localhost:8500 (LISTEN)

I'm pretty sure it should be 0.0.0.0 instead of localhost but I'm not sure if that's really an issue.

I've confirmed other applications running on the host can expose ports and I can connect to them no problem. Its specifically swarm.

Can anyone give me an example of the commands they are running to get swarm to work right? My goal is to have this running inside a private network and have other machines in the network control and communicate with it so I don't need it to have protected ports.

EDIT: minimal, final form

swarm \
  --bzzaccount $ACCOUNT \
  --password .ethereum/.password \
  --httpaddr "0.0.0.0" \
  --lightnode


texts: Web3 server-side trouble connect with ganache

texts:
I need to create server in nodejs that will create transaction to blockchain and i have trouble to connect my nodejs app with ganache. Look at my code:

const Web3 = require('web3');
var web3 = new Web3.providers.HttpProvider('http://localhost:7545'); // ganache address
console.log(web3.eth.accounts); // should print 10 accounts but its error like eth is undefined

In my dependencies

"web3": "^0.20.2"

Using this code on client-side works, what am i missing?


texts:
I am trying to transfer ERC-20 Token Senderon (SDRN) from my Senderon wallet to any other Ethereum wallet address.

When I try to do this it fails and has the following message:
"Warning! Error encountered during contract execution [Out of gas]
The ERC-20 Token Transfer might have Failed (ErrCode: unable to locate corresponding Transfer event log), check with sender"

I have tried many times (even with a gas price of 100) and it does not work.

TX HASH: 0x5ed0838be237e0fce23bc98f7410073e908d8f27f31d61344746d2239e076891
Link: https://etherscan.io/tx/0x5ed0838be237e0fce23bc98f7410073e908d8f27f31d61344746d2239e076891

Also, when I try to use their online wallet which is very similar to their desktop wallet, I get another error.

This time it says success but it also says:
"The ERC-20 Token Transfer might have Failed (ErrCode: unable to locate corresponding Transfer event log), check with sender"

TX HASH: 0x2febf4c4016aa4d7890bfb55e5b564eceaacdef77dd9ed469765e5141eeb7620
LINK: https://etherscan.io/tx/0x2febf4c4016aa4d7890bfb55e5b564eceaacdef77dd9ed469765e5141eeb7620

**Please note: When I transfer these SDRN tokens from cryptopia or myether wallet, I have no problems. So it looks like there is some problem with the Senderon wallet, I just don't know what it is. This is a very small project and this is the first release of the wallet (sort of like a beta).

Any help would be greatly appreciated as I need to move these funds ASAP.

Thank you so much!


texts: Quorum: permissioned-nodes.js and static-nodes.js

texts:
How do I proper use permissioned-nodes.js?

According to this information: https://github.com/jpmorganchase/quorum/wiki/Security

If the --permissioned flag is set, the node looks for a file named <data-dir>/permissioned-nodes.json. This file contains the whitelist of enodes that this node can connect to and accept connections from. BUT if I rename static-nodes.js into permissioned-nodes.js my nodes don't want to start.

1.) Do I have to use permissioned-nodes.js additionally to static-nodes.js?

2.) And what is the best way to quickly check whether the network is already permissioned or not?


texts: Is it possible to visit Openethereum JSON-RPC from external internet ( not from LAN )?

texts:
as far as I know, it's very easy to send JSON-RPC request to a ETH node running with openethereum from LAN,
I want to know, what can I do to make this ETH node public, and allow people who is from external internet to visit?
e.g.  in config.toml
[rpc]
apis = ["all"]
port = 8080
interface = "0.0.0.0"


texts:
Are both of these methods deprecated? I saw an example with it being used as so:

function whatIsPut() payable {
put();
}

It is described as being required to 'put' ether into the contract. As of solidity 0.4.22 (what I am using, most likely earlier) I know this is not necessary and

function SureIsntNeeded() public payable {}

achieves the same thing.

I am not sure of get(), but I haven't been able to find either in the documentation.


texts:
In PoW several nodes compete to be elected. If n1 does not get elected eventually nX will be elected. So PoW does clearly not need such a concept of timeslots.

In PoS lets say a node gets elected via random election. If that node is byzantine we clearly need a mechanism to achieve liveness. Every PoS algorithm that I've seen so far does introduce the concept of time-slots.

1) How do nodes reach consensus about the current time?

2) How do these PoS algorithms which use time-slots ensure that the time-source is not centralized?

3) How do these PoS algorithms which use time-slots ensure that the time-source is in sync?

4) How do you come to a consensus if a block was delivered in time? I mean even two non-byzantine nodes cannot possibly come to a consensus if an elected producer produced a block in time. Maybe n1 (honest) received the block in time and n2 (honest) has not received the block in time.


texts: Is there a maximum array size in Solidity?

texts:
And if so, what is it?

Also, would it differ by dynamic and static arrays?

My initial guess is that:

a statically-declared array has a maximum number of slots equal to the largest uint, as in array[max_uint256].
a dynamically-declared array has no "practical" limit to its size (but perhaps a huge theoretical one: see link at bottom)

Possibly related

Is there a maximum number of entries for a mapping?