texts: Error: Cannot find module 'truffle-expect'——truffle migrate

texts:
Thanks to Kshitij's answer at another page! but I still have this error after applying this answer. which drives me crazy! Sorry for post the question as a answer-_-

After run truffle init and truffle compile, it works fine.
the contracts that I compile are examples from truffle:(when I change to HelloWorld it's the exactly same error)

ConvertLib.sol  MetaCoin.sol  Migrations.sol

other information is:

ubuntu 14.04.2
node -v v7.10.0
npm -c 4.2.0
Truffle v3.3.2 (core: 3.3.1)
Solidity v0.4.11 (solc-js)

Every time I run "truffle migrate" it shows Error, with or without testrpc running

error message:

Error: Cannot find module 'truffle-expect'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous>
    ...

installing truffle-expect won't work, would anyone give me a hand please?


texts: What is the simplest and fastest way to mine Testnet Ether on a Windows Machine

texts:
The more I read on this, the more I see lots of general answers that either point to Testnet Ether donations, claim they have no difficulty in mining a ton of Testnet Ether (in no time at all) or suggest a private Blockchain is used.

I have found a great Testnet Ether 'donation' site at: Ethereum Ropsten Faucet but I really wish to mine using the public Testnet (rather than a private Blockchain) to ensure a 'as close to reality' simulation as possible.

Expecting life to be simple, I have downloaded the Ethereum Wallet which is connected and fully synced with Testnet and I have enabled mining (little pickaxe showing) and nothing has occurred after a few hours...

From what I have read, I was under the impression I completed these steps and I would see Testnet Ether flowing in, but alas no.

I also don't mind using Geth CLI if that's simpler and more visible but I can't find specific instructions on how to do this.

If someone can point me at a decent modern guide (or write one) that clearly communicates the dos and don'ts then I'd be delighted to complete the steps, create a video and get it live to help others out.


texts: Dapp User Account Storage and IPFS/infura

texts:
I'd like to build a dapp utilizing the power of the Ethereum blockchain and IPFS. Right now, my plan is to have users sign up to use the app and store their account data + files on IPFS through a public infura  node.

I understand that any monetary transactions between users will be handled through solidity smart contracts on the main chain, however, I don't understand whether or not I'd want the account on the blockchain as well. If I understand correctly, this would require users to pay ETH to create an account. Why not just store account data completely on IPFS for free and use the blockchain solely for sending and receiving ETH? What benefits would come with storing each user's IPFS hash on the blockchain?


texts: Why doesn't this function work and is there another way to do it?

texts:
For the function getAllcars, I wanted to return a struct array.  However, it seems this cannot be done (yet).  I attempted a workaround by using a recursive function which returns the details of each Customer one by one; the uint getCarsID starts at zero and is incremented with each loop until it is greater than the number of customers in the array (CarOwnerID), at which point it resets the value of getCarsID to zero so that it can be used again later.

Remix accepts this code when compiled and doesn't raise any issues when I execute it, but it doesn't actually return anything.  I half-expected this not to work anyways, but I can't put my finger on why.  Did I miss something?  And if this cannot be done, is there another way to return all of the information in a struct array at once?

// <----------------------- END MEMBERS ----------------------->

struct Customer {

address addr;
string custname;
string color;
string make;
uint16 year;
string license;

}

// < -------------------------- CARS -------------------------- >

uint8 CarOwnerID;
Customer[] public carowners;
mapping(address => uint8) addressIndex;
mapping(string => uint8) licenseIndex;

function newCarOwner(address _address, string _custname, string _color, string _make, uint16 _year, string _license) onlyMember public {

carowners.push(Customer(_address, _custname, _color, _make, _year, _license));

addressIndex[_address] = CarOwnerID;        //Testing to see if we can switch what
CarOwnerID = licenseIndex[_license];        //is on each side of the equation.

CarOwnerID ++;

}

function getCarByAdd(address _address) public view returns(address, string, string, string, uint16, string) {     // We must return each element in the struct
    return (                                                                                // because we cannot return an entire struct (for now)
        carowners[addressIndex[_address]].addr,              // Notice - when returning elements of an array, use "," after each
        carowners[addressIndex[_address]].custname,          // element instead of ";", and put nothing after the last element.
        carowners[addressIndex[_address]].color,
        carowners[addressIndex[_address]].make,
        carowners[addressIndex[_address]].year,
        carowners[addressIndex[_address]].license
        );
}

function getCarByLic(string _license) public view returns(address, string, string, string, uint16, string) {
    return (
        carowners[licenseIndex[_license]].addr,             // While we can return whole arrays (ex. return carowners[];), and we can return specific indexed items
        carowners[licenseIndex[_license]].custname,         // such as uint returning array[3], array[4], etc., we cannot return a specific item if it is a struct.
        carowners[licenseIndex[_license]].color,            // AKA if array[3] is a struct, we cannot say return array[3], but must say "return array[3].param1, array{3].param2, etc.
        carowners[licenseIndex[_license]].make,             // See DOC1 in NOTES
        carowners[licenseIndex[_license]].year,
        carowners[licenseIndex[_license]].license
        );

}

 uint8 public getCarsID;

function getAllCars() public returns(address, string, string, string, uint16, string) {
    return (
        carowners[getCarsID].addr,
        carowners[getCarsID].custname,
        carowners[getCarsID].color,
        carowners[getCarsID].make,
        carowners[getCarsID].year,
        carowners[getCarsID].license
        );

        getCarsID ++;

        if (getCarsID <= CarOwnerID) getAllCars;
        else (getCarsID = 0);
}

function countCars() public view returns (uint) {
    return carowners.length;
}


texts: Can a smart contract function prompt different entities for some input

texts: Let's say that in my system I have different nodes. In regular intervals some of these nodes can be chosen as "gold nodes" which means for example that they need to do some computations. Is it possible to make a smart contract function that accepts an input from each "gold node" and runs only after every "gold node" put its input?


texts: Who publishes the default DNS discovery list

texts:
Geth v1.9.11 introduced support for DNS discovery. According to the code, the default DNS list is hosted on ethdisco.net. See also: https://github.com/ethereum/discv4-dns-lists

Who publishes this list and who has access to the private keys with which this list is signed?


texts: Is there an issue using event overloading and event logs that contain arrays?

texts:
My event fires, but the last parameter is never logged. It appears as if it doesn't even exist. Here is my solidity code:

pragma solidity >=0.5.6;

contract EventTest {
  event marketCreated(address[] virtualShareAddresses, address market, uint256 indexed endTime, string description, string extraInfo);//categorical
  event marketCreated(address[2] virtualShareAddresses, address market, uint256 indexed endTime, string description, string extraInfo);//binary
  event marketCreated(address[2] virtualShareAddresses, address market, uint256 indexed endTime, string description, string extraInfo, int256 _minPrice, int256 _maxPrice, uint256 _numTicks);//scalar

  function createYesNoMarket(
    uint256 _endTime,
    string memory _description,
    string memory _extraInfo
    ) public payable returns (bool)

  {
    address[2] memory virtualShareAddresses;
    address newMarket = address(0);
    virtualShareAddresses[0] = address(1);
    virtualShareAddresses[1] = address(2);
    emit marketCreated(virtualShareAddresses, address(newMarket), _endTime, _description, _extraInfo);
    return true;
  }
}

here's how I'm calling the event with web3.js:

contract.methods.createYesNoMarket(1575158400, "Will it rain on Friday in Sacramento California?", "foo").send({from: '0x5680CA2e3b4F8bC043aCeB31837c89DbA8bFBa75', gas: 6000000}, (error, hash) => {
  console.log(hash)
  console.log(error)
})

and here's my event.returnValues logged to the console:

{ '0':
   [ '0x0000000000000000000000000000000000000001',
     '0x0000000000000000000000000000000000000002' ],
  '1': '0x0000000000000000000000000000000000000000',
  '2': BigNumber { _hex: '0x5de30280' },
  '3': 'Will it rain on Friday in Sacramento California?',
  endTime: BigNumber { _hex: '0x5de30280' },
  virtualShareAddresses:
   [ '0x0000000000000000000000000000000000000001',
     '0x0000000000000000000000000000000000000002' ],
  market: '0x0000000000000000000000000000000000000000',
  description: 'Will it rain on Friday in Sacramento California?' }

As you can see the extraInfo field is never logged. Anyone know why this is?


texts: The contract code couldn't be stored, please check your gas amount. [Zeppelin, Truffle.js, Ropsten]

texts:
I am having some problem with deploying the simple Token Contract to Ropsten network.

Error is "The contract code couldn't be stored, please check your gas amount".

I tried to change Gas values many times in "Truffle.js" file, also seems like I don't have any abstract functions in "TestToken.sol" file.

Software is up to date.  But I still can't figure out what's the problem, I am just a beginner, so please help me out, would highly appreciate!

// truffle.js
require('dotenv').config();
const HDWalletProvider = require("truffle-hdwallet-provider");
module.exports = {
  networks: {
development: {
  host: "localhost",
  port: 9545,
  gas: 6712390,
  network_id: "*"
},
ropsten: {
    provider: function() {
      return new HDWalletProvider(process.env.MNENOMIC, "https://ropsten.infura.io/" + process.env.INFURA_API_KEY) },
    network_id: 3,
    gas: 4700000,
    },
  }
};

//TestToken.sol

pragma solidity ^0.4.24;

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

contract TestToken is ERC20Basic {
    using SafeMath for uint;
    string public name;
    string public symbol;
    uint8 public decimals;
    uint public _totalSupply;

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

    function TestToken() public {
        name = "TestToken";
        symbol = "tttest";
        decimals = 18;

        _totalSupply = 4000000000000000000000000000;
        balances[0xE3FdfaAF08F4778c7E88Ed1E31696745ed610328] = _totalSupply;
        Transfer (address(0), 0xE3FdfaAF08F4778c7E88Ed1E31696745ed610328, _totalSupply);
     }
}


texts:
I'm trying to understand how to convert my transaction data into the id hash before signing the transaction.

Let's say I have this data:

transaction = {
    'to': to_address,
    'from': from_address,
    'value': 4200000000000000,
    'gas': 21000,
    'gasPrice': 22000000000,
    'chainId': 1,
    'nonce': '0x0'
}

How can I convert this into the id hash?


texts: How to read data returned by a function?


texts:
I need to deploy a lot of typical contracts with identical functionality.
Is there a way for extending the already deployed contract in solidity?
I hope to make a single big contract with main functionality and extend it in all next contracts to save a gas


texts: Measuring deployment time of a group of transactions in a heavy load testing

texts:
I am currently trying to perform heavy load testing on a ERC20 token. My plan is to use truffle to test stuff like how long it would take for 500 transfer transactions to be deployed (on a private blockchain), maximum number of transactions per second and ideally some tests on scalability by including transactions from multiple nodes. Below is my code for running 500 transactions

const EnergyToken = artifacts.require("EnergyToken");
const assert = require('assert');
const truffleAssert = require('truffle-assertions');
const { performance } = require('perf_hooks');

const numberOfTransactions = 200;
contract("Energy Token Test3 ", async accounts => {

     it("send $numberOfTransactions transactions from account 0 to account 1", async () => {

       let contract = await EnergyToken.at("0x5BbD383bD43aC3896B86207eFe88cf0628ad06F0");

        for (let i = 1; i < 1 + numberOfTransactions; i++) {
           let t0 =performance.now();

             contract.transfer.sendTransaction(accounts[1],1,{from: accounts[0]});

            let t1 = performance.now();
            console.log("Transaction " + i + " ***** From:" + accounts[0] + " ***** To: " + accounts[1] + "took " + (t1-t0) + " ms" );

        }

    });

The problem is that right now I am measuring the time it takes to submit those transactions, rather than how fast they are deployed. I tried using await before contract.transfer but then transactions are processed 1 by 1 (1 tx per block) and it also takes an enormous amount of time. My question is if there is a better way of measuring the time?


texts: Error set address/adding data, error: "gas required exceeds allowance or always failing transaction and the function doesn't work"

texts:
I'm trying to do a data access control system with smart contract. I have 3 entity:

Client: who can get data and set address of Oracle
Oracle: who can add data and have getData() function
RBAC: Role based access control, who manage permission

The system has also 2 interfaces for Oracle and RBAC for principal functions. When I test the system on JavaScript VM (on Remix) all is okay and I haven't problem. But when I trying to deploy this system on my private blockchain it's doesn't work. When I trying to set the Oracle address in the client contract I have the problem: "gas required exceeds allowance or always failing transaction and the function doesn't work". I checked if I used the correct account (is a function callable only by the owner of the contract) and is ok.

Here my setOracleAddress() function code (in client contract):

//data oracle
address internal oracleAddr = 0x0000000000000000000000000000000000000000;
OracleInterface internal oracle = OracleInterface(oracleAddr);

    function setOracleAddress(address _oracleAddress) external onlyOwner returns (bool) {
    oracleAddr = _oracleAddress;
    oracle = OracleInterface(oracleAddr);
    return oracle.testConnection();
}

Here's the testConnection() code (in oracle contract):

/// @notice can be used by a client contract to ensure that they've connected to this contract interface successfully
/// @return true, unconditionally
function testConnection() public pure returns (bool) {
    return true;
}

In my genesis blockchain block I've the follow gas limit:

"gasLimit"   : "0x8000000",

Here's how I get the Oracle address:

/// @notice gets the address of this contract
/// @return address
function getAddress() public view returns (address) {
    return address(this);
}

Modifier onlyOwner() code:

  /**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

I tried to increase the gasLimit in genesis block, to check the correct account and to update the software (truffle, geth, web3).

EDIT:
I solved the problem of setting the address by adding to the genesis file the line

"ByzantiumBlock":0

But now I get the same error when I try to add test data.

Here's the code of addData() function:

    /// @notice puts a new pending data into the blockchain
/// @param name descriptive name for the data (e.g. House001)
/// @param otherInfo about something like address (e.g. "Via roma 6, Torino")
/// @param sensorData sensor data
/// @return the unique id of the newly created data
function addData(string memory name, string memory otherInfo, uint sensorData,  uint permissionMin, uint date) onlyOwner public returns (bytes32) {

    assert(permissionMin < rbac.getNumRole());

    //hash the crucial info to get a unique id
    bytes32 id = keccak256(abi.encodePacked(name,otherInfo,date));

    //require that the data be unique (not already added)
    require(!dataExists(id));

    //add data
    uint newIndex = data.push(Data(id, name, otherInfo, sensorData, permissionMin, date, false))-1;
    dataIdToIndex[id] = newIndex+1;

    //return the unique id of the new data
    return id;
}

Get numRole() function code:

uint numRole = 3;

 function getNumRole() public view returns(uint){
     return numRole;
 }

Struct Data code:

//defines a struct "Data"
struct Data {
    bytes32 id;
    string name;
    string otherInfo;
    uint sensorData;
    uint permission;
    uint date;
    bool read;
}

Example of addData():

    /// @notice for testing
function addTestData() external onlyOwner {
    addData("House001", "via Roma 2, Milano", 0,1, 20190504);

Error when forcing the execution

Any help? Thanks!!


texts: What is the max ethereum allowed in a private network for the whole network?

texts: When I build a private chain setup, what is the maximum Geth ethereum I can have for the life of the network.  Another way of asking the question would be: What is the maximum ethereum one account can have?  What is the maximum ethereum all accounts collectively can have? On the same note, what is the maximum number of blocks I can have?


texts: ethereum wallet and mist both download separate blockchain?

texts:
I am on OSX using a mac pro.
I downloaded and installed mist, before ethereum wallet (ew) on advice from an ether forum. Mist started downloading the blockchain. It took up too much space on my SDD so I moved my home folder to another directory and decided it made sense to have a working wallet first, so I installed EW and it started downloading the blockchain, but to a different location to mist.

To clarify, EW is downloading to:
Library/Ethereum/gethchaindata

Mist has previously stored it to:
Library/application support/Mist/swarmjs/swarm/(long folder name)/chunks

should they not both point to the same geth folder?
If I run mist anew will it download the entire blockchain again, separately? confused. thanks


texts: With web3 how would I get transaction AND function result?

texts:
I'm using testrpc, truffle, and web3 in Node. I've written my contract and pushed it to testrpc with truffle. Here's the gist of the Node code I have so far:

let fs = require('fs');
let Web3 = require('web3');
let web3 = new Web3();
let settings = require('./settings.json'); // my own settings file

let abiContractContent = fs.readFileSync(settings.contractAbiPath, 'utf8');
let abi = JSON.parse(abiContractContent);
let contract = web3.eth.contract(abi).at(settings.contractAddress);

web3.eth.defaultAccount = web3.eth.accounts[0];

I've then found two ways to call a function in my contract:

contract.myFunc(param1, param2, { gas: 200000 });

which returns what I believe is the transaction ID for the changes caused by that function call.

contract.myFunc.call(param1, param2, { gas: 200000 });

which gives me the actual return value of myFunc.

I would like to have all of these pieces of information: the transaction AND the return values. I imagine I would need to call my function using the first approach and then look up the return values using the transaction ID but I have no idea how to actually do that. Am I on the right track or should I be looking for an entirely different approach?


texts: How to access string arguments from calldata in external functions? (0.5.X)

texts:
With the introduction of Solc 0.5.X , parameter memory locations for arrays (and strings/bytes) must be made explicit. For external functions, this memory location is required to be specified as calldata (as per docs).

My question is, how to convert the following function to be 0.5.X compatible and access the properties from within the function body. In addition, what changes (if any) will this have to how we call the method and pass the args?

0.4.X

function accessTheString(string _uri)
external {
    contractString = _uri;
}

0.5.X

function accessTheString(string calldata)
external {
    // check for && access the string
}


texts: calculate 24h trading fees of an Uniswap LP Token

texts:
greetings I would like to calculate how much fees an uniswap trading pair generated over 24h like in this table: https://info.uniswap.org/pairs
I guess I would have to iterate over all blocks from the past 24h and then analyze the in and out of that particular LP Token address.
before I dive deep into this and code everything from scratch I'd like to know if there are any scripts/frameworks around that make this easier or already doing what I want to code?


texts: How to query for all pending txs in web3

texts:
I've been mining testnet in http://testnet.oracles.org:4000/tx/pending Proof-of-Authority network.
I'd like to know how to query for all pending txs using web3.js


texts: How end user interact with ICO crowd sale Dapps Application?

texts:
I am new to Ethereum blockchain. I have queries regarding ICO(Initial Coin Offering) plateform. I understood basic meaning of ICO.

Suppose I have own startup company. I needs funds for development of company. So, First I create my own ethereum crypto-currency and release ERC20 based tokens on ICO crowd sale. Who buy ERC20 token he gives me crypto money. I used this to develop my company. In this case I have two query.

First Query:-

When Investors come on ICO crowd sale. He buy my ERC20 tokens. What and How he use tokens??

Second Query:-

When I got funds to investors. I got funds in form of ether cryptocurrency. So, How I use this cryptocurrency to development of company. How I will convert ether cryptocurrency to Rupee or Usd


texts:
How do I get web3 currentProvider HTTP URL? I'm using web3 1.0.0-beta.34. I tried many functions and already looked at the docs - but still couldn't find the right way to get the URL of the current HTTP RPC node.

The pseudocode that I'm looking for:

if (is_using_http_rpc_fn) {
  return currentProvider.url;
}

What functions to call for is_using_http_rpc_fn and currentProvider.url in above pseudocode?


texts:
pragma solidity ^0.5.3;

contract SimpleFallback{
    event FallbackCalledEvent(bytes data);
    event AddEvent(uint a, uint b, uint result);
    event DoubleEvent(uint a, uint b);
    event GetNameEvent(string);

    function() external{
        emit FallbackCalledEvent(msg.data);
    }

    function add(uint a, uint b) public returns(uint){
        // assert(a >= 0);
        // assert(b >= 0);
        // assert(a + b > a && a + b > b);

        uint _result = a + b;
        emit AddEvent(a, b, _result);

        return _result;
    }

    function double(uint a) public returns(uint){
        // assert(a >= 0);
        // assert(2*a >= 0 && 2*a >= a);
        uint _result = 2*a;

        emit DoubleEvent(a, _result);

        return _result;
    }

    function getName(string memory name) public returns(string memory){
        emit GetNameEvent(name);

        return name;
    }
}

contract RunTest{

    function callAddlTest(address other) public {
        // bytes4 messageId = bytes4(keccak256("add(uint, uint)"));
        // other.call(messageId, 5, 60);
        other.call(abi.encodeWithSignature("add(uint,uint)", 85, 60));
    }

    function callDoublelTest(address other) public {
        // bytes4 messageId = bytes4(keccak256("add(uint, uint)"));
        // other.call(messageId, 5, 60);
        other.call(abi.encodeWithSignature("double(uint)", 100));
    }

    function callgetNameTest(address other) public{
        other.call(abi.encodeWithSignature("getName(string)", "hello"));
    }
}

Operation as below.

Step 1. deploy 2 contracts;
Step 2. call callAddlTest whit contract SimpleFallback's address, event log is as below, which showed that called add() failed, the fallback function was triggered.

[
    {
        "from": "0x038f160ad632409bfb18582241d9fd88c1a072ba",
        "topic": "0x5cd57a899be814fb3a40e18f9d1ba77420bbd22073d35165511f750aa70538b6",
        "event": "FallbackCalledEvent",
        "args": {
            "0": "0xb89663520000000000000000000000000000000000000000000000000000000000000055000000000000000000000000000000000000000000000000000000000000003c",
            "data": "0xb89663520000000000000000000000000000000000000000000000000000000000000055000000000000000000000000000000000000000000000000000000000000003c",
            "length": 1
        }
    }
]

Step 3. call callDoubleTest whit contract SimpleFallback's address, event log is as below, which showed that called double() failed, the fallback function was triggered.

[
    {
        "from": "0x038f160ad632409bfb18582241d9fd88c1a072ba",
        "topic": "0x5cd57a899be814fb3a40e18f9d1ba77420bbd22073d35165511f750aa70538b6",
        "event": "FallbackCalledEvent",
        "args": {
            "0": "0xd524bc570000000000000000000000000000000000000000000000000000000000000064",
            "data": "0xd524bc570000000000000000000000000000000000000000000000000000000000000064",
            "length": 1
        }
    }
]

Step 4. call callgetNameTest whit contract SimpleFallback's address, event log is as below, which showed that called getName() successfully.

    {
        "from": "0x038f160ad632409bfb18582241d9fd88c1a072ba",
        "topic": "0x26c73f7f14382f5db0b9f94dd29ff8938f2e4be69fb13e0825ece287e8e538d5",
        "event": "GetNameEvent",
        "args": {
            "0": "hello",
            "length": 1
        }
    }
]

Question:

for call(abi.encodeWithSignature()), why:
  - 1)other.call(abi.encodeWithSignature("add(uint,uint)", 85, 60)); did not work?
  - 2)other.call(abi.encodeWithSignature("double(uint)", 100)); did not work?
  - 3)other.call(abi.encodeWithSignature("getName(string)", "hello")); did work?
  - 4) does encodeWithSignature not support multiple parameters, compared 1) and 3)?
       and does encodeWithSignature not support a uint parameters, compared 2) and 3)?


texts: Does the OpenZeppelin project offer security audit services for other projects and companies?


texts:
In my smart contract, I have a function that sends ether to the caller using the msg.sender.send() function.  I need to check that the value being returned by the function is correct (i.e. the amount is being calculated as expected).  How can I do this in a truffle javascript test?  I am managing to call the function etc, but I cannot seem to be able to read the value received (I need to replace the result.value call in the assertation below with the correct way to read the value received).

it('Check value received', function () {
    let meta;
    return MyContract.deployed().then(function (instance) {
        meta = instance;
        return meta.claimBalance(1, { from: accounts[0], gas: 1000000 });
    }).then(function (result) {
        assert.equal(expectedValue, result.value, "Incorrect value received");
    })
})


texts: Building a stadium with the Ethereum technology

texts:
Hristo Botev Stadium

Due to developments initiated by a group of politicians and oligarchy with alleged ties to the mafia, the construction of the new Hristo Botev stadium has been stopped since 2014. For four years, the most famous stadium in Plovdiv has been left at semi-finalized state.

Since 2014 the fans of the club,united in an official organizarion, own the club and the respective concession contract related to the Hristo Botev stadium.

Naturally, fans are looking for a way to finance the finalization of the stadium. Therefore, I would like to ask if there is a way to finance the completion of the stadium via the Ethereum technology?
Regards,
Teodor


texts: If I have a Contract A receiving 50000 'XXX' tokens from a contract B, those tokens are supposed to be distributed across 5 whitelisted users who has pooled 'xx' Ether into contract A, how can I make sure they get the correct amount of tokens? not sure how to calculate this, cheers.


texts: How do I add more gas to transaction in the Ethereum Wallet?

texts: I'm trying some things out in the ethereum wallet but it keeps guessing the amount of gas wrong. How do I send more gas in the ethereum wallet?


texts: Continuous Integration / Continuous Delivery (CI/CD) for Smart Contract Development with Solidity?

texts:
I am setting up private ethereum (Quorum) and I am trying very hard to see if one could setup a Continuous Integration / Continuous Delivery (CI/CD) infrastructure for Smart Contract Development?

Currently I am using truffle to compile and migrate my smart contract to quorum. I wish to automate that process.

Has anyone done CI/CD with solidity?


texts: Does each ERC-721 token have its own address?

texts:
I'm trying to create NFTs (non-fungible tokens), but I don't quite understand this part - is each token its own contract? or are all of them stored in the NFT equivalent of a 'balances' mapping in a factory contract?
If these are both options which is better?


texts: Solidity: substitute for returns (strings[])

texts:
I have a mapping

mapping (address => string[]) myMap;

How can I return the list of all the strings associated to a given address?

I know that in Solidity one can't return an array of strings, but what I would need to do is like

function get(address _addr) public returns (string[]){
       return myMap[_addr];
}


texts:
I have started to received this error today.

MetaMask no longer injects web3.

I understand the reason, and from my reading, I can continue to use the web3.js API, although it is no longer injected automatically. I am not however finding any example on what is the best approach and actually how to manually bring my own web3.js library to interact with the provider. Also, is web3.js still the best library to use as a convenience library today, or is ethers.js a better option?
Thank you. J


texts:
I'm using the abigen tool to interact with smart contracts in golang and am a bit confused about the Pending variable in the CallOpts.

I've been searching around for documentation about the argument but couldn't find anything. The godoc specifies this.

type CallOpts struct {
    Pending bool           // Whether to operate on the pending state or the last known one

What exactly is the pending state? Most examples have this set to true but i'm not sure why.


texts: Concurrent calls to a contract - state changes

texts:
So user a and user b both call a function (transaction) on a deployed contract with the code as bellow.

uint numberA;
uint numberB;
address playerA;
address playerB;

function playANumber(uint number){
    if(msg.sender == playerA && numberA == 0 && number > 0){
        numberA = number;
    }
    if(msg.sender == playerB && numberB == 0 && number > 0){
        numberB = number;
    }
    if(numberA > 0 && numberB > 0){
        //dosomething
    }
}

Will the part in "do something" always get called and if not, how can I make sure that it will. Or should it be split in two, setting the number and another transaction or call to execute the code in "do something"?

I have a contract with a similar setup and 90% of the time it works but theres also that 10% where the transaction clientside does not error but when I look at the state of the contract only numberA or B is set.

EDIT:

So I'm using truffle to call a deployed contract. PlayerA and PlayerB are simultaneous calling the contract. If I just rely on a successful transaction and don't explicitly check the state only the state change of one player is actually persisted. I use two different browsers for each player. The following pseudocode is used to call the contract and then check the change. Retrying after checking if the change actually is present does get the others player number in the contract and then the dosomething part is called.

contract.playANumber(1, {from: "someAddress"})).then( (tx) => {
                                 console.log(tx);
                                 return contract.getTheNumbers.call({from:"someAddress" });
                             })
                            .then( numbers=>{
                                if( (numbers.A > 0 && iAmPlayerA()) ||
                                    (numbers.B > 0 && !iAmPlayerA() ){
                                    console.log('state is ok');

                                } else{
                                    console.log('oops try again later');
                                }
                            })

Output of Player A:

Output of Player B:


texts:
If I'm building a dapp, is it worthwhile to store information that is in the contract on a server for speed purposes, and only using the contract to track ownership of tokens.

I.e. for something like Cryptokitties, could you store a mapping of userId->[kittenIds] and kittenID->userId on a central server that reads from the blockchain so that the user has to make calls to the blockchain less frequently?

Or, should it be left to the user's ethereum client to execute the public functions of the contract?


texts: Why the amount of ethers in the block chain(Private) increasing?

texts:
I have set up a private block chain. I started to mine on this network. Now the number of ethers in the coinbase account is continuously increasing. How is it getting ethers? Do the blockchain generate new ethers to reward the miner?
If so wouldn't it result in the inflation.


texts: What is the distinction between libp2p, devp2p and RLPx?

texts:
What is the distinction between libp2p and devp2p? Do they refer to the same thing? How are they related to RLPx?

In the libp2p whitepaper, dated Nov 2014, they appear to be the same thing:

  libp2p (aka ÐΞVp2p) aims to provide a lightweight abstraction layer
  that provides these low-level algorithms, protocols and services in a
  transparent framework without predetermining the eventual
  transmission-use-cases of the protocols.

In the Devcon 2 presentation "libp2p ❤ devp2p":

  libp2p is the modular secure networking suite that powers IPFS....

and

  devp2p is the secure networking suite that powers Ethereum....

I'm guessing the second link is more up-to-date and that the whole thing is evolving as I type. Perhaps the IPFS libp2p was born out of the Ethereum one linked above (or vice versa). Can anyone give summaries of libp2p and devp2p, including where they came from, what they are used for and what the main differences are, along with links to their official specifications?

Finally, how does RLPx fit in with devp2p? The docs describe it like this...

  RLPx is a cryptographic peer-to-peer network and protocol suite which
  provides a general-purpose transport and interface for applications to
  communicate via a p2p network. RLPx is designed to meet the
  requirements of decentralized applications and is used by Ethereum.

... which sounds like what I had imagined devp2p to be doing. Is there a high level description of what libp2p, devp2p and RLPx are and how they fit together?

Other links:

https://ethereum.gitbooks.io/frontier-guide/content/devp2p.html

https://github.com/libp2p/libp2p

https://github.com/ethereum/devp2p

RLP versions (Jul 16) https://ethereum.stackexchange.com/a/7221/820

Ethereum protocols mapped to OSI https://ethereum.stackexchange.com/a/9923/820

What underlying protocols are used to send packets between nodes, and how are messages encrypted?


texts: I sent My ETC to my ETH address on atrezor

texts:
I sent My ETC to my ETH address on a trezor
I read the explanation here on stackExchange and i understand i need the private keys, but I can't get the private keys on a trezor.
what should I do?

ps I am from the netherlands so sorry for my english


texts: Are Ethereum Contracts Vulnerable to Hash Table Poisoning Attacks?

texts:
Does anybody know something about this? I know that in general terms we will say not, but looking on the internet I found that isn't sure the answer to the question:
Can the EVM’s Internal Associative Array be Exploited?.

Which makes more sense, because a Hash Table poisoning attack may be "impossible" in terms of gas costs (at least this is how I see it, I'm not an expert on this subject)

If anyone knows about this, or any papers/articles related it'll be appreciated.

Thanks on advice!


texts: How to set rate in decimals in solidity?

texts: I want to set my price of token sale in ICO as 1 ether=0.0111111111. Since, solidity doesn't support decimals, what is suggested way to do that?


texts: If I scan the ETH blockchain, how do I know if the ETH addresses belong to ERC-20-compliant wallets?

texts: If I scan the ETH blockchain, how do I know if the scanned ETH addresses belong to ERC-20-compliant wallets?


texts:
According to my knowledge, GETH miners can fit many transactions on a block so long the total gas spend < block gas limit. However, in my lab network (private) when I bumped up miners gas limit from 4.7M (default) to 8,000,000 I still can't fit more transactions. I monitor ethstats and gas spending never go beyond 4.7M.

Did I miss any start up flags to allow gas spending/block go higher than default 4.7M?


texts:
Is there any way to suicide contract which was never designed for that?

If so what will happen with ethers that this contract is holding?


texts: I want to convert uint value to ether value (solidity)

texts:
My code:
uint money = (msg.sender).balance;
uint myUintValue = 20;
function getEther() public returns(uint) {
    money = money + 1 /* Istead of 1 my uint value*/ ether;
    return money;
}


texts:
I am trying to send ERC20 token to a different address.
I have stored Ethereum and ERC20 on the same wallet but with different address.

For Eg : At one Address am having 2.5 SKB (8 decimals)
on the another address am having 0.1 ETH.

Si when i try to withdraw the same 2.5 SKB am getting insufficient funds gas * price + value

here is my data parameters

        [from] => 0xfrom_address
        [contract] => 0xcontarct_address
        [value] => 0xee6b280 (2.5)
        [to] => 0xtoaddress
        [data] =>0xdata
        [gasPrice] => 0x77359400 (2000000000)
        [gasLimit] => 0x15f90 (90000)
        [gas] => 0x5208 (21000)


texts:
Using Ethereum Smart Contract i want to count incoming transaction from wallet A and after transactions count get to let's say 50 transactions release a single transaction to wallet B.

Let's say i've got 2 functions

    # Count transactions from the sender and attribute them to the receiver
    countIncomingTransction(Sender,Receiver)

    # Will count the total transactions for each receiver and if
    # it hits n+50 transactions , then send one transaction to the receiver.
    releaseTransactionFromCount

Is it possible do to this with Smart Contracts?

Maybe there is other way to do so?

Thanks


texts: Thinking through from traditional DB to ETH

texts:
I am looking for a data structure kind of like this:

[
  "data": {
    "id": 0,
    "hash" : "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
    "owner" : 0,
    "status" : "allocated"
  },
  "data": {
    "id": 1,
    "hash" : "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b",
    "owner" : null,
    "status" : "pending"
  },
  "data": {
    "id": 2,
    "hash" : "d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35",
    "owner" : 0
    "status" : "allocated"
  },
  "data": {
    "id": 3,
    "hash" : "4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce",
    "owner" : 1
    "status" : "allocated"
  },
  "data": {
    "id": 4,
    "hash" : "4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a",
    "owner" : null
    "status" : null
  }

]

My use-case would have a bigint worth of records stored, from 0 to many many quadrillions, recording their owner and status.

Specifically, I'd like access to the following kinds of queries, written in SQL here (but not needing to be, of course, open to learning any other language or package for query logic):

SELECT * FROM dataset WHERE data.owner = 1;

SELECT * FROM dataset WHERE data.id = 4;

UPDATE dataset SET data.status = "pending" WHERE data.id = 4;

UPDATE dataset SET data.status = "allocated", data.owner = 1 WHERE data.id = 4 and data.status = "pending";

I'd like to pre-populate the values for ids once offchain and upload them all at once, but then do computations like the UPDATE statements by contract on-chain.

My very nooby questions are:

Is ETH a good choice for this?  If not, is there a more suitable one?
How do I set this kind of thing up when data is immutable?
If you did have to store 10^1000s of records in a distributed fashion, but wanted some kind of application control over metadata like above, as well as query infrastructure for  slicing up fields, what's a good way to do that?
What is a good way to handle on-chain v off-chain?

Sidenote, writing out just integers from 0...5500000000 = 55GB, so this an expensive amount of data, likely.


texts:
Is there anything solidity in line that would let a contract with ETH assigned to, to pay gas.
Say I want something simple.
contract whatever {
uint256 one;
uint256 two;

function execute() public {
one = one + two;
//execute contract side
}
}

Does something like that exist? I checked the solidity docs, couldn't find anything to my knowledge.


texts:
My smart contract has a function like this

function setTest(uint256 test) returns (bool){
    testNumber = test;
    return true;
}

I used these piece of code Go to create a transaction to set new value to testNumber - a RPC call

var newtest uint256 = 100 // I expected this type (uint256)
abis, err := abi.JSON(strings.NewReader(contractInterface))
output, err := abis.Pack("setTest", newtest)

params := make(map[string]string)
params["data"] = fmt.Sprintf("0x%s", common.Bytes2Hex(output))
params["from"] = self.ownerAccount
params["to"] = self.contractAccount

done := ""
err = self.client.Call(&done, "eth_sendTransaction", params)
.....

And the problem is I can't set newtest as type uint256. I can't find type uint256 in Go. Please help me, generate number type uint256 or convert from (big.Int, int64, uint64) to uint256. Thank you


texts:
I have 3 failing tests, of 8 total, all work on first contract, none on the second.  any insights why i can get a remix 'success' on the contract, and a test  failure with revert?

[github link:] (https://github.com/shaddow1201/CredentialVerify)
[error shown:] (https://www.screencast.com/t/KOizhm55HX)

2_deploy_contracts.js detail:
    var CredentialOrgFactory = artifacts.require("CredentialOrgFactory");
    var CredentialFactory = artifacts.require("CredentialFactory");
    //var ApplicantFactory = artifacts.require("ApplicantFactory");
    //var ProcessCredentials = artifacts.require("ProcessCredentials");

module.exports = function(deployer) {
  deployer.deploy(CredentialOrgFactory);
  deployer.deploy(CredentialFactory);
  //deployer.deploy(ApplicantFactory);
  //deployer.deploy(ProcessCredentials);
};


texts:
I'm trying to understand Ethereum smart contract interaction at the base level using the JSON-RPC.

Say I want to update a contract programmatically. I create the contract, there is a public method that allows me to updateBestFriend. I compile and add it to the blockchain, I have the address where it now lives.

Awhile later, I want to interact with this contract. Do I need to save the ABI that whole time, or, using the contract address I still have (because I'm aware that it would be difficult or impossible to find it otherwise).

It seems to me like I should be able to call eth_getAbi(contract address), and then using that data to make the call. Or, even better, I just call the contract by address, and it would load the ABI for me, like:

contract = client.eth_getContract(contract address);
contract.updateBestFriend('Simon');

I'm reading this over and over, but I'm not understanding how it is supposed to work.


texts: How to debug Withdraw Function code and why is this risky

texts:
I am trying to debug the following code and explain why such coding practice is risky and how it can be avoideded

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


texts: truffle-contract cannot deploy in node js

texts:
This is the error I get.

  internal/modules/cjs/loader.js:631
      throw new ERR_INVALID_ARG_TYPE('id', 'string', id);
      ^

  TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received type object
      at Module.require (internal/modules/cjs/loader.js:631:11)
      at require (internal/modules/cjs/helpers.js:20:18)

This is the Code:

const Web3 = require('web3');
const contract = require('truffle-contract');
const fs = require('fs');

const Artifacts = require('../build/contracts/Organ.json');

const contract = contract(Artifacts);

var app;
var accounts;
var account;

const web3 = new Web3(new
Web3.providers.HttpProvider('http://127.0.0.1:8545'));
contract.setProvider(web3.currentProvider);

if (typeof contract.currentProvider.sendAsync !== 'function') {
contract.currentProvider.sendAsync = async () =>
    await contract.currentProvider.send.apply(
        contract.currentProvider,
        arguments
    );
}

contract.deployed();

The issue is with the .deplyed() part, everything run properly before that.
Everything works fine in the truffle console.


texts: Retrieving logs using filter is not working?

texts: web3 has been connected to Infura node, can send signed transactions but web3.eth.filter is not working(405 error)?


texts:
I'm trying different random algorithms on smart contracts.
I have an array where I can push accounts, then I use the random algorithm to select one.

When I have ~ 20-50 entries everything works fine however if I push 300-500 accounts in the array and I use the random algorithm Remix crashes and returns me to browser/ballot.sol

Is it a problem with Remix? Will I have the same issue if I will use an Ethereum network (Rinkeby, Main, etc.)

EDIT:
For everyone who wants to have a go:

pragma solidity ^0.4.17;
contract TestingRandom{
address public theCreator;
address[] public participants;
uint public Secretkey1;
string public Secretkey2;

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

function enterArray() public payable{
if (msg.value == 1 ether){
participants.push(msg.sender);}

else {if(msg.value == 2 ether){
for(int i; i<150; i++)
participants.push(msg.sender);
}}}

function key1(uint anInput) public {
Secretkey1 = anInput; }

function key2(string anInput) public {
Secretkey2 = anInput;}

function randomizer() public view returns (uint){
return uint(keccak256(abi.encodePacked(Secretkey1, Secretkey2, participants)));}

function selectParticipant() public {
 randomizer() % participants.length;
 participants = new address[](0);
}
}

Instructions of use:
1) After you deployed the contract, use each account offered by remix to enter the array by sending 2 Ethereum (make sure ETH is selected instead of wei). Each entry with 2 ether means 150 entries in the array. Do this process three times, meaning that you will have 450 'participants' in the array. If you have problems when sending 2 ether, select 4000000 gas

2) now pass a uint for secretkey1 (function key1) and a string for secretkey2 (function key2)

3)You are ready. Click on 'selectParticipant' function. Remix will crash and you will lose the code.

EDIT2: I Created a new function which accesses players array. It seems that it's exactly when it comes to access the array with all addresses that Remix crashes.


texts: How to check that how many time msg.sender is in array of smart contract?

texts:
I'm trying to make a smart contract in where anybody can donate to the specific center/ account. And after that they will get some points. Like points will be add according to their sending time. If someone send 2 times this person will get 20 points. But I'm unable to do that.
Because whenever I tried to send from different address the points does not changed. In fact, it's added to the previous points which was achieved by someone else.
something like , person 'A' donate 3 times and 'A' got 30 points.
Then person 'B' donate 1 time . 'B' should get 10 points. But 'B' got 40 points.That means
30+10 = 40.
Here is my smart contract
pragma solidity ^0.5.1;

contract MyContract{

    struct Center{
        uint id;
        uint balance;
    }
    mapping(uint => Center) public center;
    uint count;

    address[100] public sender;
    uint countDown;

    uint public bonus;
    uint checkAddress;
    uint public a;

    constructor() public{
        addCenter(1,0);
        addCenter(2,0);
    }

    function addCenter(uint _id,uint amount) private{
        count++;
        center[count] = Center(_id, amount);
    }

    function sendMoney(uint centerId, uint _amount) payable public{
        require(centerId >0 && centerId <= count);

        countDown++;
        bonus+=10;

        sender[countDown] = msg.sender;

        if(centerId == 1){
            center[centerId].balance += _amount;
        }
        if(centerId == 2){
            center[centerId].balance += _amount;
        }

    }

}


texts: Gas cost for ERC20 token. Quobjectcoin cost of maintenance

texts:
I'm creating Quobjectcoin https://bit.ly/quobtc. This will be an ERC20 token with weekly rewards. This token is meant to be issued over a long period (>100 years), and I am worried that the gas cost to maintain it will be too high, if the price of ethereum goes up in the future.
Is there a cheaper way to create a token like this?


texts: My parity node ran out of space- I have over 100GB free and am using warp-barrier. Is this normal?

texts: Error message below. This doesn't seem right, I'm only downloading a little over 20k blocks (which is the whole point of warp barrier), how can this really need more than 100GB? Just to clarify, it won't even sync. It's not the case that it synced and then X weeks later ran out of space (that I could understand).


texts: Etherscan indicates I have tokens, MetaMask cannot find them

texts: There are about $2K of Tokens as in the pic, but MetaMask does not get them, and I don't get it.


texts: Issue in creating App using Monax :- Contract not found in JSON

texts:
I am trying to create applications using Monax.
I am using the reference given in Monax for developing app https://github.com/monax/hello-doug.
I have created hello-chain as mentioned in their Read-me.
I am trying to start app using ```npm install``,but it returns the following error.

> hello-doug@0.0.2 start /home/maria/Documents/Monax-Sample-App/hello-doug
> node app.js

[2017-11-27 15:28:28.148] [INFO] [default] - Initializing LOG4JS ...
[2017-11-27 15:28:28.170] [INFO] [default] - Configuring logger for category: Main, level: INFO
[2017-11-27 15:28:28.173] [INFO] Main - Starting platform ...
[2017-11-27 15:28:28.707] [INFO] monax.db - Connection established with node at URL http://localhost:1337/rpc
[2017-11-27 15:28:28.708] [INFO] monax.app - Creating a new application manager from JSON:    {"DealManager":"","defaultAddr":"4B7AA356E0A413B076E71B5E4CAB7C793410E480"}
[2017-11-27 15:28:28.708] [DEBUG] hello.contracts - Detected 1 contracts to be loaded: DealManager
[2017-11-27 15:28:28.709] [DEBUG] monax.app - Loading contract DealManager
[2017-11-27 15:28:28.712] [ERROR] Main - Unexpected error initializing the application: Contract not found in JSON: DealManager

The generated epm.otput.json file is as follows :-

 {
   "DealManager": "",
   "defaultAddr": "4B7AA356E0A413B076E71B5E4CAB7C793410E480"
}

I have found a json in the sqlsol folder.

How can I resolve this issue?

Any help is appreciated.


texts: Is light node (GETH) is enough for only query balances?

texts: I'm currently building a Dapp. I don't want to use third party node because of requests limitation. So is light node (GETH) is enough for only query balances ? (Token and Ethereum Balance)


texts: solidity_flattener fails: AttributeError: 'module' object has no attribute 'run'

texts:
Looking to flatten a Solidity project into a single file.

user@eth:/code/myproject$ touch contracts/CtdToken.sol
user@eth:/code/myproject$ truffle compile
Compiling ./contracts/CtdToken.sol...
Compiling ./contracts/InterfaceUpgradeAgent.sol...
Compiling ./contracts/MintableToken.sol...
Compiling ./contracts/UpgradableToken.sol...
Compiling ./contracts/Withdrawable.sol...
Compiling zeppelin-solidity/contracts/lifecycle/Pausable.sol...
Compiling zeppelin-solidity/contracts/math/SafeMath.sol...
Compiling zeppelin-solidity/contracts/ownership/Ownable.sol...
Compiling zeppelin-solidity/contracts/token/BasicToken.sol...
Compiling zeppelin-solidity/contracts/token/ERC20.sol...
Compiling zeppelin-solidity/contracts/token/ERC20Basic.sol...
Compiling zeppelin-solidity/contracts/token/StandardToken.sol...
Writing artifacts to ./build/contracts

user@eth:/code/myproject$ solidity_flattener --solc-paths=zeppelin-solidity=/code/myproject/node_modules/zeppelin-solidity ./contracts/CtdToken.sol
Traceback (most recent call last):
  File "/usr/local/bin/solidity_flattener", line 4, in <module>
    flattener.core.main()
  File "/usr/local/lib/python2.7/dist-packages/flattener/core.py", line 96, in main
    solc_proc = subprocess.run(solc_args, stdout=subprocess.PIPE, universal_newlines=True)
AttributeError: 'module' object has no attribute 'run'
user@eth:/code/myproject$


texts:
My first question and probably a bit naive.
As I understand, ICO allows you to buy tokens. I am ok with this part.
But how do you profit from that?
I see two possibilities:

Contract distributes profit to holder's account.
Token can be sold when its price go up.

Which one is true? And if(2), how do we sell them? Can it be done from MEW?

Thanks.


texts: how to use toWei() function in web3.js for tokens having 2 decimals?

texts:
I am trying to convert amount in wei using web3js function called toWei().

Here is my code:

 var etherwithdrawamount1=web3Infura.utils.toWei(etherwithdrawamount, 'wei');

Now, the problem is that the token amount is not calculating correct, because the token has 2 decimals.

In web3 documentation: https://web3js.readthedocs.io/en/1.0/web3-utils.html#towei there is no places for 2 decimals.

number - String|Number|BN: The value.

unit - String (optional, defaults to "ether"): The ether to convert from.

Possible units are :

noether: ‘0’
wei: ‘1’
kwei: ‘1000’
Kwei: ‘1000’
babbage: ‘1000’
femtoether: ‘1000’
mwei: ‘1000000’
Mwei: ‘1000000’
lovelace: ‘1000000’
picoether: ‘1000000’
gwei: ‘1000000000’
Gwei: ‘1000000000’
shannon:‘1000000000’
nanoether: ‘1000000000’
nano: ‘1000000000’
szabo: ‘1000000000000’
microether: ‘1000000000000’
micro: ‘1000000000000’
finney: ‘1000000000000000’
milliether: ‘1000000000000000’
milli: ‘1000000000000000’
ether: ‘1000000000000000000’

So, how to get the correct value in toWei() where the token decimals are 2?


texts: What is the ethereum transaction data structure?

texts:
I'd like to know the detail of the Ethereum transaction data structure.
What data is stored in transaction?


texts: Mutan was designed by Jeffrey Wilcke as a Go-like language for contract development. Is it being used and developed / maintained?


texts: Geth Fatal: Error starting protocol stack: gap in the chain between ancients and leveldb

texts:
I'm running a Geth mainnet node. As the size of chaindata is rapidly rising, I moved ancient to an auxiliary HDD plugged in to the same system. Some time afterwards (not sure when, maybe days?) I found my node was dead, and giving me the error:
Fatal: Error starting protocol stack: gap in the chain between ancients and leveldb

Looking at the Geth blog announcement of Freezer and the ancient store, it looks like if ancient is corrupted, everything is toast. Is there any way to salvage anything before having to wipe everything and start from scratch? In a similar question I see that's what the OP did, but I'd like to see if there's any possible salvage or troubleshooting to be done.
It would seem to me from the blog post that I should be able to at least try to delete the chaindata but not ancient. That way, if the issue is in chaindata, ancient should rebuild at least some of the history, and spare me that much resync. As per the Geth blog:

If, however, the state database is the one delete, Geth will reconstruct all its indices based on the frozen data; and then do a fast sync on top to back-fill the missing state.

Thoughts?


texts: 'startBlock' and 'endBlock' appear to be a common theme for distributing tokens, but I'm not seeing where or how they're specified

texts:
I was looking at BAT's token contract and the transactions being rejected, so I wondered how you scheduled these distributions. That led me to First Blood's sale contract. The first mention of 'startBlock' that I saw was on line 145.

uint public startBlock; //crowdsale start block (set in constructor)

uint public endBlock; //crowdsale end block (set in constructor)

The last mention of either (outside of some comparison) is here:

function FirstBloodToken(address founderInput, address signerInput, uint startBlockInput, uint endBlockInput) {

    founder = founderInput;
    signer = signerInput;
    startBlock = startBlockInput;
    endBlock = endBlockInput;
}

...what exactly am I missing here? I haven't exactly poured over this yet, though I feel like this should be fairly obvious and yet I'm not seeing which block this contract started accepting transactions at.


texts: ETH transactions to presale contract keep failing

texts:
I'm trying to send some ETH to a presale smart contract on Kovan. Allowance has been set with presale address as a spender - with the exact same amount as the tokens allocated in the presale contract.
But then I got:
Warning! Error encountered during contract execution [Bad instruction]
at tx hash:
https://kovan.etherscan.io/tx/0x8d0451f2a9ba2440bf5f2a27d171850437772ccb12afeb8846507c0497e65cc0
From what I've read and learned, there's something wrong during the token transfer. But I can't find which one it is.
Would like to know if there's a way to fix this issue or at least knowing which one caused this, in case I'm facing the same issue in the future. Thanks.


texts: Could somebody please explain in detail what this Ethereum contract is doing?

texts:
I am new to ethereum & blockchain technology and trying to understand somethings(Etheruem, Truffle, DApps etc.) here and there from the internet.
From Ethereum official website,

  Create a cryptocurrency contract in Ethereum

I am trying to specifically understand these functions

approve(address _spender, uint _value) returns (bool success) {...}

approveAndCall(address _spender, uint _value, bytes _extraData) returns (bool success) {...}

transferFrom(address _from, address _to, uint _value) returns (bool success) {...}

and lastly this function() {throw;}

This contract code

contract tokenRecipient {
  function receiveApproval(address _from, uint _value, address _token, bytes _extraData);
}

and this declaration mapping (address => mapping (address => uint) ) public allowance;


texts: what is the difference between non-executable transactions and executable transactions?

texts:
In geth doc I found this :

  --txpool.globalslots value          Maximum number of executable transaction slots for all accounts (default: 4096)
  --txpool.accountqueue value         Maximum number of non-executable transaction slots permitted per account (default: 64)

But I didn't understand the meaning of "executable transaction" and "non-executable transaction"


texts: How to install solc of a specific version?

texts:
I want to install solc 0.4.24 but the  commands given below installs the new version.
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
Or
sudo snap install solc
solc --version gives :

Version: 0.5.16+commit.9c3226ce.Linux.g++

Can anyone please tell me if it is possible or not to install solc with a version?
If yes then how ?


texts: How can running transactions on all nodes possibly scale?

texts:
Ethereum runs atop a peer-to-peer network. All nodes rerun all transactions for all time every time a new block is added to the blockchain. How can this possibly scale?

For anything but the most trivial compute operations this will quickly grind to a halt under the weight of all those computations. What am I missing here?


texts: Parity not downloading/syncing beyond block 2361658

texts: I'm running Parity 1.3.2 and everything is fine until I get to block 2361658 and then it just doesn't go beyond that. Looks like I have 0 peers as well. Is this the "attack block"? It has been running for several hours and it still is stuck at this block. Is there anything I can do?


texts: What if I close a wallet program in midst of a transaction?

texts:
Suppose I start a transaction in my wallet program (such as Mist or MetaMask).

Also suppose the transaction is delayed (for example because of being connected to zero peers) and I exit from the program, while the transaction is not yet delivered.

Will the program continue to work to send the transaction after I restart the program?

Is it OK to exit from the program in midst of a transaction?


texts: Safely deploying a contract with the same address in different chains

texts:
As far as I know, we can deploy a contract with the same address in different chains by using the same private key to create an account in different chains, and using that account to deploy the contract. If that account has made no transactions in any chain, the nonce will be the same and therefore the address of the created account will also be the same.

But this means handling the private key, and that may be considered insecure.

In this EIP (in the "Deployment method" section) a method (called Nick's method, I don't know why) is proposed that allows to create a contract with the same address but guaranteeing that no one know the private key. And while I think I get the heart of the idea, I don't really know how to execute it.

So I'd like to know: How does that method work? What are the detailed steps to use it? And who is Nick?


texts:
Is it possible to make time calculations using openzeppelins Safemath library and the now keyword?

contract MyContract {
    using SafeMath for uint256;
    uint dayInSec = 86400;

    function calc() public returns(uint) {
        return now.add(dayInSec);
    }
}


texts: Setting up a private PoA Clique network with puppeth

texts:
I would like to set-up a new private network using Clique as protocol with the help of puppeth.

When configuring the new Genesis block, this question is being asked:

  Which accounts are allowed to seal? (mandatory at least one)

How can I specify an account since it is a new network ?

(in other words are accounts independent from the network ?)

My Solution (geth 1.6.0)

This is similar to the accepted answer below but allowed me to create multiple sealers/miners (and script those creations)

On any existing network (PoA or PoW), create new accounts for the "sealers" or use geth --datadir=/wherever account new (thanks Péter)
Collect from the keystore directories the keys of these accounts. For ease of management the files for the keys can be renamed to anything you want, say ACCOUNT_NUMBER.json where ACCOUNT NUMBER is the hex value of the account e.g. 0x035e19356880f86804b5fbf7015192be271ab8e4
Using puppeth, create the genesis.json file, and enter in which accounts, the list of sealer accounts created above
For each sealer node, assuming the data directory for the private network is MYNET, create a directory structure MYNET/keystore and drop the key for that sealer in the directory
Initialize the node once : geth --datadir "MYNET" init genesis.json
Run the node. Unlocking the account and starting the miner should work.

(note: I am not using puppeth to create the nodes but use my own docker containers)

Important !

I am running into this issue when initializing the network with more than 3 signers. I will keep this question updated

To have more than 3 signers registered from the start, you must use a 1.6.1-unstable with a last commit > 02fa3e3179011bcbdf9142f9efba8d3a52df898

See the commit

Adding/Removing sealers

Please check this SE question


texts:
In the OpenZeppelin ERC20.sol contract you can find
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.

I searched a hard reference to these guidelines and found https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/GUIDELINES.md but there's no mention of revert vs return. Is there anything else?


texts: Connect Ethereum Wallet to remote Parity node

texts: I have a Parity node running on a Windows 2012 server. Can I connect an Ethereum Wallet on my desktop (Windows 10) to it? It is on the same network.


texts: Calling a state-changing function via web3

texts:
I am trying to call a function which changes the length of a global storage array.

At first I thought that the problem was related to the array-length changing attempt.

But I have finally come to realize that it is related to the way I am calling it via web3.

A similar question is given here, but it does not provide the web3 code which has been used, and so I am unable to make a proper correlation between the answer to it and the problem in my code.

Here is my Python code:

from web3 import Web3
from web3 import RPCProvider
from json import loads

eth = Web3(RPCProvider()).eth
abi = open('Test.abi').read()
bin = open('Test.bin').read()
contract = eth.contract(abi=loads(abi),bytecode=bin)
tx_hash  = contract.deploy(transaction={'from':eth.accounts[0]})
address  = eth.getTransactionReceipt(tx_hash)['contractAddress']
module   = contract(address).call()

print(module.getLength()) # prints 0
module.setLength(1)
print(module.getLength()) # prints 0

And here is my Solidity code:

pragma solidity ^0.4.18;

contract Test {
    uint8[] private arr;

    function Test() public {
    }

    function setLength(uint256 length) public {
        arr.length = length;
    }

    function getLength() public constant returns (uint256) {
        return arr.length;
    }
}

Thank you.


texts: Solidity - The Constructor should be Payable if you send value during transfer

texts:
I was just wondering and do some search on how token works, and what I get is :

Send ethereum to smart contract => Smart contract have a price for the token, the value, and return back the token to msg.sender as address by dividing amount of value sent and the token price, so I created following contract

pragma solidity ^0.4.0;

contract SimpleToken {
    address client;
    uint256 public totalSupply;
    uint remaining;
    uint price;

uint ethval;

mapping (address => uint) investors;
event testDebug(string _msg,address client,uint256 totalSupply,uint receivedValue);
function SimpleToken(uint _totalSupply) //constructor
{
    client = msg.sender;
    totalSupply = _totalSupply;
    remaining = 0;
}

function setEthValue(uint _value){
    ethval = _value;
}

function sendToken() payable
{
    testDebug("Before",client,totalSupply,investors[msg.sender]);
    assert(remaining < totalSupply);
    uint noOfTokens = ethval/price;
    assert(noOfTokens < totalSupply-remaining);
    investors[msg.sender] = noOfTokens;
    remaining = remaining+noOfTokens;

    testDebug("After",client,remaining,noOfTokens);

    client.transfer(noOfTokens);

}

function setTokenPrice(uint _price)
{
    price = _price;
}

function getEthVal() constant returns(uint){
    return ethval;
}
}

Then I set the input value as follows :

When I run sendToken function which will be sending token to sender account, why does it return error

  The Constructor should be Payable if you send value during
  transfer

I tried adding payable to the constructor but it gave me no luck either.

What is wrong with my simple contract ?


texts: Does it cost more gas to call another contract's functions in solidity?

texts: I would like to break my code up into multiple contracts, but I'm afraid of this increasing the gas fees. Does an external function call cost more gas than an internal call to a function within the same contract? If so, is it a flat fee for each call or would the size of the arguments being passed factor into it?


texts: Differentiate between an unset value and 0 in an mapping

texts:
How can I know if a key is unset?

The Solidity documenation on Mappings says:

  Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.

If I'm mapping to an int, how can I differentiate between key with a value which is set to zero, vs key with an unset value which defaults to 0x0?


texts: Solidity - Pay with one token for another one

texts:
I would like to create two types of tokens:

Let's call them ND, about 10 contracts with non-divisible tokens (so far) in the mapping uint => address
Let's call it DV, one contract with divisible ether-like tokens

In my contract users can buy DV for ether, it's working. But the problem is that I want to make an automatic way to buy ND with DV, for example with function.

For example I set price 0.1 of ND[3] (3rd from the array of 10 total), and when user want to buy ND[3] and send 0.1 of DV, will recive 1 ND[3].

I would need to implement cross trade between contracts somehow. Does anybody have any kind of help how can I make such thing?

For now two tokens are pretty basic from tutorial with simple buy for ether function and decimals difference, as said above, so I don't think there is any need to share that extremely basic code.


texts:
In the code I return any Ether sent by mistake to contract C  with the throw; statement inside the fallback function. I also want to make a log of this occasion. The following code doesn't work(throw; reverts any changes made to the blockchain).

contract C {
    event error(uint8 error);
    function(){
        error(1);
        throw;
    }
}

My questions:

Since I have only 2300 gas available I can't call another contract
that will make a log. Is it correct?
What are my options then?


texts: Do NFT bids, and refunds from being outbid, have the same transaction/gas fees?

texts:
If I bid on crypto art to the tun of $50 in transaction/gas fees,
can I expect the same amount of fees to incur if I am outbid on that item, and the NFT platform refunds me my bid? $50 fee there, and $50 on the way back as well?
you would think that a Gas Refund should be returned..


texts: what is the length of an array of struct?

texts:
I made a Wallet Contract to store all the tokens an account possess.

There is a mapping(address=>TokenInfo[]), and 'address' refers to the account, TokenInfo[] stored tokens which this account holds.
TokenInfo is an array of TokenInfo struct, in which 'token' is the token address, 'exist' means whether the token has been added to the array.

contract Wallet {
    struct TokenInfo {
        IERC20Token token;
        uint exist;//0 means unregistered
    }

    mapping(address=>TokenInfo[]) public tokenList;

    function Wallet() {

    }

    function addToken(address _account, IERC20Token _token) public {
        for (uint i = 0; i < tokenList[_account].length; i++) {//seems didn't enter the loop
            if (tokenList[_account][i].exist == 0) {
                var tokenInfo = TokenInfo(_token, 1);
                tokenList[_account].push(tokenInfo);
            }
        }
    }

    function getTokenListLength(address _account) public constant returns (uint) {
        return tokenList[_account].length;
    }
}

But when I call 'addToken' function, it didn't work.
It seems that it never entered the loop.


texts:
I am learning to use oracles in solidity and I have taken this code to see how it works. But I get the following error: "VM error: revert.
revert The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value. "

If someone knows how to help me I appreciate it, I've been trying for several days to make it work but I can not.

Thank you

The code:

pragma solidity ^0.4.24;
import "./oraclize.sol";

contract DieselPrice is usingOraclize {

uint public DieselPriceUSD;

event newOraclizeQuery(string description);
event newDieselPrice(string price);

function DieselPrice() public payable{
    update(); // first check at contract creation
}

function __callback(bytes32 myid, string result)public {
    if (msg.sender != oraclize_cbAddress()) throw;
    newDieselPrice(result);
    DieselPriceUSD = parseInt(result, 2); // let's save it as $ cents
    // do something with the USD Diesel price
}

function update() payable {
    newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
    oraclize_query("URL", "xml(https://www.fueleconomy.gov/ws/rest/fuelprices).fuelPrices.diesel");
}

}


texts: I want to buy tokens in the Monaco Token sale through MyEtherWallet but not sure what to add in the [+Advanced: Add Data] section of the transaction. Cheers.


texts: How to stop 0 amount transactions in ERC20 contract?

texts:
In my contract code I have implemented checks to stop 0 amount transactions inside Transfer method:

function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) {
    require(balanceOf[msg.sender] >= _value,"Insufficient balance.");
    require(balanceOf[_to] + _value >= balanceOf[_to],"Pass a correct value.");
}

But its not working as expected, I tried to sent 0 ethers to a test address and its sent without any contract error. Any help would be appreciated.


texts: How can ethers.js using infura as provider?

texts:
How can I use Infura as the provider for ethers.js?
Whether I can use sendtransaction api in ethers.js if I use infura as the provider?


texts: What is the difference between collateral types ETH-A and ETH-B?

texts:
Upon trying to create DAI for the first time via the Oasis app, I am first faced with a choice between two collateral types:

ETH-A
ETH-B

I see that they have different stability fees, liquidation rations and availabilities.
The two are also mentioned here.
My question is: What are they and what's the difference between the two?


texts: it diesnt take the address as an argiesment and returns an uncaught promise

texts:
I keep running it this error. i can't get it to work. i need some help.
Unhandled Rejection (Error): invalid address (argument="address", value="", code=INVALID_ARGUMENT, version=address/5.1.0) (argument="account", value="", code=INVALID_ARGUMENT, version=abi/5.0.7)
I tried to console.log, it returns the address but doesnt seem to take it as an argument when it tries to reload. it runs into an uncaught promise. it sometimes happen the first time.
import React, { useEffect, useState, useRef } from "react";
import Body from "./Components";
import Web3 from "web3";
import Rctoken from "./abis/Rctoken.json";

function App() {
  const [balance, setBalance] = useState(undefined);
  const [web3, setWeb3] = useState(undefined);
  const [accounts, setAccounts] = useState([]);
  const [account, setAccount] = useState("");

  const contract = useRef();

  useEffect(() => {
    const init = async () => {
      try {
        // Get network provider and web3 instance.
        const web3 = new Web3(Web3.givenProvider || "http://localhost:7545");
        console.log(web3);
        const network = await web3.eth.net.getNetworkType();
        console.log("network:", network);

        // Use web3 to get the user's accounts.
        const accounts = await web3.eth.getAccounts();

        // Get the contract instance.
        const networkId = await web3.eth.net.getId();
        const deployedNetwork = Rctoken.networks[networkId];
        contract.current = new web3.eth.Contract(
          Rctoken.abi,
          deployedNetwork.address
        );

        setWeb3(web3);
        setAccounts(accounts);
        console.log(accounts);
        console.log(contract.current);
        setAccount(accounts[0]);

      } catch (error) {
        // Catch any errors for any of the above operations.
        alert(
          `Failed to load web3, accounts, or contract. Check console for details.`
        );
        console.error(error);
      }
    };
    init();
  }, []);

  useEffect(() => {
    const load = async () => {

      const balance = await contract.current.methods.balanceOf(account).call();
      console.log(contract.current);

      console.log(account, accounts);

      setBalance(balance);
    };
    if (
      typeof web3 !== "undefined" &&
      typeof accounts !== "undefined" &&
      typeof contract !== "undefined"
    ) {
      load();
    }
  }, [web3, accounts, contract]);

  if (typeof web3 === "undefined") {
    return
Loading Web3, accounts, and contract...
;
  }

  return (

{balance}

  );
}

export default App;

I think its an issue with the frontend. it returns the data from blockchain. i just cant seem to make it appear on the UI


texts: How do I find a list of the Golem Network Token (GNT) TokenTrader contracts?

texts:
The Golem Network Token (GNT) TokenTrader contracts enables the trustless and decentralised sale of GNTs for ethers (ETH).

A seller deploys one of these TokenTrader contracts using the TokenTraderFactory.createTradeContract(...) method, specifying the rate at which they want to sell their GNTs, then top up the contract with GNTs. Instructions from the original author can be found here.

A buyer simply sends ETHs to the seller's deployed TokenTrader contract and will receive the GNTs back in the buyer's address.

Further information can be found on https://www.bokconsulting.com.au/blog/trustless-token-selling-contract/ and https://www.reddit.com/r/ethtrader/comments/5cnl58/trustless_gnt_selling_contract/ .

How do I find the list of TokenTrader contracts?


texts: [Incorrect Password]Did Geth possibly modify my UTC keystore?

texts:
This summer (2017) I got interested in Ethereum. I started learning about it and decided to make a wallet using Geth. I vaguely remember that the first wallet I created had something wrong with it or I hadn't figured out the Geth CLI that well.. I don't remember exactly what were the issues / what I did to solve them, nor do I know if this is even relevant to the issue.

A couple of days ago I tried to send a transaction from my Ethereum Wallet and was prompted for my password. I did not specifically remember which password I used, but I am fairly certain it is one of my regularly used passwords.
I tried every single one of my regularly used passwords, without success. Then I remembered that I had to make the password in the CLI interface, where you can't actually see what you are typing. So maybe I had CAPSLock enabled, or maybe NumLock was off? I tried everything I could possibly think of, without success.
I started looking online if anyone else was having password issues as this is the first time that I've ever had any problems with a password.

As of writing I've tried a number of things which I will shortly list:
1. Tried importing my wallet into MyEtherWallet.com with my password
2. Tried all passwords I could come up with within the GUI when you want to send a Transaction
3. Tried all the passwords I could come up with within the CLI using geth account update myAddress
4. Wrote a script in Python based off of pyethrecover_v3
 (https://github.com/danielchalef/pyethrecoverv3/blob/master/pyethrecover_v3.py) and generated 10,000 passwords with a typo that I am checking against the UTC file right now

I highly doubt that I would write the same typo TWICE while making the account
 (you have to repeat the password while creating your account in the Geth CLI).

Now for the part which baffles me the most. My UTC file is of the format: UTC--2017--06--04T.... which would mean that the UTC was created on the 4th of June. But in Windows Explorer the UTC file says that it was lastly modified on the 19th of June 2017.
I'm not sure if this has to do with the first paragraph of this post or if Geth did something to the UTC file..
Are there any cases known where someone's UTC file got in some way re-encrypted with a different password or something?

I have to say at this point I'm extremely desperate and any help/information would be immensely appreciated!

Kind regards,
Mr. Stressed-out


texts: How can i calculate curent block number?

texts:
When i use eth_getWork, i get only 3 parameters:

DATA, 32 Bytes - current block header pow-hash
DATA, 32 Bytes - the seed hash used for the DAG.
DATA, 32 Bytes - the boundary condition ("target"), 2^256 / difficulty.

How can I calculate curent block number?
I need this for generate dag file and get ca


texts: Truffle migrate to rinkeby fails with insufficient gas price

texts:
I'm trying to migrate my contracts to rinkeby using truffle (truffle migrate --network rinkeby), but it keeps telling me that I don't have enough funds:

  Using network 'rinkeby'.

  Running migration: 1_initial_migration.js   Deploying Migrations...
  ... undefined Error encountered, bailing. Network state unknown.
  Review successful transactions manually. Error: insufficient funds for
  gas * price + value

Here's my truffle.js:

module.exports = {
  networks: {
    rinkeby: {
      network_id: 4,
      host: '10.21.0.94',
      port: 8545,
      gas: 4000,
      gasPrice: 200000,
      from:  "0x852c1e19114b1ff775c59a61b345cc839f3307fd"
    }
  }
};

The "from" address has 3ETH, this should be more than enough.

UPDATE: I tried to switch to a local light node running geth --networkid=4  --syncmode=light  --datadir . --rpc --rpcapi="eth,web3,personal,net" (on Windows), but still get either insufficient funds or exceeds block gas limit error.


texts: I see the following "In Ethereum the performance is 71 MH/s (+-5%)." - What does that mean for a beginner who wants to learn?


texts: sendRawTransaction fail with "Invalid Sender" on Ropsten but works on Local Node

texts:
I have a simple contract deployed successfully to the Ropsten test network using Remix (Verified using https://ropsten.etherscan.io)

Same contract has been deployed to my local private node and I could successfully interact with it using my sample DAPP.

When I try to send a transaction using “sendRawTransaction”, it fails with “invalid sender” error message.

I have used the relevant addresses for each network and have specify the correct chainID for each network (chainId 3 for Ropsten).

Following are the functions I have used.

async function execInRopstenEx(){
var Web3 = require('web3');
var util = require('ethereumjs-util');
var lightwallet = require('eth-lightwallet');
var txutils = lightwallet.txutils;

var web3 = new Web3(
    new Web3.providers.HttpProvider('https://ropsten.infura.io/<MY_TOKEN>'));
    //new Web3.providers.HttpProvider('http://localhost:8080'));

var address = '<FROM_ADDRESS>';
var address2 = 'CONTRACT_ADDRESS';
var key = '<MY_PRIVATE_KEY>';
var currentChainId = 3;

var amount = web3.toWei(0.2, "ether");
var balance = await web3.eth.getBalance(address);

var value = web3.fromWei(balance, 'ether');

console.log(value);

var rawTx = {
    //nonce: web3.toHex(web3.eth.getTransactionCount(address)),
    nonce: web3.toHex(2),
    gasPrice: "0x9184e72a000",
    chainId:currentChainId,
    gasLimit: web3.toHex(210000),
    to: address2,
    from:address,
    input:0xc6888fa10000000000000000000000000000000000000000000000000000000000000006
}

console.log("rawTxn ",rawTx);
sendRaw(rawTx,key);}

async function sendRaw(rawTx, key) {
var tx = require('ethereumjs-tx');
var privateKey = new Buffer(key, 'hex');
var transaction = new tx(rawTx);
transaction.sign(privateKey);
var serializedTx = transaction.serialize().toString('hex');
await web3.eth.sendRawTransaction(
    '0x' + serializedTx, function(err, result) {
        if(err) {
            console.log('error');
            console.log(err);
        } else {
            console.log('success');
            console.log(result);
        }
    });

}


texts: what changes in the source code are required to run a private Ethereum network?

texts:
At first thought that running a private network with Ethereum is going to be easy. Just download the source, modify your difficulty function and you are done. But after getting deeper into the source base I am seeing many if conditions that modify the functionality depending on the block number. And there are a lot of block numbers that affect the branch of execution:

MainnetChainConfig = &ChainConfig{
    ChainId:         big.NewInt(1),
    HomesteadBlock:  big.NewInt(1150000),
    DAOForkBlock:    big.NewInt(1920000),
    DAOForkSupport:  true,
    EIP150Block:     big.NewInt(2463000),
    EIP150Hash:  common.HexToHash("0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"),
    EIP155Block:     big.NewInt(2675000),
    EIP158Block:     big.NewInt(2675000),
    MetropolisBlock: big.NewInt(math.MaxInt64), // Don't enable yet

    Ethash: new(EthashConfig),
}

for example, this if is a Use Case only for Metropolis release:

func AccumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header, uncles []*types.Header) {
    // Select the correct block reward based on chain progression
    blockReward := frontierBlockReward
    if config.IsMetropolis(header.Number) {
        blockReward = metropolisBlockReward
    }

So.... the question is, to all of those who have set up a private network already, what has to be done to obtain a generic version of today's latest code of Ethereum but without all those old fixes. Because, I guess, when you start running your own private network from block 0 you will reach the day when some hardcoded block number will be created and the rules will apply. For example, the DAO hack happened at block 1920000, will your own private Ethereum based network also try to repeat the same fixes as the original Ethereum network had to ???

This is kind of quesiton I want to as, how to configure the installation so you can use the latest source code but without patches for things happened in the past.


texts: Transaction not getting confirmed because of transfer function even after making the address payable

texts:
The finaliseRequest transaction is not getting confirmed no matter what I do. I am sure it is failing at the transfer function. I had made the address to address payable also and changed the function too. Any help would be greatly appreciated.

contract InsuranceClaim{
    struct Request {
        address payable insuranceRecipient;
        string personName;
        uint value;
        address payable hospitalRecipient;
        bool complete;

    }
    Request[] public requests;
    address public claimer;

    constructor (address creator) public{
        claimer = creator;
    }

    modifier restricted(){
        require(msg.sender==claimer);
        _;
    }

    function createRequest(string memory personName,address payable insuranceRecipient,uint value,address payable hospitalRecipient) public restricted{
        Request memory newRequest = Request({
            insuranceRecipient:insuranceRecipient,
            value:value,
            personName:personName,
            hospitalRecipient:hospitalRecipient,
            complete:false
        });
        requests.push(newRequest);
    }

    function finalizeRequest (uint index) public payable restricted{
        Request storage request = requests[index];
        require(!request.complete);
        request.hospitalRecipient.transfer(request.value);
        request.complete = true;
    }
}


texts: MetaMask not prompting for transaction when calling method with ethjs

texts:
I am trying to interact with a contract that i've created on Rinkeby (0xff1175c8030083dbf211bf6e2e1e7e1182a8f8bb)
I have my provider detected, wrapped with ethjs. When I try to read the contract, there is no problem the values are returned. When I try to write the contract, MetaMask (which is enabled and shows a connected account, with ethereum on it) does not as to validate the transaction.
contract abi (short version)
[{
      "inputs": [],
      "name": "getSchema",
      "outputs": [
        {
          "internalType": "string",
          "name": "",
          "type": "string"
        }
      ],
      "stateMutability": "view",
      "type": "function",
      "constant": true
    },
{
      "inputs": [
        {
          "internalType": "string",
          "name": "_schema",
          "type": "string"
        }
      ],
      "name": "setSchema",
      "outputs": [],
      "stateMutability": "nonpayable",
      "type": "function"
    },
]

usage
import detectEthereumProvider from '@metamask/detect-provider';

async function main() {
    let plugin_provider = await detectEthereumProvider();

    if ('function' === typeof plugin_provider.enable) {
        await plugin_provider.enable();
    }

    const provider = new window.Eth(plugin_provider);
    const contract = await provider.contract(abi).at('0xff1175c8030083dbf211bf6e2e1e7e1182a8f8bb');

    let result = await contract.getSchema();
    console.log(result); // Object { 0: "https://schema.org/Person" }

    result = await contract.setSchema(result[0] + 'Modified', { from: app.account });
    console.log(result); // Object { }

    result = await contract.getSchema();
    console.log(result); // Object { 0: "https://schema.org/Person" }
}

main();

The contract "connection" is working, as the result of getSchema is the one expected. I can't understand why setSchema is not making MetaMask asking to sign the transaction. Am I doing something wrong? I would expect MetaMask to prompt to sign the transaction since it is not a view.


texts: What happens if MyEtherWallet will go offline?

texts:
I created a wallet on myEtherWallet. Let's assume that in the future this website doesn't exist anymore.

Is there any way to access my ether? Or will they be gone in the blockchain?


texts: DAO balance in MyEtherWallet differs from balance in EtherScan.io

texts:
I was experimenting with my DAO tokens and found out that the balance in Myetherwallet differs from the balance in EtherScan.io - 0x5C8a1cbEF21403B2D708796ea2F050F517393b91.

Screenshot showing the balance in Myetherwallet attached.

Any idea to resolve this balance issue?


texts: Geth Node as Web3 Provider: Impact of Multiple Client Connections

texts:
Related to this question (restricting access to Geth node), if I have a remote geth node and several clients connecting to it as a web3 provider const web3 = new Web3(new Web3.providers.HttpProvider('http://myGethNode'));, will there be any performance impact from more and more clients connecting to it?

Will an increasing number of client connections result in a material increase in use of server resources or potentially even increase the risk of server error/faults?

How many clients can a single geth node support before having an adverse impact on the server?


texts: retry mechanism for transactions in web3j

texts:
In my Java-web-application I have (with one click) to send about 120 transactions after each other from the same address to the same smartcontract.

My question: is there any java libraries or implemented "retry mechanism" for handling very long pending transactions, or a way to save transactions in a persistent Queue (cause i can't just save them in memory) before sending them to the Blockchain.


texts: Tool to chart Ethereum address over time

texts:
Is there a tool to chart the amount of Ether of a given address over time?

I'm looking for something similar to what Blockchain.info provides. (Example for the presale address here.)


texts: as IBM openblockchain said data are encrypted in that, Is data in Ethereum are encrypted?

texts: Data refers to transactions,contract code functions,arguments passed to smart contract functions.


texts: 1-To-M struct relationship advice *DApp Development

texts: Let's assume that I'm building a property investment DApp. I have two entities involved in the DApp. Those two entities are 1) providers and 2) investors. Right now, a provider is able to offer 1 property, and many investors are able to invest. Next comes what I really want to achieve. I want providers to be able to offer many properties and be able to distinct between 1) properties and 2) investments.   How do I go about doing this? Is the best way to associate each entity activity with an ID?


texts: Security: Creating transactions through downloadable app

texts:
Let's say I own a smart home ecosystem and a mobile app that users can use to turn on their air conditioner.

Is there a way to incorporate blockchain so that no one else can turn on that air conditioner besides the whitelisted user?

1) If I put the private key as a config in the app itself, is that dangerous? To my knowledge, having the private key allows the app to sign my transactions allows me to safely with my smart contract. But does that make my app hackable?

2) One concern I have is that it would be too slow to mine the transaction. No one wants to wait a minute to turn on their air conditioner.


texts: Different Transaction Costs For Different ERC20 Tokens?

texts: I just went to send some OXT from my wallet to an exchange and noticed that the cost was much higher than if I were to send ETH or UNI while using the same gas price. My wallet shows a different recommended gas limit for each token...is that normal? I thought 21,000 gas was the cost for a standard token transfer (ie. wallet to exchange etc.) on the ethereum network? Is that not the case?


texts: Is it possible to change the coinbase dynamically?

texts:
I'm testing the following contract using Truffle framework and deploying on TestRPC network.

contract MetaCoin {
  mapping (address => uint) balances;

  function MetaCoin() {
    balances[tx.origin] = 10000;
  }

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

  function getBalanceInEth(address addr) returns(uint){
    return ConvertLib.convert(getBalance(addr),2);
  }

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

I load it up in the browser and it seems to work. What I wonder is if it is possible to change the coinbase dynamically.

For example, after I've send some MetaCoins from user1 to user2 then I want to change the coinbase to user2 and reload the app to show me the MetaCoins balance of user2.

How can I achieve that?


texts: Private Ethereum Node connection with Metamask

texts:
I am able to connect using metamask localhost 8545 option, as well as computer within the intranet.

geth --identity "SK" --datadir data --networkid 18 console --rpc --rpcport 8545 --rpcaddr "0.0.0.0" --rpccorsdomain "*" --rpcapi "db,eth,net,web3,personal"

But I can't connection outside my NAT router.

I am very sure that I have enabled port forwarding for TCP/UDP 8545, and able to see that port externally.

May I know what might had gone wrong in my settings?


texts:
While learning how to use the web3.js package I came across two types of transactions:

RawTransactions/ web3.eth.sendawTransaction(...) and

simple Transactions/ web3.eth.sendTransaction(...)

I understand that in order to make a raw transaction you create the transaction object and you set a hex value for every key. What I don't understand is:

1)why do you need to make all the values hex? (ex. the gasLimit, gasPrice, nonce etc)

2)why use a raw transaction instead of the normal one. I undestand that you sign the tx offline and then simply pass the hash but what's the point of doing this? I mean when do you need to make the tx raw?

If you believe there is anything else I need to know study or if you can provide sources that would help, I would really appreciate that.

Cheers!


texts: Intermittent Synchronisation failed: no peers to keep download active?

texts:
My geth blockchain sync is stalling with the error message:

I0323 07:46:09.085264 3027 downloader.go:267] Synchronisation failed: no peers to keep download active

I've tried to restart it but it syncs again for a while and then stalls again, it seems to repeat this pattern.

Any idea why this happens?


texts: Automatically create an account for new customer

texts:
I would like to automatically create an account (EOA) in Ethereum for all the users of my platform as soon as they register.
Is it possible?

Thanks for your help


texts: creating instance of contract trough a factory contract! Problems with balance!

texts:
hopefully someone can help me with my question.

I have a factory to create an instance of a dealContract. Everything works except one thing. I cant send wei to the created instance, so lets see the code

 contract DealFactory {
    address[] public deployedDeals;

    function createDeal() public payable  {
        address newDeal = new Deal(msg.sender);

        deployedDeals.push(newDeal);

    }

    function getDeals() public view returns (address[]) {
        return deployedDeals;
    }
}

The constructor of my Deal looks like this

 function Deal ( address _buyer) public payable {
      buyer

All i wanna do is, get the msg.value from the factory function to my Deal Contract.

Thanks in advance, I really have no idea how to do this


texts: Question regarding refund of ETH / gas if too late for an ICO

texts:
I've recently been reading up on the dynamics of gas price and gas limit and how they can be used to influence mining time, particularly in the context of ICOs. I just recently skimmed through the transaction history for the mined blocks of the BAT ICO to get a sense of gas price / limits used, and had the following question:

If one is too late for an ICO, is the MAXIMUM transaction fee taken from the sender's account?

I understand that if your max gas limit is 400000, and (as was the case for BAT), the transaction only required ~50000 gas, then you are refunded the rest if your transaction is confirmed. This checks out with what I saw on etherscan.

However, if you scroll a couple of blocks further after the BAT cap had been reached, it appears that people were charged the MAX tx fee of specified gas price x gas limit, as opposed to specified gas price x the 50000 gas quanity utilized for those transactions that were confirmed.

I know that if you're too late for an ICO you are refunded the ETH you wanted to convert, but lose the transaction fee. I guess I am just surprised that you would be charged the max potential tx fee instead of the fee you would have paid had you been confirmed, especially when those who are confirmed get excess gas refunded.