texts: How to generate unique id for each tokens without using loop?

texts:
I'm creating tokens without use of any pre-defined standard. As we have requirement to track each token, I did code to assigned ids to each token.

pragma solidity ^0.5.0;

contract MyContract {

    string Name;
    string Symbol;

    using Counters for Counters.Counter;

    mapping (address => Counters.Counter) private _ownedTokensCount;
    mapping (uint256 => address) private _tokenOwner;

    constructor(string memory _name, string memory _symbol, uint256 _totalSupply) public {
        Name = _name;
        Symbol = _symbol;

        for(uint256 i=1; i<= _totalSupply; i++){
            _tokenOwner[i] = msg.sender;
        }

        _ownedTokensCount[msg.sender].incrementBySupply(_totalSupply);
    }

    function transferFrom(address from, address to, uint256 tokenId) public {

        _ownedTokensCount[from].decrement();
        _ownedTokensCount[to].increment();

        _tokenOwner[tokenId] = to;
    }

    function balanceOf(address owner) public view returns (uint256) {

        return _ownedTokensCount[owner].current();
    }

    function ownerOf(uint256 tokenId) public view returns (address) {
        address owner = _tokenOwner[tokenId];
        return owner;
    }

    function getName() public view returns (string memory) {
        return Name;
    }

    function getSymbol() public view returns (string memory) {
        return Symbol;
    }
}

The code is working fine when we pass lower number of total supply. But as increasing total supply, it will run out of gas. So, my question is, Is there any alternate way to generate unique ids for tokens without loop?

Full requirement:

I'm taking an example of an artist market place to clear up the requirement.

Roles:
- Artist
- Fans

Artists can create tokens for them using a smart contact.

Leonardo, for example, created tokens LEO with a total supply of 1000. So, currently his wallet is holding 1000 LEO tokes.

Fans can purchase tokens from an artist. I'm a fan of Leonardo, so I'll purchase some tokens from him and give some fiat currency to him. Let's say I've purchased 100 tokens from him.

Now, an artist can create a reward and sell it. For example, Leonardo has created one painting reward with a value of 50 tokens.

I've claimed that reward on 9-Apr-2020, so my 50 tokens have been used and that 50 tokens I can not be used till 3 months(9-July-2020)

There is no limit to creating reward by an artist. Now suppose Leonardo has created another reward for 1 token. And I have claimed it on 10-Apr-2020, now that 1 token from my balance is on hold for three months till 10-July-2020, and my available balance is 49 Leo tokens.

