texts: Why has remix changed so that I cannot enter a string when deploying a contract with bytes16?

texts:
I am using remix and have been for a while. Since today, I can no longer enter "ABC123" as a variable in a contract when the variable is defined as Bytes16. Instead, I have to enter 0x414243313233 as a value in Remix which is fine but not efficient. Until today it worked... Is there a setting that I inadvertently changed?

The contract looks like:

    contract myContract {

        bytes16 public myName;

        function myContract(bytes16 _myName) public {
            myName = _myName;
        }

        function foo() public view returns (bytes16){
            return fooName;
        }
}

I would appreciate any help! Thank-you!


texts: geth account creation Failed to enumerate USB devices

texts:
I'm trying to create a private Ethereum network on a Kubernetes cluster using ethereum/client-go docker image but getting bellow error while trying to create an account:

~/.ethereum # geth account import privateKey --password passwordfile
INFO [07-10|00:31:02.095] Bumping default cache on mainnet         provided=1024 updated=4096
WARN [07-10|00:31:02.095] Sanitizing cache to Go's GC limits       provided=4096 updated=1316
INFO [07-10|00:31:02.101] Maximum peer count                       ETH=50 LES=0 total=50
INFO [07-10|00:31:02.101] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
ERROR[07-10|00:31:02.102] Failed to enumerate USB devices          hub=ledger vendor=11415 failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:02.106] Failed to enumerate USB devices          hub=trezor vendor=21324 failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:02.107] Failed to enumerate USB devices          hub=trezor vendor=4617  failcount=1 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:02.107] Failed to enumerate USB devices          hub=ledger vendor=11415 failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:02.107] Failed to enumerate USB devices          hub=trezor vendor=21324 failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:02.107] Failed to enumerate USB devices          hub=trezor vendor=4617  failcount=2 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:03.109] Failed to enumerate USB devices          hub=trezor vendor=4617  failcount=3 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:03.109] Failed to enumerate USB devices          hub=ledger vendor=11415 failcount=3 err="failed to initialize libusb: libusb: unknown error [code -99]"
ERROR[07-10|00:31:03.109] Failed to enumerate USB devices          hub=trezor vendor=21324 failcount=3 err="failed to initialize libusb: libusb: unknown error [code -99]"
Killed
~/.ethereum # command terminated with exit code 137

Things work perfect when I try on a docker container, problem with both Minikube as well as IBM Kubernetes Service.


texts:
I'm new in the Ethereum and programming languages at all I have a problem with this code:

pragma solidity ^0.4.8

contract MyToken {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;

/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;

/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);

/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(uint256 _supply, string _name, string _symbol, uint8 _decimals) {
    /* if supply not given then generate 1 million of the smallest unit of the token */
    if (_supply == 0) _supply = 1000000;

    /* Unless you add other functions these variables will never change */
    balanceOf[msg.sender] = _supply;
    name = _name;
    symbol = _symbol;

    /* If you want a divisible token then add the amount of decimals the base unit has  */
    decimals = _decimals;
}

/* Send coins */
function transfer(address _to, uint256 _value) {
    /* if the sender doenst have enough balance then stop */
    if (balanceOf[msg.sender] < _value) throw;
    if (balanceOf[_to] + _value < balanceOf[_to]) throw;

    /* Add and subtract new balances */
    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;

    /* Notifiy anyone listening that this transfer took place */
    Transfer(msg.sender, _to, _value);
}

}

Thanks in advance


texts: Can a contract function both change the state and return a value when it's called externally

texts:
Assume we have a test() function in our contract:

contract {
 uint state;

 function test() returns (bool ){
   state= 5;
   return true;
 }
}

I'm aware that if the test() function didn't have to change the state, then we can use:

  ver result= instance. test.call();

where "instance" is an instance of deployed contract. But what about the above case? The above code can be used in a case where a user interface  interactively tells users that their request has been completed (e.g. their vote has been registered, etc.)


texts: Public keys of owner and sender of a smart contract

texts: I am quite new to ethereum. I would like to know if its possible to write a contract in which, I can know the Owner's public key and 'Sender's public key ?


texts: Is a race possible when checking the contract for liveness?

texts:
I wonder if a race is possible when performing a check of a return value of a call similar to eth.getCode(greeter.contractAddress) for being zero. That is, is it possible that the contract was alive during the check, but self-destructed right afterwards? I am lost with the causality rules of Ethereum.

The example call was copied from the Contract Tutorial.


texts:
I use Geth 1.7.3 in Azure Ubuntu VM to test run mining.

First I sync with main network using:

geth --fast --cache=2048

After I run for 24 hours, the progress is still 4476201 / 4973527 (around 90% sync). Then I stop the sync and change to sync light mode:

geth --syncmode "light" --cache=2048

The sync completed in few minutes. Then, I start mining by:

geth --mine --minerthreads=8

The mining starts, but very soon, it displays the following messages:

INFO [01-26|02:45:44] Commit new mining work                   number=1       txs=0 uncles=0 elapsed=57.163ms
INFO [01-26|02:45:58] Upgrading chain index                    type=bloombits percentage=99
INFO [01-26|02:46:08] Finished upgrading chain index           type=bloombits
INFO [01-26|02:46:34] Block synchronisation started
INFO [01-26|02:46:34] Mining aborted due to sync
INFO [01-26|02:46:46] Imported new block headers               count=0 elapsed=10.641ms number=4457698 hash=8e53f3…0ffac5 ignored=192

Seems that the sync is incomplete, and sync starts at block 4457698 (I thought I have completed syncing already). I cross-verify with the eth.syncing command in geth console:

{
  currentBlock: 4478249,
  highestBlock: 4973527,
  knownStates: 264144,
  pulledStates: 261773,
  startingBlock: 4457506
}

So, do I need to sync all over again? Since I'm not specifying sync mode in the mining command, does the Sync mode run in full mode now? How to check which mode the syncing is using?

Thanks in advance.


texts: Defining a block reward contract in Parity Aura consensus

texts:
I've been looking at creating a block reward contract for Parity (as documented here).  I'm wondering if I would be able to model a system using this that would send all the wei spent on a transaction back to a central faucet account.

The interface for these contracts looks as though it takes a list of accounts and reward types, and allows you to assign static values to send to those accounts, but there's no information available about the gas price/amount that went into that block.  Is that wei just burned, or is it awarded to the block author in addition to what the reward contract distributes?


texts: Three tokens transfer between each other

texts: I would like to write three token contracts A, B and C that can interact with each other. A is the main token, B and C are the sub-tokens. A buyer can buy the main token(token A) and use them to buy the sub-tokens(token B and token C). After buying the sub-tokens, the buyer's balance of the main token should decrease, and the balance of the sub-tokens should increase. How should I design these three contracts? I am now modifying the ERC20 standard token, but I don't know how to design the function transferFrom in the ERC20 to satisfy the above conditions?


