texts: How to get contract adress when contract is deployed uisng other contract?

texts:
I have a smart contract with a function named, let's say, deployNewContract(..) this function takes some arguments and deployed a new contract based on the parameters. I am able to call the function from Ethereum-Wallet and deploy the contract. Everything works smooth.

Now, I have a public array of address type in which I store address of the newly deployed contract so I can get the address of the contract from that array.

Now the problem arises when I try to deploy the contract using web3 or geth console. I execute the function of my contract and get the transaction hash and mine it obviously.

But how do I get the address of newly deployed contract?

Unfortunately, my pubic array shows no new entry this time and when I check eth.getTransactionReciept, I get null in contract address.

Here is output of eth.getTRansactionReceipt(txHash); :

{
  blockHash: "0xbde761102ec08bef4ba55a703261da071ba0e99b5ef6c8d7e77bf5c1a6e27ba1",
  blockNumber: 413,
  contractAddress: null,
  cumulativeGasUsed: 313570,
  from: "0x5cb1ffd42dea0afeefb8950adcb2b6e5cff2efc3",
  gasUsed: 313570,
  logs: [{
      address: "0x9d160c47ae9ccf33078c9513492e5499cee53439",
      blockHash: "0xbde761102ec08bef4ba55a703261da071ba0e99b5ef6c8d7e77bf5c1a6e27ba1",
      blockNumber: 413,
      data: "0x000000000000000000000000d573b1767915530a05a0250f5f4fc985427a6d534e65772050617469656e74205265676973746572656400000000000000000000",
      logIndex: 0,
      removed: false,
      topics: ["0xd5a6c4477254cab9dfc267110730e333e3c94ea3a93795b56c93b0c8757488ce"],
      transactionHash: "0x1b6e8970275eda4b39690cb868bd305983d483dee38a042a1bcfc3dbfada22d2",
      transactionIndex: 0
  }],
  logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  root: "0x87d205881fc430586b344d0dda84cf72ba99c6bd198171f6e42c008fcad7c993",
  to: "0x9d160c47ae9ccf33078c9513492e5499cee53439",
  transactionHash: "0x1b6e8970275eda4b39690cb868bd305983d483dee38a042a1bcfc3dbfada22d2",
  transactionIndex: 0
}

PS:

I am on private test network
I think it's more of what to do? So I am not posting my code (to avoid question from being lengthy). If you feel that code is needed, I will update the question.


texts: Run Ethereum Blockchain offline on Virtual Machines

texts:
It is pleasure to be part of this community.

I am doing University project, which is aiming to use blockchain technology to host and store voting event and then evaluate the security and performance.
The plan I am thinking of is to get Ethereum source code and run it on virtual machines then create an application to act as an user which is trying to vote. I have some basic coding knowledge but can you guys give me some information of where to start, which tools to use, is it possible at all?


texts: Controlling access to functions with VIEW visibility with signed transactions?

texts:
Controlling access to functions that require ETH is straight forward because you get an address you can trust because it has been signed and verified, and therefore upi can use for access control simply by inspecting the value in the msg.sender field.

I have heard of a similar technique being used in something called "meta-transactions", used for identity purposes in non-SEND transactions.  But I don't know enough to be able to execute such a technique.  I would need to know how to do both of the operation, from the Node.JS/Web3JS side and the smart contract side.  I do know how to create SEND transactions and I am doing that now from my dApp, because I sign the data package I use with sendSignedTransaction().  But I'm not sure how to do this when using a straight method call executed from the Web3JS side.  I'm referring to the common technique of calling a contract method from an contract instance object that has the ABI loaded that contains the contract method calls (e.g. - contractInstance.methods.getSomeData().call()).

If I'm correct on this, can someone point me to a code sample or document that would show me how to sign a smart contract method call with VIEW visibility, from a Node.JS/Web3JS app?  And then show me on the smart contract side how to validate the signed method call?  The data packet I would send would contain the Ethereum address I want to use for access control.  Then on the smart contract side I would validate the signature before executing the access control rules.

Can I build a raw transaction like I do with sendSignedTransaction() that contains the method call and then send it to the VIEW function with zero gas? If so, will the smart contract automatically validate the signed data package cryptographically like it does with SEND transactions and provide my contract the address of the signer in the msg.sender field? Or do I need to add some library to my smart contract that does cryptographic validation and verify the signature explicitly with code I add to the contract?


texts: What is the purpose of interface contracts?

texts:
Reading The DAO and DigixDAO source code I notice that in contract systems there are often interface contracts where functions are declared without any body.

For example,

contract TokenInterface {
    function balanceOf(address _owner) constant returns (uint256 balance);
    function transfer(address _to, uint256 _amount) returns (bool success);
}

What is the point of interface contracts? The above contract in The DAO is followed by a contract Token is TokenInterface {} which repeats the exact functions declared in the interface contract except followed by the full function logic. Not sure what the point of this is- it seems redundant.


texts: Sharing an event between a contract and a library

texts:
I've a contract that uses an event and I want to share it with a library without having a duplicated definition.

The event is in the library, and contract uses it from the library. It works but the problem is that the event is not in the contract's ABI. So a testing framework like Truffle will not recognize it as generated by the contract. I can add the event to the abi by hand but it seems 'hackish'.

library Party {
    event Pinata(uint candies);

    function showPinata() internal {
        emit Pinata(123);
    }
}

contract Birthday {
    function celeb() public {
        emit Party.Pinata(222);
    }
}

The event is in the contract an the library uses it. The problem is that it doesn't compile. 'TyperError: Member "Pinata" not found or not visible after argument-dependent lookup'. As a workaround it can be duplicated in the library but it is error prone to have two separate definitions.

library Party {
    function showPinata() internal {
        emit Birthday.Pinata(222);
    }
}

contract Birthday {
    event Pinata(uint candies);

    function celeb() public {
        emit Pinata(123);
    }
}

Is there another way to solve this issue without having a duplicated definition of the event or editing the generated ABI?


texts: How to store array parameter of a function to contract state?

texts:
I am trying to save an invoice to contract storage (see function addNewInvoice(..)) but I seem to be tripping over the data locations.
// SPDX-License-Identifier: private
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;

contract InvoiceValidator {

    mapping(uint => Invoice) private idToInvoiceMap;
    uint[] private invoicesToValidate;

    struct Treatment {
        string description;
        uint cost;
    }

    struct Invoice {
        address recipient;
        address sender;
        string patient;
        uint date;
        Treatment[] treatment;
    }

    constructor() {}

    function addNewInvoice(address recipient, address sender, string memory patient, uint date, Treatment[] memory treatments)
    external
    {
        uint invoiceId = 1;
        Invoice memory invoice = Invoice(recipient, sender, patient, date, treatments);
        idToInvoiceMap[invoiceId] = invoice;
        invoicesToValidate.push(invoiceId);
    }
}

throws
UnimplementedFeatureError: Copying of type struct InvoiceValidator.Treatment memory[] memory to storage not yet supported.

I think this is because of the line
idToInvoiceMap[invoiceId] = invoice;

which would save the invoice to contract state, which is what I am trying to do.
Is there a way to achieve this?
Also, I couldn't find a whole lot of good ressources about data location (storage, memory, calldata[, stack]), so I'm not sure if memory is even the right location for the local invoice variable. But if I change the line
Invoice memory invoice = Invoice(recipient, sender, patient, date, treatments);

to
Invoice storage invoice = Invoice(recipient, sender, patient, date, treatments);

the compiler throws
[...].sol:30:9: TypeError: Type struct InvoiceValidator.Invoice memory is not implicitly convertible to expected type struct InvoiceValidator.Invoice storage pointer. Invoice storage invoice = Invoice(recipient, sender, patient, date, treatments); ^-----------------------------------------------------------------------------^

And what I do not understand either is that when I change the Invoice struct treatment property to a single Treatment (instead of an array of them) like this:
struct Invoice {
        address recipient;
        address sender;
        string patient;
        uint date;
        Treatment treatment;
}

and try to assign it like this:
Invoice memory invoice = Invoice(recipient, sender, patient, date, treatments[0]);

it seems to work, but changing to storage
Invoice storage invoice = Invoice(recipient, sender, patient, date, treatments[0]);

throws
[...].sol:30:9: TypeError: Type struct InvoiceValidator.Invoice memory is not implicitly convertible to expected type struct InvoiceValidator.Invoice storage pointer. Invoice storage invoice = Invoice(recipient, sender, patient, date, treatments[0]); ^--------------------------------------------------------------------------------^

