texts: Metamask hangs while trying to decrypt a PDF file

texts:
I'm trying to encrypt a PDF file using the public key provided by metamask. The array buffer representing the file is converted to a Base64 string and encrypted using the eth-sig-util.
The code is given below.
const ethUtil = require('ethereumjs-util')
const sigUtil = require('eth-sig-util')

onFileUpload = (event) => {

   event.preventDefault();

   var reader = new FileReader();

   reader.onload = async (evt) => {
     if (evt.target.readyState == FileReader.DONE) { // DONE == 2
       console.log("onload res ", evt.target.result);

         let encryptionPublicKey;

           await window.ethereum
           .request({
               method: 'eth_getEncryptionPublicKey',
               params: [current_account],
           })
           .then((key) => {
               encryptionPublicKey = key;
           })
           .catch((error) => {
               if (error.code === 4001) {
               // EIP-1193 userRejectedRequest error
               console.log('We cant encrypt anything without the key.');
               } else {
               console.error(error);
               }
           });

           const filestr=this.arrayBufferToBase64(evt.target.result);

           const encData = sigUtil.encrypt(
             encryptionPublicKey,
             { data: filestr },
             'x25519-xsalsa20-poly1305'
           )

           const encryptedMessage = ethUtil.bufferToHex(
             Buffer.from(
               JSON.stringify(
                 encData
               ),
               'utf8'
             )
           );

           window.ethereum
           .request({
             method: 'eth_decrypt',
             params: [encryptedMessage, current_account],
           })
           .then((decryptedMessage) =>
             console.log('The decrypted message is:', decryptedMessage)
           )
           .catch((error) => console.log(error.message));
       }
     catch (error){
         console.error(error);
     }
     }
   };

 reader.readAsArrayBuffer(this.state.selectedFile);
 };

When I try to decrypt it using eth_decrypt, the metamask pop up hangs. This happens only with files. It works when I encrypt and decrypt strings.strong text


texts:
I'm using the Embark-Framework to handle my DApp development.  I made a new contract that has the public address owner.  Example below:

pragma solidity ^0.4.7;
contract MyContract {

  address public owner = msg.sender ;
  uint public creationTime = now;

  function getOwner() returns (address owner) {
    return owner;
  }

}

On the front-end side, I type:

var c = web3.eth.contract(MyContract.abi).at(MyContract.address)
c.getOwner()

And the output is a constantly changing string... Meaning the owner is constantly changing.  Any ideas why?

I can do the same with using the promise() formulation of embark (i.e., running MyContract.getOwner().then(...).  Still, value keeps changing.

EDIT: Screenshots provided:


texts:
I have a smart contract that emits an event, and I've set-up a listener in my client-side app that can register this event. But I'm curious, who receives this event? If say 20 different people from around the world are currently using my app, will all of them receive all triggered events?

For example, let's say I have two people using my app, client A and client B, and a function in my contract called buildHouse(). client A calls buildHouse(), and this in turn emits a HouseBuilt() event. Client A then receives the HouseBuilt() event and takes the appropriate action - and all is good. But will client B also receive this same event? Or does the contract somehow know which particular client called buildHouse(), and only sends the event there?

Any help is much appreciated.


texts: Window.ethereum undefined on tab with local webpage

texts:
I have the metamask extension. When I do typeof(window.ethereum) in the console for a chrome tab, I get the type as object. However if I open mywebpage.html in a tab, which is just a heading around:
<script type="text/javascript"> document.write(typeof(window.ethereum)); </script>

then this typeof is 'undefined', either on the page or on the console.
I want to write a webpage that accesses metamask, how do I do that?


texts: Truffle test, logs do not include an emitted event

texts:
I am calling a contract function which emits an event in a transaction. This transaction should include the event and is typically visible via:

const receipt = await contractInstance.someFunction()
let logs = receipt.logs

This normally contains a list of the emitted event names in the transaction. However in my call the tests output:

[]
    1) Test someFunction()

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

    Stored()

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

  1 failing

  1) Contract: Test.js
       Test someFunction():
     AssertionError: Stored event not emitted: expected false to be truthy
      at Context.it (test/test.js:145:12)
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

with testing block that fails:

const receipt = await instance.someFunction();
let event = validationReceipt.logs.some(l => { return l.event == "Stored" });
console.log(validationReceipt.logs);
assert.ok(event, "Stored event not emitted");

First line performs the function call which emits the event Stored. Second line retrieves the instance by event name from the logs. Third line simply logs the contained events. Fourth line asserts that the event exists in the logs.

As shown in the test output, the logs were empty [], but the event was emitted.

Why is the event being shown to have been emitted but also not present in the logs of the transaction that emitted it?


texts: How to get contract object using ABI json and address with web3j?