texts:
My doubts have to do with an implementation where a user fills a form, form data is stored in IPFS. IPFS returns a hash which is stored on Ethereum Blockchain against email ID as primary key (Solidity array). My implementation uses truffle v2 (https://github.com/shivamdawer/ethereum-ipfs-storage), and has web3.js and ipfs.js on client side. My questions are :

Should web3 be used on client side or on server side? I read somewhere that it was originally meant for server side, but I haven't found any boilerplate for the same.
Current implementation works successfully on localhost (testrpc port 8545, ipfs ports 5001 & 8080). But on replacing localhost with https://servername.com, I get '

  There was an error fetching your accounts.', 'The page was loaded over
  HTTPS, but requested an insecure XMLHttpRequest endpoint. This request
  has been blocked; the content must be served over HTTPS.

'IPFS XHR Error'. Is this because testrpc and IPFS are meant for HTTP only?  How do I address this
3. Somebody suggested that I not use Truffle if i want to go into production mode. Is there a React Webpack boilerplate for Blockchain. If so, please point me in the right direction.


texts: Syncing private blockchain between peers

texts:
I am attempting to have a second node sync up with an original node.

I had previously synced two nodes from the get-go but am unable to add a peer to an already running blockchain. In other words I want to add a peer to an already running network either for the first time or after a disconnect.

I have instantiated and started the chains with the same commands

geth --datadir test/ --maxpeers 55 --nodiscover init genesis.json

geth --datadir test/ --networkid 1234321 console 2>> myEth.log

And they have the same genesis.json files

{
  "config": {
        "chainId": 1234321,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x20000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

What am I doing wrong?
Is there some command I must use to make them sync and peer?

I have already tried admin.addPeer()


texts:
Can someone please help me understand why this smart contract compiles in ReMix?

What is the purpose of the word constant if it doesn't preclude the code from changing the state? I'm looking for a technical answer that explains why Solidity allows this, not just says "that's the way it is."

pragma solidity ^0.4.9;

contract ShouldNotCompile {
    address addr;
    function getSender() constant returns (address) {
        addr = msg.sender;
        return addr;
    }
}


texts: The transaction can get from Web3j but display as failed in Etherscan

texts:
How could I get the real status from EthBlock.TransactionObject(replayPastBlocksFlowable) in Web3j as same as Etherscan?
I couldn't find any status items from Web3j response, how does Etherscan check the status?
https://etherscan.io/tx/0x3b89a03322520c517b36573fff64913bd9eee048e4d754a8d052d68ded78c3d2

Printing EthBlock.TransactionObject from Web3j
{
    "blockHash": "0x2010f10af7babf7c3a0e19b2257820ba5e317b3d322409605a0b2d330af88444",
    "transactionIndex": 204,
    "nonce": 1146,
    "input": "0x",
    "r": "0xc084063d387979c37488d0b22f4ad1c767efcf171f2a1ffd218177d4d12e5950",
    "s": "0x521aa34adbfdb2d5b80b58bb22c8e3899d95c638819bbcbda10bfe464d65ed9f",
    "v": 27,
    "blockNumber": 11151512,
    "gas": 21000,
    "from": "0x00a131e4c53066f5846372e3b0beac4f0b3310e0",
    "to": "0xdc7cd290867032e6a720334dc47f7a0329385adb",
    "value": 255000000000000000,
    "hash": "0x3b89a03322520c517b36573fff64913bd9eee048e4d754a8d052d68ded78c3d2",
    "gasPrice": 81400000000
}


texts: Transfer ERC20 token from smart contract to wallet using sendSignedTransaction

texts:
I have s smart contract that holds ERC20 DAI token that needs to be transfer to my wallet.
Using javascript web3 side on kovan testnet:
const EthereumTx = require('ethereumjs-tx').Transaction

const Web3 = require('web3');
const web3 = new Web3('https://kovan.infura.io/v3/....');

const myWalletAddress =  '0x....';
const myContractAddress = '0x6Ba1.......';

const underlyingAsCollateral = 25;
const underlyingDecimals = 18;
const mantissa = (underlyingAsCollateral * Math.pow(10, underlyingDecimals)).toString();

const rawTx = {
  nonce: '0x00',
  gasLimit: web3.utils.toHex(6000000),
  gasPrice: web3.utils.toHex(20000000000),
  from: myContractAddress,
  to: myWalletAddress,
  value: web3.utils.toHex(mantissa)
}

var tx = new EthereumTx(rawTx, { chain: 'kovan'});
const privateKey = '....';
const privateKeyBuffer = Buffer.from(privateKey, 'hex')
tx.sign(privateKeyBuffer);
const serializedTx = tx.serialize();

web3.eth.sendSignedTransaction(serializedTx.toString('hex'), function(err, hash) {
  if (!err)
    console.log(hash);
  });

Despite the fact it doesn't spew error, the balance doesn't change or the transaction never happens. I suspect the 'value' parameter of rawTx is incorrect, but I'm not sure. Please advise what do I miss.
regards
Edit:
Since I didn't put erc20 token info, I change raxTx:
const underlyingAddress = '0x4f96fe3b7a6cf9725f59d353f723c1bdb64ca6aa'; // Dai
const underlying = new web3.eth.Contract(erc20Abi, underlyingAddress , {
    from: myWalletAddress
});

const rawTx = {
    value: '0x0',
    data: underlying.methods.transfer(myWalletAddress, 1).encodeABI(),
    gasLimit: web3.utils.toHex(6000000),
    gasPrice: web3.utils.toHex(20000000000),
    from: myContractAddress,
    to: myWalletAddress
  }

but still doesn't change the account balance.


texts:
From the solidity docs I have read that:

The version pragma is used as follows: pragma solidity ^0.5.2;

A source file with the line above does not compile with a compiler
earlier than version 0.5.2, and it also does not work on a compiler
starting from version 0.6.0 (this second condition is added by using
^). Because there will be no breaking changes until version 0.6.0, you
can be sure that your code compiles the way you intended. The exact
version of the compiler is not fixed, so that bugfix releases are
still possible.

In npm it seems to be a bit different. From this blog post it says:

So if you see ~1.0.2 it means to install version 1.0.2 or the latest
patch version such as 1.0.4. If you see ^1.0.2 it means to install
version 1.0.2 or the latest minor or patch version such as 1.1.0.

Is semantic versioning in solidity different from that in npm or am I missing something?


texts: Why do we use `serialize` function of `ethereumjs-tx` package before broadcasting a transaction

texts:
I just want to know the purpose/functionality of serialize function which we use before broadcasting a transaction:

const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')

This is the piece of code where I'm using serialize function.


texts: Validation of Smart Contract execution in Ethereum

texts:
Now I understand that miners will run smart contracts in Ethereum and other nodes in the network will be checking the validity of the contract execution from How is a node selected to run Smart Contract in Ethereum

In this case all these nodes are re-running the smart contract and then see whether the result is the same from the miner's execution? I guess not and I wonder how this smart contract validation is done exactly?


texts: web3.js new accounts without local node!

texts:
I am trying to develop an dapp, but since I am running a small server (Windows Sever 2012 R2) with limited space I don't want to host/install an ethereum node, nor geth in my server, because as many of you know it takes many Gb of hard drive.

However, my "dapp" is a simple HTML page for registration. Essentially this page allows users to register and every time a registration occur; I need to designate/create a new ethereum public address with it corresponding private keys for the user. I am planning to save this information in my database (don't judge). Since I am not hosting a node in my server, I know that I need a third party to connect to mainnet in blockchain, therefore, I am using infura! I know some developer say that you can create wallets with: web3.eth.accounts.create() but the fact is that I can use this code in node.js manually and I am able to create new wallets just fine with the following code:

var Web3 = require('web3');
var infura = "ws://mainnet.infura.io/v3/xxxxxxxxxxxxxxxxxxxxxx";
var web3 = new Web3(Web3.givenProvider || infura);
web3.eth.accounts.create(["this is my seed phrase"]);

but when I try to implement the same approach in HTML it doesn't work.
I also try keythereum.js to create wallets with the following code:

var keythereum = require("keythereum");
var dk = keythereum.create();
var readableAddress = keythereum.privateKeyToAddress(dk.privateKey);
console.log("public address:" + readableAddress);
console.log("private key in hex:" + dk.privateKey.toString('hex')

but not luck. I suspect that I may need other dependencies ir order to make it work. Can someone guide me please?

This is the code of my page!

    <!DOCTYPE html>

    <title>Test</title>

<scrip>
var keythereum = require("keythereum");
var dk = keythereum.create();
var readableAddress = keythereum.privateKeyToAddress(dk.privateKey);
console.log("public address:" + readableAddress);
console.log("private key in hex:" + dk.privateKey.toString('hex')
</script>

Registration

Error I get:

  Error: Provided address "undefined" is invalid, the capitalization
  checksum test failed, or its an indrect IBAN address which can't be
  converted. web3.min.js:1:349717


texts: Internal transactions on Rinkeby - Metamask, ICO through wizard.oracles.org

texts:
I have tried to play with solidity and smart contracts.

I created "ICO" through wizard.oracles.org on Rinkeby network. Then I tried to send ethereum there from 2nd account, I received tokens on that second account, but I cannot find where Ether went.

There is internal transaction from smart contract to my account through which I created it, but Metamask balance is not changed.

Should I call some function from smart contract? Its standard ERC20
Thanks.

Smart contract: https://rinkeby.etherscan.io/address/0x7f81fe39b181c4ef88cf30d610760ccad52af2fe


texts: Web3.js batch request error: method.callback is not a function

texts:
If I try to run the example given here: https://web3js.readthedocs.io/en/1.0/web3-eth.html#batchrequest

With the following code:

const batch = new web3.BatchRequest();
batch.add(web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest'));

batch.execute()
.then(res => console.log(res))
.catch(err => console.log(err));

I get the error:

TypeError: method.callback is not a function

Does anybody have experience with this?

version:
    "web3": "^1.0.0-beta.55"


texts:
I'm getting this error in Console OPTIONS http://localhost:8545/ net::ERR_CONNECTION_REFUSED ,Error: Error: Invalid JSON RPC response: ""  when trying to execute this piece of code from a webpage on VPS (http://example.com/test-app/web3-test.html):

   <html>
    ......
    <body>
     <button class="btn btn-primary" onclick="createAccount();">Create Account</button>
    .....

    <script src="/js/web3.js-1.0.0-beta.34/dist/web3.min.js"></script>
    <script type="text/javascript">

    //var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))

    function createAccount(){
        web3.eth.personal.newAccount('123456789abc', function(err, res){
            console.log("Error: "+err);
            console.log("Res: "+res);
        });
    }

    </script>
</body>
<html>

I have installed already ethereum on my VPS.

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum

And geth --rpc is displaying this in terminal(connected with live server through ssh)

INFO [04-17|20:14:09] IPC endpoint opened                      url=/root/.ethereum/geth.ipc
INFO [04-17|20:14:09] HTTP endpoint opened                     url=http://127.0.0.1:8545    cors= vhosts=localhost

I guess its a CORS issue, is there geth default setting to fix?(I don't want to install CORS extension for temp fix also I'm not using Node js, its a simple web page where I included web3 version 1 file)

Also tried this: geth --rpc --rpccorsdomain "*" --rpcapi db,eth,net,web3,personal

And output in terminal is:

INFO [04-17|20:52:32] IPC endpoint opened                      url=/root/.ethereum/geth.ipc
INFO [04-17|20:52:32] HTTP endpoint opened                     url=http://127.0.0.1:8545    cors=* vhosts=localhost

Thank you everyone...


texts: token (deployed by other crowdsale) not showing up on Etherscan

texts:
I have a crowdsale that creates a token. The crowdsale shows up on Etherscan and can also be used on MyEtherWallet. I read the token address which gets created by the crowdsale constructor via MEW but it is not visible on Etherscanand does also not show any values when interfacing via MEW. I was quite sure that I did not make a mistake here, so I checked in my browser console using Metamask:

> function cb(e,r){console.log(e,r);}
> web3.eth.getCode('0xad819c06a0ee792a9f16cbc5b4acb33fc4a7e4b5', cb) // shows code so it worked!

also trying to read some properties works well:

> let tokn = web3.eth.contract(tokenAbi).at(tokenAddress)
> function cb(e,r){console.log(e,r);}
> tokn.owner(cb)
null "0xf45772f7f459209e398193c80c453807255361e0"

Is this a bug in MyEtherWallet and Etherscan?

(also posted on https://github.com/MyEtherWallet/MyEtherWallet/issues/926)

EDIT:

I got the token address via MEW: Use the contract address of the crowdsale 0xf45772F7f459209E398193C80C453807255361e0 and this snippet is all we need as ABI:

[{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"}]

Then in MEW go on the "Contract" tab, paste address and ABI given above. Reading the only function token returns the token address 0xad819c06a0ee792a9f16cbc5b4acb33fc4a7e4b5.


texts: Can deploy Smart contract from Main thread but not from a class

texts:
I have a contract:

pragma solidity ^0.4.0;
contract qualification {

address owner;

/* This function is executed at initialization and sets the owner of the contract */
function qualification() { owner = msg.sender; }

/* Function to recover the funds on the contract */
function kill() { if (msg.sender == owner) selfdestruct(owner); }

}

contract credentials is qualification {

    string studentName;
    string studentEmail;
    string studentUniversity;
    string studentCourse;
    string studentStart;
    string studentEnd;
    string studentClassification;

/* This runs when the contract is executed */
function credentials(string _name, string _email, string _university, string _course, string _start, string _end, string _classification) public {
    studentName = _name;
    studentEmail = _email;
    studentUniversity = _university;
    studentCourse = _course;
    studentStart = _start;
    studentEnd = _end;
    studentClassification = _classification;
}

/* Main function */
function returnQualification() constant returns (string, string, string, string, string, string, string) {
    return (studentName, studentEmail, studentUniversity, studentCourse, studentStart, studentEnd, studentClassification);
}
}

That I want to deploy from my Java class,

Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    Web3j web3j = Web3j.build(new HttpService());

                    try {
                        com.example.QualificationAuthenticator.Credentials contract = com.example.QualificationAuthenticator.Credentials.deploy(web3j, creds, Contract.GAS_PRICE, Contract.GAS_LIMIT, record.getStudentName(), record.getStudentEmail(), "uuj", record.getCourseName(), "date", "date2   ", record.getClassification()).send();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                System.out.println("thread couldnt finish");
            }

This wont work and I get the error:

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at org.web3j.tx.Contract.deploy(Contract.java:302)
    at org.web3j.tx.Contract.lambda$deployRemoteCall$5(Contract.java:334)
    at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:30)

..and more lines of error

However if I put the deploy call inside of my Main thread then the contract deploys fine.


texts:
I am using this code below and I got an error:

await web3.eth.getTransactionReceipt(this.state.transactionHash, (err, txReceipt)=>{
          console.log(err,txReceipt);
          this.setState({txReceipt})
        }); //await for getTransactionReceipt

        await this.setState({transactionHash: this.state.txReceipt.transactionHash});
        await this.setState({blockNumber: this.state.txReceipt.blockNumber});
        await this.setState({gasUsed: this.state.txReceipt.gasUsed});

The error is:

MetaMask - RPC Error: invalid argument 0: json: cannot unmarshal non-string into Go value of type common.Hash

Can you please tell me how to solve this error?


texts: Displaying AccountBalance via Geth and Web3

texts:
I am throwing together a sample app. I want to query an address and display its account balance.

In the constructor of my React component, I am querying a random address:

constructor(props) {
  super(props)

  var web3 = new Web3(new Web3.providers.HttpProvider());

  // TODO: This should be a form input
  // Bittrex Address
  this.address = '0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98'
  this.accountBalance = web3.fromWei(web3.eth.getBalance(this.address), 'ether');
}

I am running geth with the terminal command:

geth --testnet --fast --rpc --rpcapi db,eth,net,web3,personal --cache=1024  --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*"

When I output this.accountBalance.toString() to the console, it's 0. However, if I output the account balance of a valid address on my local testnet (testrpc), it outputs 100 (default balance).

What am I doing incorrectly


texts:
I was reading Solidity's docs and found this:

// Forward the delegation as long as
// `to` also delegated.
// In general, such loops are very dangerous,
// because if they run too long, they might
// need more gas than is available in a block.
// In this case, the delegation will not be executed,
// but in other situations, such loops might
// cause a contract to get "stuck" completely.

I thought that infinite loops would just consume the gas and revert all the transactions. How can a contract get "stuck" completely?


texts:
I think it's clear that the current ethereum network is not quite suitable for IoT based micro payments. And the slow transition toward PoS, which recently started, will put even more emphasis on gas payment as a reward for mining, hence (correct me if I'm wrong) not enabling an ecosystem for high frequency affordable micro payment system in a foreseeable future.

Are there any development of an alternative on in the ethereum world? Or outside of it?


texts: Could I mine on Ethereum without storing any of the blockchain?

texts: If a reference node provides an API so that I can read from their copy of the blockchain, could I run Ethash, do proof-of-work and claim rewards while not storing anything?


texts: How to compare an address with an address using web3js?

texts:
I've been reading and trying but to no avail. I'm trying to compare the current wallet address in MetaMask with the wallet address which owns a certain token via a smart contract method "ownerOf" which returns the address of the token owner.

I tried using "valueOf()", "JSON.stringify()", toString() and also "localcompare" and none worked. Localcompare always return a value of more than 0 even the two addresses match.

Below is my code.

async function doesTokenIdExist(tokenId, contract, walletAddress) {

  await contract.methods.ownerOf(tokenId).call(function(err,res){
        if(!err){

            console.log("Output of localeCompare: " + res.localeCompare(walletAddress));

            if (tokenAddress.localeCompare(walletAddress) == 0){
                console.log("Wallet owner owns tokenId");
                setTokenExist();
            }

        } else {
            console.log(err);
        }
    });

}


texts: What does the function "abi.encodeWithSelector(bytes4 selector, ...) returns (bytes memory)" do exactly?

texts:
I tried to edit this function according to my smart contract but I couldn't understand this function. I read the docs already. can someone explain this to me with more details and examples?
Thank you.


texts: Best practice for sharing truffle build files between developers

texts:
I am working on a few projects using truffle, as you know truffle compiles and migrates contracts to various ethereum networks e.g. MyContract.sol produces MyContract.json which contains a reference to the address of that contract on that network along with the abi.

One of the problems we are having is how to share these generated build files between the team of devs that work on the project.

Has anyone had any experience with this problem and what's the best solution?

The main problems:

If we commit the build files into the source control, they contain elements which are specific to the users local machine e.g. sourcePath & absolutePath
If we dont commit them then we must either manually update the abi json files to point to the correct contract address

I feel like maybe we are miss understand what the correct process to use when using truffle between teams greater than a few people on a common project

All help appreciated


texts: Can you better explain the 50%+1 rule for token crowd sales?

texts:
I'm a bit confused about having to keep 50% of the token in reserve for the crowd sale. The documents don't really fully explain it.

Question: if I have a token with a total supply of 100 and I hold 25 and send 25 to my other wallet, "address a",  and I then send the other 50 to "contact c" for a crowd sale, how many tokens can I offer in the crowd sale contract?

Can I offer all 50 or only 25?

Sorry, I didn't mean for that to sound like an SAT question, I just don't understand how many tokens I need to issue total.


texts: What happens is somebody deploys illegal content to the public ETH blockchain?

texts:
Once a smart contract is out there on the blockchain, it can't be removed, it can only self-destruct. A smart contract can store around 1.49 GB of data (source: Is there a (theoretical) limit for amount of data that a contract can store?)

So what would happen if somebody deployed a smart contract, which contains some illegal material? e.g. copyright infringement or worse?

How would it be possible to remove that? Is there no danger that the ETH blockchain would be fully loaded with undeletable illegal material?

I'm more into the theoretical side. Maybe not 1.49 GB but a few images. Images from somebody without consent etc. Impossible to remove, censor.


texts:
I have a structure :

struct Track{
    string details;
    byte32 rc;
    byte32 sn;
}
mapping(byte32 => Track)id;

Here I am able to search using id. Required to make search possible for rc and sn. But id is unique for each entry, but more than one entry can have same rc and sn.I want to list those entries;


texts: Accessing a mapping within a struct via Truffle console

texts:
This question was asked here but I thought I would make it a little more clear. Is it possible to access the funders mapping (bolded) via Truffle console in the code below ? This is taken from the Solidity docs:

struct Funder {
    address addr;
    uint amount;
}

struct Campaign {
    address beneficiary;
    uint fundingGoal;
    uint numFunders;
    uint amount;
    mapping (uint => Funder) funders;
}

uint numCampaigns;
mapping (uint => Campaign) campaigns;

function newCampaign(address beneficiary, uint goal) returns (uint campaignID) {
    campaignID = numCampaigns++; // campaignID is return variable
    // Creates new struct and saves in storage. We leave out the mapping type.
    campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0);
}

function contribute(uint campaignID) payable {
    Campaign storage c = campaigns[campaignID];
    // Creates a new temporary memory struct, initialised with the given values
    // and copies it over to storage.
    // Note that you can also use Funder(msg.sender, msg.value) to initialise.
    c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value});
    c.amount += msg.value;
}

After you run newCampaign and contribute to add funds to the newly created campaign, the object returned back is below:

[ '0x740bd112e4d310a69aae3cee9ca8e72d1b1f8a21',
  { [String: '15000'] s: 1, e: 4, c: [ 15000 ] },
  { [String: '5'] s: 1, e: 0, c: [ 5 ] },
  { [String: '16000'] s: 1, e: 4, c: [ 16000 ] },
  { [String: '1504125631'] s: 1, e: 9, c: [ 1504125631 ] } ]

All the variables in the Campaign struct are visible except for the funders variable. Is this because funders is not initialized in storage perhaps?


texts: Whats a good ETH notary service since BTC based OP_RETRUN txns are taboo?

texts:
I want to notarize a SHA256 hash of a document I have.  Before ETH I would have used a BTC OP_RETURN transaction service.  Since BTC is trying to reduce notary spam, what would be a good ETH notary service that people might recommend that the ETH community doesn't frown upon?

A look at OP_RETURN and whether embedding arbitrary data into Bitcoin’s blockchain is spam


texts: Error Ganache: Run out of gas - Works in Remix/Not from dApp

texts:
I am working on an application that stores and retrieves personal data on/from the ethereum blockchain. Just working on this to improve my Solidity and SC expertise and get comfortable with the environment.

Situation:
I am using remix to code my Solidity contracts. I run a ganache-cli on localhost that functions as the private eth blockchain. Using node.js/express, I have build an application that is hosted on localhost at a different address. There is one particular function that creates a profile, taking in 6 parameters (of which 5 strings). Executing this function from within Remix works fine, executing this function from the dApp sends a "run out of gas error". If I set a function that only takes 3/6 parameters, it works like it should; if I add one more the "run out gas"-error shows up.

I have tried manually setting the gas limit of the ganache-cli to something high (24 million) and done the same when deploying it using Remix. Still, I can't get it to work.

Does anybody have any idea what could be the issue here? Thanks in advance.


texts:
Let's say you have a private blockchain, a DApp with an workflow to store and retrieve data from that blockchain. Now there is a need to store binary files and access it in a permissible way.

One way is we can store it using IPFS or SWARM. To make it non accessible by anyone directly the way is we just encrypt it and store it. To view the document one has to go via the DApp to decrypt it and then view.

But while developing an enterprise level application there maybe concern to make the documents available in a public de-centralized storage. Secondly when one encrypts a file the data changes every time due to encryption. Although when de-crypted one can retrieve the original file. What it means is, every time one stores the same file in IPFS/SWARM, because data has changed due to encryption a new file is created, which defy one of the basic feature of these decentralized storage applications (i.e. same content same hash).

So this is what I am looking for

An external storage app
Accessible in private network only and not in public
Should easily fit with Ethereum
Provide permissioned based access
Return a hash of the file created in the storage which could be stored in 5. blockchain
If possible directly integrate with the contract otherwise via NodeJS

Please share details in this regard as to what apps meeting these above listed criteria are available and some links to the same


texts: FIFO transaction ordering - how does this work in practice?

texts:
From what I understand, when you broadcast a transaction from a node or a service provider like Infura, it's broadcasted to other nodes and added to their mempool. Those nodes then broadcast that transaction to other nodes until it's picked up by a miner and processed.
If two transactions have the same GAS price, they will be ordered based on FIFO. But how is this determined:

If each node has it's own mempool, how is this FIFO decided? These two transactions might come from two completely different providers and reach different mempools at different times. Will they be ordered simply by which one reaches the mempool of the miner node?

Does the original broadcast time affect this ordered? I.e. if transaction A was broadcast to it's node first, transaction A will be ordered before transaction B (even though B was broadcast to another node)?


texts: IF statements in Solidity not behaving as expected

texts:
When I fire this function for the first time it seems revealEnd = now; fires because the reveal period ends.  Yet revealCount does in fact display '1', indicating that we went into BOTH if statements.

The first time through however the first if statement should be false and revealEnd = now; should be completely skipped...

Is there something wrong here?

function reveal(uint _values, uint _secret)
    onlyAfter(biddingEnd)
    onlyBefore(revealEnd)
{
    //var bid = choices[msg.sender][0];

    if (revealCount == 1)
        playerTwoChoice = _values;
        revealCount = 2;
        playerTwoAddress = msg.sender;
        revealEnd = now;

    if (revealCount == 0)
        playerOneChoice = _values;
        revealCount = 1;
        playerOneAddress = msg.sender;
}


texts: Is it possible to estimate used gas based on algorithm's Big O?

texts:
[Example Algorithm 1]: I have an array of structs(PaymentReceipt[] paymentReceiptList;) and imagine there are around 1000 pushed items and array's size keep increases. Each item has a time_start and time_end value. Inside my contract's function, I have to iterate all those members to check if any two intervals overlap among a given set of intervals, which is O(n) time.

[Example Algorithm 2]: I use an algorithm function to compute nth Fibonacci number to find 1000th value. This is a recursive function to compute nth Fibonacci number and is of O(log(n)) time.

For Algorithm_1, with a small set, and for Algorithm_2 if nth value is small there should be no problem. But large size of the array on Algorithm_1 and large value for n on Algorithm_2, I may face with inefficient gas problem. I was not sure will both of those algorithms will consume high amount of gas or not based on given n. I want to figure out the highest n that I can use for both algorithms based on given gas amount.

[Q] Is it adviced to do O(n) and O(log(n)) time algorithms inside a Contract's function, if yes, is there any way to estimate the required gas as some kind of function based on the given n for the each algorithm?

=> Related to previous question; does used gas changes for each algorithm as same ratio with O() time?

For example:
For Algorithm_1: Can we say that does the used gas will have same ratio with O(n) time.

O((n=10))       usedGas=10
O((n=100))      usedGas=100
O((n=1000))     usedGas=1000

For Algorithm_2: or can we say that does the used gas will have same ratio with O(log(n)) time.

O(log(n=10))    usedGas=10
O(log(n=100))   usedGas=20
O(log(n=1000))  usedGas=30

Thank you for your valuable time and help.


texts: What is the equivalent of solidity to perform ethereumjs-abi.soliditySHA3?

texts:
I am trying to tightly pack some typed-data (array of structs or nested JSON) and generate SHA3 hash from it.

In JS, I can use ethereumjs-abi.soliditySHA3() method,

ethAbi.soliditySHA3(
    ['bytes32', 'bytes32'],
    [
      ethAbi.soliditySHA3(new Array(typedData.length).fill('string'), schema),
      ethAbi.soliditySHA3(types, data)
    ]
  );

The above code snippet is how Metamask packed, hashed and eventually signed typed-data. See https://medium.com/metamask/scaling-web3-with-signtypeddata-91d6efc8b290

I want to replicate the logic in smart contract so that I can verify the signature.

In solidity, I tried the following when dealing with an array of 2 elements. Each element has "type", "name" and "value". The schema is a concatenation of "type" and "name".

      bytes32 schemaHash = sha3('string', 'string', elem1Schema, elem2Schema);
      bytes32 dataHash = sha3(type1, type2, elem1Data, elem2Data);
      bytes32 hash = sha3('bytes32', 'bytes32', schemaHash, dataHash);

The solidity code doesn't generate the same hash as the JS code.
I suspect I am not packing the data correctly or use the wrong solidity function.


texts: Can a smart contract safely store and use private keys?

texts: Is there a way for a smart contract to safely store (and maybe use) private keys from other blockchains?


texts: When locate a block with both the hash and block number?

texts:
In the go-ethereum code, I see functions use both the number and block hash to locate a block.

Why is that? Isn't block hash enough?

An example function: https://github.com/ethereum/go-ethereum/blob/eea3ae42a3d9bcbd33474c0e482754c5196a469f/core/block_validator.go#L53


texts:
Assume a scenario where we want to send digital signatures to a smart contract.

A user will sign a message with his/her private key and use the signature as input when triggering a smart contract.
A function in the smart contract will then use the sender's public key to decrypt the digital signature and compare it a stored value. (For simplicity, assume we are not concerned with replay attacks.)

Is there any way to do this using Solidity? Are there any known libraries that can be used?

There is an ecrecover function which returns the signing address of a signed message. However, this does not return the message itself.
The only use of this function is to make sure all the message sent are signed by the same sender. This is discussed nicely here: ecrecover from Geth and web3.eth.sign


texts: Testing smart contract with solidity vs javasciprt

texts:
I see the truffle have 3 major ways of testing smart contract

1) Testing smart contract with solidity
2) Testing smart contract with javascript (without web3)
3) Testing smart contract with javascript (with web3)

What are the advantages and disadvantages of each and which to decide.


texts:
I am currently taking a look at the slides from this presentation

I suppose the question is less with formal verification and more with solidity. Can some one help me understand what can possibly go wrong with this contract on transfer?

contract Token {
  mapping(address => uint) balances;
  function transfer(address from, address to, uint amount) {
    if (balances[from] >= amount) {
      balances[from] -= amount;
      balances[to] += amount
    }
  }
}

  Question : Example: Is the sum of all balances unchanged by
  transfer()?

Coming from a c++ background , i honestly do not see the issue.


texts: What is the approximate bandwidth used for first sync?

texts:
I began syncing the ethereum blockchain the other day and to my horror 2GB had downloaded with no sign of stopping. I've very limited bandwidth, so I cancelled the sync. Does anyone know how much bandwidth the first sync usually takes?

I was using geth --fast to do the sync. Would the bandwidth usage have been different if I had used parity with --warp?


texts: Standard work-around for using a Solidity constant array (which is not supported) in pure function?

texts:
I have an array in my contract like this and a pure method which uses it like this (simplified exmaple because my real exmaple is many more lines):

uint[16] constant x = [10, 2, 6, 42, 19, 5, 4, 36, 6, 6, 5, 5, 5, 46, 4, 4];

function foo(uint i, uint j) external pure returns (uint) {
    return x[i] + x[j] * 12;
}

But solidity doesn't seem to support this, so I can only figure out to change it to non constant, but then I'm foreced to switch to view even though my function is pure.

uint[16] x = [10, 2, 6, 42, 19, 5, 4, 36, 6, 6, 5, 5, 5, 46, 4, 4];

function foo(uint i, uint j) external view returns (uint) {
    return x[i] + x[j] * 12;
}

it seems I can only keep the funciton pure if I changd it in to a bunch of seperate uint insted of uint[16] but that's messy.

Is there a workaorund which keeps my function pure? Is just making it view the standard work-around to this?


texts: Transfer() will transfer the ether in the form of wei or ether by default?

texts:
pragma solidity ^0.4.17;
                //  I want to write a code for  loyalty points when user pays
                contract GiveRefreceId {

                     mapping(address => uint256) public referenceid;
                        address[] public clients;
                        uint256 idcounter;

                    struct  MlMMembership_Payment{
                        string CompanyName;
                        uint256 DistributorId;
                        uint256 RefrenceDistributorId;
                        uint256 Amount;
                    }

                    MlMMembership_Payment[] MlMember;

                        event createdId(address user, uint256 id);

                        function giveRefrenceId() public returns (uint256)  {
                            require(referenceid[msg.sender]==0);
                            idcounter += 1;
                            clients.push(msg.sender);
                            referenceid[msg.sender] = idcounter;
                            emit createdId(msg.sender,idcounter);
                            // return createdId[1]
                            return idcounter;
                        }

    function MLMloyalityPoints(string _Compney_name,uint256 _refreeid) public payable {
        uint256 temprefreeid  =  _refreeid-1;
        var  tempaddress = clients[temprefreeid];
        //return tempaddress;
         tempaddress.transfer(1000000000000000);

        }

}

1) I have written a  code in solidity  clients is a array type  which stores a address

2) Now my function MLMloyalityPoints  will get pass in the id  and i will pass  the id to my  clents[] array