So there seems to be another problem with arrays of reference types vs reference type only?
I would much appreciate if somebody could help me solve how to save this invoice containing a list of treatments to contract storage or shine some light on my confusion in general.
(Also: I couldn't find much information about this either but am I correct in assuming that it would be more appropriate to emit events and create an outside-the-blockchain storage to keep track of data instead of storing a lot of invoices inside the contract?)


texts: Why is this contract using too much gas? (infinite)

texts:
I've been playing around with this contract for the past couple of hours, the logic seems ok from my side (please correct me if I am mistaken), but I don't understand why in the analysis I am getting the error Fallback function of contract Lottery requires too much gas (infinite). If the fallback function requires more than 2300 gas, the contract cannot receive Ether..

pragma solidity ^0.4.19;

contract Lottery {
  address private owner;

  address[] public players;
  uint private lastCount;

  address[] public winners;
  uint[] public prizes;

  uint private min = 1 ether;
  uint private fee = 0.1 ether;

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

  function enter() public payable {
    address player = msg.sender;
    require(player != owner);
    require(msg.value >= min);
    players.push(player);
    owner.transfer(fee);
  }

  function () public payable {
    enter();
  }

  function getPlayersCount() public view returns (uint) {
    return players.length - lastCount;
  }

  function pick(uint index) public {
    require(msg.sender == owner);
    require(getPlayersCount() > 0);
    address winner = players[lastCount + index];
    require(winner != address(0));
    winners.push(winner);
    prizes.push(this.balance);
    lastCount = players.length;
    winner.transfer(this.balance);
  }

  function getWinnersCount() public view returns (uint) {
    return winners.length;
  }

  function getPlayers() public view returns (address[]) {
    return players;
  }

  function getWinners() public view returns (address[], uint[]) {
    return (winners, prizes);
  }
}

At first I thought that the issue was caused by players = new address[](0); so I switched to a safer approach (using a lastCount pointer instead of clearing the array), but still.

I also tried players[players.length++] = player; which strangely keeps the analysis engine happy, but results a broken functionality.

Anybody can shed some light on this?


texts: How to delete an element at a certain index in an array?

texts:
Anyone know how to delete an element in a array? Is there any built in method to do that?

If not, does anyone know of how to implement such a method?


texts: Are gas prices determined by how large an array is when adding to it?

texts:
I am looking at a contract where the array of digital items will get larger and larger as time goes by. Im wondering what the cost implications are over the long run as the Dapp matures, especially when it comes to adding to the array.

Please take the following basic example which assumes gas prices etc stay the same.

Example

Lets say at the start when I add my initial item after creating the contract it costs $1 to run the contract.

Now lets say a period of x days/months goes by and the array is now up to lets say 100000 items. Now when i run the contract to add a new item will the cost still be $1 or will it now increase because the size of the array has increased?

Also when fetching/reading the array from my web app is there a cost associated with this? I have read somewhere that reads from the blockchain don't cost anything?

Thanks


texts: What is the gas cost of recovering a wallet address from a signature using Solidity?

texts: As titled. I understand that there's an ecrecover function in Solidity. Can I use it for recovering a wallet address from a signature? Is it cheaper than a Keccak hash operation?


texts:
I was following a tutorial that can buy erc20 tokens and I'm now stuck with transferring tokens to a buyer account which I need more clarification. So basically, a buyer account is trying to purchase some tokens. That's it.

For example, there's a contract that implements erc20 functions

contract DappToken {
    //...
    mapping(address => uint256) public balanceOf;

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

    function transfer(address _to, uint256 _value) public returns (bool success) {
        require(balanceOf[msg.sender] >= _value);

        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;

        Transfer(msg.sender, _to, _value);

        return true;
    }
}

and there's another contract that takes DappToken contract as a parameter of its constructor.

contract DappTokenSale {
//...

    function DappTokenSale(DappToken _tokenContract, uint256 _tokenPrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;
    }

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

        tokensSold += _numberOfTokens;

        Sell(msg.sender, _numberOfTokens);
    }
}

Here's my question, how does a buyer pass below requirement in buyTokens function?

require(tokenContract.transfer(msg.sender, _numberOfTokens));

My understanding is..

When the buyer tries to buy tokens, it will call transfer function in DappToken contract passing buyer's account address (msg.sender) and the number of tokens to purchase (_numberOfTokens).
transfer function in DappToken contract will check if the buyer has existing balance. require(balanceOf[msg.sender] >= _value);

But I don't understand why there's a check to see if a buyer has existing balance? What if it was the buyer's first time purchasing the tokens? then the buyer won't have existing tokens in balanceOf variable initially.

or is the msg.sender in transfer function a DappTokenSale's contract address?


texts: how to make geth notify when any of the accounts receives ether?

texts:
I have a geth running with potentially many accounts. How do I make it execute a command whenever any of my accounts receives a transaction?

in bitcoin, you can use walletnotify in bitcoin.conf. How to do the same in Ethereum?

Thanks!


texts:
I intend to do a project on Decentralizing DNS using Blockchain.

As I was researching this topic, Namecoin was a name that popped up a lot. On searching further, I got to know that Namecoin hosts .bit addresses on its blockchain (Please correct me if I am wrong)

What I want to make is a DNS which does exactly what the current DNS does but remove the need for a centralized server. Meaning, I want to map the IP's of .com/.net etc. sites and not introduce a new top level domain.

I do not have an in-depth knowledge about Blockchain. I know what it is and the basic idea on how to make one, but I'm still learning the rest. Its a field that I am very much interested in learning more about.

I just want to know how I can go about fulfilling my requirement. To be honest, I am not even sure on where to start. My current research methodology has been watching the various "talks" about Decentralized DNS on YouTube.

If anyone could help guide me in the right direction, I would be grateful.

Thanks


texts:
I found the following case below in a book.

case 1:

contract sample1{
    function a() returns (int b);
}

contract sample2{
    function myFunc()
    {
        sample1 s = sample1(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970);

        //without abstract contract this wouldn't have compiled
        s.a();
    }
}

why use "0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970"?

I found the following second case in the Solidity docs.

case 2:

contract Feline {
    function utterance() returns (bytes32);
}

contract Cat is Feline {
    function utterance() returns (bytes32) { return "miaow"; }
}

Feline is an abstract contract, and cat inherits from Feline.

What is the difference in case 1 and case 2?

Do you need to inherit to be able to use an abstract contract?


texts: How much does it cost to upload a smart contract?

texts:
I'm using a local Ethereum testnet and it seems to me that the price of uploading a smart contract is a bit too high.

This is the code for the smart contract:

contract Transfer {
    address owner;

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

    modifier isOwner ()
    {
        if (owner == msg.sender) {
            _;
        }
        else
        {
            revert();
        }
    }

    function sendEther (address dst) isOwner payable {
        if(msg.value<=0) revert();
        dst.transfer(msg.value);
    }

    function getBalance () constant isOwner returns (uint) {
        return msg.sender.balance;
    }

    function () payable
    {
        if(msg.value<=0) revert();
        owner.transfer(msg.value);
    }

}

After deploying it with truffle, I've seen that the balance of the account from which that contract has been deployed, has been reduced by 0.045 Ether, which would be something around $15 at today's exchange rate.

I don't know if this is normal, but to me it seems way too expensive.

The gas price in my testnet is 20000000000 and current gas price (seen on https://ethstats.net/) is even higher (35500000000). So, if I'm not wrong, deploying it to the mainnet would be even more expensive!

So, in short, my question is: Is this price normal or am I missing something?

EDIT: Solidity browser says that for this very contract, "Creation: 20435 + 126600", which translates to less than $1... is truffle stealing my Ether somehow?!

Thanks a lot in advance! :)


texts:
I have spent nearly two weeks trying to download and sync mist. A few days ago I changed to parity and had a bit more success and finally achieved 100% sync, however, I then switched to test-net and ran parity --chain ropsten which started off ok but 2 days later is still trying to sync the final 100 blocks. It appears now that I have some kind of parity geth conflict idk. I've pretty much lost my mind but really don't want to give up.  I have a feeling I am close and just missing some key understanding.
I have run so many different commands from reading blogs, posts and watching videos I have no idea what could be running in the background and conflicting. Is it best to start again? Any advice would be highly appreciated at this point.
Thanks


texts: how to send a transaction with web3 and metamask

texts:
I'm trying to learn how web3 works and I'm creating a simple HTML page to send a transaction, but I'm getting the following error:

(inpage.js:1)   MetaMask - RPC Error: validateTxParams@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:80654
e/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:65579
_@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230907
[1286]</w/o._invoke@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230697
[1286]</E/</e[t]@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2231083
n@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630306
[254]</r.default/</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630285
S@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:930364
[254]</r.default/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630241
[25]</$</<.value</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:66281
e/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:64573
_@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230907
[1286]</w/o._invoke@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230697
[1286]</E/</e[t]@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2231083
n@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630306
[254]</r.default/</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630285
S@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:930364
[254]</r.default/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630241
[25]</$</<.value</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:65202
e/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:175590
_@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230907
[1286]</w/o._invoke@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2230697
[1286]</E/</e[t]@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:2231083
n@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630306
[254]</r.default/</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630285
S@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:930364
[254]</r.default/<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:630241
[70]</t.exports</<.value</<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:175752
[609]</t.exports/<.eth_sendTransaction<@moz-extension://e67892be-b68e-4c30-a024-c6ded3ddf733/background.js:1:1218722

Here's the code:

web3.eth.sendTransaction({
        from: '0xbe03ede9d060679c18df54dbdbde924b0261075b',
        to: "0xA396923aD14c3CcA2Af9D0C5BC97A5180416E700",
        value: "0.01"
    }, function(error, hash){
        alert(error);
    });


texts: Confusion With Etherscans representation of an Address

texts:
I'm trying to get a list of unique addresses that have interacted with a contract. As well as some data included in the events of each transaction. In order to do this, I use the action=getLogs query when using the etherscan API. Everything is returned in hex value it seems, and while I can decode one portion of the data I need, the address will not cooperate.

What it is returning is 0x[0(x24)]address.

My questions:

What is the purpose of adding in the 24 0's?

Do I use regex to strip the 0's, or is there a more consistent approach, perphaps using web3?

I've attemped using web3.eth.abi.decodeLog, but no matter how many times I adjust, it results in "property not found".


texts: Unable to return address array in solidity

texts:
I have the following code for a simple gambling game.
The code works fine except for getPlayers function

pragma solidity >=0.4.22 <0.6.0;

contract Lottery {
address payable public manager;
address payable [] public players;

constructor () public {
    manager = msg.sender;
}
function enter() public payable {

    require(msg.value > 0.01 ether); //condition
    players.push(msg.sender);
}

function random() private view returns(uint) {
    return uint(keccak256(abi.encodePacked(block.difficulty, now,
players)));
}

function pickWinner() public restricted{
    uint index = random() % players.length;
    players[index].transfer(address(this).balance);
    players = new address payable[](0); // new dynamic array

}

modifier restricted() {
    require(msg.sender == manager); // security
    _;
}

function getPlayers() public payable returns (address[] memory) {
    return players;
    // Error in the above line saying
    // "Return argument type address payable[] storage ref is not implicitly convertible to expected type(type of first return variable)  address[] memory."

}
}


texts: Web3js 1.0 events: closing the contract.events "socket"

texts:
My code is the following:

contract.events.Deposit({}, function (err, event) {
    if (err) {
        console.error;
    } else {
        console.log(event.blockNumber);
    }
})
    .on('data', function (event) {
        console.log(event);
    })

What I want to do is to close the event listener after some condition is fulfilled. How can I do that?


texts: Specify different solc compiler for different files in truffle?

texts:
I am using truffle, and have a number of x.sol files in the contracts directory, different files require different versions of the compiler - how do i deal with that?

I think i SHOULD be able to do something like:

truffle compile Dai.sol 0.4.13
truffle compile MyContract.sol 0.5.0