texts:
I worked with web3js(JavaScript) and used web3.eth.Contract with 2 params (json, address) and successfully got contract object.
Now I started to work with web3j(Java) and don`t understand how I have to work now.
How can I do this ?


texts: Who approves my public key in Ethereum network?

texts:
In a PKI approach, a public key is approved by a Certificate Authority (CA) in a centralized manner. However, since Ethereum is a decentralized network, how is my public key validity is approved? Or, in general, is there an approving process of public keys? And if not, doesn't that cause any security issues? How is a public/private key generated in Ethereum? Is there a way to prevent a user from generating too many public keys?

Thanks!


texts: How to set eth (not geth) data directory?

texts:
I could find solutions for geth to set the data directory

geth --datadir = ./chaindata

What is the eth alternative for the same?

Does it make a difference in using geth or eth client?

and how to initialize genesis.json


texts: Solidity "Error: Invalid type for argument in function call. Invalid

texts:
This error doesn't make sense

Error: Invalid type for argument in function call. Invalid implicit conversion from function (bytes memory) external to function (bytes memory) external requested.


texts: Most expensive DAPP (in terms of gas usage per transaction)

texts: Which DAPP currently running or in development is likely to use the most gas per transaction?


texts: Do I need to use geth --rpc with ethminer?

texts:
I've seen some tutorials where people do

geth account new
geth --rpc
ethminer -G -F your.poolurl.com:port/WALLET --farm-recheck 200

And others that are just simply

geth account new
ethminer -G -F your.poolurl.com:port/WALLET --farm-recheck 200

What is the purpose of geth --rpc? Do I really need it to start mining?


texts: Upgrade a fully synced node to archive node?

texts: Is it possible to upgrade a fully synced node to archive node ? means can i download older states by changing gcmode to archive ? or i will have to start from scratch ?


texts: How does Raiden Network prevent the attack that uses stale state?

texts:
In Lightning Network, It uses timelock to prevent attack that places stale state onto the blockchain for single channel. (Not for payment routing, only for single payment channel between two nodes) But there is no place for setting timelock on ethereum transaction structure.

Raiden Network is one of the solutions for scalability of blockchain. Can it prevent such attack without using timelock ? Or does it contact with blockchain during off-chain payment in single payment channel to update state ?


texts: transactions in rpc block response sometimes have chain null and sometimes correct chain

texts:
when doing e.g. a blockByNumber rpc request I am getting a result like this from parity:
https://gist.github.com/ligi/fbc7061d93f087cf0eb0f4db83d1fced

what is puzzling me that some transactions have:

chainId":null

and some have

"chainId":"0x1"

I do not see the pattern when either variant is returned. geth does not contain the chainId there at all.
Can someone enlighten me what is going on there? Is this a bug or am I missing some pattern/background?


texts: I successfully integrated Ethereum (ETH) in my product. Now, I want to integrate Ethereum Classic(ETC) in my product. I am using web3.py for ETH. Are there any documentations or libraries for ETC? How to get started with ETC? Please help


texts:
I was wondering if the pattern below is correct for sending a transaction with the correct gas limit.

this.contracts.myContract.methods.myMethod.getEstimatedGas().then(gas => {
  this.contracts.myContract.methods.myMethod.cacheSend(
    ["prop1", "prop2"],
    {
      gas
    }
  );
});

I've also read that adding 10% to the estimate could be sensible.

Or should I just go with whatever prices Metamask populates when making the method call?


texts: Proof Of Existence (POE) input data first 8 numbers

texts:
I am trying to implement POE model based on Ethereum blockchain. Basically, I get sha-256 hash from a document, then I send a 0 ether transaction to myself and add document's hash to the "Data" field. Transaction gets validated and I can see it: https://ropsten.etherscan.io/tx/0x1f4d3136b16de5ca56e04edfbb5139e902d624a200846374f7cba8b598f6dd82
(currently I am doing it on testnet)

However, my input data was 15e2b0d3c3..... and in receipt data is 0x53369b7315e2b0...... Everything is okay, except that I don't understand why these 8 digits were inserted, what they stand for? And what's the purpose of this 0x in front of everything?

If someone could explain this in simple terms, I would be really grateful.


texts: Can bytes32 be changed to a string in solidity?

texts:
I was wondering if it is possible to convert a bytes32 to a string in solidity like this,
I want an input bytes32 input = 0x74657374
and an output of string output = "0x74657374"


texts: Existing research about m-of-n paper seed phrases

texts:
I'm interested in designing a protocol that stores a seed phrase for a crypto wallet across N separate pieces of paper (or metal!), where any M of the pieces of paper can reconstruct the seed phrase, but less than M cannot.
I would like the entire scheme to be something you can do by hand, as these seed phrases shouldn't touch a general-purpose computer for security reasons.
Concretely: does a scheme that splits a paper seed phrase into separate parts exist?
Ideally I am looking for a scheme that uses only hand-computation, not math that you have to do on a computer.
I am not looking for a "multisig" scheme. What I want is a scheme to store the seed for a single deterministic wallet (likely a hardware wallet such as Trezor or Ledger), but in a distributed way on paper. The goal is that a person can distribute these parts to various trusted contacts, safety deposit boxes, safes, etc and not be vulnerable to a single point of failure either by losing one of the parts or by one part being compromised.


texts: Why Titan X VGA card hash rate is to low?

texts:
I have a Nvidia GTX Titan X VGA card and I want to try mining Ethereum but I don't know why my hash rate is such low !!! it's something about 2/5 MH !!!
I had read somewhere that this card's hash rate is 35MH. I didn't find any useful answer on the internet.
By the way, my motherboard is Intel DX58SO2 and my power supply is Green GP885B.
In addition, I turned on Optimize for compute performance in my VGA control option.
Does anyone knows how can I increase my hash rate ?!
My miner software is: nanominer-windows-3.1.5-cuda11
New Additions: I put my VGA card here, in this slot on my motherboard:


texts:
I was making a smart contract in which I wanted to send and receive ether.
My code:
contract coin_transfer_to {
    function() public payable {
    }
    function get_balance() public returns (uint)
    {
        returns address(this).balance;
    }
}

contract coin_transfer_from{
    coin_transfer_to private _instance;
    function coin_transfer_from () public
    {
        _instance = new coin_transfer_to();
    }

    function get_balance() public returns (uint)
    {
        return address(this).balance;
    }

    function get_balance_of_instance() public returns (uint)
    {
       return _instance.get_balance();
    }

    function () public payable
    {
        address(_instance).send(msg.value);
    }
}

I got the following error in line 2 of above code which is function() public payable:


texts: Issues running ganache-cli command options

texts:
So I open ganache-cli on one window.
And from ganache-cli github repo I can see all those command options, but don't understand where to run them..


texts: Save all customers who buy an item online

texts: I am writing a contract where I am trying to save the account addresses of customers who buy an item online. I tried it with arrays but it did not work. Can anyone please suggest a way of doing this?


texts: Compile smart contract in the console browser

texts:
I use metamask with chrome.
In console browser when I run this code

var source = "" +
    "contract test {\n" +
    "   function multiply(uint a) returns(uint d) {\n" +
    "       return a * 7;\n" +
    "   }\n" +
    "}\n";
var compiled = web3.eth.compile.solidity(source, function(err,res){
  console.log(err);
  console.log(res);
})

I have this error :

Error: Error while compiling code.(…)

Is it a way to compile and deploy a smart contract directly in the the console browser ?


texts: Is that a need to add every investors to multisig wallet?

texts:
I read an article here, it mentioned that

  Another convention which has by now become a de facto requirement is collecting all contribution in a multi-signature escrow wallet, with all the names of all key holders announced to the public.

During crowdsale, we provide the contract address in our website, and investors will send ETH to that contract, the ETH will then stored in a multisig wallet, and investors receive the token accordingly.

Is it the usual way to add the investors as the one of the owner of that multisig wallet?

Please advice. Thank you


texts: How to see pending transactions in local geth node?

texts:
I'm looking for run a local node and get pending transactions
Since 3 days runing, no pending transactions appear
> txpool.status
{
  pending: 0,
  queued: 0
}

And I use this command line (last version of geth)
geth --datadir=~/dev/chain --syncmode fast --cache 6144 --rpc --rpcaddr '0.0.0.0' --rpcapi=eth,net,rpc,web3,txpool,personal,debug --txpool.globalslots=250000 --txpool.globalqueue=500000 console

Is the command line wrong ?


texts: How to send the RFID card no read using Raspberry Pi to smart contract so the details can be stored on Ethereum blockchain?

texts: Raspberry Pi reads an RFID card and has to send the RFID number to the smart contract to check further details related to the RFID number. Based on the details the payment is done and stored on the Ethereum blockchain.


texts:
Using Parity 1.7.x, if you type "parity account new" you have to type in a password.  But there's no seed being generated.  Does that mean this wallet can't be restored without the original key?

Or is there a way to generate the seed (not from the UI)?


texts: Is it possible to implement decentralized autonomous organization in Ethereum?

texts: Is it possible to implement a DAO (Decentralized Autonomous Organization) with Ethereum? If so, has it been done in an effective way? Are there any examples?


texts: Why must gas limit be set to 900 more than actual gas usage?

texts:
I have a contract which a specific function call will always cost x gas.
However, setting the gas limit of the transaction to anything less than x + 900 will result in an out of gas error.
What is this 900 gas buffer for the gas limit? Why does it exist? Is there a way to prevent it from happening?


texts: Can you use a smart contract to generate a symmetric key?

texts: Let's say that I want to generate a key such that a user can use it and at the same time save the hashed key on the blockchain. My idea was to use a smart contract that could implement the Diffie-Hellman encryption. In this way the recipient would have the original key and the smart contract could calculate the hash of the key and store it. Is this a viable solution? What are other ways to achieve this?


texts: How to minimize gas consumption during contract creation

texts:
I have trouble deploying a contract to the main network and I believe this is due to high gas consumption.
An earlier version of the contract worked on the main network. The current version works in my private testnet (created with geth --dev).
On the testnet these contract creations use about 2.4 million units of gas. I tried to deploy it on the main net with 2 million gas at first and got an out of gas exception (TA got mined though, contract creation just was not successful).

After that I tried it with 3 million and got this (not mined):

"{"jsonrpc":"2.0","error":{"code":-32010,"message":"Transaction cost exceeds current gas limit. Limit: 2200000, got: 3000000. Try decreasing supplied gas.","data":null},"id":1}[\n]"

I am completely stuck and have no idea how I can deploy my contract now. Mainly I have two questions:

Why can I send a TA with 2.4 million gas to the testnet but not to the main-net. I know they are different chains, but shouldn't it use the same logic for TA-validation? How can I send TAs with 3mill gas limit to the main network?
I don't understand why my contract requires this much gas. It's only 264 lines of code. It's three mappings, two structs, five enums, one event and a few relatively simple functions. How can I figure out which part of my contract is using up so much gas? Is there a tool for that?


texts:
My web3 version is web3@1.0.0-beta.26, I am deploying the contract on the localhost:8545.

Here is my contract example.

pragma solidity ^0.4.18;
contract LocalEthereum {

    address public owner;
    event Created(bytes32 _tradeHash);
    function createEvent() onlyOwner external {
        Created(0x01);
    }
}

and here is my js code

init the contract instance

  var Contract = new this.web3.eth.Contract(abi_json,address);

button click events

  Created(account){
      Contract.methods.Created().send({from: account,gas:210000,gasPrice:5000000000})
                      .on('transactionHash', function(hash){
                          console.log('hash',hash);
                      })
                      .on('receipt', function(receipt){
                          console.log('receipt',receipt);
                      })
                      .on('confirmation', function(confirmationNumber, receipt){
                          console.log('confirmation',confirmationNumber);
                      })
                      .on('error', console.error);
  }

watch events

  this.Contract.events.Created({},{ fromBlock: 0, toBlock: 'latest' }, function(error, event){ console.log(event); })
                        .on('data', function(event){
                              console.log(event);
                        })
                        .on('changed', function(event){
                             console.log('on changed');
                        })
                        .on('error', console.error);

The js app can load the contract and connect the ethereum network, when I click the button, Contract will generate a 'Created' rpc call to the ethereum, the transaction can be received immediately. On the testrpc interface I could also see the transaction as shown below.

  Transaction: 0x2469f2085c8f6f23ad8aa30bc6cf99ade40ea2f0368b9bb008496ba05d927d84
  Gas usage: 21272
  Block Number: 6
  Block Time: Thu Dec 28 2017 20:38:02 GMT+0000 (GMT)

Everything works well, however the event call is never activated after the method call. There is only one time event call in the app intialization but still the

  this.Contract.events.Created({},{ fromBlock: 0, toBlock: 'latest' }, function(error, event){ console.log(event); })
                        .on('data', function(event){
                              console.log(event);
                        })

the console outputs the null.

Wonder what is the problem?

i wonder is it because of web3 provider? currently i am using web http not ws. And currently I am testing on the ganache-cli and testrpc.

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

is http provider doesn't provide event?


texts:
Cannot find the right Absolute Path For Remixd on Windows 10.
I have tried both
remixd -s C:/MyProjects/SmartContracts --remix-ide https://remix.ethereum.org
remixd -s C:\MyProjects\SmartContracts --remix-ide https://remix.ethereum.org

In Both cases the remixd is running:
[WARN] Symbolic links are not forwarded to Remix IDE

But there are no Local folders when opening Remix in Browser


texts:
To my understanding, delete x merely sets the value of x to the default value defined for the type of x (which is typically 0 in one way or another).

For example:

uint x = 1;
delete x; // sets x = 0

bool x = true;
delete x; // sets x = false

The doc actually says it pretty explicitly:

  It is important to note that delete a really behaves like an assignment to a, i.e. it stores a new object in a.

But my question is really with regards to mappings.

Suppose I have mapping (address => bool) validAddresses and some address x.

Are the following two statements equivalent:

validAddresses[x] = false;
delete validAddresses[x];

Or is there any benefit in #2 over #1 (as there would be in "traditional" languages)?

The doc states something which might answer my question:

  delete has no effect on whole mappings (as the keys of mappings may be arbitrary and are generally unknown).

But I'm honestly having problems understanding it.

I do understand that delete has no effect on anything other than mappings, in the sense that no memory is being freed as a result of executing it.

But I do not understand whether or not the same thing applies for mappings.

UPDATE:

I went ahead and disassembled each one of these two statements via solc --asm.

Statement #1:

    /* "contracts/MyContract.sol":1490:1538  validAddresses[x] = false */
  dup1
  sload
  0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
  and
  swap1
  sstore

Statement #2:

    /* "contracts/MyContract.sol":1490:1537  delete validAddresses[x] */
  dup1
  sload
  0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
  and
  swap1
  sstore

The compiled code indicates that the two statements are identical, so I'm basically just looking for a confirmation on this fact (in opposed to the answer below, which suggests that gas-refund applies only when delete is used explicitly).


texts:
I would like to buy ether, so I read and google a lot, but still wasn't able to set up my account with buying possibilities.

I registered at CoinBase, identified myself but they didn't charge my bank account (UK) so I can't use that for trading. Sometimes the website forgot that I added my debit card, so I have to do it again.

Anyway, could someone give me a step-by-step 6-year-old tutorial how you bought your first Ethereum? What exchange and bank account have you used, where the bank was located (which country), etc...

I would be very grateful,
Thanks


texts: Couldn't estimate the gas when running Mist against ganache-cli

texts:
I am running ganache-cli locally, then connecting Mist with /Applications/Mist.app/Contents/MacOS/Mist --rpc http://localhost:8545

Then, when I try to send from one test acccount to another in the Mist UI, I get the following error:

  It seems this transaction will fail. If you submit it, then it may consume all the gas you provide.

All accounts have ETH. I have the latest version of geth.

Simply running Mist without connecting to ganache works fine, but I'd like to use features of the Mist UI against the nice test setup offered by ganache, hence my current setup.


texts: Problem after withdrawal non hard fork ethereum

texts: I have a problem, I successfully withdraw some ETC but when I tried another time to withdraw the rest I think I put in more ETC and I didn't receive anything and now when I try again to withdraw any amount it won't work, not even with 1 ETC. In mist appears like the transaction was successful but the coin never reached the exchange. Can someone please help me?


texts:
I am trying to understand ERC165.
Let's say we have a contract - contractB and we have a contract contractA.
I think, what this ERC says is that before contractA can call the contractB's function, it first calls supportsInterface function on contractB.
I have 2 questions..

If contractA and contractB are completely isolated, how can I pass interfaceId from contractA to contractB ? It seems like I have to calculate it in contractA again.

What's the actual point/examples of why using ERC165 could be a good approach.

Nice/World life examples would be appreciated.


texts: How do I track down the owner of an address that stole my wallet. I have the address need to follow up. My coins show up in their wallet.


texts: How to run "geth"-console next to a geth instance that is syncing the blockchain?

texts:
Running "geth" will continuously sync the blockchain. I use a ubuntu server as ethereum node.

Now i want to start a second instance of geth to run the geth console for running some commands.

This will end up with:

  Fatal: Error starting protocol stack: datadir already used by another
  process

Is there any way to run several instances of "geth"? One for syncing, one for the console?


texts:
I did a transaction about 14 hrs ago to move some ETH from one hardware wallet to another using myEtherWallet.  I received the "Sorry, We are unable to locate the Transaction Hash" message.  The ETH is still showing in the sending wallet.

Is this transaction lost or will it eventually show up as 'pending'?   Should I wait?

Transaction  0x875dba05d7e75dcdbe5a2884f9a3a36492fe56403aeef6487c493d06d8c50ea0


texts: web3.js error: Cannot read property 'providers' of undefined

texts:
What is problem of this simple html / JavaScript / ethreumjs / web3.js code?

    <!doctype html>

    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>EthereumJS - Browser Example</title>
    </head>

    <body>
      <script src="https://rawgit.com/ethereumjs/browser-builds/master/dist/ethereumjs-abi/ethereumjs-abi-0.6.5.js"></script>
  <script src="https://rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

      <script>

      var abi = new ethereumjs.ABI()
      var Web3
      web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

      </script>
    </body>
    </html>

When I run this code I receive the following error in Console of browser in line 17 of this code (i.e. web3 = new Web3(new Web3.providers...) :

  Uncaught TypeError: Cannot read property 'providers' of undefined at
  test.html:17

Note: Please note that I cannot use Web3 = require("web3") , because I receive following error:

Uncaught ReferenceError: require is not defined


texts: How to clear large arrays without blowing the gas limit?

texts:
As posted by redditor ethererik in the post GovernMental's 1100 ETH jackpot payout is stuck because it uses too much gas, 1,100 ethers are stuck in limbo because the payout of this GovernMental pyramid scheme requires the clearing out of the arrays containing creditor addresses and amounts. This array has grown as each creditor added their ethers to this pyramid scheme. The code that clears the arrays in question follows:

creditorAddresses = new address[](0);
creditorAmounts = new uint[](0);

What is the best way to clear large arrays without blowing the gas limit?

Here is the stalled contract on live.ether.camp (link from romanmandeleil).

Here is a link to the smart contract code, and to the website.


texts: How does explicit type conversion to a contract work?

texts:
Following is an example from the Solidity doc, but I have three questions:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.16 <0.7.0;

contract OwnedToken {
    TokenCreator creator;
    address owner;
    bytes32 name;

    constructor(bytes32 _name) public {
        owner = msg.sender;
        creator = TokenCreator(msg.sender); // this part
        name = _name;
    }

    function changeName(bytes32 newName) public {
        if (msg.sender == address(creator)) {
            name = newName;
        }
    }

    function transfer(address newOwner) public {
        if (msg.sender != owner) return;

        if (creator.isTokenTransferOK(owner, newOwner))
            owner = newOwner;
    }
}

contract TokenCreator {
    function createToken(bytes32 name) public returns (OwnedToken tokenAddress) {
        return new OwnedToken(name);
    }

    function changeName(OwnedToken tokenAddress, bytes32 name) public {
        tokenAddress.changeName(name);
    }

    function isTokenTransferOK(address currentOwner, address newOwner) public pure returns (bool ok) {
        return keccak256(abi.encodePacked(currentOwner, newOwner))[0] == 0x7f;
    }
}

I'm trying to understand how this conversion works:

creator = TokenCreator(msg.sender);

I get the concept that what it's doing is an explicit type conversion, just like you'd do with uint(something), but I'm not sure the exact mechanism behind it.  I don't see a constructor in the contract TokenCreater or a function that allows this conversion.  Also, can you only convert an address to the contract type of this kind, like how this example converted msg.sender to the TokenCreater type, or can you pass other types like uint or an array?

The document explains that

  It is fine for the contract OwnedToken to reference TokenCreator
  as long as it is not used to create a new contract.

Why is that so?

OwnedToken references TokenCreator:

TokenCreator creator;
creator = TokenCreator(msg.sender);
if (creator.isTokenTransferOK(owner, newOwner))
   owner = newOwner;

But, TokenCreator references OwnedToken as well:

    function createToken(bytes32 name) public returns (OwnedToken tokenAddress) {
        return new OwnedToken(name);
    }

This recursive referencing is a bit confusing. Is this common and a good practice?


texts: Precautions before using a pre-sale address?

texts:
After the Ethereum pre-sale I've been pretty much out of the loop. Now I would like to start using my ETH but I'm not sure if it's that straightforward. I would not like to mess up and lose ETH because of my stupidity or carelessness.

Do I have to explicitly split my ETH from ETC because of the DAO hard fork? What happens if I don't do that?
Is there something else that needs to be taken into account before making transactions from a pre-sale address?


texts: How do proof of stake nodes know which chain is real?

texts: In proof of work, when a fork occurs in the blockchain, nodes trust the fork that has the most computational work put into it. How do proof of stake nodes know what chain to trust?


texts: signed message different on opera and metamask

texts:
I am using the following code to sign a message:

web3.currentProvider.sendAsync(
  {
    jsonrpc: '2.0',
    id: 1,
    method: 'personal_sign',
    params: [
      `My account is ${this.accounts[0]}`,
      this.accounts[0],
    ],
  },
  (err, res) => {
     // send res.result to server
  },
);

on the server i do the following:

// Recover the public key
const candidate = web3.eth.accounts.recover(`My account is ${account}`, signature);

// Verify the recovered key and the key making the request are the same
return ethUtil.toChecksumAddress(candidate) === ethUtil.toChecksumAddress(myPublicKey)

This works correctly when using MetaMask, but the recovered address does not match when using Opera on android. From what I can tell both are using v0.20.7 of web3. Anyone have any ideas?


texts:
I've a simple but problematic problem. I read a value of a struct from a smart contract with a function like this:

  function getOwner(address _id) constant returns (bytes32) {
    uint pos = ownerID[_id];
    Owner memory foundOwner;
    foundOwner = owners[pos];

    return foundOwner.name;
  }

Essentially I pass a key (in this case _id) that is used to get an index base on this mapping:

mapping(address => uint) public ownerID;

After I have the right index (pos), I copy the struct into a memory variable called foundOwner. At the end, I return the name field of the struct.

The problem is: If I have 2 ID registered, say ID1 and ID2:

when I pass ID1 I get back ID1 name
when I pass ID2 I get back ID2 name
when I pass ID3 (with this sequence: ID1, ID2, ID3) I get back ID1 name, and this is a problem!

I know that with mapping, all the possible indexes are referenced so that the returned struct will have all fields set to 0x0.

I've also tried without the memory variable, returning directly owners[pos].name, but when I pass an unregistered ID, I always get back the element with the first index in the mapping.

How can I be sure that when passing an ID not registered, the function returns an empty struct?

Thanks in advice!

UPDATE: The Owner is set like this

  function registerOwner(bytes32 _name, bytes32 _surname) {
    owners.length++;
    uint pos = owners.length - 1;
    ownerID[msg.sender] = pos;
    owners[pos] = Owner(msg.sender, _name, _surname, true, block.number, block.timestamp);
  }

As I've said in the comments, my temporary solution is to create (within the constructor) a dummy variable with all 0x0 or false field. I think the problem is that when there is no match in the mapping, the pos variable will assume value 0, so returning the first entity I save. I think that maybe I can solve the problem simply starting from pos=1, so removing the -1 from line uint pos = owners.length - 1;


texts: Can this function be executed multiple times?

texts:
In most contracts with ERC20 standard or with a token there is mostly in the beginning a function that defines the owner of the contract/token after the contract is runned for the first time.

Contract Token {
  function Token {
    owner = msg.sender;
  }
}

On websites like MyEtherWallet or others I can access contracts and run all functions of a contract.

So my question is following:
If the funtion name would be "TokenFunction","TokenX" or others instead of "Token", could it then be ran by anyone and so the owner variable could be changed? And why is that the only function that can be ran only on first time?
 Or did I understand something wrong? Thank you!


texts: how much are the fees for sending eth from Coinbase? Or what exchange has the lowest fees for sending etherum? Thank you!


texts: How to use path (address[]) correctly when interacting with the Uniswap V2 Router

texts:
I'm trying to use Uniswap V2: Router 2 https://etherscan.io/address/0x7a250d5630b4cf539739df2c5dacb4c659f2488d#writeContract
As a test example I am looking to swap 10 RFI (contract address: 0xa1afffe3f4d611d252010e3eaf6f4d77088b0cd7) for YLD (contract address: 0xdcb01cc464238396e213a6fdd933e36796eaff9f).
I put the amountOutMin number very low so it would go through no matter what. Sadly I don't think I've input the swap route correctly? Any advice would be appreciated.
Writing contract swapExactTokensForTokensSupportingFeeOnTransferTokens
amountIn (uint256)
10000000000000000000
amountOutMin (uint256)
500000000000000
path (address[])
["0xa1afffe3f4d611d252010e3eaf6f4d77088b0cd7", "0xdcb01cc464238396e213a6fdd933e36796eaff9f"]
to (address)
0x[redacted]
deadline (uint256)
1611748800
Error thrown: invalid address (arg="path", coderType="
[![image of the error the contract throws][1]][1]
[1]: https://i.stack.imgur.com/NufKI.png


texts:
Im trying to make a transfer ownership example by transferring ownership by sending ether. I've been trying to use msg.value and transfer() to send ether from owner B to owner A so owner B can take ownership.

address public previousOwner;
address public currentOwner;
uint public txTimeStamp;
event transferred();

function transfer() external payable onlyOwnerB {
     require (msg.value == 1 ether);
     ownerA.transfer(1 ether);
     previousOwner = ownerA;
     currentOwner = ownerB;
     txTimeStamp = now;
     emit transferred();
}

I also have a fallback function to receive funds:

function receiveTxPay() public payable returns (bool) {
     return true;
}

I'm using the Remix compiler in a Javascript VM, where owner A is one of the addresses and owner B is another. I made sure to call the transfer() function as owner B. But whenever I call the function i get a "transact to Contract.transfer() errored: VM error: revert." error. I've also tried just using the require(msg.value == 1 ether) line, and also just using the transfer() line. Trying all of these returns the same error message.


texts:
I am running a local ganache-cli as ganache-cli -p 8545.

Furthermore, I created a frontend script using web3:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Dapp</title>

This is my balance

    <button onclick="getBalance()">Update my balance </button>
     in Ether.

The script basically updates my balance which I would have in ether.

However, my web3.eth.accounts[0] is undefined. See my console.log below:

Any suggestion what might be wrong?

I appreciate your replies!

UPDATE

I added the following to my code:

    console.log("Log: (web3.eth)");
    console.log(web3.eth);
    console.log("Log: (web3.eth.accounts)");
    console.log(web3.eth.accounts);


texts: is it possible to get gas refunded if a smart contract call fails to complete?

texts:
I am using trust wallet, and whilst using a number of exchanges (for example - uniswap, balancer liquidity pool) I have paid gas prices without the exchange actually taking place. Is it possible to get the gas price refunded?
I am using a digital wallet and because of needing to undertake one task on a website and one task in my wallet as i flip between the two, it isn't clear that the trade hasn't completed or that a smart contract call has gone through as you come back to the same page on the wallet asking to agree the contract. Network fees are never defined and so I do not therefore get to boost the amount as i have no control and therefore did not know that i paid multiple times for a single trade to occur or that i paid particularly high gas prices in some cases (and it still didn't go through). Right now network gas prices are crazy (prohibitively high to most people / low level trades)and so it becomes impossible to consider undertaking the same activity again until it's easier to control the value in ethereum I have going out - as right now it isn't in my control other than to simply not agree the contract and not go ahead.
Any help greatly appreciated. (fingers crossed I've used the right terminology in the right places).
I understand similar questions have been asked but I still had to ask as in some cases haven't related to the answer completely.
Thank you


texts: Truffle Error-VM Exception while processing transaction: revert

texts:
I am creating test case of solidity in truffle and my solidity function is given below for which I am creating test cases

function isValidBuyer(uint256 buyTokenQty, uint256 senderValue) public  constant returns (bool)
    {
        if(!isUserExist(msg.sender))
        {
            msg.sender.transfer(senderValue); //Refund Ether
            return false ;
        }
        else
        {
            return true ;
        }
    }

And my test cases is as given below

it('TCC001: should check invalid buyer and should return false',   async () => {
let tempRes1=await instChain.isValidBuyer(100,1,{from:account2,gas:'220000'});

 assert.isTrue(!tempRes1);
});

While testing if clause of function in this test I am getting error

  VM Exception while processing transaction: revert

One interesting case is in function isValidBuyer() when I am passing 1 wei it gives above mentioned exception but when I send 0.99 or less it gets execute successfully without error.


texts: Ethereum light node: Light vs Cache vs fastsync

texts:
There are many different options when running a Ethereum node. I want to make sure I pick the right options before I start downloading the blockchain... can someone explain the advantages of using:

—light
—cache
—fastsync

I’m not sure which ones to use and I don’t want to break anything. The main purpose of my node is to act as wallet for my website that accepts Ether, so for example if this was a bitcoin node I’d enable pruning as I don’t need the entire blockchain.


texts: How to work with ENS without starting own node?

texts:
I am trying to get how to work with ENS. It is relatively clear how it works, but most questionable thing for me is whether it possible to work with, for instance, Ropsten resolver without running my own node (ropsten database eats more then 40Gb for now)?

I am trying to get contract deployed here via web3 and INFURA using new web3.eth.contract(jsonInterface, address) and it works but then all cals returns error TypeError: contract.abi.filter is not a function

Final question: how to test ENS without running local geth node?


texts:
If  I have a network made of IoT devices (contain 1000000 device). I need to manage them using a smart contract. And that contract contains a constant function (to avoid paying gas). How can this scenario achieve?
Can the IoT devices query that function in the contract without being a part of the etherum Blockchain as the devices are low constrained devices??


texts: How to create multisignature transaction?

texts:
I have to create a multisignature transaction which the transaction should get signed with at least 2 private keys. Could anyone explain how to do it? I am using web3.py

import rlp

    from ethereum.transactions import Transaction
    tx = Transaction(
        nonce=web3.eth.getTransactionCount(web3.eth.coinbase),
        gasprice=web3.eth.gasPrice,
        startgas=100000,
        to='0xd3cda913deb6f67967b99d67acdfa1712c293601',
        value=12345,
        data=b'',
    )
    tx.sign(the_private_key_for_the_from_account)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = web3.toHex(raw_tx)
    web3.eth.sendRawTransaction(raw_tx_hex)

In the above code, I am only signing with one private key. Could anyone explain how to sign with multiple private keys?


texts:
Here is my contract

pragma solidity ^0.4.14;
contract Sample {

  address private receiver;
  uint public amount;

  function pay(address _receiver, uint _amount) payable public returns (bool) {
    receiver = _receiver;
    amount =_amount;
    receiver.transfer(amount);
    return true;
  }
}

The error i am getting is,

  transact to browser/ballot.sol:Sample.pay errored: VM error: revert.
  revert    The transaction has been reverted to the initial state.     Debug
  the transaction to get more information.


texts: How to call a Contract from an existing contract

texts:
Is is possible to call a Smart Contract from an existing Smart Contract?
Lets say you are an function and want to call an other smart Contract - is this possible? How?


texts:
Does an account get actual tokens when you call a transfer function in an Ethereum token contract or is it just a balances mapping that registers how many tokens each account (address) has?

I am trying to figure out the difference between sending Ether (which in my opinion are real units which can be transferred from one account address to another and a token created by a smart contract is in my opinion only registered in the bookkeeping of the smart contract itself, right?

Can I say that Ether is registered in the Ethereum ledger and a Token in the ledger of a smart contract? Correct me if I am wrong.


texts:
I am trying to pass configuration values from one contract to another, so I can change them and avoid transaction fees.

I have two contracts:

pragma solidity ^0.4.23;

import "./two.sol";

contract One{

    string name;

    constructor() public{

    }

    Two two;

    function getNameFromOtherContract() public returns(string) {
        name = two.getName();
        return name;
    }
}

And second:

pragma solidity ^0.4.23;

contract Two{

    constructor() public{
    }

    function getName() external pure returns (string name) {
        name = "Amel";
    }
}

When I triger getNameFromOtherContract I get:

  transact to One.getNameFromOtherContract errored: VM error: revert.
  revert    The transaction has been reverted to the initial state.

What would be the correct syntax and solution for this approach?


texts: How to get value of a contract public property using web3.eth

texts:
using web3 javascript library how do you get the current value of a public property. e.g.

contract MyContract {
    address public owner;
    ...
}

Here's a snippet of the abi:

[{
  "constant": true,
  "inputs": [],
  "name": "owner",
  "outputs": [
    {
      "name": "",
      "type": "address"
    }
  ],
  "payable": false,
  "type": "function"
},
...
]

I've tried several methods, but to no avail:

    var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    var contract = new web3.eth.Contract([...], "0x1234...");

    // These don't work:
    var owner = contract.owner;
    console.log(owner); // "undefined"

    contract.methods.owner.call(function(error, result) {
        console.log("This doesn't get called");
    });

    contract.methods.owner(function(error, result) {
        // Displays an error to console:
        // Error: Invalid number of parameters for "owner". Got 1 expected 0!
    });

    var x = contract.methods.owner();
    console.log(x); // Displays the contract object below:

The last line displays the contract object. Here's a snippet:

{ call: { [Function: bound _executeMethod] request: [Function: bound
_executeMethod] },
  send: { [Function: bound _executeMethod] request: [Function: bound
_executeMethod] },
  encodeABI: [Function: bound _encodeMethodABI],
  estimateGas: [Function: bound _executeMethod],
  _method:
  { constant: true,
     inputs: [],
     name: 'owner',
     outputs: [ [Object] ],
     payable: false,
     type: 'function',
     signature: '0x8da5cb5b' },
  _parent:
   Contract {
       // etc...

EDIT: Using version 1.0.0-beta.4 (later packages don't install properly with dependency lerna). Docs: http://web3js.readthedocs.io/en/1.0/web3-eth-contract.html


texts: public address variable causes BadFunctionCall exception

texts:
See the contracts at the bottom. You will notice that the contracts are identical, except that the first contract's authority field is marked public, while the second isn't.
The second contract works fine. I can call hash(), test(), whatever, and everything works as expected.
However, nothing works with the first contract. I can use neither call() nor transact() on any function (although estimateGas() works fine). Instead, I get the following error:

eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

I'm not sure what the problem is, can anyone enlighten me? Here are the contracts:
contract Award {

    address public authority;
    string public hash;

    bool itWorked = false;

    mapping(address => bool) users;

    function Award(string _hash) public {
        authority = msg.sender;
        hash = _hash;
    }

    function addUser(address _address) public {
        users[_address] = true;
    }

    function deleteUser(address _address) public {
        users[_address] = false;
    }

    function hasUser(address _address) public view returns (bool) {
        return users[_address];
    }

    function test() public pure returns (bool) {
        return true;
    }

}

and
contract Award {

    address authority;
    string public hash;

    bool itWorked = false;

    mapping(address => bool) users;

    function Award(string _hash) public {
        authority = msg.sender;
        hash = _hash;
    }

    function addUser(address _address) public {
        users[_address] = true;
    }

    function deleteUser(address _address) public {
        users[_address] = false;
    }

    function hasUser(address _address) public view returns (bool) {
        return users[_address];
    }

    function test() public pure returns (bool) {
        return true;
    }

}

As requested, here is the Python code making the call:
contract = w3.eth.contract(abi=contract.abi, bytecode=contract.bytecode)
hash = contract.constructor('test_hash').transact(transaction={'from': self.account, 'gas': 410000})

while True:
        receipt = e.get_transaction_receipt(hash)

        if receipt:
            break

        sleep(2)

address = w3.w3.eth.getTransactionReceipt(hash)['contractAddress']

instance = w3.eth.contract(abi=contract.abi, address=address)

instance.functions.test().call()


texts: What is the significance of making constructor payable?

texts:
Aren`t constructors used to initialize variable at the time of contract creation? In  common patterns section in solidity documentation, payable constructor is used for withdrawal pattern example.

    function WithdrawalContract() public payable {
    richest = msg.sender;
    mostSent = msg.value;
}

