texts: VM error: invalid opcode error caused by a modifier

texts:
The following code allows a user(defined by userid) to subscribe to a policy (defined by policy address of the policy smart contract)

function subscribeToPolicy(address policyAddress, uint userId) public payable {
    uint policyPrice = 0.1 ether;
    require (msg.value >= policyPrice);
    userMapping[userId].mySubscriptions.push(policyAddress);
}

This piece of code works as expected (after supplying 0.1ETH and appropriate gas) and the policy is added to the user's subscription array.

I modified this code to add a modifier to prevent the addition of duplicate policies as follows

modifier policyExists(address policyAddress, uint userId) {
    for(uint j=0; j<userMapping[userId].mySubscriptions.length+1; j++){
        if (userMapping[userId].mySubscriptions[j] == policyAddress ){
            emit Log("Policy already purchased");
            revert();
        }
    }
    _;
}
function subscribeToPolicy(address policyAddress, uint userId)
policyExists(policyAddress, userId) public payable {
    uint policyPrice = 0.1 ether;
    require (msg.value >= policyPrice);
    userMapping[userId].mySubscriptions.push(policyAddress);
}

This code does not work as expected and the error returned by the VM is as follows

  transact to OasisUser.subscribeToPolicy errored: VM error: invalid opcode.
  invalid opcode

The execution might have thrown.
Any ideas for solving this error?


texts:
I want to store user's wallet address array as editor's address so i created struct with array like following

pragma solidity >=0.4.0 <0.7.0;
pragma experimental ABIEncoderV2;
contract PrivateSmartContract {

    string[] public buildingList;
 address public bildingOwner;
 address public biv;
    struct BuildingRental {
        string bagId;
        string rentHash;
        editor[] editors;
        uint updatedAt;
        bool status;
    }

    struct editor {
        address editor;
    }

   constructor() public {
    bildingOwner = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
    biv = 0x14723A09ACff6D2A60DcdF7aA4AFf308FDDC160C;
   }
    mapping(string => BuildingRental) rentalStructs;

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

     modifier onlyBIV(){
        require(msg.sender == biv);
        _;
    }

    function isBuildingRetntal(string memory _bagId) public view returns(bool) {
        return rentalStructs[_bagId].status;
    }

    function newBuildingRental(string memory _bagId, string memory _rentHash) public onlyOwner returns(bool) {
        require(!isBuildingRetntal(_bagId));
        buildingList.push(_bagId);
        rentalStructs[_bagId].bagId = _bagId;
        rentalStructs[_bagId].rentHash = _rentHash;
        rentalStructs[_bagId].updatedAt = now;
        rentalStructs[_bagId].status = false;

        return true;
    }

    function appendEditor(string memory _bagId, address  _editor) public onlyOwner returns(bool) {
        require(isBuildingRetntal(_bagId));
        rentalStructs[_bagId].editor.push(_editor);
        return true;
    }

    function editRentalHash(string memory _bagId, string memory _rentHash) public returns(bool) {
        require(isBuildingRetntal(_bagId));
        rentalStructs[_bagId].rentHash = _rentHash;
        rentalStructs[_bagId].updatedAt = now;
        rentalStructs[_bagId].status = false;
        return true;

    }

    function approveRentalHash(string memory _bagId) public onlyBIV returns(bool) {
        require(isBuildingRetntal(_bagId));
        rentalStructs[_bagId].updatedAt = now;
        rentalStructs[_bagId].status = true;
        return true;

    }

    function getRentalHash(string memory _bagId) public view returns (string memory, string memory, editor[] memory, uint, bool){

      BuildingRental memory buildingRental = rentalStructs[_bagId];

      return (buildingRental.bagId, buildingRental.rentHash, buildingRental.editors, buildingRental.updatedAt , buildingRental.status);

  }

  function getOwner() public view returns (address){
      return bildingOwner;
  }
  function getBIV() public view returns (address){
      return biv;
  }

}

but i am receiving error like following when i try to push new editor's address to building data.

private.sol:54:9: TypeError: Member "editor" not found or not visible after argument-dependent lookup in struct PrivateSmartContract.BuildingRental storage ref.
rentalStructs[_bagId].editor.push(_editor);
^--------------------------^


texts: Does Proof-of-Stake consensus require a blockchain?

texts:
In a proof-of-work blockchain, the validity of the network is ensured by the hashes of each block pointing to the previous block. A "block on its own" would not be very trustworthy and, without all the CPU-work required to mine a block, it seems like there would be no reason to have a blockchain because the entire chain could be regenerated at zero cost.

So a network that didn't rely on proof-of-work at all would see little need for a blockchain, right? They could simply have a list of transactions organized by index, timestamp or some other type of organization. I don't see what value the blockchain (array with hash and pointer to previous block) provides over a traditional "ordered list of transactions" if there is no proof-of-work.


texts:
Thinking about smart contract storage, how is the data arranged?

I know that every variable within a contract has an unique ID, therefore, it's possible to create a node with a structure like <varID, value> and organize something like:

                                    DATA_ROOT
                                        |
                    /----------------------------------------\
                   /                                          \
              H(H1 + H2)                                 H(H3 + H4)
                   |                                          |
          /-----------------\                        /-----------------\
         /                   \                      /                   \
H(<varID1, value1>)  H(<varID2, value2>)  H(<varID3, value3>)  H(<varID4, value4>)

Is the above correct?

This leads to this one more question:

Is this tree/trie full structure in the state tree under the node that identifies the contract account that owns this data?

                                 ACCOUNT 0X9127...
                                        |
                       /----------------|---------------\
                      /                 |                \
4817221  -------- BALANCE           DATA_ROOT           CODE ---------- 0xFA21E
                                        |
                    /----------------------------------------\
                   /                                          \
              H(H1 + H2)                                 H(H3 + H4)
                   |                                          |
          /-----------------\                        /-----------------\
         /                   \                      /                   \
H(<varID1, value1>)  H(<varID2, value2>)  H(<varID3, value3>)  H(<varID4, value4>)

Edit:

Summarizing my question:
Is contract storage a sub-tree of the following trie?


texts: Can't add numbers to an array on Solidity

texts:
i have a function that receive a number, autentic evaluates if it is already in an array, if it is it should return false, if it is not, return true. Then onlyOneVote will add the number to the array if true and not if false. The problem is the function never adds anything to the array.

uint32[100] public people;
uint8 public counter;

function onlyOneVote(uint32 ida) public returns(bool) {
  bool a = autentic(ida);
  if (a == true) {
    people[counter] = ida;
    counter = counter + 1;
  }
  return a;
}

function autentic(uint32 idb) public returns(bool) {
  bool b;
  for(uint i = 0; i< people.length; i++) {
    if (people[i] == idb) {
      b = false;
      break;
    } else {
      b = true;
    }
  }
  return b;
}


texts:
When I run truffle migrate --network kovan in the terminal the contract deployment doesn't run. Just:

Compiling your contracts...==================== >Eveything is up to date, there is nothing to compile

Here is my truffle-config.js code:

require('babel-polyfill');
require('dotenv').config();
const HDWalletProvider = require('truffle-hdwallet-provider-privkey');
const privateKeys = process.env.PRIVATE_KEYS || ""

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    },
    kovan: {
      provider: function(){
        return new HDWalletProvider(
          privateKeys.split(','),
          'https://kovan.infura.io/v3/${process.env.INFURA_API_KEY}'
        )
      },
      gas: 5000000,
      gasPrice: 25000000000,
      network_id: 42
    }
  },
  contracts_directory: './src/contracts/',
  contracts_build_directory: './src/abis/',
  compilers: {
    solc: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  }
}


texts: Ethereum Private network security concerns

texts:
Looking for some answers alongside resources that point out those answers
Background: I am a intern at a mortgage company and need help regarding a write up with their security concerns

Questions:

If only one Ethereum node is running how can we guarantee security of manipulation of smart contracts and data?
Can smart contracts be manipulated after they are uploaded onto the network?
Can unique account identification hashes be regenerated, and can passwords and private keys be regenerated after the initial creation of an account?


texts: My project is fully based on time. Is there any way to get current time without using NOW? NOW is just returns time when block was mined and always shows "transaction will fail" when I do require(now > 1517735968), but if I ignore it, everything works fine.


texts: Is each of metamask's account independent to each other?

texts: Say I create 3 accounts with my metamask (same seed phrase), if one account is "compromised" by a website, will it also affect the 2 other accounts if I didn't give the website any permission for the other 2?


texts: Can i access the Database Data in Etherum Smart Contract to transfer the funds?

texts:
Can anyone suggest whether the described architecture is not voilating the principle of blockchain.Let's say we have a huge data set of PolicyHolder,which has may attributes.There are so many regulators involved in the process of claim.Lets say Entity A(Authentic) has send some data to Insurance Company(which holds the data set of policyholders). Company has to validate whether the data that is coming is satisfying all the attributes of the (policy holder) if it is satisfying the amount has to transferred else reject the request.If doing all this of checking attributes in the Smart contract is very costly.So is it okay to do this in offchain and then write the Transaction in Blockchain(Ex-P234,has paid $400 to Address: 9090909090 for accident).Is there any better way to do this?

Can we use oracalize to fetch the data from Database and do the validation conditions here and write the transactions in Ethereum Blockchain?


texts: I deleted my network/key file and want to use my old enode because it is in the chain spec, etc.  Is there a way to do this or is it cryptographically impossible?


texts: Is it possible and sensible to deploy a contract to the same address on Mainnet and Ropsten?

texts:
Traditionally when people have deployed contracts for public use they have tended to publish separate contract addresses for Testnet and Mainnet. Often this then requires them to include code to check which network the contract is on, as we see in this example .

This seems to have been necessary previously because in the absence of replay protection, Morden used a very high accountStartNonce, making it impractical to create the same address on Mainnet. (See
Is it possible to give a contract the same address from morden )

Now that EIP 155 replay protection is live and Ropsten is using an accountStartNonce of 0 like Mainnet, are there any good reasons left to carry on using separate addresses for mainnet and testnet, or should we get rid of this code and just use a single address for both?


texts:
I've installed a Geth full node on a Raspberry with IP 192.168.1.109 on my local network.

When I try to connect via geth attach http://192.168.1.109:8545 it doesn't connect with the following error:

Fatal: Failed to start the JavaScript console: api modules: Post http://192.168.1.109:8545: dial tcp 192.168.1.109:8545: connect: connection refused

These are my geth startup variables: --syncmode fast --cache 256 --datadir /mnt/ssd/ethereum

Am I missing something?


texts: Is Truffle migrate compiling my code over and over again?

texts:
Each time I run the truffle migrate command, I see the following messages:

Compiling .\contracts\DateTime.sol...
Compiling .\contracts\DateTimeUtils.sol...
Compiling .\contracts\ERC20Token.sol...
Compiling .\contracts\Migrations.sol...
Compiling .\contracts\SafeMath.sol...
Compiling .\contracts\StringLib.sol...
Compiling .\contracts\getPrice.sol...
Compiling .\contracts\oraclizeAPI_0.4.sol...