Unfortunately it seems to always try to do the lot with whatever version is in the truffle config file. :(


texts:
When an agent deploy a smart contract, how blockchain accepts this smart contract and sends an address of smart contract to agent.

1-How the blockchain accepts this smart contract?
2-who accepts the smart contract in blockchain ?
3-which generates the address of the smart contract?


texts: truffle testing error global variables not written

texts:
Contract:

contract owned {
    function owned() public { owner = msg.sender; }
    address owner;

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

contract TestcontractCrowdSale is owned {
    uint public tokens_total = 0;

    struct holder {
        uint tokens_bonus_balance;
        uint tokens_all_balance;
        bool tokens_bonus_canspent;
        uint ethers_crowdfunded;
        uint list_pointer;
    }

    mapping (address => holder) public holders;
    address[] public holdersList;

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

    function checkIsHolder(address holderAddress) public constant returns (bool isIndeed) {
        if(holdersList.length == 0) return false;
        return (holdersList[holders[holderAddress].list_pointer] == holderAddress);
    }

    function getHoldersCount() public constant returns(uint count) {
        return holdersList.length;
    }

    function newHolder(address holderAddress) public returns(bool success) {
        if (!checkIsHolder(holderAddress)) {
            /*holders[holderAddress] = holder({
                tokens_bonus_balance: 0,
                tokens_all_balance: 0,
                tokens_bonus_canspent : false,
                ethers_crowdfunded : 0,
                list_pointer : holdersList.push(holderAddress) - 1
            });*/
            holders[holderAddress].list_pointer = holdersList.push(holderAddress) - 1;
        }
        return true;
    }

    function balanceOf(address tokenOwner) public view returns (uint balance) {
        return holders[tokenOwner].tokens_all_balance;
    }

    function preprint(address _for, uint tokens) onlyOwner public returns (bool printed, address __for, uint bonus_all_tokens) {
        newHolder(_for);
        holders[_for].tokens_all_balance += tokens;
        holders[_for].tokens_bonus_balance += tokens;
        holders[_for].tokens_bonus_canspent = false;
        tokens_total += tokens;
        return (true, _for, holders[_for].tokens_bonus_balance );
    }
}

truffle.cmd develop

truffle(develop)> compile
truffle(develop)> migrate

truffle(develop)> TestcontractCrowdSale.deployed().then((instance) => {contract = instance});

truffle(develop)> contract.preprint.call("0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef","123456",{ from: "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"})
[ true,
  '0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef',
  BigNumber { s: 1, e: 5, c: [ 123456 ] } ]
truffle(develop)> contract.preprint.call("0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef","123456",{ from: "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"})
[ true,
  '0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef',
  BigNumber { s: 1, e: 5, c: [ 123456 ] } ]
truffle(develop)> contract.balanceOf("0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef")
BigNumber { s: 1, e: 0, c: [ 0 ] }
truffle(develop)> contract.tokens_total()
BigNumber { s: 1, e: 0, c: [ 0 ] }
truffle(develop)> contract.tokens_total.call()
BigNumber { s: 1, e: 0, c: [ 0 ] }

But in remix all works OK, preprint function works fine, and i can not understand, why? Contract is same!

That's big problem for me.


texts: Fixed byte array default value comparison

texts:
What is the correct way to see if a bytesN value is of "default" value; whatever value is assigned to it upon declaration?

The following works, but seems unsafe:

contract Assertnil {
    bytes32 v;
    function test() constant returns (bool) {
        assert(v == "");
        return true;
    }
}

This seems more correct, but slightly more expensive:

contract Assertnil {
    bytes32 v;
    function test() constant returns (bool) {
        bytes32 w;
        assert(v == w);
        return true;
    }
}


texts: Can an ethereum contracts start with a non-zero balance?

texts: Since contracts are just ethereum addresses with code attached and a contract address can be calculated deterministically before even deploying a contract, is it possible to send ETH to an address which you know will hold a contract at a later time? What happens to the contract and the ETH?


texts: Anyone with knowledge in org.web3j.abi.Type Decoder?

texts:
I am trying to decode a String with this code that I found but I have not been able to do it.

String to = inputdata.substring(10, 74);
String value = inputdata.substring(74, 138);

Method refMethod = TypeDecoder.class.getDeclaredMethod("decode", String.class, int.class, Class.class);
refMethod.setAccessible(true);

String cadena = (String) refMethod.invoke(null, to, 0, String.class);
System.out.println(cadena);
Uint256 amount = (Uint256) refMethod.invoke(null, value, 0, Uint256.class);
System.out.println(amount.getValue());

I can get uint256 but not the string


texts: What is role of pure.js for adding web3.js

texts:
I am adding web3.js according to guide in: Adding web3.js. I traversed steps mentioned there that can be seen below:

There is no problem with "npm" and "meteor" steps but with "pure js" step the following problem occurrs:

That says:
dist/web3.min.js : The term 'dist/web3.min.js' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I don't know what is the problem. I have no knowledge about dist/ and don't know the problem's solution. Please help. Thanks


texts: What is the emission rate in the context of STAKE and what is the source of emission

texts:
From this document: https://www.xdaichain.com/for-stakers/stake-token
I read:

STAKE is a new ERC20-type (implemented as an ERC677) token designed to secure the on-chain payment layer and provide a mechanism for validators to receive multiple POS incentives. It is an ERC20-based staking token with a market driven value.
The initial supply of 8.5375M STAKE tokens will be released over time. Additional tokens are minted as rewards at the conclusion of each staking epoch.
Users (stakers) provide STAKE as collateral when participating in the consensus process. In exchange for providing STAKE (and supporting a node), users receive multiple rewards. The primary reward is in the form of additional STAKE tokens.
STAKE rewards: STAKE is minted as a reward based on the amount of STAKE placed in the protocol. The final emission rate is TBD through a risk assessment and community review. Target range: ~15% APR.
A STAKE transfer fee is also assessed when a user removes their STAKE from the xDai chain (using an AMB bridge extension). This fee is distributed as a reward to participating stakers.

What is the emission rate?
Are the STAKE tokens coming from the air?

I don't get it. I'm as a stakeholder, ok, but what is the source of accrued tokens?


texts: I sold zrx in binance and sent it to my ethereum address in coinbase. My coinbase account was blocked so when I went back to binance at the bottom I clicked and it showed the sale with the money sitting in etherscan.  How do I get the money out with a new digital address back to binance and buy eth there


texts: How do I list the running nodes with geth?

texts:
Is there a way to list the all nodes on my computer with geth command line, and maybe even see some status for them?

(I'm new to go-ethereum, apologies if this is a noob question, but I cannot quite find the answer.)


texts: I moved my Ethereum out of my coinbase account and to a cold wallet/address. My question is, how do I get it out of cold storage so I can trade with someone?


texts: Ether.Camp web3 js interact with contract - what am I doing wrong?

texts:
I have a working contract that I made in ether.camp with solidity, it functions as desired through the IDE contract interface and now I am trying to tie it into an html GUI with web3.

To this end I have been following a series of tutorials, but as far as I can see - what I am doing should be working but it looks like it is not connecting to the contract?

Html:

<form>
   <button id="call"  type="submit">Call</button>
</form>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="dist/app.js"></script>

app.js

var async = require('async');
var Web3 = require('web3');
var ethTx = require('ethereumjs-tx');
var SolidityFunction = require('web3/lib/web3/function');

var abi = [{
    "name": "removeElement(address)",
    "type": "function",
    "inputs": [
    {
        "name": "key",
        "type": "address"
    }
    ]
}];

var sandboxId = '<my sandbox id>';
var url = 'https://<my user>.by.ether.camp:8555/sandbox/' + sandboxId;
var web3 = new Web3(new Web3.providers.HttpProvider(url));

web3.eth.defaultAccount = '0xdedb49385ad5b94a16f236a6890cf9e0b1e30392';

$( "button" ).click(function() {
    alert("button was clicked"); //just checking the jquery was working
    var contract = web3.eth.contract(abi).at('0x17956ba5f4291844bc25aedb27e69bc11b5bda39'); //The contract address as per the ethercamp IDE
    contract.call().removeElement("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba");
});

The removeElement(address key) function in the contract works absolutley fine from the IDE. I suspect the above code is not actually 'connecting' to the contract? Wish I could be more detailed but I'm not sure whats not working here

Thank you!


texts: Sending ETH with web3.eth.sendSignedTransaction on Ropsten network

texts:
I have two question about how can I send ethereum programmatically.

1. How can I use the https://api.myetherapi.com/ropsten address to test my code?

I tried something like this:

...
web3 = new Web3(newWeb3.providers.HttpProvider("https://api.myetherapi.com/ropsten?apikey=mykey"));
...

But I get this response: {"message":"Missing Authentication Token"}

Do api.myetherapi.com and ropsten.infura.io uses the same ledger?

2. I cannot send any ETH over Ropsten network. For this one I use infura.io, and whatever I try, is not working. Here is my code:

    var Web3 = require('web3');

    if (typeof web3 !== 'undefined') {
      web3 = new Web3(web3.currentProvider);
    } else {
      web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/DvTaqzNZpFvErBoHkvwL"));   // SANDBOX
    }

    var txDecoder = require('ethereum-tx-decoder');

    gasPrice = 0;
    web3.eth.getGasPrice(function(error, result) {
            console.log('Gas Price: '+ result);
            gasPrice = result;

            const ethTx = require('ethereumjs-tx');

            const txParams = {
                      nonce: '1',           // Replace by nonce for your account on geth node
                      gasPrice: gasPrice,   // maximum price of gas you are willing to pay for this transaction
                      gasLimit: 0.0000001,  // maximum gas you are willing to pay for this transaction
                      to: '0xb8412c93aefe25937d1f5f43393d6d74382ae987',
                      value: 0.000000001,
            };

            // Transaction is created
            const tx = new ethTx(txParams);
            const privKey = Buffer.from('7dc2...private_key', 'hex');

            // Transaction is signed
            tx.sign(privKey);
            const serializedTx = tx.serialize();
            const rawTx = '0x' + serializedTx.toString('hex');
            console.log(rawTx);
            console.log(txDecoder.decodeTx(rawTx));

            web3.eth.sendSignedTransaction(rawTx, function(err, hash) {
                    if (!err) {
                            console.log(hash); // "0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385"
                     } else {
                            console.log(err)
                      }
            });

    });

My private key is related to this: https://ropsten.etherscan.io/address/0x25D8A20E97fE8af009e9A67eE5DBd4bB92751d9a - where I have 20 ETH

All the errors I get are related with the gas price/limit, or the transaction is not mined in the next 50 blocks.

Thanks in advance!


texts: SafeMath library vs SafeMath contract on the inheritance chain

texts: guys, I am developing ERC-20 token and I am wondering why SafeMath is used as as library in the OpenZeppelin implementation? Will not it be more optimal if we supply it as a base contract on the inheritance chain?


texts:
I'm new to Ethereum and I'm struggling to understand how logs are stored and can be read using geth and plain JSON-RPC (not web3.js). There's a bit of documentation out there and some posts but I'm looking for a more plain English explanation.

So far I have managed to get the log data using curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id":1}'

There's an array of logs in the transaction receipt and inside the array, there's another array called topics and a field data. What do these two fields represent? And what is the relation between logs and logsBloom? And how can I convert these hex values into the original value that was passed into the event?


texts: Why knownStates and pulledStates are always 0 on my full node?

texts:
It's the second time that I run a Geth in full node. The first one got synced fully, but the second one did not sync after a week. Both servers have the same configuration and infrastructure. Using eth.syncing I receive a strange output on the second server as below:

> eth.syncing
{
  currentBlock: 5169781,
  highestBlock: 9967108,
  knownStates: 0,
  pulledStates: 0,
  startingBlock: 5175548
}

As you see, currentBlock is about half of highestBlock, and knownStates and pulledStates are both 0. May you tell me why these values are 0 and what is the matter here?

Thank you.


texts: I have a truffle version problem. and I've done it but it's not working

texts:
I've done npm install -g solc@0.4.16 and it reads solc@0.5.16 when doing the truffle version
  compilers: {
    solc: {
      version: "^0.4.26", // A version or constraint - Ex. "^0.5.0"
                         // Can also be set to "native" to use a native solc
      //docker: <boolean>, // Use a version obtained through docker
      parser: "solcjs",  // Leverages solc-js purely for speedy parsing
      //settings: {
      //  optimizer: {
      //    enabled: <boolean>,
      //    runs: <number>   // Optimize for how many times you intend to run the code
      //  },
      //  evmVersion: <string> // Default: "petersburg"
      // }
    }
  }

truble
CompileError: /C/Users/imama/Documents/token_sale/contracts/DappToken.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.26;
^----------------------^
,/C/Users/imama/Documents/token_sale/contracts/DappTokenSale.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.26;
^----------------------^
,/C/Users/imama/Documents/token_sale/contracts/Migrations.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.16+commit.9c3226ce.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.26;
^----------------------^


texts: How to transfer wei from a contract to a specific address?

texts:
I was making an auction system and I wanted to make sure that when someone bid higher the contract would return the money to the address of the previous bid.

pragma solidity >=0.4.22 <0.6.0;

contract simpleAuction{
    uint currentValue = 0;
    address buyer;

    function set() public payable{
        uint sent = msg.value;
        require(sent>currentValue, "Bid less than current value.");

        buyer.transfer(currentValue);

        currentValue = sent;
        buyer = msg.sender;
    }

    function winner() public view returns (address addressWinner, uint newValue){
        addressWinner = buyer;
        newValue = currentValue;
    }
}

The error is in the line buyer.transfer (currentValue); that in case transfer() only works for msg.sender.


texts: Long delay when sending ETH with MetaMask

texts:
I installed MetaMask (chrome) and added some ETH to my account. I then tried sending some ETH to an ICO. I sent 0.1 ETH and the transaction has been showing as "Contract Published" for the last few hours.

I assumed that it is because I used the wrong Gas Limit so I tried again (this time for 0.15 ETH). It has been almost 2 hours and I've not seen any change yet.

Can anyone please let me know what I'm doing wrong?


texts: How to compile a smart contract to opcodes?

texts: I wish to get the opcodes of any smart contract. But I only know how to use SOLC to compile it to bytecodes. How can I get the opcodes? (I know I can use Remix to get the opcodes online, but I hope there's an offline approach.)


texts:
I followed the process by creating a tweet with my wallet Ethereum ID and submitted it but I didnt get Ethereum in my wallet.
Does the wallet have to be from a particular exchange?
My wallet address is 0xe7D0A858d258a1B664e86bee07B8E6D22432b627


texts:
How to delete the 0s within the array and reduce array to array.length - (array[i] == 0).length entries that the return is uint256[]: 1,2,3? (array[i] == 0).length not works, it just should show that it needs to be variable.

uint[] array = [1,0,2,0,3,0,0];
function remove() public returns(uint[]) {
    for (uint i; i < array.length-1; i++){
        if (array[i] == 0){
            array[i] = array[i+1];
        }
    }
    delete array[array.length-1];
    array.length--;
    return array;
}
// => 0: uint256[]: 1,2,2,3,3,0


texts: How to add function buy to buy button that need array index

texts:
I am new to this smart contract and blockchain. I'm trying to do simple selling goods dapps. But i'm stuck at the buy button.

I have array for the products.

constructor() public {
   goods[0].owner = msg.sender;
   goods[0].name = 'Product 1';
   goods[0].price = 40 ether;
   goods[0].forSale = true;

   goods[1].owner = msg.sender;
   goods[1].name = 'Product 2';
   goods[1].price = 40 ether;
   goods[1].forSale = true;
 }

and I have this javascript

  let add = goods[0];

  let a = add[0]; //address
  let b = add[1]; //name
  let c = add[2]; //available
  let d = add[3]; //price

  let fullhtml = "";

  for(let m = 0; m < a.length; m++)
  {

    //(condition) ? true : false
    var btn = (c[m]) ? "<form id='buying'><button type='submit' class='btn btn-info'>Buy</button></form>" : "<button class='btn btn-danger' disabled>Sold Out</button>";

    fullhtml = fullhtml + "
" + a[m] + "	" + "" + hex2a(b[m]) + "	" + "" + btn + "</form>	" + "" + d[m] + "
";
  }

So now I have table, each row have same index number. How can I add function to the buy button that represent each index.

My buy function is this.

function buyGood(uint index) public payable {
        Good storage good = goods[index];

        require(msg.sender != good.owner && good.forSale && msg.value >= good.price);

        if(good.owner == 0x0) {
            balances[owner] += msg.value;
        }else {
            balances[good.owner] += msg.value;
        }

        good.owner = msg.sender;
        good.forSale = false;

        emit GoodOwnerChanged(index);
    }//


texts: Empty array when adding members with mapping

texts:
I had a question. I have a mapping that maps to struct.

  contract A{

    struct struct1{
      //...members...
    }

    struct struct2{
      struct1 input1;
    }

    mapping (uint => struct1) mapToStruct;

    struct2[] allEntries;
      //...rest of the code for populating mapToStruct
    }

  contract B is A{

    function addToStruct2(uint _mappingNumber) returns(bool status){
      struct2 memory newMember;
      struct1 memory newEntry;
      newEntry = mapToStruct[_mappingNumber];
      newMember.input1 = newEntry;
      allEntries.push(newMember);
      return true;
    }
  }

But this code is not working, I am not able to add the details to allEntries. The array has a new entry but all its members are 0, even after addToStruct2 returns true. Thanks in advance


texts: Are there weaknesses in using Oraclize (or similar) for randomization?

texts:
I'm trying to learn about Ethereum Smart contracts and studying example code and existing Dapps.  If I understand things (and I probably don't), Solidity cannot create random numbers, so developers need to use a service like Oraclize.

I was stepping through transactions and saw something interesting, a bit confusing:

a transaction is created by the end user by sending ether from their
wallet to dapp_smart_contract_1
dapp_smart_contract_1 then sends a transaction to
oraclize_smart_contract
oraclize query runs (First, curious how this works.  Why do
developers need to use Oraclize?  Why not setup their own RESTful
service or other mechanism?)
oraclize returns a random number by calling
dapp_smart_contract_2
dapp_smart_contract_2 transacts with dapp_smart_contract_1
dapp presents the results

It's quite likely that I'm not understanding the process, but if I do, it appears that the dapp developer can alter the results in this setup and have the app still appear to be using Oraclize query results some of the time.

Regardless, I'm curious if there are any weaknesses or vulnerabilities in using a service like Oraclize and also if there are plans to make Ethereum smart contracts "better" so that centralized services aren't necessary?


texts: personal.sendTransaction not broadcasting? (geth)

texts:
I'm trying to use the personal.sendTransaction() method and it returns a valid txid, but looks like it never gets broadcasted to the network. (Can't pick it up on etherscan or any ETH explorers)

I've tried this on both a fast sync and a light sync with no avail.

Transactions do show up using eth.pendingTransactions:

}, {
    blockHash: null,
    blockNumber: null,
    from: "0x66ec231d3d50fd2c5a9a5242c76d91ca39a79c35",
    gas: 21000,
    gasPrice: 18010524411,
    hash: "0x9367ca24e37184f328a5b9edd67a776f98f2195803a6237d452de2e8f4fb2083",
    input: "0x",
    nonce: 5,
    r: "0x7f0e5d712072782ecb5ac39072044229d6283166a182749b0e50adce1224601f",
    s: "0x63c276600b15e7db1543fcb115c30cf94ee0948bbf7ead1200925602428ec54f",
    to: "0x4408f69a5a7ef19c5cf61309a046e735e2e38ea3",
    transactionIndex: null,
    v: "0x25",
    value: 1000000000000000
}]