What is the significance of this cant we hard code the value or initialize it with some other function?


texts: historical quotes on decentralised exchange

texts:
Dears, I'm new in Eth programming, just started to learn Solidity, so need advice.
I want to see historical prices for certain currency pair (say, USDT/DAI) traded on decentralised exchanges like Curve/Balancer/Uniswap.
Could you please suggest, is it technically possible ? If possible, in which direction should I dig to find such info ? (please tell me just main steps how to do it, how to get mentioned data).  Thank you in advance for ANY help !


texts: Is ERC721 an appropriate standard for managing licenses?

texts:
In my example scenario, I have an e-commerce dApp where e-books are sold. I originally thought that I could represent licenses to access these books using non-fungible tokens (NFTs) through the ERC721 standard. However, given that there can be infinite copies of a single e-book, thus making it not exclusive, it became apparent that several NFTs would potentially have to be minted to represent a single e-book.

It feels like requiring additional logic to maintain this many-to-one relationship strains what ERC721 was meant to support. I've explored other token standard proposals such as ERC981, but partial ownership doesn't quite capture what I need either.

What I need can essentially be summed up as a token standard facilitating non-exclusive right of access (a license) to various assets. If sticking to ERC721 is the right approach, great. Any opinions or insights are appreciated!


texts: Why did cryptokitties congest ethereum network when it has resizable block size?

