texts: How unconfirmed transaction is verified in Proof of Authority?

texts: I see a lot of articles explaining about Proof of Authority but mostly they only talk about how block is created which is by using sealer from authenticated node. I wonder when transactions arrive at authenticated node, how authenticated nodes verify the transaction and how those transactions are put into the block. If there is any links that I can refer to, please share with me. Thank you!


texts: Address checksum Solidity implementation

texts:
Looking at EIP-55, there are quite a few client-side address checksum implementations provided but no Solidity implementation. Are there any existing examples of computing address checksums directly in Solidity? Not only could an implementing contract be called by clients as a convenience function, but it would also allow for employing on-chain logic based on address checksums. For the latter case, gas efficiency would likely be an important consideration.

Here's an example of an interface that said implementation would inherit:

interface AddressChecksum {
  function getChecksum(address account) external pure returns (string accountChecksum);
  function getChecksumCapitalizedDigits(address account) external pure returns (bool[40] digitCapitalized);
  function isChecksumValid(string accountChecksum) external pure returns (bool ok);
}


texts:
I am trying to filter out transactions from BSC and read their input data (specifically borrows from venus), however I am having trouble getting my event filter to work properly.
I have already tried to search around for an answer, and found this but it doesn't seem to help me as there is no longer a contract.eventFilter() function.
Here is my code:
import json
from web3 import Web3
from time import sleep

abi = json.load(open('abi.json', 'r'))
# I got the abi from https://bscscan.com/address/0xcf6bb5389c92bdda8a3747ddb454cb7a64626c63#code

w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))

contract = w3.eth.contract(address="0xd4CB328A82bDf5f03eB737f37Fa6B370aef3e888", abi=abi)

transfer_filter = contract.events.Transfer.createFilter(fromBlock="0x0", argument_filters={'from': '0xd4CB328A82bDf5f03eB737f37Fa6B370aef3e888'})

while True:
  print(transfer_filter.get_new_entries())
  sleep(2)

I'm not really too sure where I am going wrong, as I don't know if I have the right from address for transfer_filter as the only output I am getting is [].
Thanks for any help in advance!


texts: Is every node connected to all other nodes?

texts:
In ethereum network, does every node has to be connected to each and every other node in the network?

Or for syncing, they just connect to any random node?


texts: How to save long textual data on blockchain?

texts:
I need to write blogs and save them on blockchain. What are efficient possibilities to store such data on blockchain?

Thanks for reading the question, already appreciate your time.


texts: How can I get the revert reason of a call in Solidity so that I can use it in the same on-chain transaction?

texts: I want to get the revert reason of a failed call and then use that revert reason in the same on-chain transaction. Is this possible?


texts:
Testing smart contract Via another Testing Smart contract -

X.sol

contract X{
   function reservePlace(string _name) public payable returns (bool isNotReserved) {
      // use _name to reserve it
   }
}

TestX.sol

contract TestX {

  X x = X(DeployedAddresses.X());

  function testReservePlace() public {
    // what to do here to call reservePlace with an address of my choice
    // right now it calls reservePlace with account that deployed the contract X
    bool flag = x.reservePlace.value(1 ether)("hj");
  }
}

Now Truffle always uses the address that deployed contract X to fire this call.
In order to test X I need to be able to call the reservePlace with any random address. How can I do that?

I run the tests using truffle test

I can do the same in a JS test as -

x.reservePlace (arg1, {from: account2});


texts: Even if I own 51% of stake (or have 51% computational power) and try to cheat, can't others still see that my block is invalid?

texts:
I'm thinking about how proof of stake works exactly.
As I understand, here is how it is secure:

I cannot forge a tx where random A pays me X amount because I would need the private keys of A. Validators can easily see that A did not sign this tx.
I cannot validate my invalid tx myself because I would need to be a validator.
I cannot be a validator without depositing a stake and getting selected by other validators randomly.
I cannot forge a staking tx (deposit a stake) because validators can see I do not have enough ETH.
If I am a legitimate validator, I cannot fake-validate an invalid tx/block because other validators will mark that same tx/block as invalid and see that I did the opposite and penalise me by taking some of my stake.

My question is:
Even if I have 51% stake which means my vote of validation outweighs all other validators, why can't "non-validator normal nodes" (i.e. wallets who are consuming and not publishing blocks) simply check my invalid block that I've just published and see that it's invalid? At the end of the day, every tx still needs to have valid signatures and I cannot spend more than what I own.
In fact, I could ask the same question about PoW. Even if I have computational power to calculate the next hash quicker than everyone else, any node on the network can still check the validity of my block.
Potential answer:
In, PoW, it's super easy for wallets to calculate just one hash and see if it matches the header in the new invalid block. That is enough and we do not need to inspect every tx in the block because we know that header hash requires work to be derived (it's a solution to the "target" and nonce incrementing puzzle) so we simply trust PoW i.e. PoW is vulnerable to 51% attacks by design.
However, in PoS, that "puzzle" isn't part of the algo, there is no "mining" and it's easy for anyone to publish a fake block so a non-validator node would have to check every tx in the block which is a lot more work. I don't know how deep it has to go, maybe all the way back to the start of the chain.
Could it be that in PoS it's too costly for non-validator nodes to check every block themselves so by-design they do not do so and trust the published block just like in PoW? meaning it's vulnerable to 51% attacks as well (stake this time not computational power)?


texts: DeclarationError: Undeclared Identifier. Did you mean "_data"? data = _data ^__^. All i want is to create a cryptocurrency

texts:
pragma solidity ^0.5.1;

contract owner {
    address public owner;

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

    function set( string memory _data) public {
        data = _data;
    }

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

function transferOwnership(address newOwner) onlyOwner public {
        owner = newOwner;
    }
}

interface tokenRecipient { function receiveApproval( address  _from, uint256  _value,  address _token, bytes _extradata) public; }


texts:
If you have a public variable like this:

  uint256 public totalSupply;

Is it necessary to also include a totalSupply method to a standard ERC20 contract?

I know there is a getter that Solidity generates for public vars.


texts: Solidity link to external library address - use Lib for uint256 breaks

texts:
I'm trying to link my contract to an external library by defining

an interface contract that defines the library functions and
the main contract that refers to the actual library address.

My library must be deployed externally and not be fully defined in the same contract (has presented the below challenge when using use Library for unit256)

// 1. Set up an interface defining the functions that exist within the target library (but not implementing them!!)
contract SafeMath {
  function mul(uint256 a, uint256 b) internal pure returns (uint256);
  function div(uint256 a, uint256 b) internal pure returns (uint256);
  function sub(uint256 a, uint256 b) internal pure returns (uint256);
  function add(uint256 a, uint256 b) internal pure returns (uint256);
}

// 2. Define the main contract with reference to the interface and external deployed library address
contract Foo {
  SafeMath ExternalSafeMath = SafeMath(0x013......);

  // THE LINE BELOW BREAKS
  // It expects a library but instead gets contract. I must find a work around or obtain advice on how to otherwise implement this
  using ExternalSafeMath for uint256;

  // Contract  continues ...
}