I really am at loss of what is going on

I also submitted a issue on the Github here: https://github.com/ethereum/go-ethereum/issues/21167


texts: How to compile .sol file from the command-line?

texts:
How do I compile a solidity file (e.g. 05_greeter.sol) from the command-line into bytecode?

Without using IDE such as Mix.


texts: How to integrate Dapper Wallet smart contracts with web app?

texts:
Dapper Labs who are the creators of Cryptokitties recently released their own wallet which is run by smartcontracts. They have open sourced the code:

https://github.com/dapperlabs/dapper-contracts

I am looking for some guidance on how I could integrate their wallet (smart contracts) into a web app so that it's users each would have access to their own Dapper wallet.

Would it be possible to use web3.js and if so which provider would I ideally use?


texts: How do I claim my earned Liquidity Provider fees?

texts:
I provided some tokens in a Liquidity Pool for some time, and now Uniswap says I accumulated about 130$ worth of ETH and PRQ on the provider fees.

How do I claim these 0.113 WETH and 111 PRQ? There don't seem to be any corresponding button in Uniswap webapp and zero info anywhere I look...
Do I miss some fundamental concept here? Are my earnings claimed in some implicit way perhaps, like when I do a swap or something?


texts: Calling contracts on server side with metamask

texts:
My application is in nodejs platform. I'm calling the contracts on server side by setting up provider as

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