texts:
So I am wondering how come eth network got congested when block size is resizable and it can take more trx if needed? I am reading some info that it can do that but miners don't want to do it as it causes them to basically earn less. Also I see in this post Why don't Ethereum increase the block gas limit?
that miners can even mine empty block to get advantage, how come this is possible and not banned in consensus mechanism?


texts: Main Network vs Private Network: pro and cons

texts:
i need to understand the difference between Main Network and Private Network.

Private network is only for test or it can be used for a real project?

Thank you


texts: How to pass bytes32[] array to call this function using web3 js?

texts:
I have a function

function multiERC20TransferTightlyPacked
    (
        ERC20 _token,
        bytes32[] _addressesAndAmounts
    ) public
    {
        for (uint i = 0; i < _addressesAndAmounts.length; i++) {
            address to = address(_addressesAndAmounts[i] >> 96);
            uint amount = uint(uint96(_addressesAndAmounts[i]));
            _safeERC20Transfer(_token, to, amount);
            MultiERC20Transfer(msg.sender, to, amount, _token);
        }
    }

For exmple I want to call this function with _addressesAndAmounts of 0x2970c57fe5264caf1689bc129b41bd7ddf06b4f7 10, and 0x63F69E69857dc198AE63C1BeEe26803c50C00813 10, how can I pass these as parameter to call this function?

  const multisendTx = await contract.methods. multiERC20TransferTightlyPacked(tokenAddress, addressesAmounts).encodeABI();