3) I am expecting it will give  a  address with is at index at 0

4) Now i  want to transfer value to that address  by using transfer method
i am  getting error while intracting

5)Any suggestions  in code i am thinking there is something wrong in transfer()  method i refreed to many documention they say diffrence between send and transfer


texts: How can I sign a message off-chain and verify it in the contract method that it was signed by a specific address?

texts: I have a public / private keys. I release a contract with these keys. I want some user to withdraw a token / ether, so I sign some message like {withdraw: 10, nonce:1} offchain. User uses this signed message to call some withdraw method. How can I confirm in that withdraw method that I signed that message? Either Python or PHP for signing the message will do.


texts: Error trying to create a crowdfunding contract?

texts:
I am using the template code found on the Ethereum website for crowdfunding and when I insert it in the solidity contract source code in the Ethereum wallet, it returns:

  Unused local variable

contract token { function transfer(address receiver, uint amount){  } }

What am I supposed to write there so the contract gets properly read in the wallet?


texts: Total ethereum transaction count on chainlink request

texts:
I am trying to figure out how many different transactions on Ethereum will be created when, for example, I request price of ETH using an API GET call from TWO different oracles?
Here is what transaction life cycle looks like based on my understanding.
My smart contract will send the request to oracle smart contracts (+2) which will connect to two different oracle to get result (through events, not actually call happens).
Returned results from oracles will be aggregated (off-chain) and reported to chainlink SC which will trigger a callback function to my smart contract (+1).
Is it true that this request will create FOUR different transaction on Ethereum? Am I missing anything?