Is it possible to setprovider as metamask on UI(controller) and call contracts on server side?


texts: Information lost when getting string from byte32 Solidiy smart contract

texts:
I have a number as a string which I pass to smart contract function as a parameter. The function takes byte32 as a parameter.

Here is the node.js code for executing the contract function:

const app = require("express")();
const config = require("./config");
const Web3 = require("web3");
const web3EndPoint = config.web3EndPoint;
const web3 = new Web3(new Web3.providers.HttpProvider(web3EndPoint));
const ethTx = require('./eth-transaction');
const abi = config.abi;
const MyContract = web3.eth.contract(abi);
const myContractInstance = MyContract.at(config.contractAddress);

txnCount = web3.eth.getTransactionCount(config.defaultAccount);

const parameter = '1234';
const data = myContractInstance.setID.getData(parameter);
myContractInstance.setID.estimateGas(parameter, (error , value) => {
    if (!error) {
        console.log("gasLimit" , value);
        const rawTx = {
            nonce: web3.toHex(txnCount) ,
            gasPrice: web3.toHex(100000000000) ,
            gasLimit: value ,
            to: config.contractAddress ,
            value: web3.toHex(0) ,
            data: data ,
        };

        ethTx.sendRawTransaction(config.priKey , rawTx , web3 ).then((result) => {
            console.log(result);
        }).catch(transactionFailedErr => {
            console.error(transactionFailedErr);
        });
    } else {
        console.error(error);
    }
});

myContractInstance.LogTestCase().watch((error, result) => {
    console.log(web3.toUtf8(result.args._id)); // Its logs 'M'
});

Here is the solidity code:

pragma solidity ^0.4.21;

contract test2 {

    bytes32 public _id;

    event LogTestCase(
        bytes32 _id
    );

    function setID(bytes32 cId) returns (bool){
        _id = cId;
        emit LogTestCase(_id);
        return true;
    }
}

Now when I put '1234' as a parameter, fetching it from the contract event results in 'M'.
But when I put any other string containing alphabets, I get the correct initial string

So passing any number as a string to the contract function with byte32 type cannot be retrieved. Is there any way to get exactly what I passed?


texts: How to properly convert wei to Ether in a contact?

texts:
As we know msg.value in contract is in wei. I wondered if there is a better way to convert it to Ether than dividing it by 10^18?

As an application consider the case where people buy tokens and the contract has a token balance. In this case, if we just copy user payments to the token balance array then the value will be too big and not user-friendly.


texts:
I am having trouble understanding the function confirmAndCheck (line 149 in the Wallet contract). Pasting the code below, with my addition in the last line:

function confirmAndCheck(bytes32 _operation) internal returns (bool) {
        // determine what index the present sender is:
        uint ownerIndex = m_ownerIndex[uint(msg.sender)];
        // make sure they're an owner
        if (ownerIndex == 0) return;

        var pending = m_pending[_operation];
        // if we're not yet working on this operation, switch over and reset the confirmation status.
        if (pending.yetNeeded == 0) {
            // reset count of confirmations needed.
            pending.yetNeeded = m_required;
            // reset which owners have confirmed (none) - set our bitmap to 0.
            pending.ownersDone = 0;
            pending.index = m_pendingIndex.length++;
            m_pendingIndex[pending.index] = _operation;
        }
        // determine the bit to set for this owner.
        uint ownerIndexBit = 2**ownerIndex;
        // make sure we (the message sender) haven't confirmed this operation previously.
        if (pending.ownersDone & ownerIndexBit == 0) {
            Confirmation(msg.sender, _operation);
            // ok - check if count is enough to go ahead.
            if (pending.yetNeeded <= 1) {
                // enough confirmations: reset and run interior.
                delete m_pendingIndex[m_pending[_operation].index];
                delete m_pending[_operation];
                return true;
            }
            else
            {
                // not enough: record that this owner in particular confirmed.
                pending.yetNeeded--;
                pending.ownersDone |= ownerIndexBit;
                // m_pending[_operation] = pending; // ?
            }
        }
    }

In case of multiple confirmations, shouldn't we save the local variable pending inside m_pending, since it will be accessed again later in line 155?

Thanks,


texts:
we are clear that in geth console we can add another peer with addpeer command such as

admin.addPeer("enode://41bd7d2fe91b344f0ca4ac89c217d688ef90a3616927acec428adddbc69dd2ac5470a489fd2beb67719cbd481436b98284ef9eac50efa49f55fe33e804818520@10.0.50.91:30303")

so, my question is that how to add another peer in solidity contract?


texts: Which mnemonic generators exist or existed?

texts:
I am unable to open a wallet I created roughly 2 years ago.
In that time I have been using MEW, MetaMask and something that I installed locally on Window, which I forgot the name of. Not sure which wallet actually generated the mnemonic, however MetaMask support claims it is probably not it.

The mnemonic phrase was stored in LastPass and LastPass has no history of any changes to it, so I believe it should be correct.
I've tried to create the wallet with MetaMask, MEW and MyCrypto, but none worked.

One word in an arbitrary position is "rebound".

Checking the BIP39 wordlist my mnemonic doesn't match any word, which gives me an impression that the phrase was generated with another algorithm/word list.

With what algorithm could the mnemoinic be generated?
Can we have a list of all of them here for others with similar issues?

----EDIT----

The mnemonic phrase is 12 words long.
I've never owned or used a hardware wallet.


texts:
I'm writing an application that will talk to the Ethereum network, I have decided to host my own Parity nodes in the cloud using GCP Kubernetes Engine. I set up 3 node replicas for increased availability.

Are there any implications associated with talking to a randomly load balanced node instead of always talking to the same node?

Would I have to account for the fact that I'm not always talking to the same node in my application code?

Edit: After some exploration I think the best way for me to handle this will be to send the same transaction to all nodes at the same time, instead of round robin load balancing.


texts: What are the costs of using Chainlink to generate a random number using VRF?

texts:
I'm doing some research about generating true randomness on the Ethereum blockchain.
Of course I came across Chainlink and its VRF solution.
Although there are many tutorials around, some from chainlink themselves, there is no easily available information about number generation prices (only LINK price itself) or amounts to be spent at each roll.
Does anyone who's had more experience in this know approximately how much it costs for each number roll generation?


texts: Call the function of another contract not on behalf of this contract

texts:
I have 2 contracts.
For example:
Contract 1

contract Token {

  using SafeMath for uint256;

  function transfer(address _to, uint256 _value) returns (bool) {
      var test = msg.sender; //msg.sender == address Contract2
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value);
    return true;
  }

}

Contract 2

contract Contact2{
    function test() {
          address test = msg.sender; //msg.sender==address my wallets
          Token(0x5faf852d0bae90ae3adb58f68deae7fcfc065a6d).transfer(this, 1);
        }
}

When I call test () from the contract2, msg.sender = the address of my wallet. But when running Token(0x5faf852d0bae90ae3adb58f68deae7fcfc065a6d).transfer(this, 1) then msg.sender = address Contract2

As in the contract Token get msg.sender = my wallet?


texts: change gasLimit parameter into the genesis.json file on azure priavte blockchain

texts: I am trying to deploy a smart contract to an azure blockchain. The contract is deployed without errors but i can't submit transaction to the blockchain through this contract. I guess this is an issue with gasLimit, because when I use my private geth blockhain where I can set my gasLimit in the genesis.json file, my Dapp works perfectly and I can run my transaction. The gasLimit on azure is set up by microsoft on the genesis.json file and I would like to find a way to change it. How can I do this?


texts: Ethereum private network without new coin mining

texts:
I managed to create a private Ethereum network using the following genesis.json