How should I make the addressesAmounts?

on the solidity code it says:

address to = address(_addressesAndAmounts[i] >> 96);
uint amount = uint(uint96(_addressesAndAmounts[i]));

I don't know what does >> 96 mean how does it work in js?


texts: How, precisely, a payment can be routed through N hops in a lightning network?

texts:
The question

Alice <--50--> Bob <--50--> Steve <--50--> Anna

Here, each arrow denotes a payment channel with capacity N eth. What is, step by step, the algorithm used to route a 10 eth payment between Alice and Anna? Please, include, at each step, how each party should react to the possibility of one party not following the protocol.

What I have tried

I have read some explanations but I'm missing the fine details. On that case, I assume, it'd go like this:

Anna generates a random secret, sends its hash to Alice.
Alice signs to send 10 eth to Bob given Alice's secret.
Bob signs to send 10 eth to Steve given Anna's secret.
Steve signs to send 10 eth to Anna given her secret.
Anna reveals her secret to Steve.
Steve reveals it to Bob.
Bob reveals it to Alice.
Alice now knows Anna received the payment, everyone else knows their balance are equal.

But that's pretty simple, so I'm not sure if I actually got it right. In particular, worried if one of those parties could just drop the protocol at any point to a personal benefit.


texts:
The contract I am working on is failing when trying to send a transaction with MetaMask from an address thats not the owner.  I have tried multiple times and also added huge amounts of gas. Even with the huge gas, it does not work with the non owner address. The error message on Etherscan is "Sorry, we are unable to locate this Transaction Hash". It works with the owners address.  It also works on Remix Javascript VM from other addresses.  What is causing it to fail on MetaMask from an address other then the owners?

I am calling the "update" function.  I left out SafeMath library in the example below to make things easier to see.

I tried a few other accounts out and it worked.  For some reason, the one account won't budge.

 pragma solidity ^0.4.24;

    // Allows users to "heart" (like) a DAPP by dapp id
    // 1 Like = XXXXX eth will be set on front end of site
    // 50% of each transaction gets sent to the last liker

    contract dappHearts {

        using SafeMath for uint256;

        // set contract owner
        address public contractOwner;
        // set last address transacted
        address public lastAddress;

        // only contract owner
        modifier onlyContractOwner {
            require(msg.sender == contractOwner);
            _;
        }

        // set constructor
        constructor() public {
            contractOwner = msg.sender;
        }

        // withdraw funds to contract creator
        function withdraw() public onlyContractOwner {
            contractOwner.transfer(address(this).balance);
        }

        // map dapp ids with heart totals
        mapping(uint256 => uint256) public totals;

        // update heart count
        function update(uint256 dapp_id) public payable {
            require(msg.value > 1900000000000000);
            totals[dapp_id] = totals[dapp_id] + msg.value;
            // send 50% of the money to the last person
            lastAddress.transfer(msg.value.div(2));
            lastAddress = msg.sender;
        }

        // get total hearts by id
        function getTotalHeartsByDappId(uint256 dapp_id) public view returns(uint256) {
            return totals[dapp_id];
        }

        // get contract balance
        function getBalance() public view returns(uint256){
            return address(this).balance;
        }

    }


texts: How to connect an address to the coinbase?

texts:
Basicly I'm doing the beginners tutorial and it should show this

But For me it just does this

How can I make web3.eth.coinbase refer to my adress? Do I have to run a node or test-net?

<script type="text/javascript">
///First web3.eth.watch code to monitor coinbase

  web3.eth.watch('chain').changed(function(){
  var coinbase = web3.eth.coinbase;
  document.getElementById('coinbase').innerText = coinbase;
  var balance = web3.eth.balanceAt(coinbase);
  document.getElementById('balance').innerText = web3.toDecimal(balance);
});

///Insert your contract address var here:

///Second web3.eth.watch code to monitor block number

</script>


texts:
I am calling address.transfer() from the one of the deployed contract.
While, this works fine with remix(JavaScript VM environment), the same fails if I deploy and run the same contract on 'ganache'.

I get the below stack on using ganache,