As seen above, I specify an interface contract that defines the functions that this library contains (as per suggestions in this forum's previous answers).

When attempting to issue a using ExternalSafeMath for unit256, the compiler correctly complains that it expects the ExternalSafeMath object to be a library, and NOT a contract. But as it stands, it is currently a contract for interface purposes.

THE QUESTION: How can I achieve a using Library for uint256 on an EXTERNALLY deployed library? And how will my syntax of code change in the code that follows

THE CONTEXT: My requirement is that I cannot implement the entire library in one contract deployment.

This is due to my contract implementation exceeding gas limit  during deployment. Hence needing me to modularise contracts to separate addresses but still retain functionality of the current code


texts: Does an ERC-20 token transfer cost more gas than an ETH transfer?

texts:
After messing around on the Remix IDE, I realized that initializing a uint (to any value other than 0) costs about 20,000 gas. Because of this, an ERC-20 token transfer to an account with balance 0 must cost at least 41,000 gas (transaction + initialization).

Now, is the behavior the same for an ETH transfer to a new address or would it cost less gas?


texts: A couple of questions on the Short Address attack

texts:
I have a few questions on the Short Address attack:

Is it possible to apply this attack on a function which does not take encoded byte-code as input and execute it, for example - function func(bytes data)?
If yes, doesn't this mean that one should verify msg.data.length in every public or external function?
If a function of mine verifies the value of msg.sender (doesn't matter how, but let's assume that the function can determine whether or not I trust this sender) - am I still at any risk of a non-verified sender calling it with malicious data?

I have found several partially-related answers on this website (one of them to my own question), but I have not been able to decide how this attack should be handled with in my solidity code (off-chain code is not critical as far as I'm concerned):

Answer 1
Answer 2
Answer 3

The majority opinion seems to be that such protection should not be added on-chain.

In my 3 questions above, I am trying to determine whether or not I can feel safe with that.

Thank you very much!!!

UPDATE:

As I mentioned above (and to the reader who closed this question as duplicate by specifying a question which I have explicitly linked here):

I have found several partially-related answers on this website (one of them to my own question), but I have not been able to decide how this attack should be handled with in my solidity code (off-chain code is not critical as far as I'm concerned):

Answer 1
Answer 2
Answer 3

Moreover, I have linked here both answers to the question suggested as a duplicate of mine (1 and 2 above), one of which was given by this reader (who apparently didn't bother to read through).

So again - the question (not answered anywhere within the linked material) - should I handle this attack on-chain or off-chain?

Thanks again!


texts: how does digital signature functionality in blockchain fulfil the requirement of user identification?

texts: As we are aware that blockchain is a decentralized application and it is tough to implement user identity mechansim in decentralized application so we use digital signature to verify the identity of a user. A digital signature comprise of a public key and encrypted message. A digital signature is issued by a trusted certificate authority and we can verify the digital signature from that authority. My question is  so how can it make sure in blockchain network that a digitally signed transaction is done by an authentic blockchain user.


texts: Recovering the message that is digitally signed not only the address

texts:
Is there a way to recover a digitally signed message in a smart contract?

ecrecover(msgHash, v, r, s)

returns the address that signed the msgHash. I am looking for something that can return the msgHash itself which can be decrypted using the provided public key from the signature.


texts: Metamask not allowing any transaction by code

texts:
I am building an application using ethereum smart contracts. I am using Metamask Chrome extension to run my application on Chrome. But I am facing a little issue. When I try to make any transaction by code Metamask say's that the account balance of sender is insufficient despite of the fact that sender's account has ethers in it. On the other hand when I try to make a transaction through my Metamask account there is not error and transactions are being made successfully.

Here is the screenshot of Metamask

Does anyone have an idea what could be the problem?

And here is the screenshot for the sender's account having ether


texts:
Need guideline for send ETC coin using web3js,As per documented flow I understand we can access all methods same as ETH but I have query regarding set provider for ETC after that I can connect to ETC network and send transaction.
Is there any public node url there for ETC? for any third-party which provides it as for ETH has https://Infura.io.
Kindly guide regarding provider of ETC to use in Web3js.

Thank you in advance.


texts: Does function inherit variables from modifier?

texts:
In a contract where a modifier like this would be reused a lot, is ID inherited by the function that uses the modifier? If not, this check would need to be in the function. If yes, is there any drawbacks from putting uint ID in the modifier?

modifier isMember (address _foo) {
  uint ID = memberIndex[_foo];
  require(ID != 0);
  _;
}


texts: How to remove showing of a contract source code from from etherscan?

texts: if somebody will tell me how to remove showing of a contract source code from appearing on etherscan? Once a contract is deployed? Is it possible or another contract should be deployed? thanks


texts: on the implicit type conversion rules in Solidity

texts:
Question in one sentence: Are there seperate implicit type conversion rules for function call resolution (other than the conversion rules for the remaining cases)?

Regarding the array type conversions in Solidity, it seems that the smaller size of types can be implicitly converted into the larger size of types (if the base element types are equal). For example, when we have uint[2] u2; uint[3] u3;, u2 can be assigned into u3 (u3:=u2;), but not vice versa.

My confusing part is that, the situation above does not apply in function call resolutions, i.e., in matching types between argument and formal parameters. Below is an example.

Is it a normal situation ?

contract Test{

    uint[2] public u2=[1,2];
    uint[3] public u3;

    function test() public{
        u3=u2;
        test2(u2); // compile error !!
    }

    function test2(uint[3] arr) internal{ }
}


texts: How to cite the Ethereum Yellow Paper in a scientific work

texts:
Maybe the question can be off-topic or more appropriate for other communities, I try to ask it here.

I am currently writing my thesis and I want to cite the yellow paper. Google scholar provides the original version of 2014:

@article{wood2014ethereum,
     title={Ethereum: A secure decentralised generalised transaction ledger},
     author={Wood, Gavin},
     journal={Ethereum project yellow paper},
     volume={151},
     pages={1--32},
     year={2014}
 }

I would like to cite the current version (or at least a recent one).

Where can I found the information about journal and volume and It is still correct to indicate Gavin Wood as the only Author?


texts: for loop not looping, returns only initial value

texts:
Trying to get it to subtract down from i by 4's and return the final results (answer is either: 1, 2, 3 or 4)

for(uint i = 1000; i >= 1; i-=4)    {

            return(i);

        }

but when I return(i); or return i; i get the initial value of i (in this case 1000) not the subtracted value.

Any explanations or help is appreciated.


texts: Weird Transaction input data, what is this?


texts: How to implemet condition for constructor?

texts:
Looking to learn solidity so need your support for this

I have made a constructor in my contract where

maxAvailableNumber = 1;

What I want to do is if the balance of user is more than certail limit like 500 tokens then this maxAvailableNumber should be 2 and if balance is above 1000 then this number 3.

How i can add conditions to this variable in constructor.


texts: Generating ethereum address from private key on Ubuntu 32 bit

texts:
I have a securely generated private key that I want to use to generate an ethereum address on an offline PC (Ubuntu 32 bit). My preferred way would be to use geth, but there's no geth binary for linux 32 bit. My questions are:

Why there are no 32-bit binaries available?
What are the alternative ways to generate an ethereum address (binaries preferred) except MyEtherWallet?
What happens if I try to run 64-bit geth on 32-bit Linux?


texts:
dYdX has an event called LogDeposit(address indexed accountOwner, uint256 accountNumber, uint256 market, BalanceUpdate update, address from) within their SoloMargin contract. I am trying to get the signature hash for this using the following code:

from Crypto.Hash import keccak
keccak_hash = keccak.new(digest_bits=256)
keccak_hash.update(b'LogDeposit(address,uint256,uint256,BalanceUpdate,address)')
print(keccak_hash.hexdigest())

This produces the following signature hash: ad66b490ac5d24d41e7e33a2a9ac6645bf66b577553f31d1e2917df2f83f15a6. However, I do not think it is right. When I search for this topic in etherscan nothing is returned.

I am wondering if it has to do with the BalanceUpdate parameter. I am used to searching for the other types such as address and uint256, but this one I haven't seen and do not know if I am doing this right.


texts: Is this a bug in the official doc about function overloading?

texts:
From the official doc:

  Overloaded functions are also present in the external interface. It is an error if two externally visible functions differ by their Solidity types but not by their external types.

Then followed by an example (I changed B by uint):

pragma solidity >=0.4.16 <0.7.0;

// This will not compile
contract A {
    function f(B _in) public pure returns (B out) {
        out = _in;
    }

    function f(address _in) public pure returns (address out) {
        out = _in;
    }
}

But i actually could compile the above code with no issue. Is this a bug in the doc or something?

$ truffle compile

Compiling your contracts...
===========================
> Compiling ./contracts/Test.sol
> Artifacts written to /.../solidity/study/Test/build/contracts
> Compiled successfully using:
   - solc: 0.6.4+commit.1dca32f3.Emscripten.clang


texts: Simple assignment does not work in Dapple

texts:
I'm using Dapple (http://dapple.readthedocs.io) specifically the test framework. I have the following contract

contract App {
  bytes1 public myVar;
  function App() {
    myVar = 0x01;
  }
}

and the following test

function test() {
  bytes1 variable1 = App(proxy_tester).myVar();
  bytes1 a = 0x01;
  assertEq1(variable1, a);
}

I would expect this test to pass, instead it fails with this

| Error: Wrong `bytes1' value
|   Expected: 0x01
|     Actual: 0xc6

I'm supposing 0xc6 is just a random value in memory or a wrong encoding of 0x01.

What am I doing wrong?

Note: dapple does not run in a blockchain but directly in a virtual machine. I tried this code in truffle and it works as expected.


texts:
I have pretty big smart contract with a lot of structs. Each struct has in average 3-4 related methods (i.e. methods with first parameter MyLibrary.MyType storage self).

Question about code organization: does it makes sense to store each struct/type with corresponding methods in separate library and link it to contract or keep it altogether under single big library?

Another approach I see is to store all structs/types in single library but move all methods to separate libs.

Right now I cannot see any advantages in separate small libraries except code readability.


texts:
My system:

OS: ubuntu 16.04
python version: 2.7

I am following the instructions from here : https://github.com/ethereum/pyethapp/wiki/Getting-Started
to install pyethapp from Github. However when I tried to run pyethapp, it shows this error message:

  "sorry, but this version only supports 100 named groups"
  AssertionError: sorry, but this version only supports 100 named groups

I know this has something to deal particularly with my machine and regex but I am unable to solve it.


texts:
After I mine the following contract giving the array [true, true, true] as _bools I would expect [true, true, true] to be returned by getBools().

Instead [false, true, true] is returned.

Is there something obviously wrong I'm doing?

contract Broken {

    address creator;
    uint public aInt;
    bool[3] bools;

    function Broken(uint _aInt, bool[3] _bools) public {
        creator = msg.sender;
        aInt = _aInt;
        bools = _bools;
    }

    function getBools() constant returns (bool[3]) {
        return bools;
    }

    function kill() {
        if (msg.sender == creator) suicide(creator);
    }

}

UPDATE:

Here is the script I'm using to run the contract: http://pastebin.com/h6588DXh

And the output I'm getting:

loadScript("broken.js")
I0404 11:32:43.290351    8448 xeth.go:1026] Tx(0xf66606023ae787621534949a7da16b04b3a26213a532deb16ab9bbd7c2e0bc43) created: 0x1f7099dd0c58678883e89066a95f313d4b4f40d1
I0404 11:32:43.291519    8448 miner.go:119] Starting mining operation (CPU=4 TOT=5)
I0404 11:32:43.298410    8448 worker.go:569] commit new work on block 54 with 1 txs & 0 uncles. Took 6.013736ms
I0404 11:32:43.437366    8448 worker.go:348]   Mined block (#54 / 755c7ff9). Wait 5 blocks for confirmation
I0404 11:32:43.437721    8448 worker.go:569] commit new work on block 55 with 0 txs & 0 uncles. Took 312.353µs
I0404 11:32:43.437750    8448 worker.go:447]    Mined 5 blocks back: block #49
I0404 11:32:43.923513    8448 worker.go:348]   Mined block (#55 / 1218fc33). Wait 5 blocks for confirmation
I0404 11:32:43.924200    8448 worker.go:569] commit new work on block 56 with 0 txs & 0 uncles. Took 322.033µs
I0404 11:32:43.924442    8448 worker.go:447]    Mined 5 blocks back: block #50
I0404 11:32:43.925031    8448 worker.go:569] commit new work on block 56 with 0 txs & 0 uncles. Took 256.09µs
I0404 11:32:44.335605    8448 worker.go:569] commit new work on block 56 with 0 txs & 0 uncles. Took 582.985µs
true
> Contract mined!
Bools given: true,true,true
Bools stored: false,true,true

Moreover if the constructor instead has the following signature:

function Broken(bool[3] _bools, uint _aInt) public

everything behaves as expected.


texts: Why get payments to my ERC20-Contract cancelled?

texts:
I have deployed my first coin, a ERC20 contract, on Rinkeby. But when I send ether to the contracts address, the transactions get cancelled with a state called "fail".

Code:

pragma solidity ^0.4.10;

import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/token/ERC20.sol';

contract StandardToken is ERC20 {
  using SafeMath for uint;

    string internal _name;
    string internal _symbol;
    uint8 internal _decimals;
    uint256 internal __totalSupply;

    mapping (address => uint256) internal balances;
    mapping (address => mapping (address => uint256)) internal allowed;

    constructor(string name, string symbol, uint8 decimals, uint256 totalSupply) public {
        _symbol = symbol;
        _name = name;
        _decimals = decimals;
        __totalSupply = totalSupply;
        balances[msg.sender] = totalSupply;
    }

    function name()
        public
        view
        returns (string) {
        return _name;
    }

    function symbol()
        public
        view
        returns (string) {
        return _symbol;
    }

    function decimals()
        public
        view
        returns (uint8) {
        return _decimals;
    }

   function transfer(address _to, uint256 _value) public returns (bool) {
     require(_to != address(0));
     require(_value <= balances[msg.sender]);
     balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
     balances[_to] = SafeMath.add(balances[_to], _value);
     Transfer(msg.sender, _to, _value);
     return true;
   }

  function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
   }

  function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
    require(_to != address(0));
     require(_value <= balances[_from]);
     require(_value <= allowed[_from][msg.sender]);

    balances[_from] = SafeMath.sub(balances[_from], _value);
     balances[_to] = SafeMath.add(balances[_to], _value);
     allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
    Transfer(_from, _to, _value);
     return true;
   }

   function approve(address _spender, uint256 _value) public returns (bool) {
     allowed[msg.sender][_spender] = _value;
     Approval(msg.sender, _spender, _value);
     return true;
   }

  function allowance(address _owner, address _spender) public view returns (uint256) {
     return allowed[_owner][_spender];
   }

   function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
     allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
     Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
     return true;
   }

  function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
     uint oldValue = allowed[msg.sender][_spender];
     if (_subtractedValue > oldValue) {
       allowed[msg.sender][_spender] = 0;
     } else {
       allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
    }
     Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
     return true;
   }

}

I deployed this contract with truffle:

$ truffle migrate --network rinkeby
Using network 'rinkeby'.

Running migration: 2_standard_sale.js
  Deploying StandardToken...
  ... 0xbbeddd52e9c1c648d1cc4b0203c457e2ac65f0c52e32954552c699d32fab4b4b
  StandardToken: 0xf0a1b11c9742eccbfd6aa659359328bcb814edd5
Saving successful migration to network...
  ... 0xa567aa47e110338f60c45f3207fe9b7d5e5aba07165ba6d0179f7bcd8da6eee6
Saving artifacts...

and send some Ether to 0xf0a1b11c9742eccbfd6aa659359328bcb814edd5.

However, the transaction gots cancelled: https://rinkeby.etherscan.io/tx/0x34c8d36783bbdf54cd5f34808dac58c14c0ee77eaed0ce74621b9bf4fa5d6ab0

Unfortunately, the sent Ether is gone and wasn't refunded.

What could be wrong here?


texts:
I've seen in a video that the target block time for Casper will start with 4 seconds. Eris (now Monax) is using Tendermint which is also a PoS algorithm.

What is the block time in an Eris blockchain? Also, what's the block size?


texts:
It seems (seemed) intuitive to me that there is no need to convert lower uints (e.g. uint8) to higher ones (uint256) within a formula. As I understood from the solidity docs it should be done automatically.

Am I wrong? Why am I getting "premature" overflows in the functions below?

This function works well until numSold is lower or equal to 15999. After that there is overflow.

function debugPower (uint16 numSold) public constant returns (uint) {
    return uint(2 ** (numSold/1000));
}

This function works well until numSold is lower or equal to 6999. Then overflow.

function debugPrice (uint8 x1, uint8 y1, uint16 numSold) private returns (uint80) {
    return uint80(1 finney * (2 ** (numSold/1000)));
}

The same as above setting_delay never even close to uint32, currentLevel never close to uint16 and the final result never close to uint.

function debugActivationTime (uint32 setting_delay, uint16 currentLevel) public constant returns (uint32) {
    return uint32(now + ((2**(currentLevel-1)) * setting_delay));
}


texts: Transactions not happening in Ropsten Test Network

texts:
I'm learning to set up a simple front-end website that executes smart contract methods in a testing environment, but even though MetaMask confirms the deployment of the contract, the transaction is not being executed.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Deploy a Remix Contract</title>

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

Ethereum Secret Messenger

      This site writes a secret message to the Ethereum blockchain!
      <input id="userInput" type="text" />

      <button id="setMessageButton">Set secret message</button>

I've obtained the ether from MetaMask faucet into the Ropsten Test Network.
Set the network to Ropsten Test Network on MetaMask.
Deployed the smart contract on Remix IDE through the injected web3 environment
Pointed the endpoint of Web3 in the front-end website's code to Infura's Ropsten address
Set the Remix's contract address as well as the ABI in the front-end code

As mentioned previously, MetaMask shows the log of the Contract Deployment being confirmed, but when I try to use the method setMessage, the MetaMask pop up doesn't appear and nothing else happens. The website is running on the local port 5500 through the VSC's Live Server extension and shows no error in the log.


texts: How can I check the provider status ? if testRPC connected or not?

texts:
I have a problem with using : web3.net.listening
The case when I am connected to the testRPC is working and it returns me TRUE.
But the case I am not connected it returns me INTERNAL SERVER ERROR.
I understand that this "listening" object doesn't exist when I am no longuer connected to testRPC.
How can I solve this? so I can get false as result if testrpc not connected.

const config = require('config');
const Router = require('koa-router');
const router = new Router();

const Web3 = require('web3');
const web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider(config.provider.url));

router.get('/cbn/provider-status', ctx => {

    const listening = web3.net.listening;
    if (listening){
        ctx.body = {"status":listening}
    }
    else ctx.body = {"status":"false"}

})

Many Thanks in advance.


texts: How can I highlight the syntax of Solidity in Ace browser editor?

texts:
I'm building the browser editor of Solidity using Ace Editor, and I am trying to highlight the syntax.
Remix uses Ace Editor as well, but I don't know how they successfully highlighted the syntax.

Any idea?


texts:
I am trying to write the output of a command of Geth into a text file.
Something like this in the case of Windows:

ipconfig /all > c:\my_directory\file_name.txt

Is it possible? If yes, how?


texts: What is the data field in eth_call commands for USDT?

texts:
I'm trying to use eth_call to send USDT (TetherToken) from one account to another (Although I know that eth_call just simiulate such transaction). Everything is clear in this regard, just the data parametere is a bit ambiguous. As far as I read, it must be an encoded value of the contract and some other parameteres. After checking many web pages, I found this value as ABI-Encoded and is the last bytes of the Contract mentioned in this link:

000000000000000000000000000000000000000000000000000000174876e800000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a546574686572205553440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045553445400000000000000000000000000000000000000000000000000000000

Now, my questions are:

Is using this code as data value enough for running eth_call?
The value above is a HEX one. But the givven example inside documentation uses a shorter value of data like 0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675 which is HEX too, but in a shorter format. What kind of encoding is applied to prepare such final data value?
What are other parameteres beside contract signature which have to be included in data value creation?
I've found a website to convert contract JSON to ABI encoded format. After pasting the TetherToken contract JSON in this website and pressing parse, some new field appeared. One of them was _initialSupply. Other field are clear, and their values are available. But I could not understand what is _initialSupply exactly here and where can I find it?

I hope you can help me to find the answer of my questons. Sorry for too many questions...


texts:
I am currently using the structure and mapping to store the user data in the blockchain. In the mapping I am using user's address (msg.sender) for mapping it with structure so every user can only access his/her data on the base of ethereum account.

struct User{

    byte32 fname;
    byte32 lname;
    byte32 email;

}
mapping(address => User) UserData;

I read about the function name

 web3.eth.getStorageAt

that can return the data at the particular storage point,I want to know what level of data security i could achieve as i am also making the dapp.


texts: Transaction status true when sent to an address which doesn't have anything

texts:
When you create a transaction calling a function in a smart contract the transaction status is true if it's executed correctly and false if it isn't
When testing in Hyperledger Besu, if a transaction calling a function in a smart contract which doesn't exists (IE: properly encoded tx to a wrong address), the transaction shows as successfully executed.
For example:
I successfully deploy a smart contract, I create the smart contract instance with the ABI + address, and make a call to the smart contract like so:
myContract.methods.myMethod(123).call({from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe'}, function(error, result){
    ...
});

When I recover the transaction receipt I can verify that the transaction status is true.
But if I send the same transaction to an address where there is nothing deployed, I don't get any logs the function may have, which makes sense because there is nothing deployed there. but I also get transaction status true:
result:  {
  transactionReceipt: {
    blockHash: '0xea2a7a30fcba0359b76d93d1fe4bc9c97216a720d30022b53eb9111fada263ef',
    blockNumber: 22,
    contractAddress: null,
    cumulativeGasUsed: 30424,
    from: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
    gasUsed: 30424,
    logs: [],
    logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Any idea why that happens? Why wouldn't the transaction get rejected?


texts:
I'm trying to use Web3 to access the current account I have selected on Metamask by doing web3.eth.accounts[0] in order to display it on my UI (in VueJS). However web3.eth.accounts[0] always returns the same account, the first one of the 10 given to me by Ganache TestRPC.

Even if I switch to the 8th account (screenshot below) and refresh the app, console.log(web3.eth.accounts[0]) still outputs the first account in the array.

Here's my code (in Vuejs, contract has already been created):

    var ethereumUri = 'http://127.0.0.1:7545';
        let web3 = new Web3(new Web3.providers.HttpProvider(ethereumUri));
        if (!web3.isConnected()) {
            return 'Unable to connect to ethereum node at ' + ethereumUri
        }else{
          var escrowContract = web3.eth.contract(abi); //abi initalized at start
          var instance = escrowContract.at(this.contractAddress); //contractAddress is initialized at the start

          console.log(web3.eth.accounts);
          console.log(web3.eth.accounts[0]);
        }

How would I make web3 output the current selected account address in Metamask?

Thanks!


texts: How do you use natspec comments to provide a confirmation text?

texts:
According to the docs:

  Additionally, there is another type of comment called a natspec
  comment, for which the documentation is not yet written. They are
  written with a triple slash (///) or a double asterisk block (/** ... */) and they should be used directly above function declarations or statements. You can use Doxygen-style tags inside these comments to
  document functions, annotate conditions for formal verification, and provide a confirmation text which is shown to users when they attempt to invoke a function.

But I tried this with MetaMask:

  // Sell a ticket. Validate that the email associated to the buyer doesn't have a ticket already
  /// Buy Ticket!
  function buyTicket(string fullname, string email) {
    // ...
  }

And the text did not show up.

Is there something else that needs to be done? Or is it because MetaMask does not support this yet?


texts:
Is there a more convenient way to construct the value of data for an eth_call JSON-RPC API call, than the "regular" way of first 4 bytes of web3.sha3 of canonical function signature followed by encoded and padded arguments? I know that the web3 Javascript getData method can be used but, if access via web3 is available, then one could just as well call the function directly, instead of just getting data and using JSON-RPC API. Suppose that only JSON-RPC API access is available in some situation. Is constructing data by hand for a contract function call the only option?

EDIT (6/21/2017): It occurred to me that browser-solidity might display the data for an eth_call or eth_sendTransaction, since it does display compiled contract bytecode and interface. That could have been copy-pasted. However, I checked and do not see the data needed for a function call displayed when I call a function in the right panel.

EDIT #2 (6/21/2017): Maybe my question was not clear as posted above. I will try putting it differently. Say, we have the following Solidity contract (named simple) deployed at some address, e.g. at 0xfbb5fa2ea8c5fc6f492c0795564352f262f49f50

pragma solidity ^0.4.9;

contract owned {
    address owner;
    function owned() {
        owner = msg.sender;
    }
    function getOwner() constant returns(address) {
        return owner;
    }
}

contract simple is owned {
    function twice(int a) constant returns(int) {
        return 2*a;
    }
}

The function twice can be called from Javascript code, using web3.js, as follows:

var simple = eth.contract(<ABI>).at(0xfbb5fa2ea8c5fc6f492c0795564352f262f49f50);
var result = simple.twice(7);

However, to call this function using JSON-RPC, an HTTP post request needs to be sent to the RPC port of a node, with the following body:

{
    "jsonrpc": "2.0",
    "method": "eth_call",
    "params": [
        {
            "from": "0xccf9d7d2f8be1f821cb8d9ec9553ffa92aa8fc4d",
            "to": "0xfbb5fa2ea8c5fc6f492c0795564352f262f49f50",
            "data": "0x6ffa1caa0000000000000000000000000000000000000000000000000000000000000007"
        },
        "latest"
    ],
    "id": 1
}

The value of data element is calculated as first 4 bytes of { the Keccak hash of [ the ASCII encoding of ( a canonical form of the function signature ) ] } followed by the arguments encoded in a particular way, as specified at https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI.  NOTE: Added 3 types of brackets to remove ambiguity :-)  (This is a very simple function with only 1 int argument but this can quickly get very nasty and error-prone with more complex arguments.

There is a way to easily obtain the appropriate value of data for a function call using a web3.js function, as follows:

var callData = simple.twice.getData(7);

But suppose the function is to be called from a remote machine and also that Javascript is not an option. Is there a convenient way, (i.e. not manually doing so as per the complex rules in the wiki linked above) to compute the correct value of the data element of the JSON-RPC API request?


texts: What's Byzantium? What's Metropolis? What should I do after these happen? Will I lose my ETH?

texts:
Sorry for the noob question, but I'm really confused.. :( Is there going to be a third Ethereum? Will I have to manually upgrade somehow? Which new ETH should I use?

Thanks in advance!


texts: Unable to call or transact with Rinkeby contract using Remix

texts:
I am very new to Solidity and I just managed to deploy a very simple contract to Rinkeby. However, for some reason I am unable to call or interact with it using Remix. Does anyone know whats wrong?
I have compiled the same contract on remix, changed my environment to Inject Web3 and created an instance by pasting the contract address to the At Address field, but when I try to call it or transact with it nothing happens!


texts: How to find the coin/token type of crypto payer in Ethereum blockchain?

texts:
I'm new in Ethereum based crypto concepts. I would like to know how can I differ the incomming crypto amounts based on their orginal token type?
Imagine I have an address on Ethereum blockchain. Person 1 has sent 0.1 Tether to my address, and the second person has sent 0.2 Ether to the same address. How the explorer detect the origin types?
Is there any flag, or someting else that defines the type of token/coin while sending?


texts:
At truffle.js I set the account to the third ganache's account

Then I run truffle console and coinbase was set to the first account and defaultAccount to undefined. Not only that, I've tried to change the coinbase to the second account and it also didn't work

The most interesting part is: I ran a function from a contract that stores a mapping(address=>A) v (let's say A is a contract and v the mapping name). The expected outcome from v(web3.eth.coinbase) would be the contract's address, but there was the empty address. And when I ran v(web3.eth.address[2]), there was the contract's address, meaning I just have to trust the truffle's config.

But I'd like to solve this anyways, for presentation's sake


texts:
I'm building a DAPP it works fine when I host it from a server, but when the HTML file is local MetaMask gives this error:

MetaMask does not allow file:// protocol, use http(s)://

Any ideas what that means or if theres a way to get it to work?
Thanks!


texts: Quorum Geth Folder (chaindata, lightchaindata, nodes, LOCK, transactions.rlp), Quorum Raft State (ldb, log, CURRENT, LOCK, LOG, MANIFEST)

texts:
There are many folders and files generated when I created my Quorum nodes.

Quorum geth folder:

chaindata
lightchaindata
nodes
LOCK
nodekey
transactions.rlp

Quorum Raft State:

000002.ldb
000003.log
CURRENT
LOCK
LOG
MANIFEST-000004

raft-snap folder:

Multiple *.snap files

raft-wal:

*.wal file
tmp file

Many of these files are binary files. May I know what these files are and its purpose?


texts:
I would like to know is it possible that hash of transaction will change during chain reorganization?

I noticed that difference is only between block number and block hash.

Also, polling geth with eth_getFilterChanges sometimes can deliver even number of reorganized (removed) transactions and regular one's with same hash, which means that transaction is not mined at all, but if i check that transaction through ropsten.io - it is fine. Is it bug of geth or something else?


texts:
I would like to return partially fees to users of my dApp. Once they have reached X amount in fees, I want to make a function that will pay them ethereum automatically. Now my question: Is that secure? Or can they cheat?
The code is following:
In the beginning of every function, I call

uint _gasBegin = gasleft();

And in the end

uint _gasEnd = _gasBegin.sub(gasleft());
gasPaid[msg.sender] = gasPaid[msg.sender].add(_gasEnd);

Once they reached for example 0.001 ethereum in gas fees, they can call the funcion

returnFees()

that will transfer gasPaid[msg.sender] to them.

Edit:
One way to cheat could be, that a miner sets a very high gas price in hope to empty the wallet. But however, he will not 100% surely mine the block and if it fails, he loses the fees to an other miner. Also I will limit this by allowing a max. price of for example 15 wei to be eligle to get back the fees by using (tx.gasprice <= 15, can be changed).

Is this...
1) A secure way, without them being able to cheat and
2) maybe improveable?


texts: Can the variables in a crowdsale contract be modified in future?

texts: Once one deploys a crowdsale contract, can the variables like token supply, name, symbol be modified at a later date?


texts: web3.eth.abi.encodeParameter for array of structs

texts:
Here I have a smart contract with one method batch that accepts array of users to push into users state variable.
contract UserFactory {
  struct User {
    string name;
    uint age;
  }

  User[] users;

  function batch(User[] _users) public {
    // logic to add _users to users array
  }
}

Here on the JavaScript side I'm using web3.eth.abi.encodeParameter to create bytes type for some design purpose. But the problem is I have no idea how to encode User[] with encodeParameter. There is a solution to create a type like tuple(string,uint256)[] and pass [['John', 26], ['Doe', 99]] but again for design purpose I have to use the {name: "John", age: 26} so my alternative solution wont help.
// Trying to somehow create with array of users like [{name: "John", age: 26}, {name: "Doe", age: 99}]
const payload = web3.eth.abi.encodeParameter(
  {
    User: {
      name: "string",
      age: "uint256",
    },
  },
  {
    name: "John",
    age: 26,
  }
);

// This one working fine
const alternativePayload = const payload = web3.eth.abi.encodeParameter(
  'tuple(string,uint256)[]',
  [['John', 26], ['Doe', 99]]
);


texts: Solidity. issue with fixed-sized arrays and dynamic arrays

texts:
I am passing a fixed array to a function where a dynamic array is expected.

addType([1,5, 2,5, 3,2, 4,2, 5,1], [6,1], [7,5]);
addType([1,5], [6,1, 2,5, 3,3], [7,5]);

function addType (
    uint8[] memory _build,
    uint8[] memory _input,
    uint8[] memory _output
)
.......

I get an error when compiling

Invalid type for argument in function call. Invalid implicit conversion from uint8[10] memory to uint8[] memory requested

Found a solution in using a similar structure

uint8[] memory _build = new uint8[](10);
    _build[0] = 1;
    _build[1] = 5;
    _build[2] = 2;
    _build[3] = 5;
    _build[4] = 3;
    _build[5] = 2;
    _build[6] = 4;
    _build[7] = 2;
    _build[8] = 5;
    _build[9] = 1;
uint8[] memory _input = new uint8[](2);
    _input[0] = 6;
    _input[1] = 1;
uint8[] memory _output = new uint8[](2);
    _output[0] = 7;
    _output[1] = 5;

addType(_build, _input, _output);

But it is extremely not effective!

Help, please deal with these arrays!


texts: Getting weird OpenCL error messages and a 0 H/s benchmark result when mining. What could be wrong?

texts:
I am trying to mine Ethereum using geth and ethminer using a single AMD Radeon HD 7850 with 2 GB of memory on Ubuntu 16.04. I installed the latest recommended driver, ran geth --maxpeers 0 (to avoid syncing with the blockchain) and then tried to benchmark my setup using ethminer -G -M. I get a few possible OpenCL error messages when trial 1 is beginning, then that phase ends with a hashrate of 0, same for trial 2, 3, 4 and 5. After the fifth trial, the program just keeps running, but nothing is happening. But have a look for yourself:

$ ethminer -G -M
[OPENCL]:Found suitable OpenCL device [Pitcairn] with 1692704768 bytes of GPU memory
  ◇  23:12:24.160|ethminer  #00004000…
Benchmarking on platform: { "platform": "AMD Accelerated Parallel Processing", "device": "Pitcairn", "version": "OpenCL 1.2 AMD-APP (2348.3)" }
Preparing DAG...
Warming up...
  ℹ  23:12:24.160|gpuminer0  workLoop 0 #00000000… #00000000…
  ℹ  23:12:24.160|gpuminer0  Initialising miner...
Trial 1... [OPENCL]:Using platform: AMD Accelerated Parallel Processing
[OPENCL]:Using device: Pitcairn(OpenCL 1.2 AMD-APP (2348.3))
[OPENCL]:clCreateCommandQueue(-6)
[OPENCL]:clEnqueueWriteBuffer(-36)
0
Trial 2... 0
Trial 3... 0
Trial 4... 0
Trial 5... 0

I tried reinstalling the graphics driver and ethminer. Mining without the -G parameter works just fine, but is way too slow, of course. I searched for people having the same problem and there are a few, but they didn't find any solution or the thread just died. I hope someone here can help!


texts: ERC-20 transferFrom implementation potential flaw...or not?

texts:
Let's say transferFrom function is implemented in a next manner:

function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
   uint256 spenderAllowance = allowances [_from][msg.sender];
   if (spenderAllowance < _value) return false;
   uint256 fromBalance = accounts [_from];
   if (fromBalance < _value) return false;

   allowances [_from][msg.sender] = safeSub (spenderAllowance, _value);

   if (_value > 0 && _from != _to) {
     accounts [_from] = safeSub (fromBalance, _value);
     accounts [_to] = safeAdd (accounts [_to], _value);
   }
   Transfer (_from, _to, _value);
   return true;
}

As I see it, if _to is different than msg.sender than the _to will get all the tokens which will be removed from msg.senders allowed amount.

This should not be the flaw, practically, because no one is crazy enough to send his allowed amount to someone else, but can it be used in a bad manner? What are your thoughts on this?


texts: What is the cryptic part at the end of a solidity contract bytecode?

texts:
Given the following contract:

pragma solidity ^0.4.11;

contract Simple {
    bytes32 public v;
    function set(bytes32 _v) {
        v = _v;
    }
}

When disassembling, neither remix, solc or evm can properly intepret the trailing end of the code. Additionally, the code seems unreachable (it follows a JUMP instruction), and what it seems to do doesn't make much sense.

Similar trailing code is produced when compiling with solc and remix, prefixed and suffixed similarly but contents are slightly different:

 00a165627a7a72305820...0029

In disassembly, the prefixing bytecode is intepreted by all as:

 stop
 log1
 push6 0x627a7a723058
 sha3
 ...

When compiled with remix, the "assembly" field in the web GUI describes the part as a ".data" tag:

[...]
 SSTORE             v = _v
      POP           v = _v
    tag 10          function set(bytes32 _v) {\n        ...
      JUMPDEST          function set(bytes32 _v) {\n        ...
      POP           function set(bytes32 _v) {\n        ...
      JUMP [out]            function set(bytes32 _v) {\n        ...
    .data

Thus hinting that this is not code at all, but some form of data field. If so, what is this used for?, generally and in this specific example?

remix: 0.4.14+commit.c2215d46.Emscripten.clang
evm: 1.7.0-unstable (git commit 3d32690b)
solc: 0.4.14-develop.2017.7.27+commit.16ca1eea.Linux.g++

Runtime bytecode (from remix):

60606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680637c2efcba146047578063db80813f146075575b600080fd5b3415605157600080fd5b60576099565b60405180826000191660001916815260200191505060405180910390f35b3415607f57600080fd5b6097600480803560001916906020019091905050609f565b005b60005481565b80600081600019169055505b505600a165627a7a72305820e62ffd25aaa1132d83ae4470e9f3991cb237178c38401db1857b9417b74603560029


texts: all master nodes are miners as well in Ethereum?

texts:
I have doubts about master nodes and miners in Ethereum.

1- Do all the miners have to be full nodes as well?

2- Do all the full nodes have to be miners as well?


texts:
In solidity, I can take advantage of the hex literal in order to get back the corresponding hex value of a string, in the following way:
hex"001122FF"

I am wondering how to apply such literal on a variable. Let's say my hex string is a constant hexValue.
How can I apply the literal on hexValue?
Thanks for the help


texts:
I have a 8GB ram GPU - can I save the DAG twice and produce double hashrate?
If yes - how can I program it?


texts: Negative number passed to function with uint parameter

texts:
Consider the following simple contract:

pragma solidity ^0.4.16;

contract TestContract {

    function add(uint256 amount) returns (uint256) {
       require(amount > 0);

       return 100 + amount;
    }
}

I would expect that the result of this function is always greater than 100. Except for an uint overflow scenario, but let's not discuss that.

If i call the function from geth like this the result is like expected 105.

> testInstance.add.call(5)

If i call the function with an negative number, i would expect that an exception is thrown or that the input is changed to zero and the result is 100, but instead in returns 95.

> testInstance.add.call(-5)

So how is that possible? Has anyone an idea? Is it just bad practice to pass negative numbers to the function?


texts: Ethereum's definition of difficulty and hash rate

texts:
I'm trying to make sense of geth's hashrate and Ethereum's difficulty setting. I'm running a private test net and set the difficulty to a fixed value (to big.NewInt(250)) as described by https://ethereum.stackexchange.com/a/7159/5293.
I start the CPU mining in geth using one thread with miner.start(1). Then I measure the hashrate with eth.hashrate, it's usually a value between 8 and 12 (let's say h = 10 H/s on average).  I measured the average blocktime by mining for 15 minutes and it was around 65 seconds.

Now, I'd like to use the difficulty setting and hashrate to calculate the expected blocktime. If I'd calculate it in the way the terms 'difficulty' (d) and 'hashrate'  (h) are used in Bitcoin, I'd get

t = 2^32 * d / h,

which is not even close to 65 seconds.

I'm running geth on a  Intel(R) Core(TM) i5 CPU, with 2.80GHz. I assume that the value h = 10 H/s is rather useless as it should be much higher (but where does it come from then)? With my processor, I'd assume that I cannot get higher than maybe h = 50 kH/s. However, to yield the 65 seconds, I'd need a hash rate of

h = 2^32 * d / t = 1.7 * 10^10

which is much higher than my maximum hashrate.


texts: geth commands to get the latest transactions per account or contract address

texts:
Seen the response posted here at https://ethereum.stackexchange.com/questions/6002/transaction-status#=

Tried the following commands in the geth console, but getting the errors -

  eth.getTransaction(eth.getBlock("pending").transactions[0])
  Error: invalid argument 0: json: cannot unmarshal non-string into Go value of type common.Hash at web3.js:3104:20 at web3.js:6191:15 at web3.js:5004:36 at :1:1

  getTransactionsByAccount("*")
  ReferenceError: 'getTransactionsByAccount' is not defined at :1:1


texts: Invalid number of arguments error for getter function with no passed arguments

texts:
I am receiving this error when trying to call the getUsers getter function from the contract below: Invalid number of arguments to Solidity function. Running on Truffle in develop mode.

mapping (address => User) Users;
address[] usersByAddress;

struct User {
    string handle;
    bytes32 city;
    bytes32 state;
    bytes32 country;
}

function registerNewUser(string handle, bytes32 city, bytes32 state, bytes32 country) returns (bool success) {
    address thisNewAddress = msg.sender;
    if(bytes(Users[msg.sender].handle).length == 0 && bytes(handle).length != 0){
        Users[thisNewAddress].handle = handle;
        Users[thisNewAddress].city = city;
        Users[thisNewAddress].state = state;
        Users[thisNewAddress].country = country;
        usersByAddress.push(thisNewAddress);
        return true;
    } else {
        return false;
    }
  }

//getters
function getUsers() view returns (address[]) { return usersByAddress; }

function getUser(address userAddress) view returns (string, bytes32, bytes32, bytes32) {
    return (Users[userAddress].handle, Users[userAddress].city, Users[userAddress].state, Users[userAddress].country);
}

Let's say you deploy this contract in Truffle develop testnet and get an instance of the object x. I can create a user by sending the transaction x.registerNewUser("Bob123","Orlando","FL","USA"). Then I run x.getUser(web3.eth.accounts[0]) and get the following array:

[ 'Bob123',
  '0x4f726c616e646f00000000000000000000000000000000000000000000000000',
  '0x464c000000000000000000000000000000000000000000000000000000000000',
  '0x5553410000000000000000000000000000000000000000000000000000000000' ]

This is expected since the last 3 elements in the array are type bytes32. I expect x.getUsers or x.getUsers.call() to return an array of one address (my address at web3.eth.accounts[0]) but instead get the invalid Solidity arguments error even though there are no arguments passed into getUsers.


texts:
Its outputing 173512312(1735.12312) but I just want first 4 letters
    contract SimpleAuction {
  AggregatorInterface internal ref;
  // For ETH-USD on ropsten, input the address:
  // 0x8468b2bDCE073A157E560AA4D9CcF6dB1DB98507
  address _aggregator = 0x8468b2bDCE073A157E560AA4D9CcF6dB1DB98507;
  string toni;
  constructor() public {

    ref = AggregatorInterface(_aggregator);

  }

  function getLatestAnswer() public view returns (int256) {
    return ref.latestAnswer();
  }

    int256 private Limit;

    //bool sell = false;
    //this define input for limit
    int256 yes = 1;
    int256 no = 2;

    function getEth(int256 price) public view returns (uint256){

    }
    //logic for limit
    function setLimit(int256 newLimit) public {
        Limit = newLimit;
        sellLogic();
     }

    function sellLogic() private {

        //if else to se if it will sell during the dump
        int256 price = ref.latestAnswer();
        if (price > Limit){
            sell = true;
        }else {
            sell = false;
        }


texts: If I use the light version of geth sync, can I make a token & deploy contracts using that? The light client "gets only the current state", from that point onwards or everytime I query the blockchain?


texts: Smart contract that receives only one token

texts:
Is it possible to forbid to a smart-contract to receive all erc20 tokens and ether except my own token that was created in another contract? I mean I want my contract  to receive only tokens from previously known address of smart-contract.
I tried to compare token.balanceOf(msg.sender) >= msg.value where ERC20Detailed token = ERC20Detailed(_address); but as I understood when you send tokens msg.value is always 0


texts:
How to send ERC20 to 0x0000000000000000000000000000000000000000
I have tried to do this on myetherwallet and it will not send as a transaction, is there a special way to send here?

Thanks


texts:
I have read several documentations and tutorials about solidity.
There is something which is not very clear for me:
Let's take a basic example:
contract MyContract1
{
   function public_function(uint param) public
   {
      ...
   }

   function private_function(uint param) private
   {
      ...
   }
}

We have 2 kind of situations:

Let's imagine another smartcontract MyContract2 who knows the deployment address of MyContract1. MyContract2 can call MyContract1's public or externals functions.
A Javascript "DAPP" web application (written with truffle framework for example) can also call MyContract1 public/external functions.

What i want to know is if the rules are the same for a javascript dapp and an external smartcontract like MyContract2 ?
Thanks


texts: Are Solidity modifiers functionally equivalent to Python decorators?

texts:
I understand that in Solidity if a function has a modifier, this modifier runs first, prior the the logic within the function running. This is done for checks of ownership, checks of state, etc.

In Python, the concept of decorators seems very similar—a decorator replaces the decorated function with a new function that accepts the same arguments and returns whatever the decorated function was supposed to return, while also doing some extra processing.

In terms of what goes on behind the scenes, I know that in Python, the following are equivalent:

@clock
def factorial(n):
    return 1 if n < 2 else n*factorial(n-1)

and

def factorial(n):
    return 1 if n < 2 else n*factorial(n-1)
factorial = clock(factorial)

From my understanding, the following are equivalent in Solidity:

function startSale() notCanceled {
...
}

and

function startSale() {
    notCanceled()
    ...
}

My question is, are these two features meant to perform roughly the same task? When learning solidity, is comparing a decorator to a modifier a fair comparison to make? If so, why? If not, why not?


texts: Smart Contract Interfacing - Best Practices

texts: what is a general rule of thumb for creating interfaces? Why would I want an interface i.e. IAugur.sol instead of the entire Augur.sol file? Can someone shed light on interface best practices and pros/cons.


texts: ICO contract: the missing piece of the puzzle, what happens after deployment?

texts:
I have gone through pretty much every solidity example available on the web, and deployed lots of examples to a test network Using Mist wallet.

Let us assume we have created the perfect Etherium ICO smart contract, and deploy it to live, paying the necessary ether.

The question is what happens next - how do investors purchase the ICO tokens?

Does this happen through:

A token exchange like kraken or bittrex?  I.e. the ICO contract is just another (ERC20) virtual currency.
1.1 If this is the case, can investors only purchase with Ether?  Would the exchange manage the fiat currency and other currency conversions, so the investor thinks he is purchasing the tokens say with bitcoin or fiat, but actually the bitcoin or fiat is being converted into ether behind the scenes?
your own custom website acting as the front end of a DApp using your token as the backend. This is great except to integrate a payment provider requires a longer standing company with a bank account, something many startups and ICOs dont have yet.
A specific ICO portal (like tokenMarket?). Presumably to work with such a portal, do they have a standard for ICO contract interfaces similar to ERC20?
Nothing - the investor has to know how to manually transfer ether to the ICO smart contract address.  This sounds risky for the investor, but I have seen this on some ICO sites, like lordmancer2.

Secondly, what determines the price of the ICO tokens?  Is it fixed (with discounts for volumes), or completely market led (like a real IPO has an initial price, then it could go up or down depending on the market). Is the initial price set in Eth or fiat?  Presumably Eth, so would have to be set on day of putting the contract live?

Obviously this post does not include the non-tech side of ICO including white paper, reputation, marketing, community management etc.


texts: How to import both VRFConsumerBase and ChainlinkClient in same contract

texts:
I would like to use 2 of the functionalities of Chainlink, One is VRF and another is making API requests.
So I am importing two libraries together. ChainlinkClient.sol and VRFConsumerBase.sol
Which have an Interface and a Library same so I get these errors...
browser/do-escrow.sol:4:1: DeclarationError: Identifier already declared. import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol"; ^-----------------------------------------------------------------------------------------------------------------------^ browser/LinkTokenInterface.sol:3:1: The previous declaration is here: interface LinkTokenInterface { ^ (Relevant source part starts here and spans across multiple lines).

and the other one...
browser/do-escrow.sol:4:1: DeclarationError: Identifier already declared. import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol"; ^-----------------------------------------------------------------------------------------------------------------------^ browser/SafeMath.sol:16:1: The previous declaration is here: library SafeMath { ^ (Relevant source part starts here and spans across multiple lines).

I have tried with changing the names of the library (for e.g. SafeMath) but it doesn't seem to work.
Please help me to handle this correctly.
Thank you.


texts:
I'm building my first eth mining rig. I considered the following hardware:

GPU: 6 Sapphire nitro + RX 580 8GB
MOBO: MSI Z270 TOMAHAWK LGA1151/ Intel Z270/ DDR4/ 2x CrssFX S3&U3.1/ M.2 ATX
PSU: 1 1600W or 2 850W??
RAM: FURY 4GB 2133 MHz DDR4
CPU: INTEL PENTIUM G4400 Dual-Core 3.3GHz 8.0GT/S 3MB LGA 1151
SSD: ethOS 16gb SSD (gpuShack)
6 USB risers

Are there any recommendations on this rig? Is there a better MOBO or CPU? Should I have a PSU of 1600W?

Please feel free to post any suggestions!


texts:
I want to know your opinions about what do you think the best architecture for building a decentralized application?
Taking into consideration the global adoption, and how to avoid telling the users to create wallets and use metamask...


texts: What is logIndex and logsBloom in ethereum transaction

texts: The web3.eth.getTransactionReceipt() returns a logIndex field along with a logs array and a logsBloom field. I have read many articles but somehow still confused as to what is logIndex and logsBloom.


texts: "Error: sender account not recognized" when calling transferFrom() on an ERC721 contract

texts:
I am having an issue transferring ownership of an ERC721 token to a deployed Holding contract.

The error I’m getting when running truffle test is the following - Error: sender account not recognized When calling the transferFrom() function on the ERC721 contract using the deployed Holding contract.

I have successfully approved the Holding contract before calling transferFrom() so that is not the issue, but I’m unaware where the error is in trying to transfer the NFT to the Holding Contract.

The contracts and test file are located here:
https://github.com/sharad-s/DAOjo

The specific line of code which is causing this error in my tests is line 120 of DAOjo/test/test.js

To recreate this error:

Clone repo
Install truffle globally
Run a ganache local blockchain instance (port 8545)
Run truffle test in the root of this repo

Following is the error stack trace:

Contract: Crowdsale
DAOToken
1e+23
      ✓ should have a total supply of: 1e+23
      ✓ should have transferred 1e+23 to Crowdsale
    Crowdsale
Wei Raised:  1000000000000000000
Buyer Balance:  1000000000000000000
      ✓ should accept ETH payments (144ms)

Contract: NFTTokenMetaDataEnumerableMock
  NFT Registry
      ✓ Should have a total of 0 tokens when created
NFT APPROVED FOR:  0x3a0a837952964bdf3e751ba838e04b9a1752d94a
HOUSE OWNER:  0x6e4679ddb735556a47dd548489dfab641752afd5
SPV:  0x3a0a837952964bdf3e751ba838e04b9a1752d94a
DAO TOKEN BALANCE OF BUYER 1:  BigNumber { s: 1, e: 3, c: [ 1000 ] }
      1) Should approve and transfer token to SPV contract

    Events emitted during test:
    ---------------------------

    Transfer(from: <indexed>, to: <indexed>, value: 1000)
    Transfer(from: <indexed>, to: <indexed>, value: 1000)
    Transfer(from: <indexed>, to: <indexed>, value: 1000)
    Transfer(from: <indexed>, to: <indexed>, value: 0)
    Approval(owner: <indexed>, spender: <indexed>, value: 0)

    ---------------------------

  4 passing (3s)
  1 failing

  1) Contract: NFTTokenMetaDataEnumerableMock
       NFT Registry
         Should approve and transfer token to SPV contract:
 Error: sender account not recognized
  at Object.InvalidResponse (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
  at /Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
  at /Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
  at XMLHttpRequest.request.onreadystatechange (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
  at XMLHttpRequestEventTarget.dispatchEvent (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
  at XMLHttpRequest._setReadyState (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
  at XMLHttpRequest._onHttpResponseEnd (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
  at IncomingMessage.<anonymous> (/Users/sharad/.nvm/versions/node/v8.9.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
  at endReadableNT (_stream_readable.js:1055:12)
  at _combinedTickCallback (internal/process/next_tick.js:138:11)
  at process._tickCallback (internal/process/next_tick.js:180:9)

Thank you!


texts: Can ERC-721 accept ERC-20 Tokens as a payment method

texts:
I am using OpenZeppelin as my open sourced framework for my blockchain development. I am interested to see if there is a work around to accept ERC-20 tokens as payment for the ERC-721 token?

Example: I have some OmiseGo and would Like to Purchase an ERC-721 Token (developed by myself using OpenZeppelin).

I have not come across any instance of this in the OpenZeppelin documentation or online.


texts: contract works in remix but not when deployed in ropsten test network

texts:
The contract is present at issue with var keyword in solidity. what to use instead of var keyword?

It works in remix. Using remix i deployed the contract into ropsten test network but when i try to validate the contract i don't get the expected output.

first i will add user and then view the user to see how many does he have.
Add user:

View user:

View user output:

In ropsten some times i am not able to deploy due to high gas. some time i don't get the same view user output as i get in remix. Can some one guide me on how to overcome in deploying this smart contract in test environment and get the same output as i get in remix?

Also tried in rinkeby but not able to get the output as in remix? anything wrong with my contract. Below the is output what i get in rinkeby test network.

if it is not clear any where kindly let me know. Thanks.


texts: What happens if the "balance" of the address which sends "address.transfer(amount) is " zero "?

texts:
Consider the balance of the address that sends address.transfer(amount); to receive the amount is zero.

For example we have following address with balance of zero:

web3.eth.getBalance('0x123').then(console.log) // 0

And then this address wants to receive some ether as follows in Solidity code:

address public recipient;  // The account receiving the payments.

function receive(uint256 amount) public {
        require(msg.sender == recipient);

        recipient.transfer(amount);

    }

And at th time of deploying the contract, we initiate recipient to 0x123:

constructor(address _recipient)
        public
        payable
    {
        recipient = _recipient;
    }

Also, we initiate the balance of the contract at the time of deployment.

Then this address tries to call function receive to receive 10 wei as follows (consider the contract address is 0x456) :

var contractInstance = new web3.eth.Contract(abi, '0x456' /*0x456 is contract address*/);

contractInstance.methods.close(10 /*0x123 wants to receive 10 wei*/).send({ from: '0x123' }, function(error, result) {

        console.log(error);

        console.log(result)

    });

when I do this, apparently nothing happens, because when I get the recipient balance, it is still zero.

What is my mistake ?


texts: What are the processes involved in recording electricity as a tradeable token on ethereum?

texts: How can you record the generation of electricity onto ethereum as a tradeable token. Assuming that provenance is not an issue and a raspberry pi is used as a node to record electricity generation, would an API be required to for the raspberry pi to write and read from the blockchain? If so, are there any readily available API templates for ethereum that could be used in such a case?


texts: The format of JSON keystores created by the Go-Ethereum Geth executable are slightly different format than the JSON keys created on the MyEtherWallet website. Can anyone explain the differences? I have found that the Geth executable unlocks the MEW format much faster in an embedded/low resource environment. One of the things I noticed was the "n" value in kdfparams is much lower in MEW keys than GO-Ether Geth key format.


texts: What's the best way to send many strings in only one call?

texts:
So I have to write on-chain about 15 string key-value pairs in one call. Of course, I took the naive approach first by putting all those strings as arguments of my contract, but then I run onto the 16 local variables limit.

I came up with the following solution : I convert all those strings as bytes and supply a data layout array of uint with the length of each string. It's working fine, but I'm not that confident about it being the best, cleanest and cheapest of the solutions.

Javascript side (preparing the data) :

exports.stringsToBytes = (stringArray) => {
  var res = [];
  var layout = [];
  for(var i = 0; i < stringArray.length; i++) {
    var bytesArray = this.toUtf8Bytes(stringArray[i]);
    res = res.concat(bytesArray);
    layout.push(bytesArray.length);
  }

  return {data: res, dataLayout: layout};
}

Solidity code :

  function recordStatement(
    uint[] memory statementDataLayout,
    bytes memory statementData
  ) public onlyPrimaryOrOwner returns(bytes32) {
    bytes32 statementId = generateStatementId();

    recordStatementStrings(statementId, statementDataLayout, statementData);
    dataStore.createBool(keccak256(abi.encodePacked(statementId)), true);

    emit NewStatementEvent(buildingPermitId, statementId);
  }

  function recordStatementStrings(
    bytes32 statementId,
    uint[] memory statementDataLayout,
    bytes memory statementData) internal {
    string[] memory infos = parseStatementStrings(statementDataLayout, statementData);

    recordStatementString(statementId, "pcId", infos[0]);
    recordStatementString(statementId, "acquisitionDate", infos[1]);
    [...]
  }

  function parseStatementStrings(
    uint[] memory statementDataLayout,
    bytes memory statementData) internal pure returns(string[] memory) {
    string[] memory res = new string[](statementDataLayout.length - 1);
    uint bytePos = statementDataLayout[0] * 32;
    uint resLength = res.length;
    for(uint i = 0; i < resLength; i++) {
      bytes memory strBytes = new bytes(statementDataLayout[i+1]);
      uint strBytesLength = strBytes.length;
      for(uint j = 0; j < strBytesLength; j++) {
        strBytes[j] = statementData[bytePos];
        bytePos++;
      }
      res[i] = string(strBytes);
    }

    return res;
  }

Could you please share any potential issue or threat you can think of with this method ? Any other, 'cleaner' or 'cheaper' gas-wise alternative you know of ? I remind sending a string array is supported as an experimental method, but that wouldn't be suitable for production, would it ?

Many thanks,

Thibaut


texts:
How to automatically send ether, at regular intervals. I have an array of addresses. For example. 24 hours later send all addresses send eth. I can not understand how to make the timer on the solidity and send eth all adress.

All thanks in advance.


texts:
Where are the actual blockchains for Ethereum located? Are these on End-user computers, or is there specialized computers that hold the blockchains.

p.s Is this one blockchain or many blockchains?


texts: What is the difference between web3.eth.sign, web3.eth.accounts.sign, web3.eth.personal.sign functions?

texts: Which function should be used to sign message locally? Which function is the most secure?


texts: Uncaught Error: new BigNumber() not a base 16 number (I know it might be the known bug)

texts:
I run into the uncaught error: new BigNumber() not a base 16 number.
It's been discussed here and might occur due to a bug in web3.js

Maybe it's just my code that causes this error. Here it is:

pragma solidity ^0.4.8;
contract Test {
    struct Addresses{
        string  id;
        string[] fname;
        string[] lname;
        string[] streetaddress;
        string[] zip;
    }
    mapping(string => Addresses) UserProfile;

    //Set Variables
    function setData(string uid,string firstname,string lastname,string street,string zipVal) {
        UserProfile[uid].id = uid;
        UserProfile[uid].fname.push(firstname);
        UserProfile[uid].lname.push(lastname);
        UserProfile[uid].streetaddress.push(street);
        UserProfile[uid].zip.push(zipVal);
    }

    //Return Variables
    function getFirstname(string uid, uint8 pos) constant returns (string) {
        return UserProfile[uid].fname[pos];
    }
    function getLastname(string uid, uint8 pos) constant returns (string) {
        return UserProfile[uid].lname[pos];
    }
    function getGender(string uid, uint8 pos) constant returns (string) {
        return UserProfile[uid].streetaddress[pos];
    }
    function getDOB(string uid, uint8 pos) constant returns (string) {
        return UserProfile[uid].zip[pos];
    }
}

and here is my Javascript:

function getUserProfile() {
    var struid = document.getElementById('uid').value;
    var iPos = parseInt("0");
    returnFirstname = UserProfile.getFirstname(struid, iPos);
    returnLastname = UserProfile.getLastname(struid, iPos);
    //OUTPUT TO CONSOLE
    console.log("-----------------");
    console.log("GET DATA FUNCTION");
    console.log("UID: "+struid);
    console.log("Pos: "+iPos);
    //OUTPUT TO HTML
    document.getElementById('firstname').innerHTML = returnFirstname;
    document.getElementById('lastname').innerHTML = returnLastname;
}

Maybe it's the combination of strings and integers that is throwing this error.

Any pointer would help!
Thanks


texts: How to pull metadata of NFT tokens that uses (erc721 and erc1155)

texts: Is there any apis that we can use to pull such metadata , i found that openseac provided an api for the erc721 tokens but not for the erc1155 ones.


texts: how to display a struct inside mapping inside struct in solidity on react js frontend

texts: I have a mapping of struct (mapping (address => struct)) inside another struct. I'm having issue in how to display the struct in the front end while using Reactjs.


texts: how to refer a previous transaction in current transaction in ethereum private blockchain

texts:
I am trying to build an private block chain based use case (not a financial one) to benefit from the decentralized nature of BC. The scenario is something like this, there are multiple nodes connected to the chain and deploy smart contracts onto the network. The smart contract basically has two functions one is getAccess and other is grantAccess. The getAccess function of a contract (deployed by node1 for example) is called by node 2 and an event is associated with getAccess that gets triggered. Upon this event, node1 should call the grantAccess function of the smart contract deployed by node 2. In this call, it should pass transaction ID of getAccess as argument so it is understandable by the network that node1 is replying to the getAccess request. How can i pass transaction ID as an argument to the function of smart contract is my question.

Thanks


texts:
const Web3 = require('web3');
const fs = require('fs');
const solc = require('solc');
let web3;
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/my key'));
}
const source = fs.readFileSync('./contract/coin.sol', 'utf8');
const compile = solc.compile(source, 1);
const contractCompile = Object.values(compile.contracts)[0];
const deployAddr = '0x.....';
const contractByteCode = '0x' + contractCompile.bytecode;
const contractAbi = JSON.parse(contractCompile.interface);
const gasEstimate = web3.eth.estimateGas({data: contractByteCode});
const gasPrice = '20000000000';
const myContract = new web3.eth.Contract(contractAbi, {
    from: deployAddr,
    gas: '15000000',
    gasPrice: gasPrice,
});
const initialSupply = 10000000000;
const tokenName = 'LLT';
const tokenSymbol = 'LLT';

myContract.deploy({
    data: contractByteCode,
    arguments: [initialSupply, tokenName, tokenSymbol]
}).send({
    from: deployAddr,
    gas: '15000000',
    gasPrice: gasPrice
}, function (error) {
    console.log(error);
})
.on('transactionHash', function (transactionHash) {console.log(transactionHash)})
.on('receipt', function (receipt) {
    console.log(receipt.contractAddress) // contains the new contract address
}).on('confirmation', function (confirmationNumber, receipt) {
}).then(function (newContractInstance) {
    console.log(newContractInstance.options.address) // instance with the new contract address
}).catch(err => {
    console.log("Error: failed to deploy, detail:", err)
});

I get Error: Invalid JSON RPC response: "" when I use node to run this code.

How can I solve this problem？ Thank you


texts: How can I use Geth to get all tokens on an Ethereum address?

texts:
Having an ETH address, how can I programmatically see what tokens are on this address?

Currently I have a list of tokens and a loop that checks balance on the ETH address for each contract address, but this naive approach seems to be slow and rather complex - O(n), where n is number of all available ERC20 tokens.

How can I do this in a better way?


texts: Where to save user information for a mobile Dapp?

texts:
I have been researching on blockchain technology and ethreum platform and I want to build an mobile aplication (Dapp), I know that an Ethereum account has private and public key, the private key only the user's own can use, so my questions are born here. (I know that for this I should have a blockchain network in this case I will use ethereum, I should have a web API and finally the frontend).

Where save the user's private key? In a centralized database like a bank data? in the ethereum network?
Where save the user's email and password?

or what is the flow exactly about this

please help me.


texts: ENS name reverse is not working on Ethereum address

texts:
I'm trying to both resolve and lookup using "ethjs-ens" the lookup call is working correctly. However, the resolve call is throwing an empty error.

The address I'm using on the reverse function is the one I got from calling lookup, I'm also logging a validation to check that both addresses are the same console.log("is the same", address === result);

import ENS from "ethjs-ens";

//assume metamask installed
//testing on main network
const ens = new ENS({ provider: window.web3.currentProvider, network: 1 });

const address = "0x96619cd92fe0c7deaaee1c8043a7fea79cfa3e71";
const name = "example.eth";
const fn = async () => {
  try {
    const result = await ens.lookup(name);
    console.log("adddress", result);
    console.log("is the same", address === result);
  } catch (e) {
    console.log("lookup", e);
  }

  try {
    const resultName = await ens.reverse(address);
    console.log("name is", resultName);
  } catch (e) {
    console.log("name", e);
  }
};
fn();

Code live sample

reverse is always failing not sure what could be happening.


texts: Programmatic way of generating and extracting private address using Geth

texts:
I'm not sure why this is so tough but I can't find easy answer to do what I'm trying to do, which is following:

Generate a new ETH address using passphrase using Geth (I can do this using "geth account new", and I see public key)
It generates a keystore file (which I have after step 1)
All I want to do now is extract public as well as unencrypted private key (I have the file and the passphrase) via command line (either using geth, or openssl or whatever). I can see both after importing it manually using MyEtherWallet but I need to be able to do this for multiple keys so need to do it via command line.

Is there ANY way to do the step 3 without doing it manually using some web interface like MEW?

Thanks in advance.

JT


texts: Start up ganache-cli ethereum client in travis CI for testing

texts:
I'm trying to write a .travis.yml file to test my ethereum contract.

In order to test it, I need to start up an instance of the ganache-cli ethereum client by calling

ganache-cli -p 7545

and then run some truffle commands:

truffle compile
truffle migrate

However, if I put the ganache-cli command in the script section of my .travis.yml file like so:

script:
- ganache-cli -p 7545
- truffle migrate
- truffle test

My truffle commands are never called because the entire terminal instance is taken over by the instance of the ganache-cli client that is started up.

I've tried putting the ganache-cli call in before-scripts like so:

before-script:
- ganache-cli -p 7545
script:
- truffle compile
- truffle migrate --network development
- truffle test

Using the above code, the ethereum client is never started. Does anyone have any idea how to setup my .travis.yml file to both start the ganache-cli client as well as allow me to call my truffle migrate/test commands?


texts:
We have a struct as follows :

struct ObjectStruct {
        bytes32 state;
        address owner;
        bool isObject;
    }
mapping(bytes32 => ObjectStruct) public objectStructs;
    bytes32[] public objectList;

Now, we want to modify bytes32 state; field such that it would be dynamic and so we would be able to "add" several "sub_state" to it, ex. objectStructs[_object_id].state.location = _location; or objectStructs[_object_id].state.price= _price; etc.

How we can define such a "dynamic state field" such that we would be able to add any "sub_state" to it ?

I defined it as follows:

struct ObjectStruct {
        bytes32 location;
        bytes32[] state;
        address owner;
        bool isObject;
    }

And then :

function newObject(bytes32 _object_id, bytes32 _state, address _owner) public returns(bool success) {
        require(!isObject(_object_id));

        objectStructs[_object_id].state = _state;
        objectStructs[_object_id].owner = _owner;
        objectStructs[_object_id].isObject = true;
        objectList.push(_object_id);

        LogNewObject(msg.sender, _object_id, _state, _owner);
        return true;
    }

event LogNewObject(address sender, bytes32 _object_id, bytes32 state, address owner);

then, we invoke function newObject as follows :

newObject(100, "location:Paris,price:50,sold:yes", '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773');

I am wrong ?


texts: Solidity: What is the difference between `view` and `constant`?

texts:
Solidity 0.4.16 introduced the view and constant function modifiers. The documentation says:

  constant for functions: Same as view.

Does this mean view is just an alias for constant? If so, why do we need it?


texts:
sorry for this stupid question - but I tried to follow this guide: https://medium.com/@mtrimble/watch-pasting-bytecode-and-adding-0x-290bb6dd9d65

However, when I press "details" in remix I do not get up the same alternatives as in the guide. Seems something is missing?


texts: gas required exceeds allowance or always failing transaction when I try to transfer ether...

texts:
I am trying to play with very simple contract on testnet (ropsten).
My contract code is as follows.

contract Bank11{
   mapping(address=>uint) userBalances;
   function getUserBalance(address user) constant returns(uint) {
     return userBalances[user];
   }

   function addToBalance() payable {
     userBalances[msg.sender] = userBalances[msg.sender] + msg.value;
   }
   function withdrawBalance() {
     uint amountToWithdraw = userBalances[msg.sender];
     if (msg.sender.call.value(amountToWithdraw)() == false) {
         throw;
     }
     userBalances[msg.sender] = 0;
   }
}

No problem when I try with run on remix. (Javascript VM Mode) But I've got error every time when I try to call withdrawBalance.

transaction to Bank11.withdrawBalance errored: gas required exceeds allowance or always failing transaction.

I set Gas limit, 3000000. What am I doing wrong??


texts: Invalid Address Error when interacting with a smart contract with metamask

texts:
I want to call the methods with metamask of this simple contract:

contract AssetPrices {
  mapping (uint => uint) public prices;
  uint public data;

  function EnterPrice(uint _time, uint _price){
  prices[_time] = _price;
  }

  function GetPrice(uint _time) returns (uint){
  data = prices[_time];
  return data;
  }

}

The contract is deployed at address 0xd884b7b7d6e21798814f218f2daa1054cff33ee5

The index.html file is:

<!DOCTYPE html>

A Simple METAMASK controlled contract

However when I serve the page I get the following error:

Uncaught Error: invalid address

    at inputAddressFormatter (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:3920:11)
    at inputTransactionFormatter (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:3746:20)
    at https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:5005:28
    at Array.map (native)
    at Method.formatInput (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:5004:32)
    at Method.toPayload (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:5030:23)
    at Eth.send [as sendTransaction] (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:5055:30)
    at SolidityFunction.sendTransaction (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:4121:26)
    at SolidityFunction.execute (https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js:4207:37)
    at startApp (http://127.0.0.1:8000/:27:20)


texts: Solidity - default data location for local vars

texts:
Solidity documentation states that

  the default (location -ronme) for local variables is storage

I understand that this makes sense so that localVar = contractStorageVar will result in localVar pointing, and not copying, contractStorageVar.

I'm trying to figure out how this works. For example, as local variables go out of scope, does their storage clear up?


texts: How to delete a storeage item using a local reference?

texts:
I have a reference to a storage item:
MyData storage myData = /* ... */;

How can I use myData to clear up that storage item?
I've tried
delete myData;

but this fails to compile, because Solidity assumes that I want to clear the myData reference and not the referenced storage.


texts: What is the purpose of tokenRecipient contract in token example?

texts: The example of how to create a token (https://www.ethereum.org/token) includes contract tokenRecipient. Why is it there?


texts:
Truffle has this whole build process for deploying fronted code that is kinda mediocre. Does anyone know if I can just have Truffle output a single javascript file that will work in a web3 enabled browser and then import that in a much cleaner frontend framework like React?

I guess what is the best way to get all the benefits of Truffle with the secret sauce of React going?


texts: How to make an API call in solidity using Chainlink?

texts:
I am following the documentation from the Chainlink site, and I am attempting to make an API call. The main issue is I'm not sure what "address" is referring too. I am using remix in solidity v0.6

  function requestEthereumPrice(address _address)
    public
    onlyOwner
  {
    // newRequest takes a JobID, a callback address, and callback function as input
    Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOB_ID), address(this), this.fulfill.selector);
    // Adds a URL with the key "get" to the request parameters
    req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
    // Uses input param (dot-delimited string) as the "path" in the request parameters
    req.add("path", "USD");
    // Adds an integer with the key "times" to the request parameters
    req.addInt("times", 100);
    // Sends the request with the amount of payment specified to the oracle

    sendChainlinkRequestTo(_address, req, ORACLE_PAYMENT);
  }


texts:
I have a contract(A) function with the standard onlyOwner access. If I call directly from the deployed account the function works fine. But when I import this contract(A) into another contract(B) and I call that function with the onlyOwner modifier. Report me the error.

It´s seems that the msg.sender that arrive to the modifier contract(A) is the the deployed address of the contract(B) and not the default account selected and deployed from Remix.

My doubt is how can I wrapp the msg.sender to take that that I select in Remix??

This is my idea, but any other idea is wellcome.

Thx


texts: How to verify a contract having constructor arguments?

texts:
This is a contract that requires an argument to be deployed.

The Contract Name is "Asset". The compiler used is "Compiler 0.4.16+commit.d7661dd9.Emscripten.clang" and Optimization was Disabled.

To validate it this is the tool used.

Other contracts with no constructor arguments were succesfully verified, but this one complains like this:

Error! Unable to verify source code
Missing Constructor Arguments for function Asset(address _SCIssuers)

It seems that the validator needs to know a ABI-encoded info about constructor arguments as stated here.

I tried to encode Method ID + first parameter, but had some difficulties. To deploy the contract I used:

Create("0x22bc795b5b8154fe619724e7cb1f4b931cd39c11")

So first parameter must be 0x22bc795b5b8154fe619724e7cb1f4b931cd39c11.

Problem is to find out the constructor method ID. The online IDE used to deploy doesn't tell me that information. How can I find it?

By the way, the constructor function is this one:

// Constructor
function Asset(address _SCIssuers) {
    SCIssuers = _SCIssuers;
}

Any help? Thx!

Refs.:

Having trouble verifying a contract on etherscan.io
How do I create ABI encoded constructor argument to verify an Ehtereum contract on etherscan.io when i know the arguments: adress1 uint
Please create for the contractate ABI encoded constructor argument to verify an Ehtereum contract on etherscan.io?
How to verify a deployed contract on etherscan


texts: How to get the historical Gas (Gwei) Price

texts: I would like to get the historical Gas (Gwei) price in hourly or minutely with safelow, Standard, fast and fastest. I am aware of the etherscan.io which gives avg gas price for a day and also ethstation which gives realtime data. I am able to get the real-time from https://www.etherchain.org/tools/gasPriceOracle. Is there a way where i can get historical prices?


texts: Remixd fails to run, cannot find web3-requestmanager

texts:
I have installed remixd using NPM. If I run it, it gives me the following error:

Error: Cannot find module 'web3-requestManager'
    at Function.Module._resolveFilename (module.js:555:15)
    at Function.Module._load (module.js:482:25)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/remixd/node_modules/web3/packages/web3-core/src/index.js:26:22)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)

I have searched a lot of solutions for this, like installing ethereum/web3.js or using another version of the web3 package, but none works. How to fix?


texts: Decrease polling interval for web3.myContract.myEvent()

texts:
The following seems to poll my Ethereum node every second:

web3.eth.contract(contractAbi).at(contractAddress).allEvents(callback);

Is there a way to decrease the polling interval?


texts: ethereum wallet:Your computer's clock is not synced.

texts:
i am using geth

VRSION:
   1.8.20-stable-24d727b6

and ethereum wallet Ethereum-Wallet-linux64-0-9-3 and i am using Ubuntu 18.04.1 LTS and on wallet startup wallet is showing the error message
here is the error message

To successfully synchronize with the Ethereum network, you need to sync your computer's clock with a time sync server. To enable a time sync server, install "ntp" via "apt-get install ntp".

i did run apt-get install ntp but the problem persists wallet is showing above error message after running this command


texts: I am being asked to enter my Ethereum address, but I don't know what to put there and I already created an Ethereum account.


texts: Is EOS based on an Ethereum client? (geth, parity, etc)

texts:
Do we know if EOS is based on code contributed by the Ethereum community? Is it possible that they will "steal" a lot of the open source projects that have been developed for Ethereum?

I am not, and will not, invest in EOS. Only wondering if it is based in solidity.


texts: Error whilst running solidity with python(py-solc)

texts:
I have been running my code which involves deployment of smart contract to Ethereum Ropsten network. I ran this successfully for some time but last week did installed another software after which  started getting these errors:

command: solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc
return code: 1
stderr:
stdout:
Invalid option to --combined-json: clone-bin

EDIT I'm running this on Jupyter notebook where environmental variable for python3.6 is set up. I have no clue why I'm getting them. Anyone can help?