{
    "config": {
        "chainId": 15,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
    "difficulty": "200000000",
    "gasLimit": "2100000",
    "alloc": {
        "1A77F77E1e523f9f68D97A89b0502f136fB7F942": { "balance": "300000000000000000000000000000000000000" }
    }
}

Because I already alloc the coins to this above wallet, I don't want any new coins generated in this network. With this genesis configuration will miners be able to generate new coins? or else miners will only mine for transaction validations?

How can we differentiate those two ways from the genesis block?


texts: Contract deployment using web3.eth.contract(abi) with constructor arguments

texts:
I'm trying to deploy the following smart contract:

pragma solidity ^0.5.00;

contract TestContract {

   address public owner;
   string public word;

   constructor(string memory _word) public{
      owner = msg.sender;
      word = _word;
   }

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

   function getWord() public view returns (string memory) {
      return(word);
   }

   function updateWord(string memory _word) public onlyOwner {
      word = _word;
   }
}

But I'm having trouble deploying it with the constructors parameters. I'm using MetaMask and web3.js (that I got from here: https://github.com/ethereum/web3.js/blob/develop/dist/web3.js) with the following test code:

var Web3 = require('web3');
var web3 = new Web3(web3.currentProvider);

var code = '0x608060405234801561001057600080fd5b506040516106b...';

var abi = JSON.parse('[{"constant":true,"inputs":[],"name":"word","outputs":...');

var myContract;
function createExampleContract() {

    document.getElementById('create').style.visibility = 'hidden';
    document.getElementById('code').innerText = code;

    web3.eth.defaultAccount = web3.eth.coinbase;
    document.getElementById('status').innerText = "transaction sent, waiting for confirmation";

    web3.eth.contract(abi).new({data: code}, function (err, contract) {
        if(err) {
            console.error(err);
            return;
        } else if(contract.address){
            myContract = contract;
            console.log('address: ' + myContract.address);
            document.getElementById('status').innerText = 'Mined!';
            document.getElementById('call').style.visibility = 'visible';
        }
    });
}

function callExampleContract() {
    var param = parseInt(document.getElementById('value').value);

    myContract.getWord(param, function(err, result) {
      if (err) {
        console.log('e: ' + err);
      } else {
        console.log('r: ' + result);
      }
    });
}

I got the code and abi with this two terminal commands solc --bin contract.sol and solc --abi contract.sol

I was trying arguments:['param'] after data:code and the contract deployment goes through but when I call the getWord method, this error shows up BigNumber Error: new BigNumber() not a base 16 number and searching on-line I found out that this may accour due to null values returning from the method call. So how do I deploy the contract with constructor arguments properly?

Thank you all!! =)


texts: Solidity: How can we write a error message in "require"?

texts:
Im learning Solidity. As far as I'm aware, it's recommended using "require" to handle errors. But, I'd like to inform the users about the kind of errors they make, e.g. an argument is invalid or out of range, etc.

Question: How to write a error message in error handling functions like "require"?

Also, I need to know if it makes sense to have such error messages in contract?


texts:
Can Metamask wallet ethereum addresses be created in the Tor browser, given that Metamask is a browser extension? If not, what web wallet is most appropriate for Tor users, especially on a WindowsPC running the Tails OS which deletes itself and all traces of the session upon shutdown?
Under Tails and  Tor, it seems the wallet would constantly have to be recovered because of each session being cleared, although this wouldn't really be an issue as long as the wallet only needs to be accessed seldom, since activity can be monitored on etherscan independent of Tor


texts:
Regarding acceptance/rejection of uncle blocks, what are acceptable block timestamps for an uncle block?

Say:
block123_timestamp = Y
uncle123_timestamp = X

Where X < Y. Is uncle123 a valid uncle, even though it was stated to be produced earlier by its miner?

Thank you!


texts: How do I get ETH into my testnet Metamask wallet?

texts:
After switching to testnet from the dropdown in Metamask, the address used is still my Mainnet address.

web3.eth.getAccounts(function(a,b) {
      Merchant.accounts = b;
      console.log("Merchant accounts: " + Merchant.accounts);
      let x = web3.eth.getBalance;
      console.log(x);
    });

shows 0xc27a6adac593d1c02355f307ea92f6261269566d, my mainnet address.

I've tried sending funds via truffle console:

truffle(development)> ma
'0xc27a6adac593d1c02355f307ea92f6261269566d'
truffle(development)> web3.eth.sendTransaction({from: web3.eth.accounts[1], to: ma, value: 10000000000000})
'0x9c59733f9e8bed3f13d6f96589894239a43af6a5e387b40e7a9fad4e0157aaa7'

I don't see the balance change in MetaMask.

How do I add funds to my test Metamask?


texts: increment contract value with console call on truffle / testrpc, variable is not persistent

texts:
What I want to do is make a smart contract which has a variable that can accrue value. I'd like to have it start off as 0, and then increment it, while periodically checking to verify that my calls to increase the value have in fact been working.

Here's my very simple smart contract to achieve that:

pragma solidity ^0.4.13;

// This contract demonstrates a simple non-constant (transactional) function you can call from geth.
// increment() takes no parameters and merely increments the "iteration" value.

contract Incrementer {
    uint iteration;

    function Incrementer() {
        iteration = 0;
    }

    function increment(uint count) {
        iteration += count;
    }

    function getIteration() constant returns (uint) {
        return iteration;
    }

}

However, it must be broken, or perhaps I'm not calling it in the right way, as you can see by my console output:

The execution environment I'm using is truffle.

The commands to compile were:

truffle compile --all
truffle migrate --reset

Then I fire up to truffle console to interact with it, after having started testrpc in another window.

The exact commands I've been using it call it have been:

Incrementer.deployed()

Incrementer.deployed().then(function(instance) { meta = instance; return meta.getIteration.call(); })

and alternatively:

Incrementer.deployed().then(function(instance) { meta = instance; return meta.increment.call(1); })

How can I get the value of iteration() to increase by calling increment(), and then outputting the result with getIteration()?

EDIT:


texts: Did the original Ethereum ICO have a different BIP32 word list?

texts:
I have a 12 word seed which I believe should be BIP32 compliant and I think is from the original Ethereum ICO.

It was in an email sent to me (by myself) on 10th July 2014 - which was CoinSummit London where I first learned of Ethereum.

I suspect this is for the original Ethereum ICO, however none of the BIP32 compliant wallets I can provide this to (Ledger, Trezor, MetaMask) recognise the wordlist due to having words their dictionaries are missing such as:

stop
nerd
stupid

I have investigated and learned there should be a wallet.json for this ICO which I cannot find - but thought these BIP32 memnonic should also resolve to an Ether key.

I wonder if someone has the wordlist for the original Ethereum ICO so I can see if this is a valid memnonic or not?


texts:
I wonder where "Smart Contracts" are actually running: Are they running on every node in the network? I rather doubt this, given the costs for running the contrat.

If my assumption is correct and the "Smart Contract" is only running on one single machine: How can the network ensure that the output of this Smart Contract is correct? Am I supposed to trust the machine that is running the Smart Contract?

Thanks for a quick reply.


texts: Mix just wiped my entire project directory!

texts:
Turns out if you try to create a new project using an existing directory, Mix wipes the directory first.

It's just lost me my last months DAPP work!

I ran into troubles when mix stopped acknowledging the 'Rebuild Scenario' buttons and failed to show 'expand transaction' buttons.  Restarting and reloading the scenario failed to restore functionality.  New projects could create fine but even the default Sample project fails to set()


texts: How to get ETH from Dwarfpool to Coinbase?

texts:
I have been mining Ethereum (ETH) using SMOS and Dwarfpool for the last few months.  I was also using MetaMask to transfer my mined ETH coins to Coinbase.  It was working fine until MetaMask pushed an update this week, and now all my account balances and history in their interface have been completely wiped out.  I'm familiar with their process for regenerating an account with a seed phrase, as I've had to do that a couple times to access my accounts on MetaMask through my various computers.

My question isn't about MetaMask, so much as it is about how can I can get my mined ETH coins over to Coinbase.  I've been working on this all evening, and I'm really stuck.  My confidence in MetaMask is somewhat diminished, so if there's another reliable way to do this, I'm all ears.


texts: How to write transaction logs into a text file in geth?

texts:
I have made a contract which generates a public event on blockchain that will notify client about a transaction.
To listen to the event I have written following snippet in geth console:

var event = token.CoinTransfer({}, '', function(error, result){
  if (!error)
    console.log("Coin transfer: " + result.args.amount + " tokens were sent. Balances now are as following: \n Sender:\t" + result.args.sender + " \t" + token.coinBalanceOf.call(result.args.sender) + " tokens \n Receiver:\t" + result.args.receiver + " \t" + token.coinBalanceOf.call(result.args.receiver) + " tokens" )
});

Now instead of console.log() I want these transaction to be stored in a text file TransactionHistory.txt. How can we do this? Is there a better way than listening to event, to maintain transaction logs?


texts: I got this error during migration in truffle. : ParserError: Expected '(' but got identifier

texts:
This is my smartcontract code

pragma solidity ^0.5.0;

contract DappToken{

uint256 public totalSupply;

constructor DappToken() public{
    totalSupply = 10000;

 }

}

This is code for migration in truffle.

const Dapptoken = artifacts.require("DappToken.sol");

module.exports = function(deployer) {

deployer.deploy(Dapptoken);

  Blockquote

};


texts: 'tokenupdateverifysig' on etherscan.io will not seem to process without error for me, please help

texts:
Playing around with creating an erc20 as we all do, this is the bare minimum of a coin, I'm being a script kiddie douche in that sense so preemptive apology.

I've made it this far and plan to go public by the end of the week but can't seem to get through:

https://etherscan.io/tokenupdateverifysig

If you haven't been there it asks for: Contract Owner/Creator Address:

I've been using the address with all the tokens in it and metamask to sign it, they're the same address.

Message Signature Hash:

I've copied the string out of the signed message with no quotation marks

Enter the original message that was signed:

I've been copying the whole thing every time and inserting it (being the brackets)

Troubleshooting:

This should be field 1: 0xa1d06be35a7c510db96df8ab238ca179eb66446c

Error:

It has been saying to ' Please enter valid Token Contract Address in the signed message.'

as far as I know I have been, I'm using the address: 0x2799d90c6d44cb9aa5fbc377177f16c33e056b82

This is the 'to' value / contract address.

Possible solution:

Am I messing up on the formatting of the message? It provides this template:

[Etherscan.io dd/mm/yyyy hh:mm:ss] I, hereby verify that the information provided is accurate and I am the owner/creator of the token contract address [token contract address].

Does it want the current date and time? What should be in the first brackets entirely?

Do I keep the brackets for the contract address? It just seems super fragile.

Thanks so much for taking the time for reading this!


texts: What would an Etheruem-like blockchain look like if each block were just an IPFS hash?

texts:
I see a lot of people tout the enormous benefits of using IPFS as a store of data. Meanwhile, the Ethereum blockchain is over 1TB in size, with quesitonable need to keep the earlier blocks.

In bitcoin, it makes sense to me why you would need to keep the entire blockchain hosted somewhere, since unspent transaction outputs need to be kept somewhere. Unlike bitcoin, the latest block in ethereum almost always a snapshot of the most recent state of Ethereum, effectively an auto-calculation of the unspent transaction outputs. So, with the exception of tracking how those who participated in the 80% ethereum ICO have hodled their coins, there doesn't really seem to be much need to store these early ethereum blocks.

Anyway, the point I am getting to is, if we could require a node who was a miner to link only to the IPFS hash of their block, and require them to host said block for only long enough for other miners to validate, would this be a good idea? Each IPFS hash would link to a block which contained each transaction included in said block. Miners would be required to download this block before validating the block included in the chain.  Is this any different than say just downloading block hashes? What do we lack in terms of security, because we clearly gain a lot in terms of long-term blockchain storage?

Yes, I am implying that over time (i.e. with enough block confirmations), miners would stop hosting these IPFS blocks.


texts:
As per the basic rules of blockchains believe it is mentioned that no service call from the smart contract should be made where the result is non deterministic.

What I understand is if the result is non deterministic in that case, when the transaction will be executed in different nodes it will not be possible to reach consensus as everyone may get different results.

When a new node is added it is expected to first sync to get the whole distributed ledger downloaded.

Believe every new node added on the blockchain network verifies all the previously generated transactions. So in this case it will invoke this external service as well to verify the result and based on the output will behave accordingly.

But found using Oraclize one can invoke external services from smart contract. So if the above assumption is correct then how come it is feasible to invoke external services or are they invoked for specific scenarios only


texts: How to run contracts with 'Oraclize' using truffle?

texts:
This is the contract code.I have downloaded the 'Oraclize API' (oraclizeAPI_0.4.sol)from the Oraclize github repo.I have added this file to the truffle contracts folder, and rename the file to usingOraclize.sol.And it is imported in the given contract.

 pragma solidity ^0.4.0;

 import "./usingOraclize.sol";

 contract ApiCall is usingOraclize {

       uint public DieselPriceUSD;

       function DieselPrice() {

                OAR = OraclizeAddrResolverI(0x920cd3f7ed02c5d61e2556308d53a4d9d1e58bf2);
       }

       function __callback(bytes32 myid, string result) {
                if (msg.sender != oraclize_cbAddress()) throw;
                       DieselPriceUSD = parseInt(result, 2);
       }

      function update() payable {
                oraclize_query("URL", "xml(https://www.fueleconomy.gov/ws/rest/fuelprices).fuelPrices.diesel");
     }

}

I have compiled and deployed this contract succesfully.
Then tried to call the methods available using the following.

  contract.getCall().then(console.log);

But it returns the following error.

Error: VM Exception while processing transaction: invalid JUMP at 7ed62a9ee27ba25842c0facef792865de53617fe32c09b7eb974a8bca5dd54c0/b8cd3e9aaf13b8823aa83f0f47f235943dac31c6:692

How to call _callback function in this contract with the parameters?What these parameters in this _callback means?

How to use this _callback in index.js in truffle?


texts: can we jam the ETH network with assert/require functions?

texts: If we make for example a smart contract with a require function that is always false and we execute it tons of times (knowing that we will get our gas back cause of the revert function)will we be able to jam the eth network for free?


texts: Sending ETHM to my ETH wallet address in Coinbase Wallet results in the ETHM being sent back to my ETHM wallet

texts: Using Coinbase wallet, I sent ETHM to my ETH wallet address (ETHM is ERC20). The transaction was successful and I was charged a fee. In Coinbase Wallet I now see the ETHM back in my ETHM wallet, which was sent there from my ETH wallet address. How can I transfer the ETHM to ETH? I can do it in Uniswap, but Coinbase wallet is reflecting a much higher rate for the ETHM, so I want to do the swap there.


texts:
I have a simple contract which logs an error if the input is less than 9 characters/bytes. It works fine with remix, but not in truffle js test and truffle console. Am I doing something wrong by passing the bytes32 input as "123456789"?

Contract:

pragma solidity ^0.4.11;

contract TestLength {

    event Error(string message, bytes32 input);
    bytes32[] allInputs;

    function test(bytes32 input) {

        if (!validateLength(input, 9 , 9)) {
            Error("minimum 9 characters", input);
        }

        allInputs.push(input);
    }

    function validateLength(bytes32 b, uint minLength, uint maxLength)
    constant internal returns (bool) {

      for (uint i = 0; i < 32; i++) {
        if (i < minLength) {
          if(b[i] == 0) return false;
        }
        if (i > maxLength - 1) {
          if(b[i] != 0) return false;
        }
      }

      return true;
    }
}

Truffle JS test:

var TestLength = artifacts.require("./test/TestLength.sol");

contract('TestLength', function(accounts) {
  it("should not throw an error when passing 9 characters", function() {

    var testLength;

    return TestLength.deployed().then(function(instance) {
      testLength = instance;
      return testLength.test("123456789",{from: accounts[0]});
    }).then(function(instance) {
      console.log("test: " + JSON.stringify(instance));
      assert.equal(instance.logs.length,0,"no event should be triggered.");
    });

  });

});


texts:
I need to transfer ether from one account to another using solidity contract.
I am new to ethereum and solidity , so please help me.


texts: Can't import a contract interface in vyper

texts:
I need to import a contract interface using the JSON ABI but I get syntax error when trying to import the interface.

I have created the JSON file in remix and named it IERC1620.json then I am trying to import the interface like this:

import IERC1620.json as fooBar

I have tried to remove the .json extension but I still get his syntax error:

line 1: Unknown interface fooBar import IERC1620.json as fooBar

I checked the documentation and what I am doing should be correct


texts: Does Ethereum use the longest chain rule like bitcoin?

texts: I can't seem to find a straight answer to this question. I know that Uncles are rewarded, but are they used to help secure the network? Or does Ethereum use the longest chain rule like Bitcoin?


texts:
I added the following code for implementing a wait logic after deploying the contract and before calling the functions from the contract. This is same as mentioned in some other posts in Stackexchange.

// await sleep trick
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// We need to wait until any miner has included the transaction
// in a block to get the address of the contract
async function waitBlock() {
  while (true) {
    let receipt = web3.eth.getTransactionReceipt(transferfunds.transactionHash);
    if (receipt && receipt.contractAddress) {
      console.log("Your contract has been deployed at http://testnet.etherscan.io/address/" + receipt.contractAddress);
      console.log("Note that it might take 30 - 90 sceonds for the block to propagate befor it's visible in etherscan.io");
      break;
    }
    console.log("Waiting a mined block to include your contract... currently in block " + web3.eth.blockNumber);
    await sleep(4000);
  }
  return;
}

While loading the script to Geth for testing, it returned the following error.

The error displayed points to the => from the sleep(). How can we get rid of this error ?


texts: How to get the same SHA3 hash as soliditySHA3(ethereumjs-abi) returns using web3.sha3 in js?

texts:
I'm trying to hash a message as shown here:

function constructPaymentMessage(contractAddress, amount) {
  return ethereumjs.ABI.soliditySHA3(
    ["address", "uint256"],
    [contractAddress, amount],
  );
}

how can I use web3.sha3 instead of ABI.soliditySHA3 to get the SHA3 hash correctly, is there any difference anyway? thanks.


texts: Return value from a smart contract function appearing for few seconds and then disappears

texts:
I developed a Dapp in which I am adding attributes to an entity, and finally I have a function to query some of the information about that entity, when I am clicking on the button to execute the function, the information appears for 2-3 seconds and then disappears after that, not sure why this is happening, if anyone can look at the below code and help me troubleshoot this.

Below is the code:

viewrice: function(id){
    var simp;
    Rice.deployed().

    then(function(instance) { simp = instance; simp.viewRice.call(id,{from: accounts[0],gas:3000000}).
    then(function(result){
        console.log(result);
        $("#riceowner").html(result[0]);
        $("#ricefarmer").html(result[1]);
        $("#ricestatus").html(result[2].toNumber());
        $("#riceweight").html(result[3].toNumber()); });
})
}

Click event:

    $("#viewrice").click(function(){
        var id = $("#viewid").val();
        App.viewrice(id);
    })

HTML front end:

View Rice

        <form>

                <input class="form-control" type="text" name="farmer" id="viewid" placeholder="id">

                <button class="btn btn-lg btn-primary btn-block" id="viewrice">Submit</button>

        </form>

Owner -

Farmer -

Status -

Weight -

Smart Contract function:

function viewRice(uint32 _id) public view returns(address owner, address farmer, State status, uint256 weight){
        return (rices[_id].owner, rices[_id].farmer, rices[_id].status, rices[_id].weight);
    }


texts: Get RPC URL / IP of Metamask's current provider

texts:
Suppose I have multiple copies of the same dapp running on different servers which do not directly communicate with each other, for testing purposes, and can manually interact with different dapp instances by changing which network I point Metamask to.

I would like to be able to show, on-screen, which network I am currently connected to (including the host address of my current provider), via client code.  Then, when I generate screenshots or printouts, it is clear exactly which server I was connected to when that content was generated, without having to open MetaMask and show its network selector for every screenshot (not available for printouts).  This can help eliminate speculation that an issue was caused by having an incorrect network selection in MetaMask.

More detail (skip for tl;dr): The client connects through MetaMask to a blockchain node hosted somewhere, which might be 127.0.0.1 or on a server that is part of the Infura service, or on some other machine which happens to be hosting a node for the blockchain I'm interested in reading from. It may be that there are multiple different IP addresses hosting the same blockchain (as part of a dapp) but the client will only connect to one at a time. Being able to show which one I'm reading from would also be helpful in checking for any differences between the nodes when, for example, they wind up on different sides of a virtual network partition and have no peer-to-peer communication path.

I can do web3.currentProvider and get a Proxy object revealing the selected address and network identifier code (which is 1 for mainnnet and small integers for big public testnets and settable for private networks; Ganache's default is 5777).  This network identifier is useful but not sufficient by itself.  I have not yet found a property or method I can call to get the IP address (or name set in MetaMask, which would seem less likely to be there).

Documentation on Provider objects is limited, but source code is here and the base class AbstractSocketProvider is here.

What am I  missing?  How would I programmatically find out the current network address of the blockchain node the client is interacting with?

Here is a more concrete example of what I'm trying to do, following a comment by @RobHitchens:

MetaMask has a network selector at the top of the interface, which looks like this at "Timepoint A:"

If you click the arrow in the right side of the bubble, there's a drop-down which shows other options, including Custom RPC.  Clicking that takes you to a settings menu and scrolling down allows the input of a "New RPC URL" like this:

In that box, you can enter another IP address like "http://192.168.1.24:1234" (for another machine on a local network, for example).  Clicking Save, that string becomes a new and currently-selected option in the network selector dropdown:

I'll call this timepoint B.  For purposes of this question, assume MetaMask successfully connects (no loading symbol next to that URL).

I would like a function I can programmatically call that will at timepoint A return "http://127.0.0.1:7545" and at timepoint B return "http://192.168.1.24:1234" with no change to the dapp/client source code between those timepoints.  It's OK if there are multiple functions which each return part of the information needed to construct that return value.


texts: How Long Till My Funds Show Up In My Mist Wallet?

texts: Total noob question, but I recently bought some ETH on the Kraken exchange and I also downloaded the mist wallet, made a password and added a new account. After withdrawing the ETH from the exchange to my wallet, I was just wondering how long until it actually shows up in the wallet? And I'm not sure if there's anything additionally I have to do besides what was mentioned above. I hear stuff about syncing the wallet and I'm not sure how to go about doing that exactly. Not very tech savy and new to the crypto world in general. Any help would be appreciated. Thank you!


texts:
I'm currently mining on a pool (Ethermine) with a single NVidia GTX 1060 6GB on Linux with NVidia proprietary drivers.

When I run ethminer with OpenCL (-G), I locally see a hashrate of about 18 MH/s, and the pool website is consistent with that value.
However, if I try running ethminer with Cuda (-U), I locally see a higher hashrate (20 MH/s), but the website dashboard indicates a lower hashrate (16 MH/s).

I'm a bit confused. Should I consider the local hashrate or the pool's?
For mining purposes, does Cuda produce higher hash rates with NVidia cards compared to OpenCL?


texts: How can I retrieve the stored data from blockchain?


texts: Is there a more "decentralized" way to verify an Ethereum account owns a particular Twitter handle?

texts:
Is this something fulfilled by a project like uPort?

Basically, I need a way in my contracts to verify that a particular Ethereum address (0xasdf...) and a particular Twitter handle (@user) are owned by the same person.

So far, the only solution I can come up with is me being a centralized party: the user logs into my Twitter OAuth app, I check who they are on Twitter, and write into the contract the association between the verified Twitter handle and their Ethereum address.

Was hoping there might be another way to do this using existing tools from the ecosystem where there is at least less of a dependence on me as a centralized attestator of Twitter identity.


texts: How much does the gas prices in the main eth network differ from that in the ropsten test network

texts: I'd like to know, to which degree does the Gas prices from the main eth network are comparable to the ropsten test network.


texts: How to create custom testnet like ropsten?

texts:
Is that possible to create a private testnet which can act like ropsten network.

i want to create a private net and i want to see all translation via online from etherscan.com

is that possible?


texts:
I have a voting solidity file here:

pragma solidity >=0.4.21 <0.7.0;
// We have to specify what version of compiler this code will compile with

contract Votingapp{
  /* mapping field below is equivalent to an associative array or hash.
  The key of the mapping is candidate name stored as type bytes32 and value is
  an unsigned integer to store the vote count
  */

  mapping (bytes32 => uint256) public votesReceived;

  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).
  We will use an array of bytes32 instead to store the list of candidates
  */

  bytes32[] public candidateList;

  /* This is the constructor which will be called once when you
  deploy the contract to the blockchain. When we deploy the contract,
  we will pass an array of candidates who will be contesting in the election
  */
  constructor(bytes32[] memory candidateNames) public {
    candidateList = candidateNames;
  }

  // This function returns the total votes a candidate has received so far
  function totalVotesFor(bytes32 candidate) view public returns (uint256) {
    require(validCandidate(candidate));
    return votesReceived[candidate];
  }

  // This function increments the vote count for the specified candidate. This
  // is equivalent to casting a vote
  function voteForCandidate(bytes32 candidate) public {
    require(validCandidate(candidate));
    votesReceived[candidate] += 1;
  }

  function validCandidate(bytes32 candidate) view public returns (bool) {
    for(uint i = 0; i < candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return true;
      }
    }
    return false;
  }
}