Is truffle migrate compiling all my source files again, despite there being no changes? Or is truffle just showing which files it's checking?

If not, what is it doing when it shows "Compiling sourcefilename" when doing a migration?

How can I fix this, if it's really compiling?

I'm using Truffle v4.0.0-beta.0 (core: 4.0.0-beta.0)

Thanks!


texts: How can all transactions sent to an address be found?

texts: Currently it is possible to see only the last 100 transactions from sites like etherchain (link to TheDAO contract transactions), how can all transactions sent to an address be seen?


texts:
How many blocks are created at one point of time? Can miners create a block?
If Yes, then how can we stop the same transaction to be entered in two different block?


texts: Can't connect to dynamically created contract in Mix

texts:
I have an instance of a Gizmo contract created by a Factory but I can't hook into it from JS.

> gizmoInst = web3.eth.contract(gizmoABI).at(gizmoAddr)
Error: INVALID_PARAMS: Invalid method parameters (invalid name and/or type) recognised

Any clues?


texts: What gives Dapper Labs the right to "own" and sell the NBA top shots?

texts:
AFAIK, NFT ownership does not include any legal right.
But in order to sell the ownership in the first place, you do have to "own" it, and that can be done only by a legal agreement, can't it? Did they sign something with the NBA? otherwise, anyone can "sell" NBA moves.


texts:
I'm using the latest version of Truffle. When I try to compile my contract I get this error. I don't know what is happening

/home/josue/Desktop/blockchain/ebay/contracts/Migrations.sol:20:5: TypeError: Name has to refer to a struct, enum or contract.
    Migrations upgraded = Migrations(new_address);
    ^--------^
Compilation failed. See above.
Truffle v5.0.0 (core: 5.0.0)
Node v11.5.0


texts:
It looks like the contract was deployed well on mainnet
However, eventually this error occurs
Saving migration to chain.insufficient funds for gas * price + value
Does it mean that the migration was not saved?
Does it mean the contract should be re-deployed again?
Or it is possible to fix?
Thanks!
ADDITIONAL
truffle.js
live: {
    provider: function() {
        return new HDWalletProvider(MNEMONIC, `https://mainnet.infura.io/v3/${INFURA_API_KEY}`)
    },
    network_id: '1',
    //gas: 8000000,
    gasPrice: 140000000000,
},


texts:
I've repeatedly installed web3 via pip on an ubuntu OS (17.04, running on a DigitalOcean droplet) but for some reason when I attempt to run "from web3 import Web3" I get this response:

  ModuleNotFoundError: No module named 'web3'

I think it has to do with pip because I've had trouble installing other modules (eth-testrpc). Any advice?


texts: Geth interface panic after weeks of being in sync

texts:
After weeks of being in sync and working fine, my Geth just stopped. Upon restart, what started as a long hang on FS Sync Time (repeat output with different values, no further movement beyond allocation of cache and file handles), turned into a panic on latest launch:

INFO [03-17|12:07:14.213] Initialising Ethereum protocol           versions="[63 62]" network=1
WARN [03-17|12:07:15.325] Head block missing, resetting chain      hash=5414aa…aaf1f5
WARN [03-17|12:07:15.325] Rewinding blockchain                     target=0
panic: interface conversion: interface {} is nil, not *types.Block

goroutine 1 [running]:
github.com/ethereum/go-ethereum/core.(*BlockChain).CurrentBlock(...)
        /home/travis/gopath/src/github.com/ethereum/go-ethereum/core/blockchain.go:359
github.com/ethereum/go-ethereum/core.(*BlockChain).SetHead(0x400c4aa000, 0x0, 0x0, 0x0)
        /home/travis/gopath/src/github.com/ethereum/go-ethereum/core/blockchain.go:302 +0x8a0
github.com/ethereum/go-ethereum/core.(*BlockChain).ResetWithGenesisBlock(0x400c4aa000, 0x40002d4120, 0x0, 0x0)

I am now unable to progress past this point.


texts: Ethereum Account and Address Term Used Interchangeably?

texts: Are the terms Account and Address in Ethereum used interchangeably? i.e., an Account is an address. An address points to an account


texts: Anything like a static delegatecall from a view function?

texts:
let's say there are two contracts A and B, where A calls methods in B. I understand that A can modify and read storage in B with B.call() and B.staticcall(), ie. A can execute B's methods in the context of B. For example:

pragma solidity ^0.5.0;

contract A {

    address _sub = address(B);

    function write(uint256 _a) public returns (bool, bytes memory) {
        (bool x, bytes memory y) = _sub.call(msg.data);
        return (x, y);
    }

    function read(uint256 _b) public view returns (bool, bytes memory) {
        (bool x, bytes memory y) = _sub.staticcall(msg.data);
        return (x, y);
    }
}

and

pragma solidity ^0.5.0;

contract B {
    mapping (uint256 => bool) _vals;

    function write(uint256 _a) public returns (bool) {
        _vals[_a] = true;
        return _vals[_a];
    }

    function read(uint256 _b) public view returns (bool) {
        return _vals[_b];
    }
}

However, right now I'd want A to execute B's methods in the context of A itself, And the following code actually sorta works

pragma solidity ^0.5.0;

contract A {

    address _sub = address(B);

    function write(uint256 _a) public returns (bool, bytes memory) {
        (bool x, bytes memory y) = _sub.delegatecall(msg.data);
        return (x, y);
    }

    function read(uint256 _b) public returns (bool, bytes memory) {
        (bool x, bytes memory y) = _sub.delegatecall(msg.data);
        return (x, y);
    }
}

The problem is, the read function in A cannot be declared as view-type, and despite it is calling a view-type function in contract B and doesn't modify anything on the chain, I somehow have to pay gas for it.

Since there's a staticcall() function as a view-type compatible version for the call() function, is there anything similar for the delegatecall() function, or if there's some way so that I can let A execute B's method to read some data stored in A's context without having to pay gas?


texts: I want to use Ledger Nano S to deploy the contract, but not working

texts: I wanted to deploy the contract with the Ledger Nano S wallet, but not working on truffle. I installed npm package 'truffle-ledger-provider' and followed the practice. But I got an error ReferenceError: regeneratorRuntime is not defined when I tried to deploy. I've searched google, but there was no good solution. Please help me.


texts: BlockHash used for random number generation

texts:
I am designing a lottery smart contract. A winning ticket number is drawn from a pool of tickets. In order to do this, I use the following code:

bytes32 blockhash = block.blockhash(block.number - 1);
uint32 winner = uint32(blockhash) % ticketamount;

Is this a reliable and secure way to do this? I was reading online about the risks associated with using the blockhash and how this could be manipulated, however I do not fully understand the risks involved and would like further clarification into the safety of using the above code.


texts: What's the difference between this.function() and function() in recursion?

texts:
I stumbled across some odd behavior that I can't explain regarding recursive functions in Solidity.
As a note, I have attempted to run this on ganache in case it is actually ganache that is throwing this behavior.
contract Foo {
    function bar() public {
        bar(); // This does what I expected, it consumes all available gas and reverts

        this.bar(); // This reverts at a point much below the gas limit
    }
}

The this.bar() line recurses but in a different way to bar().
The this keyword makes the function call an external one i.e. the msg.sender becomes the contract and only the top level call is by the tx.origin EOA address.
Is there a limit on the number of times an external call can be made and thus causing this revert?
What else could be the cause of this behavior?
Below is an example that causes the behaviour I am describing.
test.sol
pragma solidity ^0.6.2;

contract test {
    function doNothing() public
    {
        this.doNothing();
    }
}

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

contract ("test.sol", async accounts => {
    let contract;

    it("do nothing", async () => {
        contract = await test.new();

        await contract.doNothing();
    })
})

Running truffle test -t test.js over a ganache instance results in the following:
Contract: test.sol
    1) do nothing
    > No events were emitted

  0 passing (3s)
  1 failing

  1) Contract: test.sol
       do nothing:
     Error: Returned error: VM Exception while processing transaction: revert
      at Context.it (test/test.js:9:26)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:160:7)

The transaction that reverts consumes 463179 gas whilst the transaction gas limit is 6721975.
Using truffle v5.1.42 and ganache-cli v6.12.1.


texts: What are some practical use cases of the fallback function?

texts:
Besides receiving ethers, for which there is a dedicated receive function, what is a practical use case of fallback?
I can't think of a case when it would be desirable for a contract to execute a special logic when a caller is calling a function that doesn't exist rather than throwing an error.


texts: Is React still part of the Truffle framework? Need to set up a truffle project and would like to use React but not sure if it is still part of the truffle framework/family. Thanks, Manj


texts: Splice Struct Entry by Index in Solidity

texts:
I have a struct and I'd like to remove an item by index:

struct Payout {
  address addr;
  uint yield;
}

Payout[] public payouts;

I'm not familiar with structs and more use to dealing with arrays in javascript where I would do something like this:

payouts.splice(index, 1);

What's the best way to do this with a struct array in Solidity?

Edit: Would also like array to shift down like with the splice function. E.g. when you delete payouts[0] the data from payouts[1] shifts back into its spot.


texts: Function call always as last function call in current Block

texts:
I'm implementing a DoubleAuction and I want to call the breakEven function, that finds the market clearing price, always as very last function in the current Block.
Is there any way that I can check in solidity if the current transaction is the last transaction in the current block and if so, I'd call the breakEven function?


texts: Truffle cannot find Ethereum client when running tests

texts:
By default this is the content of the file truffle.js:

module.exports = {
    // See <http://truffleframework.com/docs/advanced/configuration>
    // to customize your Truffle configuration!
};

When I execute the command truffle test with the above configuration, it work well. However, if I change the configuration to this:

module.exports = {
    networks: {
        test: {
            network_id: '*',
            gas: 4712388,
            gasPrice: 10
        }
    }
};

When I execute the command truffle test I get the following error:

Could not connect to your Ethereum client. Please check that your Ethereum client:
    - is running
    - is accepting RPC connections (i.e., "--rpc" option is used in geth)
    - is accessible over the network
    - is properly configured in your Truffle configuration file (truffle.js)

I tried setting options host and port but still not working.

I'm using Truffle v4.1.14 on Mac.


texts: how to debugg truffle tests with built in debugger

texts:
So I'd like to use the commandline debugger in truffle.

To test I simply run truffle test

I have an empty truffle.js file.

I can get my transaction ID in the javascript tests.
When I run:

 truffle debug 0xce1bc402758bd7b6995d82430214c283967371ade97b01bd46e1fe074ea0a4c2

I get:

Error: No network specified. Cannot determine current network.

I'm guessing this is because after the test ran truffle shut down the test network?

I know I could use testrpc, but it causes a lot of problems for me.