Error: VM Exception while processing transaction: revert
    at \node_modules\web3-provider-engine\subproviders\provider.js:19:36
    at XMLHttpRequest.request.onreadystatechange (\node_modules\truffle-hdwallet-provider\node_modules\web3\lib\web3\httpprovider.js:118:13)
    at XMLHttpRequestEventTarget.dispatchEvent (\node_modules\xhr2\lib\xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (\node_modules\xhr2\lib\xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (\node_modules\xhr2\lib\xhr2.js:509:12)
    at IncomingMessage.<anonymous> (\node_modules\xhr2\lib\xhr2.js:469:24)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

I tried also setting 'gas' with in my contract but, that too did not help


texts: Swap token to ether through Uni-V2 yields Fail with error 'TransferHelper: ETH_TRANSFER_FAILED'

texts:
I have two interfaces:
interface IUniswap {
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable /*DELETE MAYBE*/ returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
}

interface IERC20 {
     function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
     function approve(address spender, uint256 amount) external returns (bool);
     function allowance(address owner, address spender) external view returns (uint256);
}

I would like to swap some tokens (that the contract already has) into ETH, using the following function:
function swapTokenForEth(address token, uint amountIn) external returns (bool) {

    address[] memory path = new address[](2);
    uint deadline = block.timestamp + 600;

    path[0] = token;
    path[1] = WETH;

    require(IERC20(token).approve(address(uniswap), (amountIn + 10000)), 'Uniswap approval failed');
    uniswap.swapExactTokensForETH(
        amountIn,
        1, //MIN FIXED TO 1 FOR TESTING
        path,
        address(this),
        deadline
    );

    return true;

}

The transaction reverts giving the following error:  Fail with error 'TransferHelper: ETH_TRANSFER_FAILED'.
Thanks in advanced for the help.


texts: send tokens from etherscan adress to MEW

texts:
I was have wallet on etherdelta, with etherdelta generated address, but now my account just dissapeared on that exchange.
Anyway, I can see my account on etherscan, with my corect balans-tokens (aion).
Now, how can I send that aion tokens from my address which I can see on Etherscan, directly to my My Ether Wallet ?


texts:
I have a question do these if conditions take same gas  mean if condition body with && or || with simple if condition with true or false? Same gas  or different? How can I check that?

if(msg.sender != MainFounderAddress && msg.sender != teamAddress && msg.sender != adviserAddress && msg.sender != FounderAddress1 && msg.sender != FounderAddress2 && msg.sender != FounderAddress3 && msg.sender != FounderAddress4){}

Other

if(true){}


texts:
I requested active account address from Metamask and received it successfully. After that I tried to authenticate user by signing data with eth.personal.sign, but getting errors unfortunately.

signMessage( publicAddress: string, nonce: number ): Promise<any> {
        return this.web3.eth.personal.sign(
            this.web3.utils.fromUtf8( `Sign: ${nonce}` ), publicAddress ).then( ( signature ) => {
            return signature;
        } )
    }

Getting this error: Invalid Arguments length: expected: 3, given: 2
(guess need password as 3rd argument?)

When using eth.sign( hash, addr) it gives: Uncaught TypeError: t is not a function (inpage.js)

I was following this tutorial: https://www.toptal.com/ethereum/one-click-login-flows-a-metamask-tutorial, and here he doesn't need the account password to sign data.

Also, if I do this from the browser in my app it works, I get back the signature:

web3.eth.personal.sign('data','0x7567d83b7b8d80addcb281a71d54fc7b3364ffed',(err,sig) => console.log(sig) )

So what can be the difference? web3 from Metamask seems to be beta_37 while in my app beta_46, but now I am a bit lost.

Thanks


texts: cpp-ethereum could not punch through NAT error

texts:
I have cloned the cpp-ethereum for Linux (Ubuntu) from git as follows:

$ git clone https://github.com/ethereum/cpp-ethereum

$ cd cpp-ethereum

cpp-ethereum$ git checkout 5669c209f4f8dbb7dc3f744e8e2a9c92f1104ca3

cpp-ethereum$ git checkout -b develop

cpp-ethereum$ git submodule update --init --recursive

cpp-ethereum$ mkdir -p build cpp-ethereum$ cd build

cpp-ethereum/build$ git clone https:///github.com/cinemast/libjson-rpc-cpp

cpp-ethereum/build/$ cmake .. && make

cpp-ethereum/build/$ eth

It shows the following error:

  12:27:18|p2p Couldn't punch through NAT (or no NAT in place).

How to solve this problem?

Also when we are running in local machine, what is the need of NAT? Is it using looking for some server outside our network?


texts: Ropsten Geth node consuming max CPU, RAM and DISK and geth logs show "Failed account unlock attempt"

texts:
I have been running a Geth node on Ropsten for the past couple of months and it has been running fine; all my transactions go through and it hasn't been too heavy on the system resources either. I use the following command to start the node:

geth --datadir "C:/ropsten-test-net-project/Data/Node" --testnet --rpc --rpcport "8545" --rpcaddr "0.0.0.0" --rpccorsdomain "*" --rpcapi="personal, eth, network, web3, net" --ipcpath "C:/ropsten-test-net-project/Data/Node/geth.ipc" --syncmode "fast" console 2>>"E:/Etherium + Solidity/test-net-project/Logs/myLog1.txt" --cache 2048

For testing purposes, I have enabled port forwarding on my router and added inbound and outbound rules in windows firewall to allow other systems in my network to connect to this node.

The last few days, Geth started getting heavy on the resources, maxing out the CPU, SSD writes and almost maxing out 16 GB of RAM. At first i thought it is just processing new blocks but after a few Geth crashes and out of memory errors, i decided to look at the Geth logs and found the following lines repeated numerous times:

I was not conducting any transactions and my smart contract and server were not running when these logs were generated. To ensure this wasn't an attack, i enabled logging in windows firewall. Upon observing the firewall logs, i did not see any repeating IP addresses that would indicate requests coming from an attacker.

I would like to know if anyone else has experienced this (or similar) issue and how it can be resolved.


texts: Remix Error: This contract does not implement all functions and thus cannot be created when trying to pass modifiers

texts:
In the below code I can successfully deploy the "UserRegistry" contract, but when I try to deploy the "User" contract, I get the error This contract does not implement all functions and thus cannot be created. Based on this example, I thought I could inherit modifiers from a contract containing only modifiers. I am not seeing why I can compile this Reddit user's code but not mine as it seems to fit the same pattern.

    pragma solidity ^0.4.19;
contract UserRegistry {

    address owner;

    struct user {
        uint dateAdded;
        uint repuation;
    }

    mapping(address => user) users;

    modifier IsUser(address account) {
        require(
            users[account].dateAdded != 0
        );
        _;
    }

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

     constructor(address _owner) public {
        owner = _owner;
    }
}

contract User is UserRegistry {

    event EventAddUser(address account);

    function addUser(address account) public {
        users[account].dateAdded = now;

        emit EventAddUser(account);
    }

    function updateUserRep(address _user) public IsUser(_user) OwnerApproved {
        users[_user].repuation +=  1;
    }

}


texts: Remix Warning: This looks like an address but has an invalid checksum

texts:
I have the following contract:

pragma solidity ^0.4.13;

contract Test {

    function test() public payable {
        address(0xCF5609B003B2776699EEA1233F7C82D5695CC9AA).call(1);
    }
}

The Remix static code analysis tool gives me a warning:

  Warning: This looks like an address but has an invalid checksum.

How do I fix it?


texts: How to know when a transaction is finished? (web3.js)

texts:
I make a contract method call using .send() method:
    contractInstance.methods.pay(itemId).send({from: defaultAccount, value: web3.utils.toWei(String(price*1.0000001)), gas: '1000000'},
                                              function(error, transactionHash) {
        if(error)
            alert("You tried to pay below the price or payment failure! " + err);
    })

How to be notified when the transaction fully happened (cannot be canceled by clicking Cancel in MetaMask anymore)? Is it called a confirmation?
If I just add .on('confirmation'):
    contractInstance.methods.pay(itemId).send({from: defaultAccount, value: web3.utils.toWei(String(price*1.0000001)), gas: '1000000'},
                                              function(error, transactionHash) {
        if(error)
            alert("You tried to pay below the price or payment failure! " + err);
    })
        .on('confirmation', function(receipt){ showFilesWithMessage(); });

it does nothing (showFilesWithMessage() is not called).
web3.js 1.2.9.

Addition:
When I "follow the example on the official docs":
    contractInstance.methods.pay(itemId).send({from: defaultAccount, value: web3.utils.toWei(String(price*1.0000001)), gas: '1000000'})
        .on('transactionHash', function(hash){
            console.log('transactionHash');
        })
        .on('receipt', function(receipt){
            console.log('receipt');
        })
        .on('confirmation', function(confirmationNumber, receipt) {
            console.log('confirmation', confirmationNumber);
            showFilesWithMessage();
        })
        .on('error', console.error); // If a out of gas error, the second parameter is the receipt.

the confirmation event is not issued either! Instead I get only transactionHash event.
How to get the confirmation event for .send()?


texts:
I am having serious issues with mist, is it possible to open geth in command line (mac) and send a. erc20 token via it?

for example

send _____ from _____ to _____ gas = ______


texts: Truffle: Hanging on "Deploying Migrations..."

texts:
I am deploying a contract on a private testnet.  I am using Parity.

When I type:

$ truffle migrate --network my-network-name

I get a popup in the Parity interface for a password to my account.  I enter it.  (And I know it's correct because I get an error when I intentionally enter it incorrectly.)

The popup goes away, but:

a) no ETH has been removed from the account

b) the console does not change.  It still shows:

Running migration: 1_initial_migration.js
   Deploying Migrations...

...and it hangs there for at least 10 minutes.

Has anyone encountered this before?

EDIT: I have also unlocked an account on the command line as described here:
Truffle migration stuck  The result is the same: the migration hangs.

I am sure I have unlocked the correct account because "web3.eth.accounts[0]" from the web3 console (see here)returns the account I am unlocking.


texts: How to get contract instance address for Web3 1.0 contract API?

texts:
With truffle-contract, all you needed to do to get the contract instance was something like this:

const getContract = require('truffle-contract')
const contractJSON = require('./MyContract.json')

const contract = getContract(contractJSON)
contract.setProvider(web3.currentProvider)

const instance = await contract.deployed()
return instance

Please note that the MyContract.json file is the build artifact from Truffle.

But since the instance created by truffle-contract returns promises instead of the PromiEvent which came with version 1.0 of Web3, I decided that I wanted to use regular v1.0 Web3 in order to get the contract instance. In other words, I no longer wanted to rely on truffle-contract.

Unfortunately, I am not that familiar with the contract API in the new 1.0 Web3. This is my attempt:

const contract = new web3.eth.Contract(contractJSON.abi)
contract.methods.get().call()

The first line is okay, but the second line throws the following error:

  This contract object doesn't have address set yet, please set an address first.

I see that this makes sense because the documentation seems to state that you can set an address so that it will know where to find the deployed instance.

Does this mean that I'd have to go to my Truffle Console (aka testrpc) to find the contract address and copy and paste this in every time? I sure hope not, because with truffle-contract, all I needed to do was just include the JSON file and it figured it out for me.

How am I supposed to get this address and pass it in?


texts:
Any examples where I can encode some private string and will decode it for someone automatically once he pay for it.

Ex.

I encode the string with password
Upload the contract: pay 1 eth and get the password
Someone pays 1 eth
Buyer received the key to decode the string

And all of this should be done without me sending him the key manually.

Any examples? Is it possible?

I mean I want automatically share some information with someone who paid for it


texts: which type can use to store abi in a contract

texts:
If I want to store abi in contract, which type can be use? and How can I get it later.

For example, if I use bytes to store a contract's abi. How can I use JSON.parse to get it. I have not find a  proper api in web3.


texts: Truffle configuration file name - is it 'truffle.js' or 'truffle-config.js'?

texts:
Truffle configuration file is mentioned in several places on the web (GitHub, truffle package on npm, solidity-coverage package on npm, etc.).

Some refer to it as 'truffle.js, others refer to it as truffle-config.js.

When creating a project with truffle init, both files are created.

Which one of them should I use?

Thank you.


texts: Successfully migrated Solidity file isn't showing up in Ganache GUI

texts:
I was trying to test out deploying a 'hello world' equivalent smart contract via truffle onto ganache for practice and ran into the following issue with the network/deployment step:
I ran truffle init and then added a Greeter.sol file into the directory.
The truffle.config file regarding my network is setup as follows:

Additionally, I had a successful migration:
truffle(develop)> migrate -Greeter.sol

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

Network up to date.

truffle(develop)>

However, In the ganache GUI it doesn't recognize the deployment.

I'm pretty new to this so I might just be missing something straightforward, any help is appreciated!
-arelius


texts: Error Transaction revert / no balance but Balance is there

texts:
contract MyToken is ERC20 {
    constructor ()
        ERC20("StableToken", "STBL")
        public
    {
        // Mint 100 tokens to msg.sender
        // Similar to how
        // 1 dollar = 100 cents
        // 1 token = 1 * (10 ** decimals)
        //Unter welcher eth adresse der contract deployed wird = msg.sender
        _mint(0x5B38Da6a701c568545dCfcB03FcB875f56beddC4, 1000000);
        _mint(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2,1000000);

    }
}

contract testProtocol {
//Gibt Guthaben an STBL Tokens zurück der aufrufenden Adresse
function checkStableTokenBalance() public returns(uint256) {
    STBLInterface stbl = STBLInterface(stblContract);
    return stbl.balanceOf(msg.sender);
}

//transfer
function transferStableToken(address _recipient, uint256 _amount) public payable returns(bool) {
    STBLInterface stbl = STBLInterface(stblContract);
    return stbl.transfer(_recipient, _amount);
}

function approveStableToken(address _spender, uint256 _amount) public returns (bool){
    STBLInterface stbl = STBLInterface(stblContract);
    return stbl.approve(_spender, _amount);

}

//transferFrom
function transferFromStableToken(address _sender, address _recipient, uint256 _amount) public payable returns(bool) {
    STBLInterface stbl = STBLInterface(stblContract);
    return stbl.transferFrom(_sender, _recipient, _amount);
}

}

I have this setup in remix , i mint erc20 tokens and i can check the balance also from the contract testProtocol and its showing the right balance. So the function "checkStableTokenBalance()" is working.
But when i want to transfer the tokens with function "transferStableToken", i get the Error that transaction is reverted "ERC20: transfer amount exceeds balance".
Whats wrong?


texts: Why does solidity (*sol) file starts with pragma? What does pragma stands for and its origins?


texts: web3 eth return returns a nonexistent transaction hash

texts:
I'm trying to create transactions something like this:
var sender = meth.eth.accounts.privateKeyToAccount(data.fromPrivate)
meth.sendTransaction({
  sender,
  to: data.to,
  amount: data.value,
}, cb)

MEth.prototype.sendTransaction = function(data, cb, curCb, nonce_offset) {
    nonce_offset = nonce_offset || 0
    var meth = this
    this.eth.getTransactionCount(data.sender.address).then(nonce => {
        nonce = nonce + nonce_offset

        this.l.acquire("tx", function(done) {
            if (nonce <= meth.nonce) {
                nonce = meth.nonce + 1
            }
            var tx = {
                nonce: web3.utils.toHex(nonce),
                value: web3.utils.toHex(data.amount || 0),
                to: data.to,
                // from: data.sender.address,
                // gasPrice: web3.utils.toHex(data.gasPriceGwei * 1e9),
                gasLimit: web3.utils.toHex(data.gasLimit || 3000000),
                data: '0x0'
            }

            if(data.encodedData) {
                tx.data = data.encodedData;
            }

            data.sender.signTransaction(tx).then(raw => {
                meth.eth.sendSignedTransaction(raw.rawTransaction, err => {
                    if (!err)
                        meth.nonce = nonce
                    else {
                        if(err.message.startsWith('Returned error: known transaction') ||
                            err.message.startsWith('Returned error: already known')) {
                            var newtx = tx
                            meth.sendTransaction(data, cb, curCb, nonce_offset + 1)
                            done()
                            return
                        }
                    }
                    done()

                    if (!err) {
                        meth.eth.getTransaction(raw.transactionHash).then(function(nettx) {
                            if(!nettx)
                                var fee = undefined
                            else
                                var fee = parseInt(nettx.gasPrice) * nettx.gas
                            cb(err, raw.transactionHash, fee)
                        })
                    } else cb(err)
                })

                curCb && curCb(null)

            })

        })
    });
}

The problem is that periodically I do getTransaction and I manage to steal information, but at another moment I do not even have time. And in any case, the transaction does not appear on the network, that is, as if the node manages to accept the transaction and immediately deletes it for some reason. There are no error messages in the console, I tried to use .on('error'), it also returns nothing, I don’t understand anything and I don’t understand how I can understand what my problem is. I use infura ropsten network.
$ node eth.js
balance, 98276995500000000
null '0xc33771b09d8f9a922cb3daf5623cca2997b49b0fce503dcb55f1e97306cc2734' undefined // getTransaction -> fee = undefined

$ node eth.js
balance, 98276995500000000
null '0xc33771b09d8f9a922cb3daf5623cca2997b49b0fce503dcb55f1e97306cc2734' 9000000 // getTransaction -> fee = 9000000, the hash is repeated accordingly, there are no errors at the same time, there is no transaction in the explorer

$ node eth.js
balance, 98276995500000000 undefined undefined
null '0xc33771b09d8f9a922cb3daf5623cca2997b49b0fce503dcb55f1e97306cc2734' undefined // again fee undefined, and again the same hash


texts: How to get token amounts in a Uniswap Liquidity pool?

texts:
I've searched and found a couple examples, but they don't seem to work anymore with the uniswap API.
I'm looking to get the liquidity amounts of 2 tokens in a uniswap pool, and found through the documentation reserve0 and reserve1, but when I access these propteries, they dont produce a number on the pair


texts: Can a smart contract code be used to generate a bitcoin public/private key pair address?

texts: Seeing that a smart contract is just code. How would it be possible to make a smart contract generate a Bitcoin public/private key pair and send it to a user without anyone knowing the pair.


texts:
contract MyContract {
struct Posposal{
    uint posposalId;
    address voteSponsorAddr;

    bytes1 description_;
    uint userId;
    string message;
    uint amount;
}
Posposal[] public curPosposals;
uint public posposalNextId=0;

function MyContract() {

}
uint public expId;
address public expTarget;
uint public expAmount;
string public expMessage;
function issuse(uint userId,address target_,uint amount_,string message_)  {
    expId=userId;
    expMessage=message_;
    expAmount=amount_;
    expTarget=target_;
    curPosposals.push(Posposal(posposalNextId,msg.sender,0x01,userId,message_,amount_));
    posposalNextId++;
}}

the transaction could perform successfully. I debug in ethereum wallet, but the curPosposals[0] could not have the values.Why? But when I remove string message from struct Posposal ,curPosposals[0] have the values, but it is not the values I pass params.


texts:
I got some Rinkeby ethers from the Rinkeby faucet, after a minute or so, it showed up in my MetaMask Rinkeby network. But then after a while, my MetaMask shows 0 balance for the Rinkeby network. How did that happen?

Somehow I got some ethers in Ropsten & Kovan network but not on my Rinkeby network. What's going on here?


texts: My C: drive in my WINDOWS PC is almost full. How can I change both geth and Mist path to relocate my blockchain files?

texts:
I read here somewhere that I have to execute geth --datadir "NEW PATH". But this solution:

1) Doesn't work in a permanent way for me (it will actually point geth in that direction but if I after execute geth -help it will show the old path).