This is my migration file 2_deploy.js

const Votingapp = artifacts.require("Votingapp");
listOfCandidates = ['Rama', 'Nick', 'Jose']
module.exports = function(deployer) {
  deployer.deploy(Votingapp, listOfCandidates.map(name => web3.utils.asciiToHex(name)));
};

this is my js test script

var Votingapp = artifacts.require('Votingapp');
contract('Votingapp', function(accounts) {
  let instance;
  before(async () => {
    instance = await Votingapp.deployed();
  });
  it('check users in list',async () => {

    console.log("this is the" +  instance.candidateList.call());
    await instance.candidateList.call()

  });
});

However I keep getting a

  Contract: Votingapp
this is the[object Promise]
Error: Invalid number of parameters for "candidateList". Got 0 expected 1!
Error: Invalid number of parameters for "candidateList". Got 0 expected 1!
/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:726
  err.uncaught = true;
               ^

TypeError: Cannot create property 'uncaught' on string 'abort(Error: Invalid number of parameters for "candidateList". Got 0 expected 1!). Build with -s ASSERTIONS=1 for more info.'
    at Runner.uncaught (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:726:16)
    at process.uncaught (/usr/local/lib/node_modules/truffle/node_modules/mocha/lib/runner.js:839:10)
    at process.emit (events.js:189:13)
    at process.emit (/usr/local/lib/node_modules/truffle/build/webpack:/node_modules/source-map-support/source-map-support.js:485:1)