During this time, I can sell all the tokens(49+1+50) to another user (let's take a name, Alex). But the tokens are on hold will be transferred with dates, meaning that Alex can't use 50+1 token till its holding ends.


texts: Rewriting msg.sender.call.value(amount)() into one under version 0.5.x

texts:
I want to rewrite

  - bool ok = msg.sender.call.value(amount)();
  - emit WithdrawalEther(msg.sender, amount, ok);

into

  - (bool ok, bytes memory returnData) = msg.sender.call(abi.encodeWithSignature(???,amount));
  - emit WithdrawalEther(msg.sender, amount, ok);

But I am not sure what a signature string must be given for the part of the three question marks. The original statement is simply a sending of money amounting 'amount', and so if the receiver account is a contract, its fallback function must be called. This is my understanding. Then, my question seems to be what is a signature for fallback function.

The example needs a boolean value to check if sending money succeeds or not. In case it fails, an event with false must be created in the next statement.

The reason for the rewriting is because of this.

I have a solc compiler version 0.5.7 but the Solidity example program that I try to compile has a declaration of pragma 0.4.8.

If I simply change the version number, I will get a compilation error for

 -  bool ok = msg.sender.call.value(amount).()

because the style of the statement seems to be old and it is not supported by the solidity compiler version 0.5.7.

Can you please help me out to resolve this issue?

Thanks in advance.


texts: Get method signature from contract rather than manually constructing

texts:
Is there a way to get a method signature from the contract object (using Web3.py) rather than manually constructing it?  I don't see a function in there that accomplishes this.  It seems like something should be built-in.

I have always calculated the method signature manually using Web3.sha3 as seen below, but this requires me to manually type out the function params.

params = 'uint256,uint256,bytes,address[]'
method_signature = Web3.sha3(text=f"functionNameGoesHere({params})")[0:4]

The contract object already knows the ABI JSON, so shouldn't it be able to generate it for me?

It would be nice if I could do this:

function.method_signature

Since I can already do this:

function.abi

Note, I'm NOT trying to build a transaction to broadcast to the network.  I'm trying to generate lots of function hashes from contracts given the contract object an ABI.  And these contracts will change over time so I don't want to hard code anything.

Edit: I wrote this myself to do the job.  It supports regular types as well as tuples.  Would still prefer to use something built-in though.

def GetMethodSignature_GivenAbi(methodName, abi):
    params = ''
    for index, input in enumerate(abi['inputs']):
        if index > 0:
            params += ','

        if input['type'] == 'tuple':
            params += '('
            for index2, tupleComponent in enumerate(input['components']):
                if index2 > 0:
                    params += ','

                params += tupleComponent['type']

            params += ')'

        else:
            params += input['type']

    methodSignature = GetMethodSignature(methodName, params)
    return methodSignature

ABI simple example:

{
  'constant': False,
  'inputs': [
    {
      'name': 'name1',
      'type': 'uint256'
    },
    {
      'name': 'name2',
      'type': 'uint256'
    }
  ],
  'name': 'simpleFunction',
  'outputs': [

  ],
  'payable': False,
  'stateMutability': 'nonpayable',
  'type': 'function'
}

ABI tuple example:

{
  'constant': False,
  'inputs': [
    {
      'name': 'name1',
      'type': 'uint256'
    },
    {
      'name': 'name2',
      'type': 'uint256'
    },
    {
      'name': 'name3',
      'type': 'uint256'
    },
    {
      'components': [
        {
          'name': 'makerAddress',
          'type': 'address'
        },
        {
          'name': 'takerAddress',
          'type': 'address'
        },
        {
          'name': 'feeRecipientAddress',
          'type': 'address'
        },
        {
          'name': 'senderAddress',
          'type': 'address'
        },
        {
          'name': 'makerAssetAmount',
          'type': 'uint256'
        },
        {
          'name': 'takerAssetAmount',
          'type': 'uint256'
        },
        {
          'name': 'makerFee',
          'type': 'uint256'
        },
        {
          'name': 'takerFee',
          'type': 'uint256'
        },
        {
          'name': 'expirationTimeSeconds',
          'type': 'uint256'
        },
        {
          'name': 'salt',
          'type': 'uint256'
        },
        {
          'name': 'makerAssetData',
          'type': 'bytes'
        },
        {
          'name': 'takerAssetData',
          'type': 'bytes'
        },
        {
          'name': 'makerFeeAssetData',
          'type': 'bytes'
        },
        {
          'name': 'takerFeeAssetData',
          'type': 'bytes'
        }
      ],
      'name': 'order',
      'type': 'tuple'
    },
    {
      'name': 'name4',
      'type': 'bytes'
    },
    {
      'name': 'name5',
      'type': 'address[]'
    }
  ],
  'name': 'functionName',
  'outputs': [

  ],
  'payable': False,
  'stateMutability': 'nonpayable',
  'type': 'function'
}


texts: I'd like to generate and sign a transaction offline and then send that transaction with a different account.  I've found a few web3js sources and I've read the web3 documentation, but I haven't found any clear solutions for doing this in Java with web3j.  Thanks for the help.


texts: I sent eth 2.62(NETWORK ETH) ON the eth ropsten wallet address 0xe2fcd50EfdD674C26f894aB5ad71fEcB14b7cDA4(BUT NETWORK ETH (myetherwallet.com)NOT ropsten eth). How to transfer to the wallet Eht 0xAd9BA786b9692371E9DBDcCb8A51ff6ec94C6Fc0 ? TELL MONEY LOST OR CAN BE SEND BACK?


texts:
Why we need to register Interface ID in ERC721 token. I was just going through the openzeppelin-solidity erc721 code and curious to know that why we need to use this. That interface id register code is something like this:

/*
 *  bytes4(keccak256('name()')) == 0x06fdde03
 *  bytes4(keccak256('symbol()')) == 0x95d89b41
 *  bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
 *
 *  => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
 */

bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;

constructor (string memory name, string memory symbol) public {
  _name = name;
  _symbol = symbol;

  // register the supported interfaces to conform to ERC721 via ERC165
  _registerInterface(_INTERFACE_ID_ERC721_METADATA);
}


texts:
I'm trying to build multi-threading in my contract by mapping a mapping:

struct Structure {
    bytes32 byteCode;
    uint integer;
}

//Mapping a structure to the address in order to hold address specific information.
mapping (address => Structure[]) mapping1;

//Mapping a mapping to uint256 in order to keep track of which thread it is concerning.
mapping (uint256 => mapping1) mapping2;

I am getting errors all over the contract wherever I try to do mappings like in the code above. The error is:

 Name has to refer to a struct, enum or contract.
mapping (uint256 => mapping1) public mapping2;
                    ^------^

Any ideas about a workaround or should I just hope that next version of Solidity supports this kind of linking?

EDIT: I worked around the issue by using structures that have sufficient indexes in order for my mechanics to work. Unfortunately this method is way more wasteful than double linking, so I still hope someone knows the answer to my issue.


texts:
Hello Ethereum community, I'm building a mobile app with ionic, i want that app to acces a specific smart contract address (that i made and own) and extract variables of that contract, at first i thought about using web3.js but it requires a RPC layer to work with and implies downloading the whole blockchain wich is not practical as a quick mobile app, second guess was using etherscan api but i dont find it usefull on that matter or i'm missing something. I need some suggestions thank you.

TL;DR Extract smart contract variables on a mobile app without downloading the whole blockchain.


texts: Is this approach to an ethereum lottery sound and/or novel?

texts:
I'm looking at making gambling apps is ethereum. Currently made a contract that can flip a coin. After looking at this question:

How can I securely generate a random number in my smart contract?

and thinking about the problem that large lotteries face, in that players would need to put up a huge deposit in order to guarantee that they do in fact reveal their random number, I thought of a potential solution. It is my understanding that, in order to participate in a 4 way flip, each player would have to put up a bet of 1 unit and a deposit of 9 units (in order to pay each other player 3 units if they don't reveal). I have an idea for an alternative approach that works as follows:

Players 1, 2, 3, and 4 put up a bet of 1 unit and a deposit of 1 unit.
They all submit and reveal their random number.
P1 & P2's numbers are used to determine a winner between the two of them, the loser gets their deposit of 1 back.
The same occurs with P3 & P4.
Let's assume P1 & P3 win. They now have 3 units each. They put up a bet of 1.5 units and a deposit of 1.5 units.
Let's assume P1 wins. He now has 4.5 units and P3 has 1.5 units. This could end here so that P1 wins first place of 3.5 units and P3 gets 2nd for 0.5 units(a net gain of 2.5 for P1 and a net loss of 0.5 for P3).

Alternatively:

They each put up a bet and deposit of 0.5 units each and flip again. If P1 wins, he has 5 units and P3 has 1 unit (his deposit) and the bet is over. If P3 wins, P1 has 4 units and P3 has 2 units and we proceed to step 8.
They each put up a bet and deposit of 1 units each and flip again. If P1 wins, he has 5 units and P3 has 1 unit (his deposit) and the bet is over. If P3 wins, P1 has 3 units and P3 has 3 units and we go back to step 5.

A new random number must be submitted and revealed each time. A limit could be set on number of flips and, if a winner is not found, the current payments are paid out. I'm aware that this is the same as just upping the stakes every time you bet but a contract that implements this on a large scale seems in no way different to a normal lottery.

In order to prevent players from "chickening out" after winning several flips, an additional small deposit could be made. For example a bet of 1 unit, a standard deposit of 1 unit to prevent gaining an edge by cheating and a deposit of some amount, say 0.2 units, to prevent people being denied their large flip. The other player either gets their flip or gets bought out of it.

This can be applied to allow 2^x people to gamble with 1 winner or a series of progressively larger winners. Is this all logically sound and do you think it solves the problem that lotteries face? Any other problems with it?


texts: ethreum sent to my wrong adress im worried it wont be recovered

texts: hi all I'm new to  trading I'm hoping someone can help me out here I purchased a good bit of ethreum on the coinbase platform I made a ether wallet I had all the accounts and my security accounts saved I accidently transferred my ethreum from coinbase to the wrong address that being my private key address I went under the etherscan and sure enough its sitting in my private key address instead of my wallet account I contacted coinbase and explained the situation thinking the worst they explained to me that basically it will be sent back to them but it may take awhile and it would be credited back to my ethreum wallet on their platform .I am just curious if this has ever happened to anyone else and if this is correct what they are saying thank you


texts: How can a peer request another peer to invoke a function from his private contract

texts:
I build a permissioned network using Quorum,

I have a peerA which has a private smart contract, another peerB that cannot invoke functions of the smart contract as it is private

So, can peerB send transaction to peerA to request it to invoke a function from his private contract.


texts:
I have seen two ways to assign the creator of the contract.
The first way is this way which you don't put the assignment in the constructor function.

pragma solidity ^0.6.6;

contract Test {
   address creator = msg.sender;

   constructor() public {}
}

The second way is when you assign the creator inside the constructor function

pragma solidity ^0.6.6;

contract Test {

   constructor() public {
       address creator = msg.sender;
   }
}

Is there any difference between these two? which one is better? and why?

EDIT : i wrote the second code in a totally wrong way. i meant this code

pragma solidity ^0.6.6;

contract Test {
   address creator;

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


texts:
im getting this erorr. Operator >= not compatible with types function (address,address) returns (uint256) and uint256.
here is the code for the function with the type eror.
pragma solidity 0.6.3;

contract zylus {

    mapping (address => uint256) public _balances;
    uint256 constant private MAX_UINT256 = 2**256 - 1;

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

    string public _name = 'Zylus';
    string public _symbol = 'zyl';
    uint8  public _decimals = 6;
    uint public _totalSupply = 100000000000000000;

    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);

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

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

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

    function totalSupply() public view returns (uint256) {
        return _totalSupply;
    }

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

    function transfer(address _to, uint256 _value)payable public returns (bool success) {
        require(_balances[msg.sender] >= _value);
        require(_balances[_to] + _value >= _balances[_to]);
        _balances[msg.sender] -= _value;
        _balances[_to] += _value;
        emit Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public view returns (bool success) {
        uint256 allowanc = _allowances[_from][msg.sender];
        require(_balances[_from] >= _value && allowance >= _value);
        _balances[_to] += _value;
        _balances[_from] -= _value;
        if (allowance < MAX_UINT256) {
            _allowances[_from][msg.sender] -= _value;
        }

        emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
        return true;
    }

    function approve(address _spender, uint256 _value) public view returns (bool success) {
        _allowances[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
        return true; // NANDE (why)
    }

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

}


texts: Connecting to Geth private network from Metamask using RPC URL

texts:
I have created a private chain in Geth which is running in machine1. I want to connect to the private chain running in machine1 from machine2's Metamask using rpc. machine1 and machine2 are connected to the same Wifi network.
The IP address of machine1 is 192.168.0.103 and I am opening port number 8501 for RPC connections.
The following are the flags that I have used to start Geth in machine1:
geth --datadir "C:\Users\smuth\Desktop\GETH DAPP POA\node1" --port 30311 --http --http.addr "192.168.0.103" --http.port 8501 --http.corsdomain "*" --http.api "personal,db,eth,net,web3,txpool,miner" --networkid 1515 console --ipcdisable --nat extip:192.168.0.103

I tried using the rpc url http://192.168.0.103:8501 and chain ID as 1515 in Metamask of machine2. But Metamask doesn't connect and displays the error : "Could not fetch chain ID. Is your RPC URL correct?"
The console log of Metamask displays a timed out HTTP POST request to the RPC URL (http://192.168.0.103:8501)
A similar question is posted here:
MetaMask and Access Ethereum Private Chain from other PC in the same network (for test)
But the solutions for the above question does'nt work for me.
What could be changed to make this connection work?


texts: Store and retrieve data of MongoDb documents using hash which is stored in blockchain

texts:
Blockchain can not store and shall not be used to store all the data of users. There are 2 reasons for that -

1) To store data in blockchain requires gas price (transaction cost)

2) Since all blocks are replicated on all the nodes participating in blockchain there are some limitations for storing big data in blockchain.

Blockchain is not replacement of a database but it is another layer on top of that to store transactions which are crucial for business and to ensure trust among multiple entities.

I read that remaining data shall be stored in IPFS and hash of that data is stored in blockchain. But as IPFS only supports unstructured data i.e. images and videos.

I want to store remaining user data in MongoDB and I will store hash of MongoDB document in blockchain. I shall be able to retrieve data stored in document from hash that is stored in blockchain. Are there any resources or tutorials available for implementing the same?


texts: Many errors when using Oraclize (Remix with Mist)

texts: Hi when I use Remix with Mist, I get these error with Oraclize. How do I solve it?


texts: How to backup account information from Geth in a Docker container?

texts: I created a Geth node using the default Docker container, but realized I need to make some adjustments to the docker run command, which requires removing the current container. How do I backup my current account information so that isn't lost when removing the container?


texts: Is there a way to view the private key of test account in Remix (javascript VM)

texts: Seeing how the keys are random and those "100 ethers" aren't real I can't think of why this is not obvious functionality, I'll need this for many reasons.


texts: Why is an ephemeral key used in creating a digital signature?

texts:
When creating the 'S' component of a digital signature, both the actual private key and an ephemeral private key are used.

The reasoning I've read is to ensure that the sender’s actual private key can’t be calculated by attackers watching signed transactions on the Ethereum network.

How would an attacker be able to calculate a private key anyway? Is the purpose of the ephemeral key to simply further obfuscate?


texts:
web3 API has method getBalance. How does it work? geth just calculates and cache balances of all addresses, i.e. it works as block explorer? Or there is some magic?

How fast is getBalance? Can I make 100 requests per second to one geth instance?


texts: Error while opening Mist on ubuntu 16.04

texts:
I want to connect mist on my private net however it give error of already connect but there is no connect there. Please advise me how to resolve the issue.

Note:- Please see the attached error screen shot


texts: Where is this contract's string written and viewable?

texts:
I have a very simply contract.  I am testing writing to the blockchain (on a private network).  The contract seems to deploy successfully but I don't see "this is a hardcoded string" anywhere on my block explorer.

Can anyone help me to create a simple contract where I can write "Hello World" in a way that is viewable on the blockchain?

Here is the code I'm using now:

pragma solidity ^0.4.18;

contract TestString {

    string testStr;

    function TestString() {
        testStr = "this is hardcoded string";
    }

    function setString(string str) {
        testStr = str;
    }

    function getString() constant returns (string) {
        return testStr;
    }

    function() payable {
        revert();
    }
}


texts: What is the difference between Ethereum 2.0 and the beacon chain?

texts:
There's a lot of promise to Ethereum 2.0 and questions like the following:

How to deploy Smart Contract on Ethereum 2.0
Will gas be free in ETH 2.0?
Does Ethereum 2.0 still have use cases for oracles, why?
At which (average) rate will block numbers increase with ETH 2.0?

Most of these questions are misunderstanding the difference between Ethereum 2.0 and the beacon chain.
What is that difference?


texts: I'm trying to open ethereum studio, but the tab closes a second after it opens. I've tried opening it through both chrome and edge.


texts: How to use our own crypto currency for transactions in smart contract

texts: I have created my own crypto-currency and tried sending it to an address through my ethereum wallet but can anyone tell me that how can I use this crypto-currency in another smart contract for transactions instead of ether?


texts: How to create modifers for permissioned access

texts:
I have a citizenship persona contract which acts as a personal identity file which is under the control of the user. Personas can make other personas in the system into trustees or allies. As part of the persona contract I'd like to implement a feature called publicity, which has three settings, denoted by -1, 0, 1. publicity controls who can access the persona's general information.

-1 = only trustees can access info.

0 = trustees and allies can access info.

1 = full publicity to anyone who requests it.

There are two lines of security I'm concerned about: interacting with functions themselves and viewing the state on the blockchain.

The first issue can be solved against with modifiers, although I'm not exactly sure the following attempt works (persona is a struct containing all the relevant details about the human being which can be queried):

mapping(address => int) allies;
mapping(address => int) trustees; //

modifier Security {
    if(persona.publicity = -1) {
        if(trustees[msg.sender] = -1) {
            _ } else throw;
    }
    else if(persona.publicity = 0) {
        if(allies[msg.sender] = 0 || trustees[msg.sender] = -1) {
            _ } else throw;
    }
    else _
}

I'm not sure if this is valid. Would appreciate if this syntax could be verified.

The second line of attack is reading state directly on the blockchain. This is a little more complicated. I know many of the state variables that hold data can be encrypted using the sha3(x,y,z) approach. But how would you implement this?

This is the struct which holds persona information:

struct Persona {
        bytes16[] name;
        bytes16[][] residency;
        bytes32 id;
        string origin;
        uint created;
        uint access;
        int birth;
        int exit;
        int publicity;
        int status;
        Sex assigned;
    }
Persona public persona;

How could these state variables be encrypted so that they can't be read on the blockchain? What sort of scheme could you implement so that people in the trustees or allies permission group would be able to decrypt the data on their end? Apologies if this is too much for one question but I think it might be useful for others with permission group/access restriction questions.


texts:
In a regular solidity function, we have to name the arguments like:

function getAddr(string AddrName) public. . .

Here's the argument is a string which is named AddrName.

I had build a dapp which simplifies the interaction with smart contract using URL parameters. So to initiate the function with prefilled values in arguments I can simply browse: https://conteract.io/c/moataddress?function=getAddr&AddrName=owner

But prefilled input values doesn't work in mapping as the arguments is not named in mappings: https://conteract.io/c/moatfund?function=Investors

mapping(address => uint256) public Investors;

Provided that the mapping is used more often, is there any way to name the arguments in mapping or any workaround which might solve this issue.

Thanks.


texts:
I have read that "try catch" structure in solidity is dedicated to external calls.
Are there other reasons we should work with "try catch" structure ?
Here is what i've tried in a solidity function:
try c.myfunction(param)
{
    // What should i put here ?
}
catch
{

}

My first question is: What should i put inside the try section ? Usually, this is where i put the code which could throw an exception. But in solidity, this should be put upside.
Let's suppose myfunction returns a value.
I have tried this:
try ret=c.myfunction(param)
{
}
catch
{

}

But i got a syntax error when i try to compile this contract
Thanks


texts:
I'm using Nethereum (.NET MVC project) to register in blockchain, I never had any problems, I always recorded on networks: ETH Mainnet, Ropsten, Rinkeby, Kovan, Mordor and Kotti. However, using the same code, transactions are not being registered on the ETC Mainnet network. The transaction hash code is generated, but I cannot find it in the explorer. Can someone help me?
Code below (I just change the URL to the desired endpoint):
var url = "ethercluster.com/etc";
Nethereum.Web3.Accounts.Account account = new Nethereum.Web3.Accounts.Account(privatekey);
Web3 WEB3 = new Web3(account, url);

TransactionInput transaction = new TransactionInput() {
   Data = "hello world".ToHex(),
   From = account.Address,
   Gas = new HexBigInteger(1000000),
   GasPrice = new HexBigInteger(Web3.Convert.ToWei(200, EthUnit.Gwei)),
   To = account.Address,
   Value = new HexBigInteger(0),
};

var tx = await WEB3.TransactionManager. SendTransactionAsync(transaction);


texts: How to store encrypted mnemonic for Truffle + Infura mainnet deploy

texts:
I'm about to deploy a small Dapp to Mainnet using infura. Built using express + truffle.

I'm curious to hear how people are storing their mnemonic value when deploying to mainnet using truffle + Infura.

All examples I've found thus far store the mnemonic value as plaintext inside truffle.js.. which seems to me like a giant red flag.

According to http://truffleframework.com/tutorials/using-infura-custom-provider :

  Warning: In production, we highly recommend storing the mnemonic in
  another (secret) file, to reduce the risk of the mnemonic becoming
  known. If someone knows your mnemonic, they have all of your addresses
  and private keys!

I'm curious to hear how people are setting up this mnemonic secret file ? Are you just restricting perms to the mnemonic file to +r inside express (or whatever..)? Or are you encrypting the mnemonic file on the fs and then decrypting it inside express? The latter feels safer.

Perhaps someone has an example of a solution they have come up with.. ?


texts: How often the ether is deposited in my wallet when pool mining?

texts: I am using ethOS and using 6 gpus. And i have a wallet with Jaxx. My question is when or how often does ether is deposited in my wallet, when i do pool mining. I have started mining since yesterday evening and it's around 22 hours mining now.


texts: Is it possible to mine Ethereum with the MultiMiner app?

texts: Are there any pools that are compatible with MultiMiner? It can mine coins with Groestl,Keccak,Lyra 2RE,Neo Scrypt,Quark,Scrypt,Scrypt Jane,Scrypt N,SHA256,X11,X13,X14 and X15 algorithms and,while I dont know what algorithm Ethereum is,I know it is a PoW one and I wonder if any of those algorithms are what is used or can be used for mining ETH. Its such a pain to mine on Windows and there has to be a way to simplify it.


texts:
I am using Infura and web3.py. When I connect to Infura the web3 object has a clientVersion property that reads this from JSON RPC

"Geth/v1.8.15-omnibus-255989da/linux-amd64/go1.10.1"

Can someone explain to me what this client is and what the version number represents? Would the version number be the same for everyone connecting to Ethereum via Infura?

Ty!


texts: Ensuring correct block order with subscribe on "newHeads"

texts:
I have an issue with processing new blocks through a WebSocket connection on a local node. Sometimes I receive multiple events with the same blockNumber but different blockHashes.
I understood from some StackExchange threads that one of these blocks are just not part of the canonical chain. However, my question is: How do I determine which one of them is on the canonical chain? What would be the exact steps I need to take when I open a WebSocket connection and receive a new block after subscribing to "newHeads" to ensure this block is canonical?
Example
This is a shortened log of an application that stores some transactions from the newest blocks into an SQL db.
Added block #7665190 | hash 0x9ba66766f3835d5be9191e0ad7c79b741707e78dcf1f2a8898b7a7c2141d357c
Added block #7665191 | hash 0xe550f98974b4b02fff709842f670e682fc90403ead36d6258927b38cd45a56bc
Added block #7665191 | hash 0x068f5648b0509303640a1aa9c10764c89f33482148fde4ef94ce0ab4f21c25d1
Added block #7665192 | hash 0x36c2f7e9a4542a2311c91e8cd1560994ca14841086be86d0f6dbb1be9eae9d46
Added block #7665193 | hash 0x0cd7d6e0dac1c3288e574b454d7e4dee9123c4e1e94b6e87307aae32e812f1f1

Is using a getBlockByNumber RPC call after receiving a new block number sufficient to determine that this is indeed the "right" block that I want to store transactions for in my DB?
I don't think so because if I would use getBlockByNumber on the first 7665191 I would still receive the transactions in that block. Then after using it on the subsequent 7665191 I would receive another set of transactions that might include a bunch of the previous ones. Thus introducing redundancy and possible mismatches between the canonical transactions hashes / addresses in my SQL db.
Second option I could think of would be to wait until I receive just a single blockNumber after  (e.g. 7665192 in this case) and then check it's parentHash. If one of the 7665191's hash is equal to 7665192's parentHash I would take this one as the canonical block. However this just introduced a lot more questions:

What if I would receive duplicate blockNumbers multiple times in a row?

e.g. 7665191, 7665191, 7665192, 7665192, 7665193, 7665193 ...

What if the parentHash wouldn't be one of the previous duplicates?

e.g. parentHash of 7665192 wouldn't be equal to hash of any 7665191

To reiterate my question: What is the recommended way to ensure that I only store the real transactions from the blocks that you can find on bscscan.


texts:
i am wanting to import an array of json data into my contract on construct.  I want to pass it an array of address to be saved into an array in my contract.  Is this possible?  I have seen a few posts about phrasing json into a contract but could't quite extract what i am looking for.
The json data i have is structured like this; - i am wanting to extract only the HolderAddress's.
[
  {
    "HolderAddress": "0x00007569643bc1709561ec2e86f385df3759e5dd",
    "Balance": 100,
    "PendingBalanceUpdate": "No"
  },
  {
    "HolderAddress": "0x00089553ab5a08bfdf1dc324845a4ad7a63e26b8",
    "Balance": 9,
    "PendingBalanceUpdate": "No"
  },
  {
    "HolderAddress": "0x0017bf3bca94a016a27d496363cec4d868758bb7",
    "Balance": 650,
    "PendingBalanceUpdate": "No"
  }
]

Can this data be passed at the deployment of the contract and how would i link the contract to read the json file?
Many thanks


texts:
When I compile the below code in 0.6.6 it doesn't compile (requires public) but in 0.7.3 it does compile.
If I make the below code compilable (adding public) in 0.6.6 I can successfully deploy on Rinkeby.  If I compile the below code in 0.7.3 I can successfully deploy on Rinkeby.  This would suggest that there are no changes to Rinkeby EVM, only the way compiler versions enforce Bytecode arrangement has changed?
Does this imply I could use 0.6.6 compiler standards for many more years down the road and my code won't break?  The numerous compiler iterations is a new experience for me and I'm trying to wrap my head around it.
Thank you
contract A { constructor () payable {} }


texts: User Management in private ethereum block chain app

texts:
I am doing a POC block chain application, not a crypto currency once.

I saw many examples determining user by using msg.sender attribute, my question is can we manage users in block chain app like we do in regular applications?

Or

Do all users need to have an EOA type account ?


texts: Can i use geth for other purposes than mining

texts:
As you can understand from question, Iam totally new to crypto currencies. I have a node running on amazon linux ec2 instance.

I do NOT want to use it for mining. I want to create and manage accounts and do transactions with them.

I want to interact from browser rather than command line. Is that possible with geth Or did I pick the wrong application? If not geth please suggest another OR combination of others.
Also how much will it take to start geth completely so that I can run commands. I start node by following command

  go-ethereum/build/bin/geth --rpc --rpccorsdomain "*"

I usually end up doing Ctrl+C Is that okay?

Please help.


texts: How to connect Ethereum Wallet to geth node?

texts:
Disclosure: I am a complete noob to the cryptocurrency world and just started to try stuff since last night. My aim is to have an ethereum wallet to which I can transfer ETH from coinbase.

I have tried to download ethereum wallet .dmg file from GitHub release several times but the sync not progress after it reaches beyond a certain number of blocks. From reading stuff online, I understand that there is a fast option to sync. So I deleted the ethereum application and installer, installed geth using homebrew and then ran the following:

geth --fast --cache=2048

After a while I see this which keeps on adding a new block every couple of seconds.

From the Wiki, I realize that this is "Normal Sync In Progress" that happens after "full sync transitioning to incremental single block updates".

My first question is: The above sync looks like a continuous process that is never going to stop since a new block will be created somewhere every couple of seconds. So should I just kill the process with ctrl+c? Why or why not?

Second question: The whole reason I did all of the above was to basically be able to use an ethereum wallet which was having trouble syncing out of the box via installer. Now that I have the synced blocks, How do I install a wallet and make it use these blocks instead of starting a new sync?

Thanks for your patience. Really appreciate your help.


texts: Can we write whole documents in ethereum blockchain?

texts:
How write a whole documents in ethereum blockchain?

Suppose i have a text file halo.txt in my system. How to write it in ethereum blockchain and how to retrieve it?

I have gone through IPFS example but it is only returning hash value, I need to return full text.


texts: Problem with invoking a function with byte32 parameter : "Given parameter is not bytes"?

texts:
We have a function as follows:

function newObject(bytes32 _id, uint256 number_of_sub_states, bytes32[10] sub_states_types, bytes32[10] sub_states_values, address _owner) public returns(bool success) {
        require(!isObject(_id));

        uint256 counter=0;
        for(counter; counter < number_of_sub_states; counter++) {

            objectStructs[_id].state.sub_state[sub_states_types[counter]] = sub_states_values[counter];

            emit LogNewObject(msg.sender, _id, bytes32(sub_states_types[counter]), bytes32(sub_states_values[counter]), _owner);

        }

        objectStructs[_id].owner = _owner;
        objectStructs[_id].isObject = true;

        objectList.push(_id);

        return true;
    }

I can invoke this function in remix successfully as folloaws :

40,3,["location","price","sold","","","","","","",""],["Paris","50","No","","","","","","",""], 0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773

But when I invoke this function with web3 as follows :

contractInstance.methods.newObject("40","3",["location","price","sold","","","","","","",""],["Paris","50","No","","","","","","",""], '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773').send({ from: '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773' }, function(error, result) {
    console.log(error);
    console.log(result)
});

I receive following error :

Error: Given parameter is not bytes: "40"
    at SolidityTypeBytes.formatInputBytes [as _inputFormatter] (/home/s/node_modules/web3-eth-abi/src/formatters.js:56:15)
    at SolidityTypeBytes.SolidityType.encode (/home/s/node_modules/web3-eth-abi/src/type.js:188:17)
    at /home/s/node_modules/web3-eth-abi/src/index.js:255:29
    at Array.map (<anonymous>)
    at ABICoder.encodeParameters (/home/s/node_modules/web3-eth-abi/src/index.js:254:34)
    at /home/s/node_modules/web3-eth-contract/src/index.js:420:24
    at Array.map (<anonymous>)
    at Object._encodeMethodABI (/home/s/node_modules/web3-eth-contract/src/index.js:419:12)
    at Object._processExecuteArguments (/home/s/node_modules/web3-eth-contract/src/index.js:735:39)
    at Object._executeMethod (/home/s/node_modules/web3-eth-contract/src/index.js:760:54)
>

Also, I tried following according to comment of user goodvibration :

> contractInstance.methods.newObject(0x28,0x3,["location","price","sold","","","","","","",""],["Paris","50","No","","","","","","",""], '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773').send({ from: '0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773' }, function(error, result) {
...     console.log(error);
...     console.log(result)
... });
Error: Given parameter is not bytes: "40"
    at SolidityTypeBytes.formatInputBytes [as _inputFormatter] (/home/s/node_modules/web3-eth-abi/src/formatters.js:56:15)
    at SolidityTypeBytes.SolidityType.encode (/home/s/node_modules/web3-eth-abi/src/type.js:188:17)
    at /home/s/node_modules/web3-eth-abi/src/index.js:255:29
    at Array.map (<anonymous>)
    at ABICoder.encodeParameters (/home/s/node_modules/web3-eth-abi/src/index.js:254:34)
    at /home/s/node_modules/web3-eth-contract/src/index.js:420:24
    at Array.map (<anonymous>)
    at Object._encodeMethodABI (/home/s/node_modules/web3-eth-contract/src/index.js:419:12)
    at Object._processExecuteArguments (/home/s/node_modules/web3-eth-contract/src/index.js:735:39)
    at Object._executeMethod (/home/s/node_modules/web3-eth-contract/src/index.js:760:54)

However, I receive same error.

What is the reason ? and how can I fix this ?


texts: why .call() in Truffle did not return results as expected?

texts:
I'm deploying a contract to my private chain and try to call the contract's function.

After I got in the geth console and finished deploy contract, I called the  function but it doesn't work correctly.

pragma solidity ^0.5.6;

contract SimpleBank {
 uint256 storedData;
 function set(uint256 data) public{
  storedData = data;
 }
function get() public view returns (uint256){
    return storedData;
  }
}

// I tried to call contract’s function like this in the geth console:

  storage.set.sendTransaction(42,{from:eth.accounts[0],gas:10000000})

// After mining like this:

  miner.start(1);admin.sleepBlocks(1);miner.stop();

// I called the get() function:

  storage.get.call()

It should return storedData’s value 42
But it returns 0

And I tried to use other available contract on the web:

pragma solidity 0.5.1;

contract MyContract {
enum State { Waiting, Ready, Active }
State public state;

constructor() public {
    state = State.Waiting;
}

function activate() public {
    state = State.Active;
}

function isActive() public view returns(bool) {
    return state == State.Active;
}
}

// I called activate() first :

  storage.activate.call()

//And I called isActivete():

  storage.isActivate.call()

It should return true, but it return false

if the function’s return type is uint256, it always returns 0
And when the return type is Boolean, it always returns false

It seems like function do not actually work so it returns the default value


texts: Newbie error: I am trying to deploy my first contract and get an error with the first function

texts:
When I try and complie the following code:

pragma solidity ^0.4.18;

contract mortal{

    address owner;

    function mortal(){

        owner = msg.sender;
    }

    modifier onlyOwner{

        if (msg.sender != owner){
            throw;
        }
    }

    function kill() onlyOwner{

        suicide(owner);
    }
}

I get the warning:

  No visibility specified. Defaulting to "public".  function mortal(){

  ^ Spanning multiple lines.

I am sure this is a very basic newbie error but I would appreciate your help!

Thanks,

Phil


texts: Deleting index of an array in terms of optimization for looping

texts:
I have a dapp where an admin can upload a number of cakes (20 to 30). People can come into the site and decide whether they want to buy a cake uploaded by admin.

So for smart contract, I made an array of uint to store each id of Cake whenever admin uploads. Once the buyer bought one of the cakes, it would delete that id of Cake in the array. I decided to delete it to avoid loops as much as possible since it would cause out of gas while I iterate the array to return the remaining list of cakes to buyers. How does it sound in terms of optimization?

Below is my implementation. Are there any better solutions or is this enough to continue?

struct Cake {
    uint id;
    address buyer;
}

mapping (uint => Cake) public cakes;
uint[] public cakeIds;

function addNewCake(uint _id) public {
    cakes[_id] = Cake(_id, 0x0);

    cakeIds.push(_id);
}

function buyCake(uint _id) public {
    Cake storage cake = cakes[_id];
    cake.buyer = msg.sender;

    removeCakeInArray(_id);
}

function removeCakeInArray(uint _id) private {
    for (uint i = 0; i <= getNumOfCakes(); i++) {
        if (cakeIds[i] == _id) {
            remove(i);
        }
    }
}

function remove(uint index) private {
    if (index >= getNumOfCakes()) return;

    for (uint i = index; i < getNumOfCakes() - 1; i++){
        cakeIds[i] = cakeIds[i+1];
    }
    cakeIds.length--;
}

function getAllUnsoldCakes() public view returns (uint[]) {
    uint length = getNumOfCakes();
    uint[] memory ids = new uint[](length);

    for (uint i = 0; i < length; i++) {
        uint cakeId = cakeIds[i];
        Cake memory cake = cakes[cakeId];

        if (cake.buyer == 0x0) {
            ids[i] = cake.id;
        }
    }

    return ids;
}

function getNumOfCakes() public view returns (uint) {
    return cakeIds.length;
}


texts: How to go about user login in an Ethereum web DApp?

texts: The approach I'm currently using in my DApp is mapping Ethereum addresses to a solidity struct which contains all of that specific user's data. But since the address is publicly available can't someone just use that user's address and by manipulating their keystore file or some other way send messages to the contract with other user's Ethereum address? If yes, then what can be done to prevent this and what other login/authentication methods are there? If no then I guess I have some wrong ideas about how contracts are signed(?), so please direct me where I can find out more in depth information about this.


texts: How TokenCreator/OwnedToken example from Solidity documentation works

texts:
In this post (Understanding TokenCreator/OwnedToken example from Solidity documentation) the detailed response was given, but I still have a question about "how it works".
contract OwnedToken {
    // TokenCreator is a contract type that is defined below.
    // It is fine to reference it as long as it is not used
    // to create a new contract.
    TokenCreator public creator;
    address public owner;
    string public name;

    // This is the constructor which registers the
    // creator and the assigned name.
    function OwnedToken(string _name) {
        owner = msg.sender;
        // We do an explicit type conversion from `address`
        // to `TokenCreator` and assume that the type of
        // the calling contract is TokenCreator, there is
        // no real way to check that.
        creator = TokenCreator(msg.sender);
        name = _name;
    }

    function changeName(string newName) {
        // Only the creator can alter the name --
        // the comparison is possible since contracts
        // are implicitly convertible to addresses.
        if (msg.sender == address(creator))
            name = newName;
    }

    function transfer(address newOwner) {
        // Only the current owner can transfer the token.
        if (msg.sender != owner)
            return;
        // We also want to ask the creator if the transfer
        // is fine. Note that this calls a function of the
        // contract defined below. If the call fails (e.g.
        // due to out-of-gas), the execution here stops
        // immediately.
        if (creator.isTokenTransferOK(owner, newOwner))
            owner = newOwner;
    }
}

contract TokenCreator {

    mapping(string => address) addresses;

    function getAddress(string name) constant returns (address) {
        return addresses[name];
    }

    function createToken(string name)
       returns (OwnedToken tokenAddress)
    {
        // Create a new Token contract and return its address.
        // From the JavaScript side, the return type is simply
        // "address", as this is the closest type available in
        // the ABI.
        tokenAddress = new OwnedToken(name);
        addresses[name] = tokenAddress;
    }

    function changeName(string oldName, string newName) {
        // Again, the external type of "tokenAddress" is
        // simply "address".
        address tokenAddress = addresses[oldName];
        delete addresses[oldName];
        addresses[newName] = tokenAddress;
        OwnedToken(tokenAddress).changeName(newName);
    }

    function isTokenTransferOK(
        address currentOwner,
        address newOwner
    ) returns (bool ok) {
        // Check some arbitrary condition.
        address tokenAddress = msg.sender;
        return (sha3(newOwner) & 0xff) == (bytes20(tokenAddress) & 0xff);
    }
}

I didn't get when "function OwnedToken(string _name)" is called? As far as I understand When we call "new OwnedToken(name);" - "this does not execute a constructor" (c) as it's said in official documentation. As I assume it only creates an instance of "OwnedToken" contract and SOMEHOW (how it works, tho?) deploys it to SOME (where this address is located at?) address;


texts: Difference between Main Account and Account 1

texts:
Is there a Difference between "Main Account" and "Account 1", because I lost my password for the Main Account, which has no Eth on it? Do I need the password for the main account in any way (technical or maybe in the future for updates etc)?
Thx.


texts: Getting and storing address of erc20 contract after dynamically creating it

texts:
I have a function which dynamically creates an ERC20 contract on calling a function in another contract as follows:

function createDao(string _tokenName) public payable {

  tokenNumberIndex = safeAdd(tokenNumberIndex, 1);

  string memory _tokenSymbol =
         bytes32ToString(uintToBytes(tokenNumberIndex));

  address _tokenAddress =
       (new REP).value(msg.value)(_tokenSymbol, _tokenName);

  erc20SymbolAddresses[_tokenSymbol] = _tokenAddress;

  proposalIndex = safeAdd(proposalIndex, 1);

  emit NewProposalCreated(proposalIndex);

  newProposalInternal(
    proposalIndex,
    _tokenSymbol,
    _tokenName,
    _tokenName,
    msg.sender,
    msg.value);
}

I am confident that the following code is executing correctly:

address _tokenAddress =
   (new REP).value(msg.value)(_tokenSymbol, _tokenName);
erc20SymbolAddresses[_tokenSymbol] = _tokenAddress;

However, erc20SymbolAddresses gives 0 address for all possible token symbols. How long does creation of rep take? How would I know if the creation fails?

REP Contract code is as follwing:

contract REP is ERC20Interface, SafeMath {
string public symbol;
string public  name;
uint8 public decimals;
uint public _totalSupply;

mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;

constructor(string _tokenSymbol, string _name) public payable{
    symbol = _tokenSymbol;
    name = _name;
    decimals = 18;
    _totalSupply = msg.value;
    balances[msg.sender] = _totalSupply;
    emit Transfer(address(0), msg.sender, _totalSupply);
}
 ..........
 ..........
}

What am I missing here?


texts: How to Check & Get Balance of ANY Ethereum address

texts:
I already know how to retrieve the ether balance of MY account with the below command.

web3.eth.getBalance(MY_ADDRESS).

But, I can't seem to find a way to retrieve the ether balance of ANY account.

Does anyone know how to retrieve the balance of any account?

Any references or help will be thankful.


texts: Smart contract with infinity loop fetching DEX prices

texts:
I am trying to create an arbitrage bot which swaps between 2 decentralised exchanges. Lots of tutorials say that I need a Javascript or Python program that continuously runs and fetches prices from different DEXes and if it finds an arbitrage opportunity it calls a smart contract which does the actual swap.
But I wondered if it's possible to deploy a smart contract which runs an infinity loop like a while(true) which fetches prices from different DEXes and when it finds an opportunity it can instantly swap the tokens on the 2 exchanges.
I thought of this because the arbitrage opportunities only last for a few moments and while I am calling my smart contract the opportunity could be gone already.


texts:
For reasons I can't figure out why open-zeppelin's IncreasingPriceCrowdsale and TimedCrowdsale seem to be conflicting with each other.  Here is a basic version of the Crowdsale contract I'm working with:

contract MyCrowdsale is Crowdsale, MintedCrowdsale, TimedCrowdsale, FinalizableCrowdsale, IncreasingPriceCrowdsale{

    Crowdsale(_rate_initial, _wallet, _mintableToken)
    TimedCrowdsale(_openingTime, _closingTime)
    IncreasingPriceCrowdsale(_rate_initial, _rate_final)

When IncreasingPriceCrowdsale isn't there everything works fine.  However when IncreasingPriceCrowdsale and TimedCrowdsale are there I get an error being thrown in the constructor in TimedCrowdsale.sol that require(openingTime >= block.timestamp).

constructor(uint256 openingTime, uint256 closingTime) internal {
    // solium-disable-next-line security/no-block-members
    require(openingTime >= block.timestamp);

I'm initializing openingTime  to web3.eth.getBlock('latest').timestamp + 20 which works fine when IncreasingPriceCrowdsale isn't there.

Any ideas how to fix this?


texts: What happens when you use multiple "call" arguments?

texts:
I have a piece of code like so:

address x=0x01234..;
x.call(data1, data2, data3);

Will this do what I expect and call the contract at address x while passing the data in concatenated like data1+data2+data3 (and bare, without any solidity ABI formatting)? I can't find any documentation about this.


texts: Uniswap ETH to Tokens to ETH swap function

texts:
UniswapV2Router02.sol has 2 interesting functions which i'd love to combine swapExactETHForTokens and swapExactTokensForETH. Basic idea is arbitrage from ETH to tokens and back to ETH.
As far I understand swapExactETHForTokens deposits ETH and performs swaps and swapExactTokensForETH performs swaps and withdraws ETH. Is it possible to implement my idea by simply adding withdrawal code to the end of swapExactETHForTokens?
function swapExactETHForTokensForETH(uint amountOutMin, address[] calldata path, address to, uint deadline)
    external
    virtual
    override
    payable
    ensure(deadline)
    returns (uint[] memory amounts)
{
    require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
    amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
    require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
    IWETH(WETH).deposit{value: amounts[0]}();
    assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
    _swap(amounts, path, to);

    // Adding code from swapExactETHForTokens here
    IWETH(WETH).withdraw(amounts[amounts.length - 1]);
    TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}


texts: How do miners claim gas from an invalid transaction?

texts:
Suppose a transaction T changes the state from S to an invalid state S'. For example, say, it ran an long loop of no operations (no_op), and attempted a double spend. Since this T transforms the state to an invalid state S', the transaction should not make it into the blockchain. How does a miner claim gas for the computation power they invested in running the transaction, if they cannot show everyone else the transaction they wasted time on ?

I'm assuming gas economics in Ethereum are similar to transaction fees in Bitcoin. Is my understanding right ?


texts: Local node doesn't see that many transactions?

texts: Just to be clear, this is for binance smart chain not eth chain.  I'm running a local BSC node and I have a filter for pending transactions and this was working well as of a couple days ago, but for some unexplainable reason the amount of transactions totally plummeted.  It's seeing ~1/10th of what it used to.  When I revert to using a public node, I see roughly the amount of transactions that I used to.  I have ~100+ peers so I have no clue what could have changed.  Any ideas?


texts: How to run your own bootstrap node in Ethereum?

texts:
How do I run my own bootstrap node? I mean how do I make my geth only provide peers information not the blockchain. And also how does geth know whether a node is a bootstrap node or regular node? Becz without knowing the difference geth will start requesting the blockchain to the bootstrap node.

The command line option bootnodes let's us add bootstrap nodes and the JavaScript addPeermethod let's us add regular nodes. So if I add a regular node using bootnodes than won't my geth instance request the blockchain from the bootnode?


texts: Executing estimateGas() return meta mask error?

texts:
Running the following line of code to get the Estimated Gas, returns some errors more here

Solidity

function deposit() public payable {
    store.deposit();
}

JS

const deposit = await contract.methods.deposit()
const gas = await deposit.estimateGas({from: myAddress, value: value})

Here you can see someone had similar issue by incorrectly passing arguments, this is not true in my case sense I don't pass anything


texts: Casper Friendly Finality Gadget - Greater degrees of transaction/settlement finality over existing PoW?

texts: With Casper Friendly Finality Gadget, can one expect greater degrees of transaction/settlement finality over existing PoW?


texts: Possible to do bitwise operator on byte array (bytes)?

texts:
Or do only bitfields like bytes32 support the xor function (a ^ b)?

Related, Why can't we do bitwise operations on Bools?


texts: On OpenSea, if buyer makes an offer and seller accepts, does the sale go through?

texts: On OpenSea, if a listing has an offer, will that sale automatically go through (the buyer is charged) once the seller accepts? Or does the buyer at that point have a chance to decline?


texts: What will happen to GETH node once Ethereum 2.0 releases?

texts:
I have a full GETH node running and looks like Ethereum 2.0 is about to release. My question is:

Will I need to do tweak anything in my node once Ethereum 2.0 releases?
Will my GETH full node be able to use Mainnet for transactions in Ethereum 2.0?


texts: Error: Invalid number of arguments to Solidity function - I'm pretty sure the number of arguments is correct?

texts:
General problem:
Using double linked list. Because of block gas limits, I call a function off-chain to find the exact insertion point.

https://github.com/genesisdotre/ethereum-auction
Branch: no-limit

Code:
function bid(uint insertionBidId) public payable {
    emit LogText("derived class (multiple)");
    ...
}

https://github.com/genesisdotre/ethereum-auction/blob/no-limit/contracts/AuctionMultiple.sol#L64
Tests:
var insertionPoint = await auction.searchInsertionPoint.call(2.6e18, tailBidId, { from: bidderE });
console.log(insertionPoint);
var tx = await auction.bid(insertionPoint, { value: 1e18, from: bidderE });

https://github.com/genesisdotre/ethereum-auction/blob/no-limit/test/AuctionMultiple.js#L472

Error: Invalid number of arguments to Solidity function

I have no idea what is wrong.
This runs till the end
var tx = await auction.bid({ value: 1e18, from: bidderE });
(using bid function from the base class that does not require parameter)


texts:
I am busy with a project. So I have an array of a struct within another struct. In this case for example array of CattleHealth in Cattle. In my RecordHealth function, I am taking the address of the Cattle struct and adding the current length of its current list to create a unique address. Is this a correct way to do it?

  contract WagyuRecordContract
    {
        address owner;

        struct Cattle
        {
            address RFID;
            string Name;
            uint256 Weight;
            string Gender;
            string Colour;
            string Breed;
            uint Age;
            uint DOB;
            string Location;
            bool Parent;
            string SireName;
            string DamName;
            bool Active;
            bool ForSale;
            CattleHealth[] HealthRecord;
            CattleGrowth[] GrowthRecord;
            CattleMovements[] MovementsRecord;
            Facility SlaughterDetails;
            Meat[] DistributionDetails
        }

        struct CattleGrowth
        {
            uint DateRecorded;
            uint256 FoodIntake;
            uint256 Growth;
        }

        mapping (address => Cattle) public cattle;
        mapping (address=> CattleGrowth) public growth;

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

        function RecordHealth(address rfid, string _bodyCond, string _healthStat, uint256, string _med) Owner public
        {
            health[rfid+cattle[rfid].HealthRecord.length].DateRecorded = now;
            health[rfid+cattle[rfid].HealthRecord.length].BodyCondition = _bodyCond;
            health[rfid+cattle[rfid].HealthRecord.length].HealthStatus = _healthStat;
            health[rfid+cattle[rfid].HealthRecord.length].Medication = _med;
            cattle[rfid].HealthRecord.push(health[rfid+cattle[rfid].HealthRecord.length]);
        }
}

Edit:
My Buddy used this method below without using a mapping. I don't understand how this works. What is the -1 for? How is it unique to the cattle?

   function RecordHealth(address rfid, string _bodyCond, string _healthStat, string _med) Owner public
    {
       cattle[rfid].HealthRecord.push(now, _bodyCond, _healthStat, _med)-1;
    }


texts: EtherScan API get erc20 token balance at specific block?

texts:
I am trying to find a way to get the balance of erc20 token of any specific address at given block.
So far i succeeded in getting current balance but couldn't find a way to get it from the specific block using EtherScan API, is there a way?

I am using this to get current balance of specific ERC20 token,

https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=0x57d90b64a1a57749b0f932f1a3395792e12e7055&address=0xe04f27eb70e025b78871a2ad7eabe85e61212761&tag=latest&apikey=YourApiKeyToken


texts: Passing command-line arguments to 'truffle test'

texts:
I have a JS script which I pass to truffle test from command line:

truffle test my_script.js

I would like this script to take an input argument (retrieved via process.argv[2]).

Does `truffle support this in some way?

I tried truffle test my_script.js 0 and received the following error from truffle:

TypeError: file.match is not a function
    at C:\Users\...\cli.bundled.js:319282:21
    at Array.filter (<anonymous>)
    at C:\Users\...\cli.bundled.js:319281:21
    at getFiles (C:\Users\...\cli.bundled.js:319274:16)
    at Object.run (C:\Users\...\cli.bundled.js:319280:5)
    at Command.run (C:\Users\...\cli.bundled.js:160766:20)
    at Object.<anonymous> (C:\Users\...\cli.bundled.js:318404:9)
    at __webpack_require__ (C:\Users\...\cli.bundled.js:22:30)
    at C:\Users\...\cli.bundled.js:68:18
    at Object.<anonymous> (C:\Users\...\cli.bundled.js:71:10)

I tried truffle "test my_script.js 0" and received the following error from ganache-cli:

TypeError: Cannot read property 'toJSON' of null
    at C:\Users\...\cli.node.js:90686:25
    at C:\Users\...\cli.node.js:21771:5
    at C:\Users\...\cli.node.js:88595:7
    at C:\Users\...\cli.node.js:7542:16
    at C:\Users\...\cli.node.js:7759:32
    at C:\Users\...\cli.node.js:7534:16
    at C:\Users\...\cli.node.js:88590:9
    at Object.decode (C:\Users\...\cli.node.js:49614:5)
    at C:\Users\...\cli.node.js:88587:20
    at C:\Users\...\cli.node.js:7671:20

I tried truffle test "my_script.js 0" but then the test doesn't seem to be doing anything:

0 passing (0ms)

Thank you!!!


texts: What causes .deployed() to return same contract instances in each test

texts:
It took me awhile to diagnose the problem. At first I just noticed that the states of my contracts were being affected by previous tests when running truffle test I then looked in the terminal tab in which I was running geth for my private network. I looked through the transactions and contract deployments and noticed that every time another test file begins execution all of my contracts are deployed again as expected. Then I realised that even after this all the transactions coming through from the tests were interacting with the first deployed contracts from the first test. All the contract instances returned by .deployed() in the second through last tests were referring to the contracts originally deployed in the in the first test. Below is a more simplified version of what I would see in the tab where I was running my geth node.

//executing test/first.js
Submitted contract creation fullhash=0xTransactionHash0 contract=0xContractAddress0
Submitted contract creation fullhash=0xTransactionHash1 contract=0xContractAddress1
Submitted transaction fullhash=0xTransactionHash2 recipient=0xContractAddress1
//executing test/second.js
Submitted contract creation fullhash=0xTransactionHash3 contract=0xContractAddress2
Submitted contract creation fullhash=0xTransactionHash4 contract=0xContractAddress3
Submitted transaction fullhash=0xTransactionHash5 recipient=0xContractAddress1

geth version => 1.9.12-stable

truffle version =>
Truffle v5.1.20 (core: 5.1.20)
Solidity v0.5.16 (solc-js)
Node v8.10.0
Web3.js v1.2.1

Here is my startnode.sh file

geth --networkid 122349 --mine --minerthreads 2 --datadir "." --nodiscover --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal,net,debug --unlock 0 --password ./password.sec --ipcpath "~/.ethereum/geth.ipc" --allow-insecure-unlock --targetgaslimit '9000000'

I don't have this problem when I use ganache-cli this seems to be specific to geth. If any of you have any ideas as to what the cause of this error could be or and suggestions as to how I could potentially fix this I really apreciate them. Thank you all!


texts: In a private blockchain network, can we delete the first N blocks and reassign the N+1th block as the genesis block?

texts:
I am aware of the data loss caused by deleting the first N blocks. But I am curious to know whether such a task is possible or not. If so, how to practically implement it?

( I am using go-ethereum. If it is not possible in go-ethereum, I would like to know whether it is possible in other blockchain-based projects like bitcoin. )


texts: Can I verify my Smart Contract on Etherscan but still hide the coding to prevent others from cloning the smart contract?


texts: running cpp-ethereum nodes for local development

texts:
I cant seem to find how to start my local only private node just for development purposes.
like I want to run my node and i want to have a list of addresses with balance test eth on my local machine just for the purpose of development.
Please dont suggest to use geth as I am development on a fork of cpp-ethereum/aleth.
But i dont have an idea where to get the initial funds and put it on an account so i can use that account for testing.


texts: Function 'sendTransaction' - can any error occur before the 'transactionHash' event?

texts:
Function web3.eth.sendTransaction can throw an error.

For example:

Transaction gas is too low
Transaction execution error

But can it possibly throw an error before emitting the transactionHash event?

I am pretty sure that the two errors above cannot possibly occur at this point.

Am I right?

What about other errors?

For example, what if there's a network problem, or an Ethereum-client problem?

Here is a coding example (taken directly from the docs), with the question embedded:

web3.eth.sendTransaction({
    from: '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe',
    to: '0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe',
    value: '1000000000000000'
})
.on('transactionHash', function(hash){
    // Can it possibly throw an error before reaching here?
})
.on('receipt', function(receipt){
    ...
})
.on('confirmation', function(confirmationNumber, receipt){ ... })
.on('error', console.error); // If a out of gas error, the second parameter is the receipt.

Thank you!


texts: What solutions are proposed to Long Range Attack?

texts: Long Range Attack (explained here) is one of attacks against Proof of Stake. What kind of solutions are proposed to it?


texts: DeclarationError: Undeclared identifier while it's declared

texts:
I get "DeclarationError: Undeclared identifier" on _totalSuppy and _balances. Could anyone help me figure this out?
Parent contract
pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping (address => uint256) private _balances;
    mapping (address => mapping (address => uint256)) private _allowances;
    uint256 private _totalSupply;
    string private _name;
    string private _symbol;

    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }
}

Child contract
pragma solidity ^0.8.0;

import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';

contract METoken is ERC20 {
    string public constant name = 'Mastering Ethereum Token';
    string public constant symbol = 'MET';
    uint8 public constant decimals = 2;
    uint constant _initial_supply = 2100000000;

    function METoken_settings() public {
        _totalSupply = _initial_supply;
        _balances[msg.sender] = _initial_supply;
        emit Transfer(address(0), msg.sender, _initial_supply);
    }
}


texts: Unknown account error when initiating transactions from remote node

texts: I am using Ropsten network and trying to transfer ether from my metamask account to my another account using geth client. I am using the methods like eth.signTransaction, eth.sendTransaction in CLI, it returns unknown account error. Whether the initiating account should be available in the node or not ?


texts: Why is that the 'blocks count' is always in multiples of 192?

texts:
I'm running light node client for rinkeby using command:

geth --rinkeby --syncmode=light --rpc --rpcapi personal,db,net,eth,web3

The terminal runs continuously and I don't quit it when I close the laptop monitor. When the laptop is hibernated (monitor is closed), the node stops syncing. And when I resume the laptop (re-open the monitor), the node starts syncing.

While importing the 'new block headers', the 'blocks count' is always in multiples of 192 (Example: count=192 | count=1344 | count=576), until full import is done.

Why in multiples of 192? Why not 50 or 100?

Log trace:

INFO [06-03|01:29:38] Imported new block headers               count=1   elapsed=75.603ms  number=2393660 hash=12f7ae…f39bd4 ignored=0
INFO [06-03|01:29:38] Imported new block headers               count=0   elapsed=129.563µs number=2393660 hash=12f7ae…f39bd4 ignored=1
INFO [06-03|13:35:03] Imported new block headers               count=192 elapsed=330.559ms number=2393852 hash=609755…460a4e ignored=0
INFO [06-03|13:35:04] Imported new block headers               count=192 elapsed=462.307ms number=2394044 hash=320d10…133b2e ignored=0
INFO [06-03|13:35:05] Imported new block headers               count=192 elapsed=771.555ms number=2394236 hash=f0e2f4…32160b ignored=0
INFO [06-03|13:35:08] Imported new block headers               count=192 elapsed=2.406s    number=2394428 hash=8df410…bff82b ignored=0
INFO [06-03|13:35:09] Imported new block headers               count=192 elapsed=1.123s    number=2394620 hash=3b472e…304d40 ignored=0
INFO [06-03|13:35:11] Imported new block headers               count=1344 elapsed=1.589s    number=2395964 hash=f11335…bdb486 ignored=0
INFO [06-03|13:35:16] Imported new block headers               count=576  elapsed=5.749s    number=2396540 hash=83b56f…2d34b7 ignored=0
INFO [06-03|13:35:17] Imported new block headers               count=22   elapsed=88.833ms  number=2396562 hash=4a2013…e490b5 ignored=0
INFO [06-03|13:37:08] Imported new block headers               count=8    elapsed=46.601ms  number=2396570 hash=14f9a5…9bf85e ignored=0


texts: How can I accept Bitcoin payment in a smart contract? What would be the code for that?

texts:
I will create my personal token and I would like to be able to sell it for ETH and BTC. I know how to add the sell function for ETH, but how can I sell the tokens for BTC?

The ETH sell function I will use is the following:

function sell(uint256 amount) {
        if (balanceOf[msg.sender] < amount ) throw;
        balanceOf[this] += amount;
        balanceOf[msg.sender] -= amount;
        msg.sender.send(amount * sellPrice);
        Transfer(msg.sender, this, amount);
}


texts: How do I get started with Ethereum in practical terms?

texts:
I've read on the official website. I understand the "overall idea". I also think I can buy Ether, so that's also not what I'm asking.
I'm simply wondering how I actually start using it. The most official software, that is. Not an "app" for a smartphone and not a hardware device. An application for my PC, which I assume has a GUI part like Bitcoin Core.
The official website appears to only list non-desktop software, and the "fullnode" clients I've been linked to by random people all seem very... "unofficial". As in, not intended to be used by normal people.
I've spent many hours of my life simply trying to "try out" Ethereum without finding out how. It really confuses and worries me that the website's section for finding a "wallet" or "client" seems to only talk about smartapps, third-party websites and hardware devices.
Where is the desktop application? It doesn't even need to be a "fullnode", as long as it's "official-ish" the same way that Bitcoin Core is.
One problem I had with some of the Github fullnodes I found are that they seem to have a lot of weird software dependencies. I'd strongly prefer if it's "stand-alone" like Bitcoin Core.


texts: Dealing with events from other contracts

texts:
I have 2 contracts. One contract is the one which I'm interacting directly with.

The event I want to listen is not triggered by the main contract, but the one it is called internally.

In the following example, if I invoke "testing" method, how can I listen for "MyEvent" triggered by the other contract?

contract OtherContract {

event MyEvent(uint8);
function doSomething() {
         MyEvent(1);
    }
}

contract Test {

    OtherContract constant otherContract  = OtherContract(0x0b258ee7bf483bb49a5956407702ca5b08197b4c);

    function testing() {
         otherContract.doSomething();
    }
}


texts: Link between Logarithmic market scoring rule and Automated market makers

texts:
In most articles I read about AMMs, there is a link or a mention to Hanson's work about the Logarithmic scoring rule. But I don't clearly see the link between AMM's and the LMSR. Can someone help me ? Like, on Uniswap are used some constant product function, and in some articles (see below) are links to LMSR (Hanson, 2002). Thank you
Here are some articles talking about constant functions market makers : https://arxiv.org/pdf/2003.10001.pdf
You can see than there is a reference to Hanson's work in the intro.
here is the article about Hanson's Work:
http://mason.gmu.edu/~rhanson/mktscore.pdf


texts:
I'm using Atom, with solidity linther package.

my local solc version is 4.15

In Atom, I cannot use anything higher than 0.4.4:

  Error Solidity    Source file requires different compiler version (current compiler is 0.4.4+commit.4633f3de.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version

Is there a way to force it to upgrade?


texts: Should I run mining on Private Test Network?

texts:
I strongly believed that pending transactions can not be approved and included into a block without mining, isn't it? But now, I'm into confusion about this. One of my customers said that there should not be any mining processes on a private test network.

So, for example, if I preallocate Ether in Genesis block and run the network without mining, will I be able to send transactions, create contracts?

Please, clarify that.


texts: Can a contract access the code of another contract?

texts: Using web3.js, the EVM (bytecode) of a contract can be obtained by web3.eth.getCode(addressOfContract).  Can this be performed by a contract using the address of another contract?  If so, how?  address.code isn't in Solidity.


texts: How do I deploy a contract via a contract factory in truffle?

texts: The code below does not set the simpleStorage instance's value to 55, but identical code works when the contract is not generated via a factory


texts: ERC20 approve and transferFrom from a contract

texts:
I have a contract with the following function:

function offerTokenTribute(address[] _tokenContractAddresses, uint256[] _tokenTributes) public {
  require(_tokenContractAddresses.length == _tokenTributes.length);

  Member storage member = members[msg.sender];
  member.approved = false; // should be already, but lets be safe

  for (uint8 i = 0; i < _tokenContractAddresses.length; i++) {
    ERC20 erc20 = ERC20(_tokenContractAddresses[i]);
    erc20.approve(this, _tokenTributes[i]);
    member.tokenTributeAddresses.push(_tokenContractAddresses[i]);
    member.tokenTributeAmounts.push(_tokenTributes[i]);
  }

  TokenTributeOffered(msg.sender, _tokenContractAddresses, _tokenTributes);
}

The problem is the erc20.approve function is not approving on behalf of the original msg.sender, it is changing msg.sender to the contract address (I verified this by checking allowances).

Is there any way to do this from my contract, or is the only solution to call the approval outside of my contract (non-ideal)?


texts: Unsure why my 0x transaction failed (more details inside)

texts:
I've written a simple contract tries to swap a few 0x pairs, for doing simple arbs or other 3 way trades.
However, when I get the quotes from their API https://0x.org/docs/api (in serial, which takes about 3-4 seconds), by the time I send the transaction to the chain it reverts.
Here's the transaction:
https://ethtx.info/mainnet/0x0c615e69766bfae68ea8afcb8d48b6456ba5fb09822abcf1e9326b52e112c22d
Can anyone help me figure out WHY this reverts? I'm assuming its because perhaps someone has already taken the trade? I can see where it reverts but I'm not 100% sure how to determine why it reverted here in the transferFrom function when executing the trade.
Thanks!


texts: Contract inheritance? Need some help to understand certain things

texts:
I'm using testrpc, and truffle. I created a simple token as seen in many tutorials which shall be used to buy or enable certain actions when clicking a button on an UI.

contract MyToken {
    mapping (address => uint) balanceOf;

    event CoinTransfer(address indexed _from, address indexed _to, uint256 _value);

    function MyToken() {
        balanceOf[msg.sender] = 21000000;
    }

    function sendCoin(address receiver, uint amount) returns(bool sufficient) {
        if (balanceOf[msg.sender] < amount) return false;
        balanceOf[msg.sender] -= amount;
        balanceOf[receiver] += amount;
        CoinTransfer(msg.sender, receiver, amount);
        return true;
    }

    function getBalance(address addr) returns(uint) {
        return balanceOf[addr];
    }
}

So far so good.

The UI has a button "buy 10 MyToken" which is working as I have implemented a function in app.js with the deployed JS object of that contract.

function buyMyToken(amount) {
  var mytoken = MyToken.deployed();

  showStatus("Initiating transaction... (please wait)");

  mytoken.sendCoin(myaccount, amount, {from: spender}).then(function() {
    showStatus("Transaction complete!");
    refreshBalance();
  }).catch(function(e) {
    console.log(e);
    showStatus("Error sending coin; see log.", true);
  });
};

Now I want to create another contract which will allow the user to buy a licence,service or enable some action for instance,when clicking another button.Which in that case shall enable a picture permanently on the UI when being bought once with that token.
So that second button should enable a gimmick permanently and the cost is for instance 5 of my own created token --> "enable gimmick (5 MyToken)"

For that contract inheritance is needed right?
Because the second contract has to check if the user has already bought some of the tokens with the first contract, which would allow him to buy some license,service or enable some action with the second contract.
So what do I need for that second contract and how can I build and use it in connection with the first contract?

Could second contract be like this or what else do I need?I know I need for instance the getBalance function from the first contract right?But how and where I put it?

contract PermService {
  address vendor;

  event ServiceTransfer(address _from, address _to, uint _amount)

  function PermService() {
  vendor = msg.sender;

  }

  function buyPermService() returns (bool success) {
  if...
  ...
  ServiceTransfer(msg.sender, receiver, amount);
  return true;
  }
}

Does that even make any sense?

Can not really find good tutorials for subcurrencies and how to use them with other contracts. I'm also a noob and not a pro coder.

And can I do simulate that with truffle console?

Help is much appreciated. Thanks in adavance.


texts: Deriving a Bitcoin Address from Ethereum Private Key

texts: There have been many answers about how to derive an Ethereum Address from a Bitcoin private key, but a curious problem has led me to ask how one would do the reverse. I'm sure it's possible because they have the same elliptic curve and key signature setup if but in a slightly different format. How would one go about generating a bitcoin address from an Ethereum private key?


texts: How can I tell from raw transaction data if it succeeded or failed?


texts: Error: Invalid JSON RPC response | ropsten.infura

texts:
I'm trying to deploy my contracts to the ropsten test network, but I get this error.

the message error :

C:\Users\acer\test>truffle migrate --reset --network ropsten
Using network 'ropsten'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0xf9d9daf3c904e239bc27fd70a51916e1dd954238215f631e7f341e1270fa55ab
Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (C:\Users\acer\test\node_modules\web3\lib\web3\errors.js:35:16)
    at XMLHttpRequest.request.onreadystatechange (C:\Users\acer\test\node_modules\web3\lib\web3\httpprovider.js:115:32)
    at XMLHttpRequest.dispatchEvent (C:\Users\acer\test\node_modules\xhr2\lib\xhr2.js:76:20)
    at XMLHttpRequest._setReadyState (C:\Users\acer\test\node_modules\xhr2\lib\xhr2.js:422:14)
    at XMLHttpRequest._onHttpRequestError (C:\Users\acer\test\node_modules\xhr2\lib\xhr2.js:669:14)
    at ClientRequest.request.on (C:\Users\acer\test\node_modules\xhr2\lib\xhr2.js:499:23)
    at ClientRequest.emit (events.js:182:13)
    at TLSSocket.socketErrorListener (_http_client.js:391:9)
    at TLSSocket.emit (events.js:182:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  Migrations: 0x116940816fb03041b4fc9018dffdef346fe0932b
Saving artifacts...
Running migration: 2_migration.js
  Replacing DinarCoin...
  ... 0x8b1ddbc08abb3561be6df6148a7a5cf9006e1e6ae520dd9e8a67713ed6af33cd
  DinarCoin: 0xeb43d979ec0d3d004c5d50c202e2cbec02edf2e1
Saving artifacts...
  Deploying DinarCrowdsale...
  ... 0x949fff0717b07829fd62f5df0fb9f21ad1ed2d4b9665704c75aab206fcf49921
Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (C:\Users\acer\test\node_modules\web3\lib\web3\errors.js:35:16)

Please How can I fix this problem ? and Thank you in advance.


texts: Smart Contract - Display / Return all the Structure Contents

texts:
I have a smart contract written, which stores a file ID alongwith its description.

struct AllFiles
 {

    string fileDesc;        //Description of a file
    uint fileId;            //Corresponding file ID
}

This is mapped to a uint value, which basically corresponds to the file ID here, as

  mapping (uint =>AllFiles) public allFiles;

I want to return all the contents of this mapping just like we return the entire structure array in OOP. Is there any way to do that in Solidity? I read it somewhere long back (can't find the resource now) that arrays can't be returned. But since this is a mapping, I wonder if it is possible.


texts: I cannot send ETH from my blockchain wallet

texts:
Yesterday i have Transaction {Dropped & Replaced)
https://etherscan.io/tx/0xfdca0e5c597f0a3f298afd5d56e939a8cefc10117df6b22d5342e1b6d5803caf
I saw it Replaced by TxHash:0x2e441fa6a1fd48119c79352275522673780f1bf920318f67c4722a311f70cae1 and Success. But til now i cannot send ETH from my blockchain wallet. It said Please wait until your previous transaction confirms.
Anyone can help me?.
Thanks


texts:
I want to use the transfer function to send value to another contract from a contract, however it fails if I set a state variable in the called contract as seen below:

contract Sender {
    function() payable {
    }

    function sendTo(address receiverAddr) {
        var receiver = Receiver(receiverAddr);
        receiver.transfer(this.balance); // This fails
    }
}

contract Receiver {
    bool public received;

    function() payable {
        received = true;
    }
}

Doing other stuff doesn't cause an error. What is the problem with setting a state variable in the fallback function?


texts: Does externally owned account have two parameters ("codehash" and "storage root")?

texts:
I often see the following figure.

That figure explains to me that every contract account has four parameters for computing the global state root.

But I can't understand what parameters the externally owned account has for calculating the global state root.

I think the user's account should have two parabeters(nonce and balances) at least.

I'm sorry that I'm not good at writing English.

Thank you for your reading effort about my question.

editing ...

I find the answer from the website "https://medium.com/@preethikasireddy/how-does-ethereum-work-anyway-22d1df506369".

That says

[The account state consists of four components, which are present regardless of the type of account:]


texts: Can successive confirmation length blockhashes be used to generate an effective random number?

texts:
I've been trying to make a random number generator that doesn't need to be outsourced like Oraclize or break down at scale like RanDAO where n deposits gives 2^n possible manipulations for the random number.

What I was thinking is that you could use the same concept that gives the blockchain value to generate a random number.

So if you take amount of block confirmations needed for a transaction to be secure and use that many blocks to create a portion of a random number (based on the blockhash), you could effectively create a random number equal to that of even odds with enough sets.

As an example, let's say it's 6 confirmations for a transaction to be secure. This means that a miner can't mine 6 blocks in succession (otherwise there would be double spend attacks and no assurance in the blockchain, right?)

For example:

6 confirmation length
Base of 2
Targeted random number range of >1000

With 6 consecutive blocks, a miner would be able to manipulate the hash of the first 5 but not the 6th, giving them a 1/2 chance of getting their desire output.

Block 1: 0 (Manipulated by Miner)
Block 2: 0 (Manipulated by Miner)
Block 3: 0 (Manipulated by Miner)
Block 4: 0 (Manipulated by Miner)
Block 5: 0 (Manipulated by Miner)
Block 6: 1/2 Chance of the Miner's desired output

So for a random number range of >1000, you would need 10 6-blockhash sets (60 total hashes) to give a miner trying to manipulate the block a 1 / (2 ^ 10) or 1/1024 chance.

What I'm trying to achieve is to have a random number in a certain range, and using the number of block confirmations considered secure to give the same or better odds to a miner trying to manipulate said number.

Is my rationale right here or am I missing something critical?

Sorry if my explanation isn't great, but here's an example in solidity I've made called the Blockchain Assured Random Number Generator (BARN Generator) where you basically have to give it the base, ending block, confirmation length, and number of sets (base^number of sets should be >= the desired random number range).

contract BARNGenerator {

    function BARNGenerator() {

    }

    function getRandomNumber(
        uint _base,
        uint _endBlock,
        uint _confirmationLength,
        uint _blockSets) returns(uint) {

        uint[] numberArray;
        uint totalBlocks = _blockSets * _confirmationLength;
        if (_endBlock - totalBlocks < block.number) {revert();}
        for (uint i; i < totalBlocks; i++) {
            numberArray.push(uint(block.blockhash(_endBlock - i)) % _base);
        }
        return convertToDecimal(numberArray, _base);
    }

    function convertToDecimal(uint[] bitArray, uint _base) returns(uint) {
        uint decimalSum = 0;
        for (uint i=0; i< bitArray.length; i++) {
            decimalSum += bitArray[i] * _base ** (i + 1);
        }
        return decimalSum;
    }

}


texts: Can a contract know at what position in a callcode an argument begins?

texts:
using for example inline assembly with calldatacopy(t, f, s), which copies s bytes from calldata at position f to memory at position t

in a call to for example function newContract(bytes data) { ... }

is it possible for a contract to know at what position in the callcode the data bytecode begins ?


texts: How to check if there is no smart-contract deployed on selected address?

texts: For example if I want to warn my user that he make mistake in contract address.


texts: Becomes a transaction part of a new block?

texts:
I volunteered to challenge functional questions for a meetup where we simulate Ethereum by the use of Post-Its. I want to stay as close to the technical reality as possible. Would you be willing to offer your expertise for checking my assumptions?

We simulate the creation of a new Smart Contract. Is it safe to say:

Some properties of the Transaction (such as its Id and Gas usage) is added to the new block.
As such it is possible to check if the Transaction was a success by passing the Transaction id to a tool like etherscan.io/txs.
Etherscan may inspect the Blockchain or trace its events to retrieve the details of the Transaction.

The posts that I found are contradicting. For instance "Can a contract view details of a TX" says "no", whereas "Need for Merkle path of a transaction" says "yes".

I am sorry if I am duplicating. I could not bring things together so I will be most happy if you could indicate if my assumption is correct.


texts: Help with Withdrawal of ETH from TheDAO Withdrawal Contract

texts:
I obviously screwed up when attempting to convert TheDAO to ETH using the DAO withdrawal contract.

I sent my DAO tokens to the withdrawal contract address http://etherscan.io/tx/0x7f5674b1ab461f99a0fae9fa00453c7cf312c2c2e02aaf7d32260162d75386b3 and they show as sent to the contract, however I cannot figure out how to withdraw ETH from that as I didn't send them in an 'approved' transaction as the instructions say to do.

Any help would be appreciated.

The problem I am having is that my DAO tokens are now at the DAO contract address and I am unable to withdraw the ETH from the contract after sending it my tokens.  I cannot go back and redo the steps to correct it or follow the tutorial on how to convert the DAO tokens to ETH using the contract because I don't have the tokens anymore.

I am unsure who to contact or how to get the tokens back.


texts: MetaMask breaking change - does ethereum.enable() prompt an Access signature every time it's called?

texts:
Does ethereum.enable() prompt an Access signature every time it's called?
Or will access-granted status persist?


texts: Adding Struct to Array - Invalid OpCode - Solidity 0.6

texts:
I've been wreaking my brain on this for a while, could use some help. Bottomline, the newProposal function throws an VM Exception while processing transaction: invalid opcode error. The puzzling thing is that this function was working fine with Solidity 0.5, but not with 0.6. Here is what I've attempted so far, any further insight is greatly appreciated.

According to the breaking changes in Solidity 0.6, I suspect that the issue is about the resizing of the proposals array to add a new Proposal struct, which is somewhat supported by this issue.

Member-access to length of arrays is now always read-only, even for storage arrays. It is no longer possible to resize storage arrays by assigning a new value to their length. Use push(), push(value) or pop() instead, or assign a full array, which will of course overwrite the existing content. The reason behind this is to prevent storage collisions of gigantic storage arrays.

So I have attempted a number of variations here (i.e., proposals.push(), hard coding proposalID). No luck. I don't believe the struct and its properties are the problem, but I can't be 100% sure of that either. So I feel like I'm missing something relatively obvious here, and I thank you for any assistance.
The function that returns an invalid opCode error
    /**
     * Add Proposal
     *
     * Propose to send `weiAmount / 1e18` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code.
     *
     * @param beneficiary who to send the ether to
     * @param weiAmount amount of ether to send, in wei
     * @param jobDescription Description of job
     * @param transactionBytecode bytecode of transaction
     */
    function newProposal(
        address beneficiary,
        uint weiAmount,
        string memory jobDescription,
        bytes memory transactionBytecode
    )
        public onlyShareholders
        returns (uint proposalID)
    {
        proposalID = proposals.length+1; //I suspect the problem is here...
        // I've tried proposals.push(); proposalID = proposals.length; instead, no luck
        Proposal storage p = proposals[proposalID]; //...or here
        p.recipient = beneficiary;
        p.amount = weiAmount;
        p.description = jobDescription;
        p.proposalHash = keccak256(abi.encodePacked(beneficiary, weiAmount, transactionBytecode));
        p.minExecutionDate = now + debatingPeriodInMinutes * 1 minutes;
        p.executed = false;
        p.proposalPassed = false;
        p.numberOfVotes = 0;
        emit ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription);
        numProposals = proposalID+1;

        return proposalID;
    }

The Proposal struct and proposals array
    Proposal[] public proposals;

    struct Proposal {
        address recipient;
        uint amount;
        string description;
        uint minExecutionDate;
        bool executed;
        bool proposalPassed;
        uint numberOfVotes;
        bytes32 proposalHash;
        Vote[] votes;
        mapping (address => bool) voted;
    }

EDIT: This fixed it, see comments below with @goodvibration
proposalID = proposals.length;
proposals.push();
Proposal storage p = proposals[proposalID];


texts: How can I convert a 24 word seed into a 12 word seed (BIP39)?

texts:
The Ethereum wallet app Blockwallet for iOS generates seed phrases with 24 words (BIP39).

Using their keytools I am able to get a private key.

How do I convert the private key into a 12 word seed phrase that works with Metamask?


texts: Connecting Ethereum private forks with the public chain

texts: What are the mechanisms involved when trying to shift content from private forks onto the public chain? e.g. if R3 did indeed fork Ethereum and they decide later to utilize the public chain, how difficult would it be on a technical level to do so?


texts: How to unlock all accounts or unlock an account forever under parity?

texts:
I want to use an account to make some transactions at the same time. So I need to unlock this account each time when I send transaction. But because it sends at the same time, it may happens that only some transactions are unlocked, the others are not...

So I think I need to unlock all accounts. Or unlock an account forever. Is there any way that I can do it?

I find that there is a config --unlock can unlock some accounts when Parity start. But my accounts are increasing. So it's not useful for me...

Can you give me some advice about it? Thanks a lot~


texts: what happen if my node synced with uncle block?

texts:
I'm not sure that this question is correct or not.
But let me explain.
As you know, two blocks may be mined at almost same time then one of the block will be uncle block.
My question is what happen if uncle block is synchronized with my node.
For example, let's assume that my node got newly mined block numbered 10,600,000.
But, there was another mined block 10,600,000 at almost same time around the world and it is finally included as main blockchain.
So.. sadly, the block synced to my node become uncle block which can't belong to main Ethereum blockchain.
My question is.. in that case, when my node will synchronize with correct block 10,600,000?
Why I ask this is because I wonder whether every latest block synced to my node is always correct main block, or "sometimes" uncle block which will be resynced to my node.
If latter is correct, in order to guarantee data correctness, should I access 5times or 10times confirmed block instead of accessing the latest block?