texts: Sending ether to Contract from another Contract

texts:
pragma solidity ^0.5.0;

contract Contract1 {

  address payable owner;
  uint public value;

  constructor() public payable {
    owner = msg.sender;
    value = msg.value;
  }

  function() external payable {

    value = msg.value;

  }

}

contract Contract2{

    Contract1 public c;

    function setContract(address payable _addr) public{

     c = Contract1(_addr);

    }

    function() external payable{

    }

    function sendEther() public payable{

        address(c).transfer(msg.value);

    }

}

Whenever I try to call the sendEther() I get the following error

  transact to Contract2.sendEther errored: VM error: revert.
  revert  The transaction has been reverted to the initial state.
  Note: The called function should be payable if you send value and the value you send should be less than your current balance.  Debug the transaction to get more information.


texts: DAG generation failure Reason: Invalid argument

texts:
I'm using ethminer, the geth is synced and I used to be able to mine. The ethminer stopped working suddenly saying that : DAG generation failure.

I tried removing old DAG files and it didn't help. Can someone help me with this.


texts:
I noticed that geth stopped running on my system, so I tried restarting it but got the following error:
Fatal: Error starting protocol stack: datadir already used by another process

I checked whether there is another active instance of geth by running ps aux but found nothing. So I'm not sure how the directory can possibly be used by another process. Any ideas for debugging this situation?