2) Will not update the Mist (or Ethereum Wallet) path. Every time I execute it will try to download the entire blockchain again in the old path.

I know this has been treated before here, but couldn't find an answer for this particular situation. Thanks in advance.

EDIT: This question is Windows specific, and hasn´t been answered before


texts: Will people still be able to see my smart contract code if I make the functions private?

texts: I am interested in knowing if someone can read the code for my smart contract after I deploy it to the live ethereum blockchain. If I make my functions private. The goal is to hide the code.


texts: Why is it so expensive to trade with Uniswap?

texts:
Please please please, I really would like to know by someone knowledgeable. I looked at the other responses but I still do not truly understand. It just doesn't make sense why anyone would want ETH to be this high. Bought a bunch a while ago and locked it in a smart contract before the last bull run years ago. Sold most of it now, but I still want to keep using the network, as much of the sales went to ERC20 tokens. Now I am basically locked out of swapping it like many others. I am trying to execute larger trades but the fees for swapping are freaking ridiculous ($5000+). To me it seems there is no reason to participate, unless I am doing something wrong.
Is Ethereum 2.0 going to solve this? I'm still kind of a noob about ETH2.0.
I just cant find any good concrete information and I have been trying to FOBM. Never actually asked a question before until now.
Thanks in advance.


texts: Is there a way to broadcast account addresses to other nodes in a private blockchain?

texts: I am running a private blockchain and have a couple of geth nodes which are connected. I have multiple accounts on both the nodes. From node 1, through the admin.peers command, I can get the enode URL of node 2. With this enode URL(including IP address and port #), is it possible to retrieve the list of accounts on node 2 from the geth instance on node 1?


texts: Rationale for using ETH as the unit of account for oracle pricing data

texts:
These are Compound Finance's former oracle contracts:

PriceOracle
PriceOracleProxy

I say "former" because Compound switched to the Open Price Feed UniwapAnchoredView.sol oracle on Aug 17, 2020.
While studying this function:
function getUnderlyingPrice(CToken cToken) public view returns (uint) {
    address cTokenAddress = address(cToken);
    (bool isListed, ) = comptroller.markets(cTokenAddress);

    if (!isListed) {
        // not listed, worthless
        return 0;
    } else if (cTokenAddress == cEtherAddress) {
        // ether always worth 1
        return 1e18;
    } else if (cTokenAddress == cUsdcAddress) {
        // read from hand picked key
        return v1PriceOracle.assetPrices(usdcOracleKey);
    } else {
        // read from v1 oracle
        address underlying = CErc20(cTokenAddress).underlying();
        return v1PriceOracle.assetPrices(underlying);
    }
}

I started to wonder why did they choose ETH as the base unit of price reference? Their web interface tracks all values in USD.
What advantages are there in using ETH instead of USD?


texts:
I am new to Ethereum dev.

I wrote the code below in my local node to transfer 1 ether between my two Rinkeby testnet.

From account: 0xffD8eb81304291AFcA2C4DA5D26B691b8CC81Bd5
It has 21 ether in Rinkeby (Hope this is sufficient).

// Environment
"web3": "^0.19.1"

Geth
Version: 1.7.2-stable
Git Commit: 1db4ecdc0b9e828ff65777fb466fc7c1d04e0de9
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.9.2
Operating System: darwin
GOPATH=
GOROOT=/usr/local/Cellar/go/1.9.2/libexec

My nodejs code:

var Web3 = require('web3');
var util = require('ethereumjs-util');
var Tx = require('ethereumjs-tx');
var lightwallet = require('eth-lightwallet');
var txutils = lightwallet.txutils;

var web3 = new Web3(

new Web3.providers.HttpProvider('https://rinkeby.infura.io/qyft9l9yABZ7tJuoX8R4')
//Local RINKEYBY
//new Web3.providers.HttpProvider('http://127.0.0.1:8545')
);

var addr1 = '0xffd8eb81304291afca2c4da5d26b691b8cc81bd5';
var addr2 = '0xba5453837f30b2ba413c06567dd9ea812abf123f';
var privateKey = new Buffer('bf36e0ba1bb26ad4949df0d92554b8702cb595a23410ba8ecac8dbde0d607dfc', 'hex');

var rawTx = {
chainId: web3.toHex('4'),
gas: web3.toHex('21000'),
gasPrice: web3.toHex('25000000000'),
gasLimit: web3.toHex('90000'),
from: '0xffd8eb81304291afca2c4da5d26b691b8cc81bd5',
to: '0xba5453837f30b2ba413c06567dd9ea812abf123f',
value : web3.toHex(web3.toWei(1, "ether"))

}

var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();

web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
if (!err)
  console.log(hash);
else
  console.log(err);
});