Any help what im doing wrong?


texts:
my MetaMask does sometimes load infinitely.
It then says "Connecting to Main Network" until I click on "Ropsten" and then back to "Main Network". That normally is no problem for me.

But as I am a dApp developer I have no idea how to identify this when a user has this problem. When checking network, it does not define any network. When checking if user is logged in/has an account, it also simply says nothing.

Is it possible to detect this loading process with web3?


texts:
I'm not getting the same hash running this function

    function getMineDigest(uint256 challenge_number, bytes32 nonce) public view returns (bytes32 digesttest) {
        bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce));
        return digest;
    }

As running this in python

web3.solidityKeccak(['bytes32','address','uint256'],[challenge_number, account, nonce])

Perhaps "msg.sender" is not the value I anticipate.

To test this I added this function to my contract

    function getSender() public view returns (address) {
        return msg.sender;
    }

But it is returning '0x000000000000' which menas that either msg.sender is not my metamask account or I'm unfamiliar with more nuances of ethereum.


texts: Problem accessing variables stored in event log

texts:
I have succesfully implemented an event in my contract Portfolio:

// Define eventlog for myEvent
event myEvent(uint indexed eventDate, address indexed sender, myArray[] eventList, uint eventBalance);

function setEvent() public {
    // Function to track event
    myEvents.push(now) -1;

    uint totalBalance = getTotalBalance();

    emit myEvent(now, msg.sender, myArray, totalBalance);
    }

The event is being created succesfully. I can find it in the Etherscan (Ropsten). I can retrieve the events from web3 and if there are multiple events see them. I have added the ABI and use the following code to read the events:

    function getEventClick() {
        $("#loader").show();

        myPortfolio.myEvent({}, { fromBlock: 0 }).get((errGetEvent, resGetEvent) => {
            if (!errGetEvent) {
                for (var p=0;p<resGetEvent.length;p++)
                    {
                    console.log(resGetEvent[p]);
                    }

                $("#loader").hide();
                }
            });
        }

If I look in the console I see the event. My question is though, how do I access one of the event variable? For example eventDate? I tried the format resGetEvent[p][0] but that does not work.

@smarx the output looks something like this:

"47966a823fc8fa850a44428b5cb3b30efedb40248b6a9f867e7341a7ca1608", blockNumber: 6453810, logIndex: 30, removed: false, …}address: "0x714e7201582e138e5g3177c1f98370f14735fa69"args: eventBalance: X {s: 1, e: 12, c: Array(1)}myArray: ["0xb045ca6e22fbb0cbeabc6ec32923d86948c0b423"]eventDate: X {s: 1, e: 9, c: Array(1)}sender: "0x6d4dcc21e77ee5bc18d0d91497fc5285a71c836a"proto: ObjectblockHash: "0x0547966a822fc8fa850a44758b5cb3b30efedb40248b6a9f867e7341a7cb1608"blockNumber: 6454880event: "myEvent"logIndex: 30removed: falsetransactionHash: "0xa75d74264e05807e87d32135f9c1b9ed242af67584dcbb42cca9303ed0ee5c44"transactionIndex: 19__proto__: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()defineGetter: ƒ defineGetter()defineSetter: ƒ defineSetter()lookupGetter: ƒ lookupGetter()lookupSetter: ƒ lookupSetter()get proto: ƒ proto()set proto: ƒ proto()
(index):5348

I would appreciate any help you can give me.

Thanks!


texts:
I'm using Web3.py with Infura
Is it possible to see in real time the last pending transactions ?
And have all the informations about it like who send it, who received it and more.
The idea is to do a specific action when a specific transaction is seen in the mempool


texts:
I'm going over Chainlink tutorials.
Sometime I see Chainlink imports using @chainlink/path/to/contract and other times https://github.com/smartcontractkit/chainlink/blob/path/to/contract.
Are Contracts in production suppose to use the live Github link? Or the other import?
I'm confused, because I can't find any explanation for when you'd want to use one vs the other.
When do you use one over the other?


texts:
I'm reading about Casper protocol and the hybrid solution that Ethereum is going to adopt in the first place. Can you tell me if I understand the mechanism well?

The hybrid solution initially provides both pow and pos. Starting from the Genesis block C_0, the notion of epoch is presented. Between two epochs the blocks are still mined with pow mechanism. Then, the epoch block is selected by pos algorithm where a set of validators "bet" and choose it. This choosing procedure is done as follows:

1) Validators lock some of their money in the network (The higher the quantity of money is locked by a validator, the greater his influence during the betting phase)

2) Validators choose the best block they believe it can be the next block in the blockchain, aware that if they choose a block containing invalid transactions, they will lose their money. To choose the block they partecipate in 2 phases:

Prepare ( I omit the details about its structure [prepare, hash, epoch, previous hash, previous epoch]), where validators choose the best block for them. When 2/3 of the validators (or better, 2/3 of the money locked) agree on a block, it comes the other phase;

Commit ( I omit as before its structure), where validators "confirm" this block. When 2/3 of the validators agree, the block is added at the blockchain.

( If a validator chooses a block with malicious transactions, or bet on more than one block, he loses their money. If a validator chooses a valid block but that block does not reach the 2/3 in the Prepare phase, he does not lose his money.)

3) After the epoch block has been selected, the miners start to mine other blocks until the next epoch block is reached and so on.

Is this procedure right? Did I get it right? Also, if I missed some details, please tell me :) Thank you all!


texts: p2p connection library for Blockchain example

texts:
I would like to implement the missing p2p communication for this example repo.

Does anyone know the best library I could use to implement communication between nodes? Moreover a tutorial or guide to understand communication between nodes in a blockchain?


texts: In solidity smart contracts how do you access internal state variables declared in the constructor?

texts:
I'm working with a solidity contract that declares a state variable in the constructor like this this:

    constructor(
    address vault,
    address proxy
)
    public
    MarginAdmin()
{
    state = MarginState.State({
        VAULT: vault,
        PROXY: proxy
    });
}

My understanding is that this state variable is internal and will not have a getter created. How do I access this state variable from outside the contract like from a dApp?