texts: transferFrom function works but approve does not

texts:
I'm building an escrow contract and using web3js to interact with it. Currently, I am trying to approve and send an amount of custom ERC20 token from a wallet to the escrow contract. The problem is, the approve function doesn't work, but the transferFrom function that I call from the escrow contract itself does. I know the approve function doesn't work because I check the allowance from Remix and it shows none. Why does one transaction work and not the other?

Transaction Data:

//This doesnt work
    let approveSpender = async(batch=false) => {

                const txOptions = {
                    from: address_from,
                    nonce: await web3.eth.getTransactionCount(address_from, "pending"),
                    gasLimit: web3.toHex(210000),
                    gasPrice:web3.toHex(web3.toWei('30', 'gwei')),
                    to: gntAddress,
                    data :gntContract.approve.getData(escrowAddress, (40e18)),
                    value: "0x0",
                };
                let transaction = new EthereumTx(txOptions);

                if(batch) return sendRaw(transaction);

                const txResult = await sendRaw(transaction);
                if(!txResult) {console.error('Something messed up')}
                else console.log('Actually worked?');
            };
//This works
    let depositToEscrow = async(batch=false) => {
                let nonce = await web3.eth.getTransactionCount(address_from, "pending");
                if(batch) nonce += 1;

                const txOptions = {
                    from: address_from,
                    nonce: nonce,
                    gasLimit: web3.toHex(210000),
                    gasPrice:web3.toHex(web3.toWei('30', 'gwei')),
                    to: escrowAddress,
                    data :escrowContract.deposit.getData((40*1e18)),
                    value: "0x0",

                };
                let transaction = new EthereumTx(txOptions);

                if(batch) return sendRaw(transaction);

                const txResult = await sendRaw(transaction);
                if(!txResult) {console.error('Something messed up')}
                else console.log('Actually worked?')
            };


texts: How to compute the Contract Address from the Transaction Hash?

texts:
I am aware that different versions of this question were asked but my interest is specifically working out the contract address following dynamic deployment in a UI using web3 or something similar. I can recover the transaction hash and I want the contract address before it is fully deployed.

What happens is the UI session ends before the return to it by Metamask.

I think the best answer is to compute the contract address manually and then store that off chain (that is needed for the use case). Another option is to somehow wait for the return by Metamask.

This is my code -

 status("compiling");
    document.getElementById("compile-output").value = "";
    var result = compiler.compile(getSourceCode(), optimize);
    var stringResult = JSON.stringify(result);

    var bytecode = result.contracts.greeter.bytecode;
    var abi = result.contracts.greeter.interface;

    web3 = new Web3(web3.currentProvider);

    // Our future code here..
     web3.eth.defaultAccount = web3.eth.accounts[0];

    var contract = web3.eth.contract(JSON.parse(abi));
    var hash = web3.sha3(getSourceCode());

    contract.new(
       {
         from: web3.eth.accounts[0],
         data: "0x"+bytecode,
         gas: '4500000'
       }, function (e, contract){
          console.log(e, contract);
          if (typeof contract.address !== 'undefined') {
             console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
           }
    });


texts: How can I calculate the real Ethers from the API of etherscan

texts:
Having this address:
https://etherscan.io/address/0x7cB57B5A97eAbe94205C07890BE4c1aD31E486A8

The balance on the web is 21.76252288478066826 Ether

But using the API the balance is:
https://ropsten.etherscan.io/api?apikey=GY9KKYEJF1HDEPIAIRGA66R2RIQWQXV9UZ&module=account&action=balance&address=0x7cB57B5A97eAbe94205C07890BE4c1aD31E486A8&tag=latest

5000014636180791194320764

I don't even know what unit is that. Because the documentation don't say anything.


texts: Trying to interact with ganache-cli fork through script

texts:
const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent} = require ('@uniswap/sdk');
const ethers = require('ethers');

const chainId = ChainId.MAINNET;

how would I specify it to be the locally forked ganache chain?
tried this:
const Web3 = require('web3');
const web3 = new Web3(`http://localhost:8545`);

const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';

const init = async ()=> {
  const chainId = await web3.eth.getChainId();
...

following error is shown:
/Users/GreyShadow/node_modules/@ethersproject/logger/lib/index.js:179
        var error = new Error(message);
                    ^

Error: unsupported getDefaultProvider network (operation="getDefaultProvider", network={"chainId":1337,"name":"unknown"}, code=NETWORK_ERROR, version=providers/5.0.17)

Help is much appreciated


texts: Import accounts of Ropsten node in localhost to metamask

texts: I have ropsten node in localhost:8545 with 2 accounts. Inorder to connect ropsten and metamask I need wallet seed... From where I could get wallet seed for accounts in localhost.


texts: What function/method does MetaMask use to generate the entropy for mnemonic keys?

texts:
I am trying to understand how exactly MetaMask is generating the initial entropy to create its mnemonic key. There are questions like this, MetaMask's documentation, or their GitHub but I can't find the answer I'm looking for in either one.

What is the source of entropy in MetaMask for generating mnemonic words (if they are using BIP39)? If not BIP39, what standard are they using to create mnemonic words?


texts:
The below given code is from the a tutorial given here at one of the tutorials on Truffle

// Set the provider for our contract
App.contracts.Adoption.setProvider(App.web3Provider);

I see we set up a Web3 provider for the contract.

What basically are providers? What do they do?


texts: Ethereum private key recovered from Chrome

texts:
I had an IDEX exchange eth address created, long time ago and I no longer find the private key or keystore file.

Until today I was just opening Chrome and everything was working without to ask for my pvkey.
Can chrome save my private key in previous cookies or memory files?
If yes, can be recovered?

Thanks a lot!


texts: How does a node execute the smart contract in the EVM and update the blockchain with result of contract execution

texts:
I would like to understand how the Ethereum Node is loading the contract bytecode in the EVM and then write everything that it needs, back to the blockchain.
This is how I understand it.
The contract get compiled into bytecode.
It's deployed on the chain.
When a user call that contract address to run a function.
The node loads the contract in the EVM as bytecode.
Run the request made by the user.
It all happens in the EVM.
So how, after execution on the node. does the node Write back the new data on the blockchain?
For example my contract have an empty array.
One of the function to call will add an entry in the array.
The new array contain 1 entry and need to go back on the chain. Does the node pull the data from EVM to recompile and rewrite it? I doubt it works like that since the EVM serve the purpose of running a code in the virtual environment.
My best guess would be that the EVM is actually program to run the bytecode and then rewrite the new content on the blockchain.
Now as per why this question?
I'm trying to repeat the process with the JVM or the V8 engine VM in NodeJS.
Instead of using solidity, I compile Javascript into Bytecode. So this would be my smart-contract like.
And it's working. I can load a Javascript in the VM and call the functions and get response back.
Now all this code remains in the VM. And this is where I'm not sure what I would do next.
In my example where a call add an entry in an array. I want to write that new array back to the blockchain and I'm not sure about the approach. Does the Ethereum node make the bridge between EVM and the Blockchain? Or does the node use the EVM and only interact with the EVM that in turns interact with the blockchain?


texts: msg.sender.transfer(purchaseExcess); failure in solidity test

texts:
Got an exception at the line msg.sender.transfer(purchaseExcess); in my truffle solidity unit test. Any idea the reason?

my contract code:

function purchase(uint256 _tokenId) public payable {
    address oldOwner = tokenOwner[_tokenId];
    uint256 sellingPrice = emojiIndexToPrice[_tokenId];
    address newOwner = msg.sender;

    require(oldOwner != newOwner);

    require(newOwner != address(0));

    require(msg.value >= sellingPrice);

    uint256 percentage = SafeMath.sub(100, ownerCut);
    uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentage), 100));
    uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);

    emojiIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), percentage);

    _transfer(oldOwner, newOwner, _tokenId);

    if (oldOwner != address(this)) {
      oldOwner.transfer(payment);
    }

    msg.sender.transfer(purchaseExcess);
}

unit tests code:

contract TestEmojiCoin {
    uint public initialBalance = 1 ether;

    function testPurchase() public {
        address contractAddress = DeployedAddresses.EmojiCoin();
        EmojiCoin emojiCoin = EmojiCoin(contractAddress);

        // Emoji 0 is created in previous test.

        emojiCoin.purchase.value(1 ether).gas(30000000000)(0);
    }
}

error msg

     Error: VM Exception while processing transaction: revert
  at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
  at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
  at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
  at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
  at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
  at endReadableNT (_stream_readable.js:1101:12)
  at process._tickCallback (internal/process/next_tick.js:114:19)


texts: Store data on ethereum blockchain from a text file

texts:
I have a simple smart contract running over a local Ethereum node. It has two functions: one for sending data and another for retrieving it back. I have a text file and want to send data from it to the smart contract to store in the blockchain, something like autofilling a web form. I am running a local ethereum node using geth and attaching it to the web3 provider environment in the remix ide.

Can anyone suggest any methods that will be useful for doing this?

Here is the solidity code