Is there a way to use truffle debug with their new built in test framework?

Thanks

edit
When attempting to use testrpc I get this error message after every test case  : Error: VM Exception while processing transaction: revert

this is my truffle.js

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

  }
};

but when I comment out the development network, then truffle defaults to the "test" network and everything works fine.

edit2 I should note that my tests take a lot of gas. So im guessing that the reverts are caused because an object that is expected to be there is not because I didn't have enough gas to deploy it. I tried increasing the gas limit in truffle.js but that fails with some other error...


texts: Data Scientist wanting to simulate a DAO on private network, unsure of where to begin

texts:
My apologies for such a broad question, I couldn't find anything remotely similar to my case and I've got lots of questions - I'll try to narrow the scope down here.

Premise:
I'm a data science student doing a research project regarding DAO-based community insurance pools, and I'm interested in running some simulations based on collected data to see how a DAO would handle "normal" activity regarding insurance claims and procedures.

Tools and Languages:
Ganache-cli, JavaScript, Solidity, (maybe) Python and/or Java? I've already got a private chain set up and a basic smart contract framework implemented, but no idea how to begin automating processes.

Problem Description:
Simulate arrivals (interactions with smart contract platform) and events (automated payouts to customers, etc) utilizing collected real-world data in XML format. Obviously, utilizing the data as a basis for simulation is my problem to handle, and not the purpose of the question. I'll be basing the simulation on Poisson arrival processes and queueing theory, randomizing events reflecting the occurrence of real-world events, collecting data on wait times, throughput, transactions, and attempt to stress the network in as many ways as possible.

Goal:
To identify structural bottlenecks/weaknesses in a distributed/decentralized community pool, compare processing times to centralized solutions (I'll be simulating the mainnet throughput in this private chain), and start building a prototype to be used as an example in my research proposal.

QUESTIONS FOR THE COMMUNITY / TL;DR:

Are there any repositories, references, examples, or existing projects I can reference that involve (any kind of) simulations of interactions with smart contracts and the Ethereum network of any kind?
I'm not a true software engineer, I just know how to program in a few languages - would it be the most straightforward approach to just write the entire simulation environment in JS, interacting with the backend in this way? Or is there a better approach for this? Any tips/tutorials/references?
Are there any specific sources/guides/tutorials available involving JS scripts that automatically interact with smart contracts in both directions? It's one thing to store information on the blockchain, but I'm not sure where to start learning how I can take observe the blockchain via ganache/truffle and reinput this back into the simulation to update parameters. I've already found an open-source smart contract platform for insurance (Etherisc), although many of the dependencies in this project (such as Oraclize) are unnecessary for this project and I'll have to find ways to remove such dependency.

Again, sorry for such broad questions - it seems like we're in such uncharted territory that most people are just bumping around and trying new things, and very few concrete examples or advanced guides are easily found. Although I've read lots of documentation, so much of it is cumbersome, I've already got the basics down, and I'm on a strict timetable so I can only do so much reading before I need to start working. Apologies for my naivety.

Thanks for the replies in advance!


texts: truffle console issues without testrpc running

texts:
I am attempting to deploy a contract to the ropsten network and having issues with truffle console. I am following this tutorial. When I try to access the console with this command -

$ truffle console

I get this error:

➜  voting truffle console
Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse

I don't have an issue accessing the console while testrpc is running. Any help is greatly appreciated.


texts: How is conflict handled in the case of smart contracts .For eg -in the case of an insurance smart contracts,there might be conflit between both parties.How does blockchain ensure the validity of trigger conditions


texts:
I am currently getting started into developing involving Ethereum. I know what the function w3.eth.account.create() does and returns but I am unsure what happens behind the scenes.

Specifically, does the function store anything on the computer?


texts: Is there a way to lock my coins in an account for X days?

texts: I would like to lock my ether in an account 90 days. Is there a way of doing this? How can it be done? Would it be a smart contract?


texts:
I created 2 nodes . I connect an accounts to metamask. I connect the smart contract with remix on the node. Now i am trying to connect frontend with the smart contract with web3. In the index.html i write :

if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);

// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://ip:8545"));

and then i run in my browser th index.html but i press buttons and nothing.


texts: In parity, how can I delete the last blocks I downloaded without corrupting the database?

texts:
I have found the blockchain data in parity. I go to overlayrecent folder and from there to the db folder. It looks like the blocks are the .sst files.

How can I delete the last blocks I downloaded without corrupting the database?

For example when I just deleted the last .sst file, and then went to terminal and ran parity, I got "Client service error:

Client(Database("Invalid argument: You have to open all coloumn families. Column families not opened: col5, col4, col3, col2, col1, col0"))".


texts: Whenever I sync my node, does it replay all steps ever taken by the ethereum virtual machine?

texts:
For what I understand unlike with bitcoin, the ethereum network has some kind of state, and all the virtual machine bytecode does is to execute some commands to create transitions between these states.

But does it mean that when I start a full node from scratch it will have to essentially re-run all code specified by all smart contracts published ever?


texts: How can i return a dynamic number of values

texts:
i have consulted this thread:
How can I return multiple strings from a contract function?

but i cant find a way to adapt it, as the number of variables i need to return is not set.

here is my top 10 PhD certified code:

mapping (uint256=>string)  fieldNameArr; //filled in another function
function getAllFields()  public view returns (string){
    uint g;
    for(g=0;g<=e ;g++){

        arr.push(bytes(fieldNameArr[g]));
        arr.push(",");

    }
return (arr);
}

Remix is returning an error regarding the type, but i have tried a lot of tricks to solve this and i can't find a way.

Please ask for precision if you need any.
Thank you for your help.


texts:
I run ethereum wallet on my Windows 10 PC, sometimes it displays "1 peers", and sometimes it display "remote", would you please see the image?

What are different between peers and remote in ethereum wallet?


texts: Oraclize API not returning anything in Morden testnet

texts:
I use Geth 1.3.6 and a Morden testnet.
I am trying to test the Oraclize API for my Ethereum smart contracts.

First, I have compiled and deployed the simple smart contracts as DieselPricePeg.sol and PriceTicker.sol, also using dev.oraclize.it/.
I have not any correct output by query, even I don't get id by oraclize_query.

One of the two smart contract is visible at the following link: https://github.com/oraclize/ethereum-examples/blob/master/solidity/DieselPricePeg.sol

(I think that the problem is not in the code of smart Contract.)

Any suggestions?


texts: Oraclize handling long response from cryptocompare

texts:
I have very custom task and I need to make sure what are limits of each technology. I haven't found nothing similair in this forum yet. I am using Oraclize to get response from this url:

  https://min-api.cryptocompare.com/data/histominute?fsym=ETH&tsym=USD&limit=1&aggregate=30&e=Kraken&extraParams=your_app_name.data

and I get such response:

  {"Response":"Success","Type":100,"Aggregated":true,"Data":[{"time":1536559200,"close":197.88,"high":197.99,"low":196.45,"open":197.71,"volumefrom":948.44,"volumeto":186888.76},{"time":1536561000,"close":199.19,"high":199.35,"low":196.68,"open":197.88,"volumefrom":448.02,"volumeto":88870.37}],
  "TimeTo":1536562560,"TimeFrom":1536559200,"FirstValueInArray":true,"ConversionType":{"type":"force_direct","conversionSymbol":""}}

What I need to get is "open" price of first array element from Data which is 197.71 in this example and "close" price of second array element which is 199.19;

However, when I use my code, all I get is [] empty array or empty string. Here is the code:

function updatePriceSingle(uint256 timeStamp) payable {
   if (oraclize_getPrice("URL") > this.balance) {
       emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
   } else {
       emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
       oraclize_query(timeStamp, "URL", "json(https://min-api.cryptocompare.com/data/histominute?fsym=ETH&tsym=USD&limit=1&aggregate=30e=CCCAGG).Data",200000);
   }

}

and here is callback:

function __callback(bytes32 myid, string result) {
  if (msg.sender != oraclize_cbAddress()) revert();
  emit LogPriceUpdated(result);
}

I know workaround to make 2 calls json(...).Data[0] and json(...).Data[1], but I want to save gas and get results from 1 call in such case above. Is it possible ? Maybe there are solutions using "Test query" in http://app.oraclize.it/home/test_query . Thank you in advance.


texts: I cannot see Ethereum accounts in Browser

texts:
There are 10 Ethereum accounts in Ganache. I work on a Truffle project. Whenever i run the following codes in Nodejs:

var Web3 = require('web3');
var web3 = new Web3("ws://localhost:8545");
var acc= Promise.resolve(web3.eth.getAccounts());
acc.then(function(ins){console.log(ins[0]);});

Address of the first account will be shown:

But i want to see that address in my browser. What is the appropriate code?


texts: How can oracle PROVE that a transaction was mined?

texts:
I want to build an oracle similar to OmniBridge for xDai or Arbitrary Message Bridge but I am worried about how to make it secure.
It would seem such an oracle should be reliable, as long as there is a way to take the hash of a transaction and prove that it was included in a block, which in turn was mined on the "main blockchain". (That last part is subjective, but as long as we can prove enough block difficulty after the transaction, the  smart contract calling the oracle can be satisfied). The components I need to verify all this are:

The Merkle Branch (or some other proof) that the transaction was mined in its Block

Some way to verify how many blocks were "legitimately" mined until we get to the hash of the "latest/top" block (which the oracle would just get from the blockchain nodes).

The person will provide the actual transaction parameters, and the transaction's hash would have to be computed again by the smart contract, to make sure it is the right hash.

Is 1, 2, 3 even possible? That's the question!
The idea is to "cash out" X amount of FOO tokens which were sent to a smart contract on the Ethereum mainnet and locked there. For example if someone sends corresponding X amount of xFOO tokens on the xDai chain, and this transaction is "confirmed" after a few blocks, then the person can call a method on the smart contract, and it will release X tokens to the same wallet EOA address that sent them.
Security analysis: Presumably, under a large enough blockchain like xDai, whether it's PoW or PoS, it should be secure, but if X is large enough, someone might want to fool the oracle network by mining more fake blocks on top and then "proving" that the transaction happened. I guess they can't really fool the oracle, though, because the ERC1677 token contract on xDai would roll back any transaction that didn't have enough balance. They'd have to fork the entire xDai network and mess up a lot in order to fake a transaction that violates the smart contract logic.


texts:
I have some doubts regarding the Smart Contracts. First of all, I know that when I deploy a Smart Contract, this will have an address. We can suppose that I deployed the smart contract on blockchain. So my questions are:

Is it true that a smart contract can be invoked only if a user make
a transaction towards the smart contract address?
If an user A make a transaction towards user B, or C, and so on, can
the smart contract self-execute?(be careful, the transaction is not
towards the smart contract itself).
Can a smart contract work like a listener on all blockchain transactions and
execute itself if there are all necessary conditions to activate it?