I always end up with this below error msg :-( Same happens for me in other private network and mainnet also.

Can you please tell how to get rid of this insufficient funds error.

  Error: insufficient funds for gas * price + value
      at Object.InvalidResponse (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/web3/lib/web3/errors.js:38:16)
      at /Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/web3/lib/web3/requestmanager.js:86:36
      at XMLHttpRequest.request.onreadystatechange (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/web3/lib/web3/httpprovider.js:118:13)
      at XMLHttpRequestEventTarget.dispatchEvent (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/xhr2/lib/xhr2.js:64:18)
      at XMLHttpRequest._setReadyState (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/xhr2/lib/xhr2.js:354:12)
      at XMLHttpRequest._onHttpResponseEnd (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/xhr2/lib/xhr2.js:509:12)
      at IncomingMessage. (/Users/antonyjohnson/Documents/development/angularjs/mean/todo-app/todo-api/node_modules/xhr2/lib/xhr2.js:469:24)
      at emitNone (events.js:111:20)
      at IncomingMessage.emit (events.js:208:7)
      at endReadableNT (_stream_readable.js:1056:12)


texts: What is the target block time for Casper?

texts: With PoW, the block time is around 17 seconds. What is the target block time for Casper's PoS?


texts: If one started out on ethereum blockchain and found out it is not suitable any longer, how would one go about migrating from one blockchain to another? this would require predefined upgradeable/migratable paths for the smart contracts yes?


texts: How to set web3 provider from external host?

texts: I have installed testrpc in AWS and also started it with testrpc -h 'my address'. In remix ide when I choose web3 provider and set url to myaddress:8545 it shows 'Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).' I make sure it is running on AWS. This is purely for demo purpose, also I need some public address along with some ethers. What things should I consider to make sure web3 provider is from my AWS server. Thank you very much.


texts:
i need help com many parameters for sign a transaction.

What is "nonce"?

How i calculte gas value?

How i calculate gasPrice?

what is data field?

Chain ID 1 is a Mainnet?

I will using infura.

$transaction = new Transaction([
'nonce' => '0x'.$hexNonce,
'gas' => '0x'.$gas,
'gasPrice' => '0x'.$gasPrice,
'value' => '0x'.$hexValue,
'chainId' => 1,
'data' => '0x0'
]);


texts: Samsung is making an ASIC to mine bitcoin and ether so is GPU-mining of ether going to be non profitable?

texts:
Ethereum PoW is designed to be ASIC-resistant but Samsung is making an ASIC to mine bitcoin and ether so is GPU-mining going to be non profitable?

https://techcrunch.com/2018/01/31/samsung-confirms-asic-chips/


texts: What to do with smart contracts to avoid replay attacks?

texts: I am trying to write a smart contract for Crowdsale. What extra measures should one keep in mind during smart contract development to avoid replay attacks (after the hard fork of block 1,920,000)?


texts:
I have geth installed and running and I am connected to a private network. As given in https://github.com/ethereum/web3.js, I have created a test html with jquery-3.1.1.min.js and web3.min.js and then my custom js code as shown below. However I am getting error: 'Web3' is undefined in the below line. Any help please.

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


texts: Sorry for the noob, probably stupid question

texts:
You must get these all the time from idiots that don't know what they're doing. But I have to ask.

Anyway if anyone can help I'd be much obliged. So I've got multiple exchange accounts, too many tbh and today I transferred 2.4 Eth from bibox to fatbtc or so i thought.

After it hadn't come through I checked the address and the address I'd sent to was 0x91d969681ea03a49639f7f144d698fd8f3a62b05

Which wasn't my fatbtc Eth deposit address at all. Cutting to the chase I've no idea what that address I've sent to is. I can't find it in any of my other accounts although looking through my bibox withdrawal history it would seem I have used it before which initially reassured me but I've exhausted all my accounts and cannot find that address or my eth.

I just don't understand what I'm looking at when I look on that etherscan. Is there a way of knowing what exchange (if it is an exchange) that I've sent my eth to.

Sorry for such an idiotic question but I'd really appreciate it if anyone can throw any light on this for me


texts: Accessing Public State Variables Between Contracts - Solidity - Error

texts:
I have an error accessing a public variable between contracts. It works if I change x.myname to x.myname() but I do not understand why that works. Can anyone explain why the () are needed?

Here is the code which fails -

pragma solidity ^0.4.18;
contract MyAddr {
uint public myname=1;
function getName() view  public returns (uint name) {
name = myname;
}
}
contract MyAddr2 {
MyAddr private x;
string private myname1;
  function getStateVar() view public returns (uint stateVar) {
       stateVar = x.myname;
   }
}

contract MyAddr3 {
}

MyAddr.sol:12:20: Error: Type function () view external returns
(uint256) is not implicitly convertible to expected type uint256.
    stateVar = x.myname;
               ^------^

x.myname to x.myname() does work.


texts: How can I use .deployed() with a constructor argument?

texts:
My contract has a constructor argument, is there a way to use puddings handy Contract.deployed() function together wit a default argument?
How can one achieve this?

Somehow there are args in the construction of a new contract, but I don't get it how to initialize them.


texts: What module can be used for a client side wallet in a DApp?

texts:
If you want to create a DApp that is a stand alone single page application, there is the need to have access to Ether.
There are serveral ways to do that:

Metamask accesses your geth server
Mist is a stand alone browser with a wallet integrated
MyEtherWallet is a single page application that integrates contract functionalities
A fourth way would be to have a single page application that cane generate a wallet just for your application. Then you load money on it from where ever you want.

Question: are there ready made java script wallet libraries that can be used for 4? Or do you think web3 is just enough?


texts: Does the default Oraclize gas price change over time?

texts:
Is the default gas price of oraclize callbacks adjusted over time?

In the docs it says:

  If no settings are specified, Oraclize will use the default values of 200,000 gas and 20 GWei. This last value is on the higher-end of the pricing spectrum right now, but it helps having faster confirmation times during network-wide congestions.

Is this default gas price of 20 GWei fixed forever? What happens if demand surges and 20 GWei is way too low, would my contract wait forever for the callback by oraclize?

Moreover, if I use oraclize_setCustomGasPrice once how can I reset the gas price to the default value? I mean I can alway say oraclize_setCustomGasPrice(20000000000), but this setting would only work if the default gas Price remains 20 Gwei forever. Hence, if it does change, how can my contract now about it?


texts: What is the cheapest way for an off-chain oracle to demonstrate "proof of life" to a smart contract?

texts:
Suppose you have a smart contract which relies on an off-chain oracle in order to function effectively. In fact, suppose that this oracle is so important to your contract, that you want to disable your contract if the oracle goes offline.

Clearly, the contract cannot directly check whether the oracle is online; it must rely on more indirect means. In your opinion, what is the cheapest way (in terms of Ether spent) to accomplish this?


texts: How do I uninstall Metamask from Brave. I have forgotten password and lost seed phrases. I want to uninstall so that I can connect My Ether Wallet.Any suggestions?


texts: Transaction does not get mined on rinkeby

texts:
so I'm trying to deploy my first contract on rinkeby using web3 and truffle/hdwallet-provider.

even with different gas prices it doesn't get mined.Please help out.

const HDWalletProvider = require("@truffle/hdwallet-provider");
const Web3 = require('web3');
const {abi , bytecode} = require('./compile');
const provider = new HDWalletProvider(
    'december blossom school two brief lunar siren truth purse violin car submit',
    'https://rinkeby.infura.io/v3/737d5964ada94e2a8d812f1414c89c4e'
)
const web3 = new Web3(provider)
async function scan(message) {
    process.stdout.write(message);
    return await new Promise(function(resolve, reject) {
        process.stdin.resume();
        process.stdin.once("data", function(data) {
            process.stdin.pause();
            resolve(data.toString().trim());
        });
    });
}

async function getGasPrice(web3) {
    while (true) {
        const nodeGasPrice = await web3.eth.getGasPrice();
        const userGasPrice = await scan(`Enter gas-price or leave empty to use ${nodeGasPrice}: `);
        if (/^\d+$/.test(userGasPrice))
            return userGasPrice;
        if (userGasPrice == "")
            return nodeGasPrice;
        console.log("Illegal gas-price");
    }
}

const deploy = async() =>{
    const accounts = await web3.eth.getAccounts();
    console.log('attempting to deploy from account',accounts[0])
    const result = await new web3.eth.Contract(abi)
        .deploy({data:'0x' +bytecode ,arguments: ['hii']})
        .send({from: accounts[0],gas: 1500000,gasPrice: await getGasPrice(web3)})
    console.log('contract deployed to', result.options.address);
}
deploy()

Output :

 node deploy.js
attempting to deploy from account 0x010Ff624891610c8538824AB6F5AF4abfD1c3bfd
Enter gas-price or leave empty to use 1000000000: 1050000000
Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!
C:\Users\Ketan Verma\Desktop\blockchain\solidity-etherium\index\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { "use strict";var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in
Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_HAS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_HAS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_NODE=ENVIRONMENT_HAS_NODE&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locat

RuntimeError: abort(Error: Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!). Build with -s ASSERTIONS=1 for more info.
    at process.abort (C:\Users\Ketan Verma\Desktop\blockchain\solidity-etherium\index\node_modules\solc\soljson.js:1:14506)
    at process.emit (events.js:189:13)
    at emitPromiseRejectionWarnings (internal/process/promises.js:119:20)
    at process._tickCallback (internal/process/next_tick.js:69:34)


texts: How exactly does a keystore file enable you to interact with the blockchain

texts: So I am pretty new to ethereum and development, one of my discoveries was MyEtherWallet. My question is how does the keystore file enable you to interact and use the blockchain. The keystore file obviously needs to have enough information so that it can retrieve your details. So my understanding is that it is a Json file containing details relevant to your account, when going through a specific process to then access your details. I need a better understanding of this process, or just an explanation of the contents contained in the keystore file. Any additional explanation or resource will be much appreciated. Again, I am a fairly new to ethereum.


texts:
I have the following code to create my own wallet:

var ethers = require('ethers')

    let data = {"address":....}
    var password = "***";
    var json = JSON.stringify(data);
    ethers.Wallet.provider = new ethers.providers.Web3Provider(web3.currentProvider);
    ethers.Wallet.fromEncryptedWallet(json, password).then(function (wallet) {
        console.log("Wallet address: " + wallet.address);
    });

But it does not work because: TypeError: ethers.Wallet.fromEncryptedWallet is not a function

Am I missing something?