pragma solidity ^0.4.18;

contract MemUsage {
  uint cpu;
  uint ram;

  function setVal(uint _cpu, uint _ram) public {
    cpu = _cpu;
    ram = _ram;
  }

  function getVal() public constant returns (uint, uint) {
    return (cpu, ram);
  }
}

And this solidity code is attached to this form

Here is the code for the form

<!DOCTYPE html>

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

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

Memory Usage

        CPU
        <input id="cpu" type="text">

        RAM
        <input id="ram" type="text">

        <button id="button">Update</button>

Now, I have a text file with multiple cpu and ram values. I need to automate the form filling process so that I do not have to manually enter all the values through the form.

Thanks


texts: In Ethereum blockchain does smart contract can have token balance

texts: In Ethereum we have 2 different types of account Externally owned accounts (EOAs) and Contract accounts . EOA's can have balance of ether and tokens . smart contract can have balance of ether, but can they have balance of tokens? I have created ERC 20 token , can i send this tokens to other smart contract?


texts: How can I create a modifier that requires the msg.sender be one of multiple addresses?

texts:
I apologize if this has been asked already.  It seems like a very basic question but I cannot find an answer to it.  Every example of using a modifier to create a "ownerOnly" function uses the "owner = msg.sender" in the constructor, but what if I want to allow a few different addresses/people to modify a contract or execute a function.  How do I write the modifier to do this?  I tried this, but it didn't work:

modifier onlyMembers {
    require(msg.sender == owner || "0xdaa602d3e2aeea57ee753e40ac1639ed20e3174f" || "0x3147ca98dc9235e38c4cd3f82315332294e9234a");
    _;
}

I also tried using checksum addresses and created new, global address variables called "member1" and "member2" which point to those addresses like this:

contract Autos {

address owner;
address member1;
address member2;

constructor() public {
    owner = msg.sender;
    member1 = 0xDAA602D3E2Aeea57eE753E40AC1639eD20e3174F;
    member2 = 0x3147cA98dc9235e38c4cd3F82315332294e9234A;
}

modifier onlyOwner {
    require(msg.sender == owner || member1 || member2);
_;

}

Remix tells me "Operator || not compatible with types bool and address", but I feel like there must be a way to "or" the addresses somehow.


texts: On the unstructured storage upgrade pattern, why do we have to follow the structure of the previous contract?

texts:
ZeppelinOS has adopted the unstructured storage proxy pattern to upgrade contracts.

In the blog post that introduces this pattern, they say:

"The only thing you will have to care about is that further versions of your contract have to follow the storage structure of the previous ones."

What does it mean to follow the structure?
And why is it that we have to follow the structure?


texts: What number of confirmations is considered secure for Geth PoA Clique?

texts:
In Ethereum PoW the recommendation is to wait for 12 confirmations at least.

[Q]: What rules to apply for Geth PoA Clique algorithm?

My best guess so far:

lower limit: sum of confirmation block difficulties >= (floor(N/2) + 1) * 2

upper limit: sum of confirmation block difficulties <= N * 2

where N = number of sealers in the network

The reason that I'm multiplying with 2 is that in-order sealers are contributing 2 to the block difficulty, otherwise it's 1.

Update. After reading Castro/Liskov Paper on PBFT (http://pmg.csail.mit.edu/papers/osdi99.pdf), I beleive that the rule of 2*f + 1 confirmations for a N = 3*f + 1 applies for Clique too. At least as lower limit. Upper limit could stay as is. See the comment below.


texts: lost private key for MEW . how can i move my tokens from Etherscan

texts: Lost private key for MEW. How can I move my tokens from Etherscan to another wallet or exchange?


texts: delegatecall executes but does not change state

texts:
I am trying to make use of delegatecall function in solidity.

function delegateTokens(uint256 _value) returns (bool result) {
    tokens[msg.sender] = _value;
    return token.delegatecall(bytes4(sha3("transfer(address,uint256)")), address(this), _value);
}

There is no error thrown but values are not changed.
Code is available at https://github.com/nirmalgupta/delegatecall steps to reproduce is also available there. Any help with this is appreciated.


texts: Getting "gas required exceeds allowance (93846700840810) or always failing transaction" on private network. How to access geth client via nodejs?

texts:
I have recently started using Ethereum. I am trying to test my contract using multiple machines. Only solution I found was to setup a private network using Geth and add peers. Following is the genesis block for my network.

{
"config": {
"chainId": 16,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"alloc": {},
"difficulty" : "200"
"gasLimit" : "99999999999999"
}

I created nodes/accounts on both the machines. Have been able to add peers as well as send ether and do dummy mining etc. on both the nodes. I use the following command to start the network.

geth --datadir ./exp3 --networkid 16 --rpc --rpcapi "eth,net,web3,personal,miner" --nodiscover --allow-insecure-unlock --port 3000 console

My project was in Truffle Suite so I changed my truffle-config as following:

rpc: {
host: "localhost",
port: 8545},
networks: {
development: {
  host: "127.0.0.1",     // Localhost (default: none)
  port: 8545,            // Standard Ethereum port (default: none)
  network_id: "16",       // Any network (default: none)
  from: "0xf4ffdeedd1f02171e554e4ef40fb42a9f087166f",
  gas: 20000000,
  websockets: true}

All of this runs well, the contract is depoyed. Now, when I run a NodeJS script to even estimate the gas it shows the error: "gas required exceeds allowance (93846700840810) or always failing transaction". My nodejs script is:

var Web3 = require('web3');
var web3_http = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
const fs = require('fs');
const con = JSON.parse(fs.readFileSync('./build/contracts/DecentralisedBroker.json', 'utf8'));
var abi = con.abi;
var cont = new web3_http.eth.Contract(abi, "0x85256Ccc77DD205dabE906bF63c6128c311E7881");
console.log(cont.options.address);
cont.methods.registerUser('XYZ').estimateGas()
.then(function(gasAmount){
console.log(gasAmount);
}).catch(function(error){
console.log(error);});

I don't understand why this problem occurs. The gas limit for each block in genesis.json is pretty high, which I don't think is crossed at all during this call. Also my geth client account has sufficient dummy ether. It may be the case that call is not made from my geth client address but even if I specify the address in the call, it shows the same thing. Is there a way to make calls via the geth client(using nodejs) in ./exp3 folder where the blockchain is instantiated in my system. Following is a snapshot of the function in contract.

struct User{
    string user_name;
    uint8 flag;
    Specification[] requests;
  }
mapping(uint => uint) indexOfPendingRequests;
  mapping(address => User) users;
  address private_blockchain;
  uint total_requests;
constructor(address _blockchain) public {
    private_blockchain = _blockchain;
    total_requests = 0;
}
function registerUser(string memory name) public{
    require(msg.sender != private_blockchain, 'Permissioned blockchain can not be a user');
    require(bytes(name).length > 0, 'Name should be > 0.');
    if(users[msg.sender].flag != 1){
      users[msg.sender].user_name = name;
      users[msg.sender].flag = 1;
    }
    return;
  }

Can you please specify what may be the problem. Also, is there any other efficient way to test contracts on multiple machines (submitting transactions and listening to events, etc.). Thank you.


texts: Struct creates instances with zero values for all of it properties instead of using function arguments

texts:
Inside my smart contract I have a struct type NotaryEntry and a function addNotaryEntry which creates an instance of the struct and add to a mapping, I do pass the right values to the function but the struct is created with zero values and ignores the values I parse to it even though I passed the right parameter types values to the function. How do I resolve this problem? Thanks

This is what function addNotaryEntry creates :

1: string: description
2: uint256: timestamp 0
3: string: hash
4: address: setBy 0x0000000000000000000000000000000000000000
5: bool: isSet false

Below is my code:

    uint filesCount;
    mapping(uint => NotaryEntry) public files;
    mapping(address => uint[]) public personFiles;

    struct NotaryEntry{
        uint id;
        string description;
        uint timestamp;
        string hash;
        address setBy;
        bool isSet;
    }

    function addNotaryEntry( string memory _hash, string memory _desc) public {

        uint _id = filesCount += 1;

        NotaryEntry memory notary;
        notary.id = _id;
        notary.description = _desc;
        notary.timestamp = now;
        notary.hash = _hash;
        notary.setBy = msg.sender;
        notary.isSet = true;
        personFiles[msg.sender].push(filesCount);
    }
`


texts: create new account using personal.newAccount

texts:
How to retrieve their private and public key.I created one ethereum address using command line personal.newAccount .When I am checking this address in etherscan it shows 0 balance but in my ethereum geth its shows have balance.Where I can see the my private ethereum blockchain detail with all transaction.I setup mist wallet also but its not working.Please Help.

Thanks!


texts: Can transaction hash be used to get v, r, s parameters using web3js?

texts:
I am trying to create a function which can be used to get the v, r, s parameters (ECDSA) of the signature.
So i am thinking to pass a random tx hash from etherscan and it will return v,r,s parameters of the signed tx.

Can somebody please help me in this?


texts: Is there a private key of an ICO/Contract?

texts:
I have deployed my contract on the main net, is there any private key of that address? If yes, where can I find it?

Thanks, any help will be appreciated!


texts: How to get the call graph of a mainchain transaction?

texts:
Simple question, but I couldn't find the answer.

There are transactions like this one which involve many chained contracts.

But as storage modify the functions being called and calldata doesn t specify names (but hex) it s hard to find what is being called or delegatecalled by what and where.

I know about emulation solutions which consist of replaying the transaction however, this is not possible here as I don't know the full storage parameters of the involved contract at that block and finding it out would likely mean dtermining what was being called.

So how to perform this?


texts: Block header broke chain ordering - Geth 1.3.5

texts:
I noticed the following log entry from Geth 1.3.5:

queue.go:331] Header #1118680 [a94d89ec] broke chain ordering, expected 1118747

yet the log shows that block #1118680 was successfully downloaded earlier.

What can cause this "broke chain ordering"?  Does these mean another node was late in propogating this block?


texts: Solidity: Creating contracts with contracts by "new" operator

texts:
I'm creating "Trade" contract inside "Token" contract.
I used an array to store each "Trade" contracts.
Used web3, truffle.

Token.sol:

mapping (address => Trade[]) private _Trade;
event tradeMade(address maker);
...
function createTrade(params...)
public{
    Trade newTrade = new Trade(params...); // line A
    _Trade[msg.sender].push(newTrade);     // line B

    emit tradeMade(msg.sender);
}

Trade.sol:

constructor(params..)
public {
    // Set variables. Parameters are correct
}

Run.js:

Token.createTrade(params..., function(err, res){
    // Do jobs
});
var event = Token.tradeMade();
event.watch(function(err, res){
    if(!err) console.log("Maker: " + res.args.maker);
});

Compiling / Migrating: Succeed.

Running js file: Failed with the following Error

> Error: VM Exception while processing transaction: revert

Truffle debugging screen:

Token.sol:createTrade() -> Roles.sol:add() -> Roles.sol:remove():require(has(role, account));
> TypeError: Cannot read property 'replace' of undefined
      at process._tickCallback (internal/process/next_tick.js:68:7)
      at Object.interpreter (C:\Users\cosgenio\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\commands\debug.js:695:1)
      at printState (C:\Users\cosgenio\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\commands\debug.js:167:1)
      at Object.formatRangeLines (C:\Users\cosgenio\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-debug-utils\index.js:233:1)
      at Object.formatLineNumberPrefix (C:\Users\cosgenio\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-debug-utils\index.js:157:1)

and if I continue, it stops with the following error...

Roles.sol:
> Transaction halted with a RUNTIME ERROR.
  This is likely due to an intentional halting expression, like assert(), require() or revert(). It can also be due to out-of-gas exceptions. Please inspect your transaction parameters and contract code to determine the meaning of this error.

When I delete line A and B, the js listener works fine(printing address).
But when I add line A or both, the error happens.

What is making errors now and how can I fix it?
How can I create new contract inside another contract?


texts:
How can I make an asynchronous interaction between two contracts? I have contract A and contract B.

contract A calls contract B
contract B obtains data from an external source
contract B returns the data to A.

is it possible to realize the interaction between A and B through callback?


texts:
contract MyContract {
struct Posposal{
    uint posposalId;//防止复核数组变动时
    address voteSponsorAddr;//投票发起人

    bytes1 description_;//投票内容信息  0 转币  以后扩展
    uint userId;//投票给目标以太币地址所对应的id
    uint amount;//转多少代币
}
Posposal[] public curPosposals; //当前提议投票记录
uint public posposalNextId=0;// 标识投票建议递增

function MyContract() {

}
uint public expId;
address public expTarget;
uint public expAmount;
function issuse(uint userId,address target_,uint amount_)  {
    //投票目标用户肯定是存在的
    expId=userId;
    expAmount=amount_;
    expTarget=target_;
    curPosposals.push(Posposal(posposalNextId,msg.sender,0x01,userId,amount_));//0 未投票 默认情况  1支持票 -1 反对
    posposalNextId++;
}}

Why the curPosposals[0] is wrong? But when I move bytes1 description_; to the end of struct Posposal, all are designed answer. Why?
Following :

invoke function and pass params:

the result:

expId=2 (right); and
curPosposalId[0].userId should be 2, curPosposalId[0].amount should be 20000, but they are wrong. Why?


texts: Clarification on decimals and ERC20 token amount

texts:
I am creating an ERC20 token and have specified decimal as 2 since the token can have values like 10.32

When I minted 1000 coins using smart contract invocation from my dapp, I got 10 coins in my wallet. Shall I assume that in mint function inside smart contract, I should multiple amount with 100 (due to 2 decimals) before actual number of coins are minted? Or is there another way to handle this?

Update: I invoked balanceOf method and it returns the balance correctly as 1000 without any conversion but in my dapp, it shows as 10.


texts: How can I program my DApp to tell my user that their action/transaction has been confirmed?

texts:
Take an example of a voting DApp.  A user clicks on a vote button, then behind the scenes the transaction containing the vote gets mined on the blockchain.  The DApp then wants to alert('You have voted').

Since the transaction takes some time to get mined and get some confirmations, what code should the DApp do before it does the alert?  I have heard of people running loops and calling getTransactionReceipt.  Is this how it should be done, or alternatives?  Are there any code snippets or libraries for them?


texts:
This is my simple html source code for my website.

<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta name="viewpoint" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>ABI test</title>

Successful!

And i got error message :
Uncaught ReferenceError: Web3 is not defined
    at SimpleStorage2.html:21
in the console of website

line 21 is

Web3.providers.HttpProvider("http://localhost:8545"));

i already installed Web3 by npm installation

i also have error message :

'web3.min.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND'

please help me to solve problem
Thank you


texts: which is a better method to use for signing messages between two parties in web3?

texts:
I have been searching for a while for the most secure and supported way for off-chain channel messaging.....so i was using web3.eth.sign(address, keccak256(msg)) for singing messages ....but then used to get a BIG FAT notification in MetaMask when signing that "this is unSafe"....so i started using:

web3.currentProvider.sendAsync(
      {
        method: "eth_signTypedData",
        params: [msgParams, web3.eth.defaultAccount],
        from: web3.eth.defaultAccount
      }, [, call])

as mentioned in this article by Official MetaMask that its more safe and make more sense that the user SHOULD know what they are signing.... but then i get this BIG FAT warning in the console that says:

  MetaMask: This experimental version of eth_signTypedData will be
  deprecated in the next release in favor of the standard as defined in
  EIP-712. See https://git.io/fNzPl for more information on the new
  standard.

when followed the link didn't get a clear answer....so anyone here could help with which way to with ???

Thank you in advance.


texts: Interacting with Contract Abstraction from file

texts:
In the official Truffle Docs over here, it is demonstrated how to interact with a deployed contract. So far, I've come across only the Truffle Console, which is everything but intuitive for larger expressions and .then()-chains.

Is there a way to execute such a script from file, instead of using the interactive console?


texts: How to download contracts by address from Etherscan using web3.js

texts:
I want to download all contracts (open source code) from etherscan.io using Web3js. Etherscan gives only the list of such verified open source contract with txHash, name, and their addresses. Is there any way to write a program that takes address (from mentioned list) and then download its source code and save to local folder. If, yes, then is there any way to download only the source code of contract having version ^0.5. ?

I am trying to follow this code from EtherScan, and intend to give the address field data run-time/dynamically, but I'm not sure how to proceed in web3.js, node.js or with other APIs.
Also, I am not sure how to call $.getJSON? Where it is defined?

    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider());
    var version = web3.version.api;

    $.getJSON('http://api.etherscan.io/api?module=contract&action=getabi&address=0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359', function (data) {
        var contractABI = "";
        contractABI = JSON.parse(data.result);
        if (contractABI != ''){
            var MyContract = web3.eth.contract(contractABI);
            var myContractInstance = MyContract.at("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359");
            var result = myContractInstance.memberId("0xfe8ad7dd2f564a877cc23feea6c0a9cc2e783715");
            console.log("result1 : " + result);
            var result = myContractInstance.members(1);
            console.log("result2 : " + result);
        } else {
            console.log("Error" );
        }
    });

NOTE: I have read all questions regarding this topic on this forum, but no one is providing a solution.


texts: Make a transaction to Node 1 without syncing the blockchain on Node 2

texts:
Is there any way in which I can send a transaction to a contract deployed on Node 1 from Node 2 without syncing the entire blockchain on Node 2. I basically want to access the Node 2 without having the blocks stored on Node 2.

It should be like a 'partial' blockchain.


texts: Store decimal number in contract and then read it back

texts:
I am trying to store a decimal number in a smart contract struct which represent the price of an item.

The field in the struct is uint and I want to store values like 0.001 which is the cost in ether. When I read the cost value I get a BigNumber similar to this:

BigNumber { s: 1, e: 0, c: [ 0 ] }

How can I read the value 0.0001 from the frontend?


texts:
I need a command line compiler in order to make an expert system that automatically builds, tests, and deploys systems of smart contracts based only on metadata. I have tried for several days to install solc without success. I will admit that I only have average intelligence but I thought the point of Ethereum was to empower regular people. It shouldn't be this complicated unless the point of the complexity is to limit the amount of people who can solve the puzzle in a given amount of time. It feels like I am doing a proof of work.

Everything I have tried so far (NPM) is documented but before I post everything here I want to know if there are alternative compilers that can be used in an automated process or if there is another way to install solc or perhaps build it from source. If building from source is an option I will need a tutorial because I have no experience with C++. I do have Visual Studio installed on my machine if that will help.

Very briefly I have tried installing from NPM both locally and globally and I have tried geth --solc path and admin.setSolc('path'). In any case, I don't think defining the path is my problem because after NPM installs there is no solc.exe installed anywhere on my computer that I can find - only a solc directory populated with solcjs files.

Any ideas would be greatly appreciated
Thanks, John

As a side note I had a lot of difficulty making a local blockchain and I had difficulty finding learning resources. To that end I made a tutorial found here on GitHub which should get another noob like me up and running in short order. One can cut and paste code from the tutorial to start a local block chain and the most helpful resources are indexed. I will continue to work on the index to make it more clear and to add new resources as they are found. If I can find out how to install solc I will write something similar so that the next person coming along can have an easier time.

Thanks again, John

Hi All, it's a day later now and I have some of this problem solved.

Neither the command npm install solc nor npm install -g solc actually installs solc. Those commands install JavaScript bindings for solc.

Check out the The NPM page for solc. It is very misleading- it says solc in big letters at the top. But right below are two links where I think solc and be found.

The links are reproduced here and here.

The problem is that I don't know how to install solc from either of those two GitHub pages and so I didn't even recognize them as places where solc could be acquired. I still don't know what to do with those pages.

Not to worry, after googling for a few hours more I found the this page with a big picture entitled Village Idiot. I hope this is some kind of inside joke and not and insult to average people like myself looking for help. Anyway, on this page is a release of of an executable that installs solc along with the Mix IDE, AlethZero, geth and eth.

Now if I start Geth with the following option --solc "C:\Program Files\cpp-ethereum\solc", I can then type eth.getCompilers() into the console and I will see [solidity] as the result returned.

In the alternative I can start geth without the solc option and later type the following command into the JavaScript console when I want to use the compiler.
admin.setSolc('C:\\\Program Files\\\cpp-ethereum\\\solc')
Notice that the JavaScript console requires that three slashes be used where there would normally be only one. I read on Stack Exchange that this is because the slash is an escape character in JavaScript. Also note that a single or double quotes are required around the path in this case because there is a space in the path between the words "Program" and "Files".

I haven't actually tried to compile anything yet. I will report back if there is trouble.

In the mean time I would be grateful if someone would tell me how to install solc from the following pages here and here. I need to know because the version on the Village Idiot page is from June and I don't think the page is supported anymore.

Thanks again, John


texts: 'hex data is odd-length' error occured when using web3 & testrpc

texts:
Here's my code .
var Web3 = require("C:\\Users\\Administrator\\node_modules\\web3")
con_abi = [
    {
        "inputs": [],
        "name": "sloc111",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "pure",
        "type": "function"
    }
]
con_addr = "0x0ed72dfd4c63dd97df8fec07e5a6bba466c6adf5";
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
var echoContract = new web3.eth.Contract(con_abi,con_addr);
// console.log(echoContract.sloc111);
// console.log(typeof(echoContract));
echoContract.methods.sloc111().call().then(console.log);

Error :
Error: hex data is odd-length (argument="value", value="0x0", code=INVALID_ARGUMENT, version=bytes/5.1.0)
    at Logger.makeError (C:\Users\Administrator\node_modules\@ethersproject\logger\lib\index.js:180:21)
    at Logger.throwError (C:\Users\Administrator\node_modules\@ethersproject\logger\lib\index.js:189:20)
    at Logger.throwArgumentError (C:\Users\Administrator\node_modules\@ethersproject\logger\lib\index.js:192:21)
    at Object.arrayify (C:\Users\Administrator\node_modules\@ethersproject\bytes\lib\index.js:79:24)
    at AbiCoder.decode (C:\Users\Administrator\node_modules\@ethersproject\abi\lib\abi-coder.js:93:53)
    at ABICoder.decodeParametersWith (C:\Users\Administrator\node_modules\web3-eth-abi\lib\index.js:304:30)
    at ABICoder.decodeParameters (C:\Users\Administrator\node_modules\web3-eth-abi\lib\index.js:285:17)
    at Contract._decodeMethodReturn (C:\Users\Administrator\node_modules\web3-eth-contract\lib\index.js:470:22)
    at Method.outputFormatter (C:\Users\Administrator\node_modules\web3-eth-contract\lib\index.js:760:42)
    at Method.formatOutput (C:\Users\Administrator\node_modules\web3-core-method\lib\index.js:147:54)
    at sendTxCallback (C:\Users\Administrator\node_modules\web3-core-method\lib\index.js:523:33)
    at C:\Users\Administrator\node_modules\web3-core-requestmanager\lib\index.js:308:9
    at XMLHttpRequest.request.onreadystatechange (C:\Users\Administrator\node_modules\web3-providers-http\lib\index.js:9
8:13)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\Administrator\node_modules\xhr2-cookies\dist\xml-http-request-e
vent-target.js:34:22)
    at XMLHttpRequest._setReadyState (C:\Users\Administrator\node_modules\xhr2-cookies\dist\xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\Administrator\node_modules\xhr2-cookies\dist\xml-http-request.js:318:
14) {
  reason: 'hex data is odd-length',
  code: 'INVALID_ARGUMENT',
  argument: 'value',
  value: '0x0'
}

My TESTRPC version is
EthereumJS TestRPC v6.0.3 (ganache-core: 2.0.2)

Thank you!


texts:
I am seeing a lot of posts that suggest that peer discovery isn't possible on private networks.  Here is one:

Automatic peer discovery in a private blockchain

And another (less clear on this point):

Peer discovery not working on private network

So that raises a few questions:

1) Is that actually true?

2) Is it true with Parity as well as geth?

3) If (1) is true, then does anyone know how Expanse, etc. handle peer discovery?

Thank you.


texts: Have any (cryptocurrency + blockchain)s switched from proof-of-stake to proof-of-work?


texts: API Call in solidity: gas required exceeds allowance (8000029) or always failing transaction

texts:
I'm trying to make an API call in solidity.

pragma solidity ^0.6.0;

import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";

contract GetData is ChainlinkClient {
  uint256 public currentPrice;
  address public owner;

  address ORACLE = 0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;
  string constant JOB = "c179a8180e034cf5a341488406c32827";
  uint256 constant private ORACLE_PAYMENT = 1 * LINK;

  constructor() public {
    setPublicChainlinkToken();
    owner = msg.sender;
  }

  function requestEthereumPrice()
    public
    onlyOwner
  {
    Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOB), address(this), this.fulfill.selector);
    req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
    req.add("path", "USD");
    req.addInt("times", 100);
    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);
  }

  function fulfill(bytes32 _requestId, uint256 _price)
    public
    recordChainlinkFulfillment(_requestId)
  {
    currentPrice = _price;
  }

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

  function stringToBytes32(string memory source) private pure returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
      return 0x0;
    }
    assembly { // solhint-disable-line no-inline-assembly
      result := mload(add(source, 32))
    }
  }
}

When I run the requestEthereum function, I get the following error in my remix IDE.

gas required exceeds allowance (8000029) or always failing transaction


texts:
I would like to use my Ethereum to buy Tezos.
Does anyone know if Coinbase pass transaction data along with the transaction?
Thanks.


texts:
I'm trying to create and deploy a smart contract through NodeJS using web3, but it is not working as I get a "web3.eth.contract.new is not a function". Here is my code:

var web3 = require('ethereum.js');

var solc = require('solc');

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8101/'));

var input = 'contract Hello{ string h = "hello"; function g() constant returns(string){ return h; } }';
var output = solc.compile(input, 1);

for (var contractName in output.contracts) {

    var bc = output.contracts[contractName].bytecode;
    var abi =  output.contracts[contractName].interface;

    var contact = web3.eth.contract.new(abi,{from: web3.eth.accounts[0], data: bc});

    if (typeof contact.address !== 'undefined') {
         console.log('Contract mined! address: ' + contact.address + ' transactionHash: ' + contact.transactionHash);
    }

}

Any idea on how to solve this issue? Thanks in advance.


texts: Solidity: Raise events via Assembly using log3

texts:
I want to raise events from inside a piece of assembly code.

I've extended the answer here with the function AssemblyEvent() which currently causes a runtime error.

Working example:

pragma solidity ^0.4.21;

contract Demo {
    event Deposit(
        address indexed _from,
        bytes32 indexed _id,
        uint256 _value
    );

    function highLevelEvent() public {
        bytes32 _id = hex"420042";
        emit Deposit(msg.sender, _id, 123);
    }

    function lowLevelEvent() public {
        bytes32 _id = hex"420042";
        log3(
            bytes32(uint256(123)),
            bytes32(keccak256("Deposit(address,bytes32,uint256)")),
            bytes32(uint256(uint160(msg.sender))),
            _id
        );
    }
    // ##########################
    // this function doesn't work
    // ##########################

    function AssemblyEvent() public {
        bytes32 _id = hex"420042";
        bytes32 t1 = bytes32(uint256(123));
        bytes32 t2 = bytes32(keccak256("Deposit(address,bytes32,uint256)"));
        bytes32 t3 = bytes32(uint256(uint160(msg.sender)));

        assembly {
            let s := 0x20
            let p := _id
            log3(p, s, t1, t2, t3)
        }
    }
}

What have I done wrong in the above code?  Also, as Assembly only has functions up to log4, does this mean that 4 the maximum number of variables I can create logs for?


texts: How does addition look like at the opcode level in Solidity v0.8 and above?

texts:
In Solidity v0.7 and below, addition was a simple opcode:
ADD

Which cost 3 gas units and didn't handle overflows, silently returning the overflown value.
But Solidity v0.8 made addition overflow-safe. How does the sequence of opcodes look like today?


texts: How to solve Transaction has been reverted by the EVM , In need of a solution based on my code?

texts:
I have been using ropsten with infura.
SMART CONTRACT
   contract Don
         {

         struct Details
         {

          uint id;
          string name;
          string dob;
          string sex;
          string bg;
          string org1;
          string org2;
          string org3;

           }

            uint rQ=0;

             mapping(uint => Details) Donate;

             mapping(uint => Details) Recieve;

                 function setBook
                (uint Did,string memory Dname,string memory dob,string memory sex,string memory bg,
                  string memory dorg1,string memory dorg2,string memory dorg3)
                  public {
                   Donate[Did] = Details(Did,Dname,dob,sex,bg,dorg1,dorg2,dorg3);

                     }

                      }

Error part 1

error part 2

config File

       [1]: https://i.stack.imgur.com/qWoXo.png


texts: Is a constructor needed to set a contract owner?

texts:
until now I have set the owner in a contract like so:

pragma solidity ^0.5.2;

contract SampleContract{

     address payable owner = msg.sender;

}

in the docs it is suggested to do it this way:

pragma solidity ^0.5.2;

contract SampleContract{

     address payable owner;

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

}

I don't notice any difference in the behavior of the contract. Are both ways equivalent or is there a possible security issue with the first one?

Thanks a lot


texts: How ERC20 and ERC721 deals with confirmation level

texts:
a smart contract store the internal balance per owner.
when we transfer tokens from Owner A to Owner B, we update the internal balance sheet.
but the internal balance sheet is a most recent snap shot.
it does not tell you that Owner A balance was updates 15 blocks ago, while Owner B balance was update just 2 blocks ago.
when i call the balanceOf(address) it will read the balance from the local node.
so, How can i tell if the value is confirmed?
should i store the recent tx-hash per owner and relay on it to calculate the confirmation level?

thnx


texts: Display the value of a smart contract's variable with Truffle External Script

texts:
I will like to display the value of a variable in an existing smart contract in Truffle.

Here's my script:

module.exports = async function(callback) {
const project = artifacts.require("project");
let p = await project.at('0x4514bC8332c94AEE465e7c70B0d0497424A66D67');
console.log(p.methods.state.call());}

So I run it hoping that it displays the value of state.

truffle exec test.js

But all I get is this, with no values displayed:

Using network 'development'.


texts: Solidity - Setting the length of an EnumerableSet UintSet

texts:
Is it possible to pre-set the length of the set of an EnumerableSet.UintSet type?
For instance, if I declare this mapping:
mapping (address => EnumerableSet.UintSet) private agentTickets;

and then in the constructor I want to initialize a particular agent-address so that it already "owns" 100 tickets right off the bat - how would I do that?
I tried the following, and it didn't work:
  constructor() public {

      // This failed - because ".length" is a read-only property I think:
      agentTickets[address(this)].length = 100;

      // This also failed:
      uint256[100] memory ticketIDsArray;
      agentTickets[address(this)] = ticketIDsArray;
  }