texts: Am I installing Casper FFG node correctly?

texts:
After I begin running the node (normally or with the miner turned on), I see this message:

  2018-01-02 16:47:02,428 WARNING:p2p.discovery.kademlia  recv ping from self?!

Is this what should be outputting or have I done something wrong?


texts:
I am newbie to solidity, this is my first PoC on testnet, i am just trying to understand how things works.

i am following the main tutorial on Ethereum website, under this URL https://www.ethereum.org/token

i followed all the instructions until I have reached the "How to Deploy" section. when i click on the "Deploy" button nothing is happening at all. i have closed it and running again and hit the Deploy button, nothing is happening.

below is the code i am using, it is exactly how the tutorial is asking me to do it.

    pragma solidity ^0.4.11;

    contract MyToken {

    string public name;
    string public symbol;
    uint8 public decimals;
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    event Transfer(address indexed from, address indexed to, uint256 value);

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function MyToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) {
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
        name = tokenName;                                   // Set the name for display purposes
        symbol = tokenSymbol;                               // Set the symbol for display purposes
        decimals = decimalUnits;                            // Amount of decimals for display purposes
    }

    function transfer(address _to, uint256 _value) {
        /* Check if sender has balance and for overflows */
        if (balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to])
            throw;

        /* Add and subtract new balances */
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        /* Notify anyone listening that this transfer took place */
        Transfer(msg.sender, _to, _value);
    }
}

what should i do?


texts: Transfer of Ethereum coinbase wallet to ethereum wallet

texts:
I have been perusing these wonderful threads for about a week now to get a better understanding of Ether and the ecosystem. I recently downloaded the Ethereum wallet client from the Ethereum website to secure my Ether that I purchased via Coinbase. I sent a small amount of Ether from my Coinbase to my Ethereum wallet and noticed that the amount sent was too small and that the gas price was higher than the amount sent. I canceled the transaction since the price to transfer exceeded the transfer amount.

Coinbase now shows that the request was executed successfully, but the amount sent is neither in my Coinbase wallet nor in my Ethereum wallet via the Ethereum client.

Anyone have any ideas as to where that portion of Ether is?


texts: Unused Local Variable error in Crowdsale contract

texts: I've been trying to create a crowd sale contract but it does not compile and comes with the error "unused local variable". Really not sure what to do as the code came directly from the ethereum crowd sale guide.


texts: Does view functions cost gas? And how to send transaction in a proper way?

texts:
I have a method defined as:
getNames() view public , if i call on it
contractInstance.getNames.estimatedGas() it returns me a non-zero value, why? I mean, view methods should not consume any gas! On the other way, since this is a call it does not return to me a tx hash so i can't invoke the eth.gettransactionReceipt, how can i check if it really consumed gas ?

Furthermore, supposing method() is a set function of my deployed contract, hence  a transaction mining is needed, which is the difference between calling:

contractInstance.method(args,{from:web3.eth.coinbase, gas:...})

and calling:

contractInstance.method.sendTransaction(args,{from:web3.eth.coinbase, gas:...})


texts: I have been thinking:"All tutorials show you how to mine in a pool, but i want to mine solo." And now I finally decided to ask this here. Does anyone know how to use ethminer to mine solo and set wallet adress to custom outside of geth?


texts: ERC20, how to calculate how many tokens for crowdsale?

texts:
If you look at this article, the total tokens for crowdsale is 100 tokens and defined in the code as

uint256 public maxTokens = 100000000000000000000;

how come 100000000000000000000 becomes 100 tokens?


texts: Insufficient funds error on deploying smart contract

texts:
I am writing a Java program to deploy a smart contract. I have created the Java Wrapper class. This is the essence of the code.

static final BigInteger GAS_PRICE = BigInteger.valueOf(20_000_000_000L);
static final BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);
Credentials creds = WalletUtils.loadCredentials(password,
            pathtowalletfile);
Greeter contract = Greeter.deploy(web3j, creds, GAS_PRICE, GAS_LIMIT, BigInteger.ZERO, new Utf8String("Hello")).get();

When I run my program I am getting this error

Error processing transaction request: Insufficient funds for gas * price + value

I must say that I am quite new to ethereum and web3j. My geth version is 1.6.0-stable-facc47cb

Any help would be much appreciated.

Updated with Contract

contract mortal {
    address owner;

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

contract greeter is mortal {
    string greeting;

    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    function greet() constant returns (string) {
        return greeting;
    }
}


texts: Deploy smart contract to private network

texts:
I have been having issues deploing any smart contract to my private network.
I'm using geth 1.9.15.
Here ALL the steps that I made to get the error:
//CustomGenesis.json
{
  "config": {
    "chainId": 48,
    "homesteadBlock": 0
  },
  "difficulty": "0x40",
  "gasLimit": "0x80000000",
  "alloc": {}
}

I have started two nodes:
geth --identity "node1" --datadir ./node1 init ./CustomGenesis.json
geth --identity "node2" --datadir ./node2  init ./CustomGenesis.json

nohup geth --identity "node1" --datadir ./node1 --networkid 48 &
nohup geth --identity "node2" --datadir ./node2 --networkid 48 --port 30305 --http &

Attached the peers:
# geth attach ./node1/geth.ipc
Welcome to the Geth JavaScript console!

> admin.addPeer("enode://[...]:30305")
true

Created the account:
> personal.newAccount()
Passphrase:
Repeat passphrase:
"0xdc[...]b5"

Started the miner on the second node:
# geth attach ./node2/geth.ipc
Welcome to the Geth JavaScript console!

> miner.setEtherbase("0xdc[...]b5")
true
> miner.start()
null

On the first node:
> personal.unlockAccount("0xdc[...]b5","Password")
true
> var contract = eth.contract([{...ABI DATA...}])
undefined
> var bin = "0x...BIN DATA..."
undefined
> var x = {from:eth.coinbase, data:bin, gas: 2000000}
undefined
> var instance = contract.new(x)
Error: invalid transaction v, r, s values
        at web3.js:6347:37(47)
        at web3.js:5081:62(37)
        at web3.js:3021:48(134)
        at <eval>:1:28(6)

I don't think the issues are related but I also tried with truffle without success.
Configuration file:
//truffle-config.js
module.exports = {
  rpc: {
      host:"127.0.0.1",
      port:8545
  },
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "48",
      from: "0xdc[...]b5",
      gasPrice: 100000000000,
      gas: 47123880
    }
  }
}

Deploy file:
//2_deploy_contracts.js
var contract = artifacts.require("contract");

module.exports = function(deployer) {
        deployer.deploy(contract,0,"TEST","TST");
};

But when it runs:
# truffle migrate --reset
Starting migrations...
======================
> Network name:    'development'
> Network id:      48
> Block gas limit: 1715282554 (0x663d227a)

1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" -- Returned error: unknown account.

What did I did wrong?
I haven't found any useful information elsewere as seems that all the related question are from 2016.


texts:
I am using IPFS-multihash method to store IPFS hash in smart contracts.
For that I need to decode base58 format:

QmaozNR7DZHQK1ZcU9p7QdrshMvXqWK6gpu5rmrkPdT3L4

to binary(as hex):

1220b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

But I am unable to use bs58 module in browser (I tried using Browserify). Can you tell me the javascript implementation for decoding and encoding in base58 so that I can implement the above method without using node_modules?


texts: Can the precompiles in Byzantium for pairings be used for implementation of BLS verification?

texts:
I am looking into implementing some operations for the BLS signature scheme in Solidity, using the new precompiled contracts for pairing operations released with Byzantium.

In BLS verification, to check the validity of a signature s in F_q corresponding to public key V in G_2 and message M:

Find y in F_q with sigma = (s, y).
Compute R <- MapToGroup(M) in G_1.
Test if either e(sigma, Q) = e(R, V) or e(sigma, Q)^-1 = e(R, V).

(see page 310 in the BLS paper for more details)

Supposing we have R and sigma, is step 3 possible with the precompiled contracts: addition (0x6), scalar multiplication (0x7), and pairing check (0x8)? I am not sure I can find a formulation since there is no implementation for evaluating the pairing function e itself.

Also, how would steps 1 and 2 be accomplished in Solidity?

Edit: asked a similar question on the crypto StackExchange


texts: How can I create an array of objects of a specific smart contract in solidity?

texts:
I am developing a university management system using ethereum. So,for that I need an entity "Student" and I have created a smart contract with some basic functionalities. Here is my code snippet for student.sol

pragma solidity ^0.5.0;

contract student
 {
    string private name;
    string private birthdate;
    string private department;
    string private location;
    string private email;
    uint256 private id;
    uint256 private mobile_no;
    uint256 counter=0;

    function setName(string memory myname) public
    {
        name=myname;
    }
    function getName() public view returns(string memory )
    {
        return name;
    }

     constructor ()public
    {
        id=counter+1;
        counter=counter+1;
    }
    function getid() public view returns(uint256 id1)
    {
        id1=id;
        return id1;
    }

    function setbirthdate(string memory _birthdate) public
    {
        birthdate = _birthdate;
    }

    function getbirthdate() public view returns(string memory )
    {
        return birthdate;
    }

    function setdepartment(string memory mydepartment) public
    {
        department = mydepartment;
    }
    function getdepartment() public view returns(string memory )
    {
        return department;
    }
    function setlocation(string memory mylocation) public
    {
        location= mylocation;
    }
    function getlocation() public view returns(string memory )
    {
        return location;
    }

    function setmobileno(uint256 myphonenumber) public
    {
        mobile_no = myphonenumber;
    }
    function getmobileno() public view  returns(uint256 )
    {
        return mobile_no;
    }

 }

I have used web3.js to interact between the smart contract and web page. Now I want to create an array of student object and use them whenever I need to create a student. How can I do it? Please help me


texts: Invalid sender error when creating contract through web3

texts:
I am trying to create a managed account and deploy a custom wallet contract through web3 on my own private network. The code I'm using is:

// Create account
let account = this.web3.eth.accounts.create();
let encryptedAccount = account.encrypt(password);

// Create and deploy contract
let walletCreationData = new this.web3.eth.Contract(walletContractAbi, null, {
    data: walletContractData
}).deploy().encodeABI();

// Sign contract creation with created account
this.web3.eth.accounts.signTransaction({
    data: walletCreationData,
    from: account.address,
    gasPrice: 0,
    gas: 200000
}, account.privateKey).then((signedTransaction) => {
    this.web3.eth.sendSignedTransaction(signedTransaction.rawTransaction).then(console.log);
});

Now this will give me an error with the message invalid sender at the sendSignedTransaction promise. I have tried many combinations, among which using an in-memory wallet and loading an account with an existing balance instead of freshly creating one, but they all ended up giving the same error. What crucial part is missing that would allow me to create a smart contract?

This was tested using web3 1.0.0-beta.24 and geth 1.7.1-stable.


texts: how to change all the ethereum blocks from C drive to D drive on windows?

texts:
I have just finished downloading the ethereum blockchain data with the go client but my c drive is full, however I have 900 gigabytes of free space on d drive.

how can I make my blockchain data to d drive without starting downloading them from scratch again as they took me a month to download them ?

I also want to know does the go client will keep syncronizing automatically or I have to do something ?

I am new to ethereum.

thanks in advance


texts: Is there any website or online community maintaining a spreadsheet comparing the different crypto exchanges?


texts: npm ERR! when installing ethereumjs-testrpc in Ubuntu 16.04

texts:
'...
npm ERR! git clone --template=/home/uspace/.npm/_git-remotes/_templates --mirror ://github.com/debris/bignumber.js.git /home/uspace/.npm/_git-remotes/git-https-github-com-debris-bignumber-js-git-master-df3f1ce1: remote: Invalid username or password.
npm ERR! git clone --template=/home/uspace/.npm/_git-remotes/_templates --mirror //github.com/debris/bignumber.js.git /home/uspace/.npm/_git-remotes/git-https-github-com-debris-bignumber-js-git-master-df3f1ce1: fatal: Authentication failed for '//github.com/debris/bignumber.js.git/'
npm ERR! Linux 4.8.0-56-generic
npm ERR! argv "/opt/node/bin/node" "/usr/bin/npm" "install" "-g" "ethereumjs-testrpc"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! code 128

npm ERR! Command failed: git clone --template=/home/uspace/.npm/_git-remotes/_templates --mirror//github.com/debris/bignumber.js.git /home/uspace/.npm/_git-remotes/git-https-github-com-debris-bignumber-js-git-master-df3f1ce1
npm ERR! Cloning into bare repository '/home/uspace/.npm/_git-remotes/git-https-github-com-debris-bignumber-js-git-master-df3f1ce1'...
npm ERR! remote: Invalid username or password.
npm ERR! fatal: Authentication failed for '//github.com/debris/bignumber.js.git/'
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <//github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /home/uspace/npm-debug.log


texts: Does it cost gas if a non view/pure function does not alter the blockchain?

texts:
Say I have a function which 'might' alter the state of the block chain depending on conditions.  Will I get charged gas if it does not?  For example:
if (conditionMet) {
  callContractWhichAltersBlockchain();
} else {
  // do nothing, return false
}


texts: web3.eth.filter({ fromBlock:1, toBlock: "latest" }).get() not working

texts:
web3.eth.filter({ fromBlock:1, toBlock: "latest" }).get() is not working on my geth console. I downgraded my geth from 1.5.9 to 1.3.5 to resolve this but it's still not working.
Strange thing is that it is working on one machine with geth 1.3.5 but not on a cloud VM with same geth version.
web3.eth.filter({ fromBlock:1, toBlock: "latest" }).get() return [] while my blockchain has transactions in the blocks.How to resolve this.

Later I found out that this is not working on the Linux OS. Any help will be appreciated.


texts: How to pass nested array values to the solidity function?

texts:
For Example:

I am trying a sample contract where i want to pass nested array values.

But i cant able to find the suitable solution ?

Is it possible or do i have to change the way to send the data ?

Thanks


texts: Truffle Debugger: Inspect Transaction object?

texts:
Is it possible to inspect the transaction object 'msg' in the truffle debugger? When I step through the below and type :msg.value I get ReferenceError: msg is not defined

Code:

    string public name;

    function changeName(string newName) public payable {
       require(msg.value >= 1 ether);
       name = newName;
    }


texts:
I am looking for historical ether prices. There was a thread already discussing this enter link description here, however, I would like to get not only the prices available for Ether on Poloniex but also for other VCs (e.g. BTC, LTC) to USD. In the end the web output should look like the output in the other thread. It looks like this.
Can someone please help me?

Thank you in advance!


texts: block download canceled, geth 1.5.9 would not download blocks

texts:
when starting out geth I cant download past block 1292880

does anyone have any idea why it would not download any more blocks?


texts: Can a library function operating on a struct work for non "storage" structs?

texts:
I'm just getting started with solidity, and I'm working on a contract that calculates the periodic payment on an amortized loan.  My goal is to implement the annuity formula:

I've started a library for rational data and a struct for the fraction.  In order for the library function to compile the function signature requires any struct parameters be marked with the storage keyword.

library Rational
{
    struct FractionUint
    {
        uint numerator;
        uint denominator;
    }

    function multiply(FractionUint storage self, FractionUint storage other)
    {
        self.numerator *= other.numerator;
        self.denominator *= other.denominator;
    }

...
}

contract testRational
{
    using Rational for Rational.FractionUint;
    Rational.FractionUint f1;
    Rational.FractionUint f2;

    function testMultiply()
    {
        f1 = Rational.FractionUint(1,10);
        f2 = FractionUint(100,2);
        f1.multiply(f2);
        if (f1.numerator != 100)
            throw;
        if (f1.denominator != 20)
            throw;
    }

    /*
    function testMultiply2()
    {
        var f3 = Rational.FractionUint(1,10);
        var f4 = Rational.FractionUint(100,2);
        f3.multiply(f4);
        if (f3.numerator != 100)
        throw;
        if (f3.denominator != 20)
        throw;
    }
    */
}

Compiling testMultiply2 restults in the error:

Error: Member "multiply" is not available in struct FractionUint memory outside of storage.

There are multiple intermediate steps for which I'd like to use some variables defined in the scope of the contract function.

Can a library function called from a contract function perform operations on variables defined in the contract function scope?


texts: Will we be able to use dapps on smartphones?

texts:
I know currently there is no chance to use Dapps on mobile. Are there any upcoming projects to solve this issue?
I think this is most necessary part of Dapps. Without mobile support there is no way.


texts: How data is stored in Ethereum blockchain?

texts: If I become a full node in Ethereum and retrieve the current state, how all this data is going to be stored in my physical drive?


texts: Remix - Solidity IDE - function revealWinners not public

texts:
I defined a modifier in my contract Auction

modifier onlyOwner() {                                 //Part 2 Task 1
    require (msg.sender == beneficiary);
    _;
}

This modifier should be used in the revealWinners function instead of public.
 But it's not working and I don't know why.

function revealWinners() onlyOwner returns {                       //Part 2 Task 1
     for (uint id = 0; id < 3; id++) {
         Item storage currentItem=items[id];
         if (currentItem.itemTokens.length != 0){
             uint randomIndex = (block.number / currentItem.itemTokens.length)% currentItem.itemTokens.length;
             uint winnerId = currentItem.itemTokens[randomIndex];
             winners[id] = winners[winnerId];               //Part 1 Task 6 – 1 line
        }
    }
}

I got the message: Expected token LParen got 'LBrace' (behind returns).
Who can assist me?


texts: instance.balanceOf(...).call is not a function

texts:
I have ERC20 standard token functions in my code...I´m trying to test the function balanceOf(address _owner) with a javascript test on truffle but I have the following problem:

 TypeError: ovxet.balanceOf(...).call is not a function
  at test/test1.js:48:46

It´s weird, because I always pay attention on how I define the functions in the code and how I have to call them...

I´ve tried in my test in both ways (async/await and promise chaning) but the result is the same "is not a function":

it("should call balance", function() {
    account1 = accounts[0];
    return OVXET.deployed().then(function(instance) {
        ovxet = instance;
        return ovxet.balanceOf(account1).call({from: account1});
    }).then(function(balance){
        console.log(balance);
    });
});

And this async/await call inside another promise:

    var balance2 = await ovxet.balanceOf(account1).call({from: account1});
    console.log("balance using erc20 function: " + balance2.toNumber());

Here you have the code inside the .sol script:

function balanceOf(address _owner) public constant returns (uint balance) {
    return _sumBalances(_owner);
}

It´s really strange because It´s so easy coding-function...so I am really frustrating with this situation...

This is the ABI part related to this function:

{
      "constant": true,
      "inputs": [
        {
          "name": "_owner",
          "type": "address"
        }
      ],
      "name": "balanceOf",
      "outputs": [
        {
          "name": "balance",
          "type": "uint256"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },


texts: How to set byte in fixed-size byte array?

texts:
function computePairId(bytes20 base, bytes20 quote) public view returns (bytes4) {

    bytes32 pairHash = sha256(abi.encodePacked(base ^ quote));

    bytes4 pairId;
    pairId[0] = pairHash[28];
    pairId[1] = pairHash[29];
    pairId[2] = pairHash[30];
    pairId[3] = pairHash[31];
    return pairId;
  }

However I get

SolcCompilationError: Zocr.sol:31:5: TypeError: Expression has to be an lvalue.
    pairId[0] = pairHash[28];
    ^-------^

in Solidity ^0.4.24;


texts: Does next hard frok (initial PoS implementation) remove difficulty bomb?

texts:
To my understanding, we now started something called ice age period where difficulty bomb becomes harder exponentially and this was implemented to make sure everyone switches to new PoS chain when it is out.

However according to recent articles PoS will start off in hybrid mode where 99 blocks are still validated via PoW and 1 is validated via PoS (again we can never be 100% sure this is the case, but it looks like it from what I've read). This means we will still be able to mine for a couple of months until PoS is fully implemented.

My question is: the hybrid stage of PoS requires hard fork, will this hard fork remove difficulty bomb and will another difficulty bomb be implemented to account for next step of PoS transition, or will it be possible without hard forking again?

Subsequently, it seems like Casper is still in development, what happens if it is not ready in time before difficulty bombs effect becomes too hard?


texts:
My transaction of 0.003 ETH from MEW shows "FAIL" in etherscan when checked with Tx.

The required Gas was set as 170000.
No reason is shown on the etherscan page.
What must've gone wrong?
Does the amount bounce back?
Need help.
Thanks


texts: GPU can't allocate the DAG in a single chunk. Bailing?

texts:
I decided to do solo GPU mining and set everything up (probably). Synced the blockchain, ran the Genoil 1.0.7 beta of ethminer on Windows. But I keep receiving this error:

Creating one big buffer for the DAG Allocating/mapping single buffer failed with: >clCreateBuffer(-61). GPU can't allocate the DAG in a single >chunk.Bailing. clEnqueueWriteBuffer(-38)

I used

export GPU_FORCE_64BIT_PTR=0 export GPU_MAX_HEAP_SIZE=100 export GPU_USE_SYNC_OBJECTS=1 export GPU_MAX_ALLOC_PERCENT=100

but to no avail. I am using Intel HD 4000 which has about 1.7/1.8 GB I guess. I reckon my Nvidia GT 620M is not enough. I am using Win 8.1 64bit. Any help please?


texts:
The Configuring Parity wiki page says:

Snapshot Options:
  --at BLOCK            Take a snapshot at the given block, which may be an
                        index, hash, or 'latest'. Note that taking snapshots at
                        non-recent blocks will only work with --pruning archive
                        (default: latest)

What is a snapshot?

Does it cause the whole blockchain at that block to be saved to disk in a separate file? If so, where are these stored?


texts:
Can you explain me what this piece of code does please?
i don't understand it at all.

 struct Candidate {
        uint id;
        string name;
        uint voteCount;
    }

mapping(uint => Candidate) public candidates;
uint public candidateCount;

constructor() public {
    addCandidate("candidate 1");
    addCandidate("candidate 2");
}

function addCandidate(string name) private {
    candidateCount += 1;
    candidates[candidateCount] = Candidate(candidateCount, name, 0);
}

Thank you very much
Take care


texts: Ethereum private chain resets back to block 0 when restarted

texts:
I am currently running the latest geth 1.8.1 Iceberg version.

I set up a private ethereum network as per tutorial and everything including mining works fine, but every time I restart geth - the chain resets back to block number 0, all the mining transactions have gone missing and no ETH balance as well, but transactions are recorded in the logs. Please help me to figure out the issue.


texts:
This StackExchange question ALMOST answered my question. However I don't know how to exactly correct my code so that the function named after the contract is replaced by the constructor.

How specifically would this function be corrected?

contract Fake_Smrt_Coin is EIC20{

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

string public name;
uint8 public decimals;
string public symbol;
//I know this line needs improvement
function Fake_Smrt_Coin (
    uint256 _initialAmount,
    string _tokenName,
    uint8 _decimalUnits,
    string _tokenSymbol
) public {
    balances[msg.sender] = _initialAmount;
    totalSupply = _initialAmount;
    name = _tokenName;
    decimals = _decimalUnits;
    symbol = _tokenSymbol;
}

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

Would the updated code be?

  constructor(){
    string public name;
    uint8 public decimals;
    string public symbol;
    }

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


texts: Ropsten testnet connecting to fork before ropsten revival

texts:
I was syncing ropsten testnet using geth. Command used-

geth --testnet --syncmode "full"

At some time, eth.syncing returned-

{
  currentBlock: 353883,
  highestBlock: 1172714,
  knownStates: 0,
  pulledStates: 0,
  startingBlock: 353878
}

Notice the highest block. Its supposed to be 24xxxxx.
When I let it sync, syncing stopped at 1172xxx block.
I checked blocks manually and compared them with http://ropsten.etherscan.io/ , blocks were same as ethscan upto 585000 blockNumber(and different afterwards), that is the block number where ropsten testnet revival took place from.
Now I assume that it somehow synced with a fork where revival did not take place.

Can anybody explain me how did it happen? Aren't all nodes on same fork?
How can I make sure when I start geth that it doesn't sync with blockchain from pre-ropsten revival fork?
Can something like this happen on main-net?


texts: Parity 1.6.3 issue building with multirust

texts:
cat /Users/xxxxxxxxxxx/Library/Logs/Homebrew/parity/01.multirust
2017-03-21 16:08:46 -0500

multirust update stable

Failed to execute: multirust update stable

HOMEBREW_VERSION: 1.1.11
ORIGIN: https://github.com/Homebrew/brew
HEAD: 394f9fa0aaa5854aa52bc589708a079665dcf462
Last commit: 2 weeks ago
Core tap ORIGIN: https://github.com/Homebrew/homebrew-core
Core tap HEAD: b0a8468bfeab9b147ec5e8a311557a17d1e4722e
Core tap last commit: 9 hours ago
HOMEBREW_PREFIX: /usr/local
HOMEBREW_REPOSITORY: /usr/local/Homebrew
HOMEBREW_CELLAR: /usr/local/Cellar
HOMEBREW_BOTTLE_DOMAIN: https://homebrew.bintray.com
CPU: quad-core 64-bit haswell
Homebrew Ruby: 2.0.0-p648
Clang: 7.3 build 703
Git: 2.7.4 => /Library/Developer/CommandLineTools/usr/bin/git
Perl: /usr/bin/perl
Python: /usr/bin/python
Ruby: /usr/bin/ruby => /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
Java: N/A
macOS: 10.11.6-x86_64
Xcode: N/A
CLT: 7.3.1.0.1.1461711523
X11: N/A

HOMEBREW_CC: clang
HOMEBREW_CXX: clang++
MAKEFLAGS: -j4
CMAKE_PREFIX_PATH: /usr/local
CMAKE_INCLUDE_PATH: /usr/include/libxml2:/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers
CMAKE_LIBRARY_PATH: /System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries
PKG_CONFIG_LIBDIR: /usr/lib/pkgconfig:/usr/local/Homebrew/Library/Homebrew/os/mac/pkgconfig/10.11
ACLOCAL_PATH: /usr/local/share/aclocal
PATH: /usr/local/Homebrew/Library/Homebrew/shims/super:/usr/local/opt/multirust/bin:/usr/bin:/bin:/usr/sbin:/sbin


texts: geth never finishes fast sync on Linux Mint

texts:
$ geth version
Geth
Version: 1.10.2-stable
Git Commit: 97d11b0187b4695ccf44e3b71b54155fe405a36f
Git Commit Date: 20210408
Architecture: amd64
Go Version: go1.16
Operating System: linux
GOPATH=
GOROOT=go

Start-up parameters:
geth --mainnet --syncmode fast --cache 2048 --datadir ./blockchain-data/ --mine --miner.threads 4 --ws --ws.addr 192.168.1.38 --ws.port 6691 --ws.api eth,net,web3,personal console 2> ./blockchain-data/node.log

It never stops syncing. When it gets down to 63 blocks left to sync, it does nothing until it has 127 blocks left. Then it brings in 64 blocks and waits again.
It seems like the most common way to solve this problem is to set up NTP on the system. I am running this on Linux Mint 20.1. Here is what happens when I try to set up NTP.
$ sudo timedatectl set-ntp true
Failed to set ntp: NTP not supported

$ sudo timedatectl
           Universal time: Wed 2021-04-14 14:35:30 UTC
                 RTC time: Wed 2021-04-14 14:35:30
System clock synchronized: yes
              NTP service: n/a
          RTC in local TZ: no

$ sudo systemctl start ntp
Failed to start ntp.service: Unit ntp.service is masked.

Has anyone run a client on Mint before? Any ideas on how I can solve this problem?


texts:
My thought is that we come up with a random number in one block and make it private so no one can see it. The timer will allow a few blocks to be mined and then the revealNumber function allows the secret number to be known and then generates another random number. I think this would eliminate the possibility for block manipulation? Is there any way that someone could see something that is private?

pragma solidity ^0.5.4;

contract SKYLotto {

  uint256 private secretNumber;
  uint256 public releasedNumber;
  uint256 public time;

    function randomGen() public {
        secretNumber = uint(keccak256(abi.encodePacked(now, msg.sender))) % 10;
        time = now + 30 seconds;
    }

    function revealNumber() public {
      enter code here  require(now > time);
        releasedNumber = secretNumber;
        randomGen();
    }
}


texts: Hello! I erroneously transferred my Ethereum coins in my Coinomi Wallet to the Ethereum CLASSIC Wallet on Cryptopia

texts:
SO, here's the story; yesterday, I wanted to sync all my wallets to be on one exchanger and I found cryptopia to be reliable.
But I wasn't paying attention when I generated the wallet for ETC and so I just copied the address and sent all the ETH on my Coinomi to that account. Now it's been 8 hours and I can't see a reflection of the coins anywhere. Is it possible to reverse this action?

PS: I'm new to cryptocurrencies. I'm not sure how all of this works...


texts: How could "ethereum block explorer" connect into geth that is already running on the main server securely?

texts:
I am working on private Ethereum Network. I run Ethereum boot-node and Ethereum Block Explorer app ( https://github.com/etherparty/explorer (A lightweight ethereum block explorer.) ) on the main server.

Inside the main server where I run Ethereum node, at the browser I could connect into the Ethereum Block Explorer from localhost:8000:

But from an external node on the browser, when I try to connect from main server's ip address < ip-address >:8000 I have faced with the following error message. The main reason of this error message was "web3 is not connected"

var eth_node_url = 'http://localhost:8545'; // TODO: remote URL
web3.setProvider(new web3.providers.HttpProvider(eth_node_url));

if(!web3.isConnected()) {
    $('#connectwarning').modal({keyboard:false,backdrop:'static'}) //enters here
    $('#connectwarning').modal('show') //enters here
}

On the external node, if I run geth app on the background that is already connected to the private Ethereum network, it solves the problem.

[Q] On the external node without running the geth app on the background, is it possible for Ethereum Block Explorer to connect into the geth app that is already running on the main server? If yes, is there a secure approach as running geth with --rpcaddr="localhost" --rpccorsdomain="*" on the main server?

Thank you for your valuable time and help.

Note:

=> The way I run the Ethereum Node:

geth --port 3000 --networkid 23422 --nodiscover --datadir="/home/MyEthereumEbloc"
--rpc --rpcaddr="localhost" --rpccorsdomain="*" --maxpeers=6 --ipcapi
"admin,eth,web3" --autodag

=> In order to install Ethereum Block Explorer, I have followed the installation guide on https://github.com/etherparty/explorer.

[~$] git clone https://github.com/etherparty/explorer
[~$] cd explorer
[~/explorer$] npm start

> EthereumExplorer@0.1.0 prestart /home/netlab/explorer
> npm install

> EthereumExplorer@0.1.0 postinstall /home/netlab/explorer
> bower install

> EthereumExplorer@0.1.0 start /home/netlab/explorer
> http-server ./app -a 79.123.177.145 -p 8000 -c-1

Starting up http-server, serving ./app on port: 8000

=> Inside package.json file that is located under explorer folder: app started as follows:

"start": "http-server ./app -a localhost -p 8000 -c-1"

Please know that when I have changed localhost to node'a ip-address it didn't help:

"start": "http-server ./app -a <ip-address> -p 8000 -c-1"


texts: Smartcontract: Warning! Error encountered during contract execution [Reverted]

texts:
I have sent ETH to a contract address, and it "failed" the transaction saying it is: Warning! Error encountered during contract execution [Reverted]

contract address and transaction failure here:
https://etherscan.io/tx/0xa790149d714d614601ded9df1ad40b3830953b5a019b4ea9030cd1699344f2acE

can someone help and explain please?


texts:
An investment round ask new investors to put exactly 0.1 ether to enter the round.

function invest() public payable {
    require(msg.value == 0.1 ether);
}

How can I save every new investor address into an indexed list? Considering that there could be thousands of investors.

The idea is that, given a condition, the investors will exit the round. So the list (investorsList) should be iterable with a for loop, kind of like this:

function withdraw() public {
    for (uint i = 0; i < investorsList.length; i++){     // iterates investors list
            if (address(this).balance = 1 ether){       // if condition reached
                investorsList[i].transfer( 0.5 ether); // transfers eth to investor
        }
    }

// Eth amounts are just for example

EDIT: This question asks for a use case where could be hundreds of thousands of addresses stored and iterate over them, so the contract should never get stuck, it should be able to run forever.


texts: How to call undefined method of a contract using truffle javascript?

texts:
I have a dispatching contract, that defines fallback function to send all "undefined" calls to implementation contract using delegatecall:

contract Dispatcher{
  address _implementation;
  function() public{
    bytes4 sig;
    assembly { sig := calldataload(0) }
    var len = _returnSizes[sig];
    var target = _implementation;

    assembly {
    // return _dest.delegatecall(msg.data)
        calldatacopy(0x0, 0x0, calldatasize)
        let ret := delegatecall(sub(gas, 10000), target, 0x0, calldatasize, 0, len)
        jumpi(0xffffffff, iszero(ret))
        return(0, len)
    }
}

However, I have no clue how to write tests in truffle in javascript, e.g. to call Implementation.methodA(). I guess I have to SOMEHOW format data in sendTransaction, but can't find any documentation or sample code. Help is appreciated.


texts: Accept USDT (Tether) for payment method in website

texts:
Is it able to use Binance API to accept USDT as a payment method on the website?
For this purpose we need can generate a unique USDT address per order and can track it. If Binance is not a good solution what is the best solution for this.
We need to create 3 types of addresses ( TRC20, ERC20, Omni).


texts:
I know that msg.sender will be the address that connects to the contract.
Address(this) is the current contract address
Then == means it connects to itself. When using this condition in require, the function only accept the contract call itself internally? Is this the right understanding and does it make sense?


texts:
So, there is this rumor about a massive 72GB of ram "ASIC" miner coming up from bitmain specifically to mine Ethereum.

I knew that Ethereum is ASIC resistant, so how would this potential miner even work ?

Will Ethereum be capable to resist this kind of miner ? And in general, what could it mean for the whole Ethereum ecosystem ?


texts: GPU issues w/Claymore dual miner (eth/sia)

texts:
Wondering if anyone can help me please...

Been running stable for some time on 9.5 (6x Strixx ROG 8GB OC GPU's) running around 27.8M/H each dual mining Eth and Sia.

I tried v9.6 and used the following when running Claymore: -cclock 1000 -mclock 1850 -cvddc 850

Shortly after starting it, my rig crashed and struggled to come back to life. Best I've been able to do is have any 2 of the GPU's connected at once for it to work.

Starting Claymore without (-cclock 1000 -mclock 1850 -cvddc 850) seems to be resulting in both GPU's running at around 29M/H. Connecting anymore than 2 GPU's and my rig is unstable, either Win10 doesn't load properly (graphics look knackered - can only see mouse pointer on black screen) or Claymore crashes.

It seems like using -cclock 1000 -mclock 1850 -cvddc 850 to run Claymore once has saved settings on the cards that they don't like? is that even possible? If not, why would the rig not reboot fine with all 6 GPU's connected, surely it should be the same as before? or why are the 2 GPU's running at a higher M/H when I'm running Claymore as I did before using those switches.

Has anyone experienced this before?

Any guidance would be greatly appreciated.

Cheers


texts:
Created 3 accounts as follows:

$ eth account new

Couldn't open wallet. Does it exist?
Enter a passphrase with which to secure this account:
Please confirm the passphrase by entering it again:
Created key 0d3860d4-48b0-2a5e-9677-2e3407f41a48
  ICAP: XE173DQUQX2GT7YB1KPVK75A7RO17YCS2F
  Address: {00cde0300ff89aac1850e1d1c02929ba9bf70717}

$ eth account new

Couldn't open wallet. Does it exist?
Enter a passphrase with which to secure this account: person
Please confirm the passphrase by entering it again: person
Created key a50567a5-456e-2162-781b-e75fddc54a12
  ICAP: XE411X0X8K6BJ8AJ28HXU9Q0EX3J7GOPKH
  Address: {0074b96916bf30f7484ec6510923d33d13881371}

$ eth account new

Couldn't open wallet. Does it exist?
Enter a passphrase with which to secure this account: miner
Please confirm the passphrase by entering it again: miner
Created key 1e6674fd-bbf3-d7c3-b608-ec2d74260013
  ICAP: XE381P6BO9O6ZGEMM8XY0NXKSVHIYGWO8M
  Address: {006773224bca7cdfca7a487964a5861543bb7ab6}

Not sure why the message:

Couldn't open wallet. Does it exist?

Then start a private blockchain peer:

$ eth -j --no-ipc --json-rpc-port 8081 -a '006773224bca7cdfca7a487964a5861543bb7ab6' --client-name 'test' --listen-ip 127.0.0.1 --listen 30001 --network-id 12321 --no-discovery

Try to list the accounts using the following command:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}' htt://127.0.0.1:8081

Get back the following response:

  {"id":1,"jsonrpc":"2.0","result":["0x00a81525276c4e9e1b517e2fff7f7e2a979c3bbb"]}

Was expecting to see my 3 accounts. Any help appreciated.


texts: How to get a nested map value from web3.js?

texts:
In contract:

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

How to retrieve spentLimit[a][b] for given a and b from web3.js?


texts:
I have a betting contract, such that each week the prior week's bets are no longer relevant. I'm thinking about the most efficient way to store and process these bets. The alternatives are many, and so I just want to present my favorite and see if there are any obvious deficiencies. I have simplified/omitted things to be clear, hopefully not too much. I'm leaning towards a method that puts new bets into separate dynamic arrays, and then deleting them each week.
Dynamic arrays capture the relevant data: when the bettor puts 1.45 ETH on the Chicago Bears to beat the point spread. The are dynamic arrays, state variable:
address[] public bettorAddress; // eg, 0x123...
uint[] public betAmount;        // eg, 145e16
uint[] public betPick;         // eg, 7

For any bet the relevant data needed to process are all in the same slot, as each bet is processed with a method such as the following:
function takeBet(bet1, team)
    external
    {
    betAmount.push(bet1);
    bettorAddress.push(msg.sender);
    betPick.push(team);
 }

I can process the winners and losers in a loop by running it in chunks (say, 100 max). A variable (loopCounter in this example) is set to zero each week. At the end of the week, each team corresponds to a slot in the bool array resultsVector to indicate whether the bettor won or not (eg, if the Chicago Bears are team #7, 'resultsVector[7] = true' if the Bears beat the spread).
Thus, if there are 589 bets, and processing 100 bets costs 4e6 in gas, that's 6 separate transactions if I break it into chunks of 100. The settlement function would work as follows:
  function settleBook()
        external
        {
        uint top = min(loopCounter + 100, betAmount.length);
         // other code...
        uint i;
 /** state variable loopCounter = 0 at start
 **/
                for (i = loopCounter; i < top; i++) {
 /** results for 32 teams updated outside this function, in state variable: bool public resultsVector[32]
 **/
                    if (resultsVector[betPick[i]]) {
 /** processes the results by giving bettor[i] appropriate credit for his successful pick. State variable bettorBalance defined as: mapping(address => uint) public bettorBalance
**/
                        bookiePot -= betAmount[i];
/** state variable bettorBalance defined as:  mapping(address => uint) public bettorBalance;
**/
                        bettorBalance[bettorAddress[i]] += betAmount[i];
                    }
                }
/** advance the loopCounter to start at the next unprocessed bettor on the next function call
**/
                    loopCounter = i;
/** if all done, delete and reset loopCounter for the next week
**/
                    if (i == betAmount.length) {
                        // other code....
                        loopCounter = 0;
                        delete betAmount;
                        delete bettorAddress;
                        delete betPick;
                    }
  }

It works, but my biggest concern is that while it seems linear, I'm not sure it is: if I had 8765 bets, requiring 88 function calls to ultimately process, would this still work?
I could require users to process their bets, which breaks it up into single calls. Yet, some would not respond, and then I would need a method to purge lazy/distracted user data that creates problems. Further, it's more gas efficient to process them all at once.
Criticisms and suggestions welcome.


texts: DeclarationError:Identifier not found or not unique

texts:
pragma solidity >=0.4.22 < 0.6.0;
pragma experimental ABIEncoderV2;

contract BloodDonationProcess {
    struct LongTermInformation {
        bool allergies;
        bool diabetes;
        bool piercing;
        bool gay;
        bool transfusionRelatedAcuteLungInjury;
        bool drugs;
        bool cancer;
    }
    struct ShortTermInformation{
        bool childBirth;
        bool cholestrol;
        bool dentist;
        bool soreThroat;
        bool tickBite;
        bool cold;
        bool vaccination;
    }
    struct Person{
        string name;
        uint age;
        uint weight;
        LongTermInformation longTermInformation;
        ShortTermInformation shortTermInformation;
     }

    mapping (address => Person)person;
     Person tempPerson;

    constructor(string memory name,uint age,uint weight,LongTermInformation
 memory longTermInformation,
     ShortTermInformation memory shortTermInformation) public {
         tempPerson.name =name;
         tempPerson.age=age;
         tempPerson.weight =weight;
         tempPerson.longTermInformation =longTermInformation;
         tempPerson.shortTermInformation =shortTermInformation;
     }

     ShortTermInformation public shortTermInformation;
     LongTermInformation public longTermInformation;

     BloodDonationProcess bloodDonationProcess;

    function canDonate(Person memory p) public returns(bool) {
          return ((!p.longTermInformation.drugs) && (!p.longTermInformation.gay)) &&
         ((!p.shortTermInformation.soreThroat) && (!p.shortTermInformation.tickBite));
    }

    function _generateRandomNumber(Person memory p ) private view returns (uint) {
        uint rand = uint(keccak256(abi.encodePacked(p.name)));
        return rand;
    }

}
 ***this is the code I've written at the solidity remix and I've written the uinttest for that.***

pragma solidity >=0.4.22 <0.6.0;
import "./blood_donation_process.sol";

contract BloodDonationProcessUnitTest {

    BloodDonationProcess bloodDonationProcessToTest;
   function test (address account, uint age,string memory name,uint weight,LongTermInformation longTermInformation,ShortTermInformation shortTermInformation) public{
        tempPerson=person[_account];
        tempPerson.age=age;
        tempPerson.name=name;
        tempPerson.weight=weight;
        tempPerson.longTermInformation=longTermInformation;
        tempPerson.shortTermInformation=shortTermInformation;
    }

   function beforeAll () public {
        bloodDonationProcessToTest.shortTermInformation = ShortTermInformation(true,true,true,false,false,true,false);
        bloodDonationProcessToTest.longTermInformation = LongTermInformation(false,false,false,false,false,false,true);
        bloodDonationProcessToTest.personToTest = Person("Person1",25,75,shortTermInformation,longTermInformation);
        bloodDonationProcessToTest = new BloodDonationProcess(personToTest);
    }

    function shouldBeAbleToDonate() public {
        bool isAbleToDonate = bloodDonationProcessToTest.canDonate(personToTest);
        Assert.equal(isAbleToDonate,true);
    }
}

Unfortunately on the test i received the error of DeclarationError.
I would be thankful if someone can help me.


texts:
ethminer.exe -G -F
  poolurl/mywallet

it stops working at Grabbing DAG for #deb.

Mining is impossible...


texts: How to get the return value on a state altering function?

texts:
I'm playing around with ERC721 tokens.
I have this mint function in my contract that is supposed to return a value, but in my client app (using Web3), the result I get from this function call only contains the transaction id.
Here is the function :
    function mint() public returns (uint) {
        uint newId = currentTokenId + 1;
        _mint(msg.sender, newId);
        currentTokenId = newId;
        return currentTokenId;
    }

The point of this is just making an interface to issue/mint new tokens out of this smart contract.
Here is how I call it in my client app :
this.contract.methods.mint().send({from: this.account}, function(error, result) {
    console.log(result) // 0x08e...00d0
})

Am I missing something?
Am I misusing the Web3 framework?
Or maybe I just misunderstood the return statement in Solidity?


texts: go-ethereum: Return data from contract function

texts:
I have a smart contract written in solidity.  I deployed the contract to my Ganache network and I can interact with it via go-ethereum using stubs generated by abigen.  My function returns a uint256, what I want to do is see this contract return data via the stubs I have generated with abigen.

I can successfully interact with the contract.  I just want to know how to use the returned types.Transaction to obtain what my contract function returns - I am guessing the decode 'instructions' are in the generated abi.  thanks

    instance, _ := tictac.NewTictac(address, client)

    privateKey, _ := crypto.HexToECDSA("1234")

    transactOpts := bind.NewKeyedTransactor(privateKey)
    publicKey := privateKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)

    fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

    gasPrice, _ := client.SuggestGasPrice(context.Background())

opts := &bind.TransactOpts{
    From:     fromAddress,
    Signer:   transactOpts.Signer,
    Value:    big.NewInt(1),
    GasPrice: gasPrice,
    GasLimit: 1000000,
}

    types, _ := instance.StartGame(opts, "player1", true, big.NewInt(1))


texts: Is an ERC20 token more of an 'IOU' token or is it capable of being a stand-alone crypto?

texts: Say someone was to launch an ICO on the ethereum network. The token created, would that be better as an 'IOU' until I make a cryptocurrency to replace this one (due to ETH fees), or would it be capable of being a standalone crypto with its own wallet etc? Apologies if this seems ambiguous.


texts: how to find if a Tx hash is in pending state in ethereum mainnet after web3j fastTxMgr timeout

texts: I am using QueuingTransactionReceiptProcessor() with callback accept(). DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH is 10 and POLLING_FREQUENCY is 15000. That gives nearly 3 min wait for network to acknowledge. But I noticed that ethereum mainnet takes 8 to 10 minutes to give a response. At the end of timeout window (which leads to exception), i want to check if TxHash is still in pending state with the network and if so extend the timeout interval. Timeout does not really mean transaction has failed on the network. It could mean I need to wait for more time. it works fine on r


texts: What's the best way to check that events were fired in a Truffle test?


texts: Why was it necessary to develop Solidity?

texts: I am wondering why it was necessary to develop a whole new programming language for smart contracts. Stratis for example claims that C# can be used to write smart contracts. Couldn't Ethereum implement a compiler for any programming language? What is the advantage of Solidity over say C# etc?


texts: I think I owned some ether. Where can I find my keys?

texts:
I started messing around with the Ethereum geth client when the Ethereum main network was just launched. I remember I bought some ether for maybe €30 and then I kinda lost sight of the whole thing. With ether now being worth so much, that would mean it's worth a lot more than it was.

So I just went to look if I could find the keys on my Mac. According to this answer they should be in the ~/.ethereum/keystore/ folder
So I checked the ~/.ethereum/ folder, which unfortunately doesn't contain a keystore/ folder:

$ ls -la
total 16
drwx------    7 kramer65  staff   238 Aug  8  2016 .
drwxr-xr-x+ 145 kramer65  staff  4930 Jul 13 10:25 ..
drwxr-xr-x    4 kramer65  staff   136 Jun 29  2016 d4e56740
drwxr-xr-x    7 kramer65  staff   238 Aug  8  2016 devchain
-rw-------    1 kramer65  staff   165 Jun 29  2016 keys.info
-rw-------    1 kramer65  staff    32 Jun 29  2016 keys.info.salt
drwxr-xr-x    7 kramer65  staff   238 Jun 29  2016 natspec

I checked keys.info, but that only contains some binary data.

I messed around with private ethereum networks using geth, so it could be that I somehow overwrote or deleted the keys. But it would be cool if I could find them. Does anybody know where I can find my keys? All tips are welcome!


texts: Transaction Confirmations in the transactions log

texts:
I setup a private net where only 4 nodes are connected. But when I am doing transactions and checking my transactions log. I am getting hundreds of confirmations.
Who can see my private Ethereum blockchain transactions and confirming it?


texts: Withdrawing ethereum from a smart contract (return to sender)

texts:
Let's say I have a decentralized application that allows people to buy some object at an arbitrary price.

User 1 purchases the object for 1 eth. A few moments later, user 2 purchases the same item. How can I monitor for this event and automatically return the appropriate amount of etherium to user 2? Here's what I have so far:

contract Adoption {
    address[16] public adopters;

    function returnEth() public payable {
    msg.sender.transfer(msg.value);
    }
    // Adopting a pet
    function adopt(uint petId) public payable returns (uint) {
        require(petId >= 0 && petId <= 15);
        //require(msg.value == 1 ether);
        adopters[petId] = msg.sender;
        returnEth();
        return petId;
        //return value;
    }
    // Retrieving the adopters
    function getAdopters() public view returns (address[16]) {
        return adopters;
    }

}


texts: Solidity function returning large json object

texts:
So I have a basic function call in Solidity that returns a string

function getString() constant returns (string) {
  return "hello";
}

I call it using web3 after instantiating the contract

const Contract = new web3.eth.Contract(abi, contractAddress, {
  from: applicationAccount.address,
  gasPrice: '20000000',
  gas: 4711489
});

async function getString() {
  let hash = await Contract.methods.getString.call()
  return hash;
}

The object returned is a large object describing the contract, when all I want returned is the string hello

{ call: { [Function: bound _executeMethod] request: [Function: bound _executeMethod] },
send: { [Function: bound _executeMethod] request: [Function: bound _executeMethod] },
encodeABI: [Function: bound _encodeMethodABI],
estimateGas: [Function: bound _executeMethod],
arguments: [],
_method:
 { constant: true,
 inputs: [],
 name: 'getString',
 outputs: [ [Object] ],
 payable: false,
 stateMutability: 'view',
 type: 'function',
 signature: '0xb96d1702' },

How can I return the string hello?


texts: If I stored the blockchain in shared storage, can multiple miners work on it?

texts: So I have a crazy idea to speed up the mining process.   If I stored the blockchain in /data/ethData (which is on shared storage like a SAN), I can then mount it on multiple machines and then have miner workers go at it.    Do you think it's possible?


texts: What is the best way to represent infinity in Solidity?

texts: Solidity does not natively support infinity, so how would I represent infinity as a variable in Solidity? For example, if I wanted to write an implementation of Dijkstra's algorithm in Solidity it would need infinity.


texts: How can I convert natspec into human readable document from Windows and Linux?

texts:
How can I convert natspec into human readable document?

Doxity looks good, but I need something for Windows or Linux.


texts: How to get all my users stored in a smart contract in aim to display themn into a Dapp?

texts:
Let's consider the following:
struct SkillStruct{
  bytes32 skillName;
  uint index;
}

struct UserStruct {
  bytes32 userEmail;
  bytes32 userFirstname;
  bytes32 userLastname;
  uint index;
  uint amount; //amount of ECR token
  address[] userSkills;
}

mapping(address => UserStruct) private userStructs;
address[] private userIndex;

mapping(address => SkillStruct) private skillStructs;
address[] private skillIndex;

Is there a way to display all my users and theirs skills in an HTML list in my Dapp ? How can I process to get all my users ? What's the best for doing that ?
I tried to get inspired by https://www.cryptokitties.co/ source code, but all I found is a function to return kitten one by one but not all of them.
The only clue I see right now is to call a function to get users.length and then in an asynchronous loop call the getUser() function as many times as there are users. And then maybe use caching or localstorage to store them into the browser.
Is there a better way ??
Thanks u all


texts:
The following code is compiled with solc 0.3 with correct --libraries linking and deployed to morden. Math library is deployed just fine and can be accessed. However A doesn't get deployed on morden with geth 1.3.5.

// on morden at 0xcb264e62f89c121f785dc61daa97c1e3134a6653
library Math {
  function and(bool a, bool b) returns (bool c) {
    return a && b;
  }
}

contract A {
  function testTrue() returns(bool){
    return Math.and(true, true);
  }
}

The transaction is accepted and a contract address generated, but no code is left on the chain:

> web3.eth.getTransactionReceipt('0x65b7915ecfad660a2076fee5ac800c94864bf2b1edf3ecb4432971af994404b7')
{
  blockHash:     "0x8e2ebd5d9fe2588470bc699afb94a3488bd68772115abd7eafc509f1124179c9",
  blockNumber: 663022,
  contractAddress: "0x1d9b45e1519fef452e2fdab6a5aa75d8eee35f99",
  cumulativeGasUsed: 122279,
  gasUsed: 90000,
  logs: [],
  transactionHash:     "0x65b7915ecfad660a2076fee5ac800c94864bf2b1edf3ecb4432971af994404b7",
  transactionIndex: 1
}
> web3.eth.getCode('0x1d9b45e1519fef452e2fdab6a5aa75d8eee35f99')
„0x"

A is deployed with the following bytecode:
    606060405260938060106000396000f3606060405260e060020a60003504634e4fb1fa8114601a575b005b608a7f9f6ee0fc0000000000000000000000000000000000000000000000000000000060609081526001606481905260845260009073cb264e62f89c121f785dc61daa97c1e3134a665390639f6ee0fc9060a4906020906044818660325a03f41560025750506040515191505090565b50604051602090f3

EDIT: solved. trivial out of gas error.


texts:
I am trying to upload ensutils.js from https://github.com/ethereum/ens to my geth console. I am using loadScript('/home/path/to/ensutils.js').

Every time I try it, it gives me an invalid address error and I am not sure why. Would anyone happen to know what the issue is here. I have my default address set and the account unlocked.

loadScript('/home/path/to/ensutils.js')


texts: How does metamask choose the msg.sender?

texts:
When coding an application that looks to be metamask compatible how are multiple account handled by meta mask ? how can i make sure that metamask / my app are in sync account-wise ?

does metamask set the web3.eth.defaultAccount ?


texts: Enable a download only for an NFT holder?

texts: Could someone enable a download only for an NFT holder?   What would be the mechanism for this?