texts: Unable to connect two private nodes on different systems

texts:
I am using the same logic for adding peers but admin.peers is just showing [] on GETH console. I have already make sure that I am connecting via same --networkid.

The command I am using is admin.addPeer("enode://e3c8b88a63e175e612bdc7258ba47290be643132a713cef8b1cfadab14466ee75d14b4a4b4309d41675b1ce2f65483af6b1c35ea32ed088aaa093675e1de131d@10.130.5.69:30304")

where 10.130.5.69 is the IP of the machine where another node is running followed by the port num.

I have checked by adding it on the local system, it is working with the same IP but not when I am trying on different systems. Am I missing some details?


texts: Running a shell script in after a contract is deployed in a private blockchain network

texts:
Is there any way that i could run a shell script after a contract is deployed,since the terminal has geth Javascript console running,and there are some commands which are already in the shell script.

  ./deployContract.sh

command=$(echo'loadScript("./Coin.js")');
eval $command;


texts: Whats the difference between pyethapp and pyethereum?

texts:
This one:
https://github.com/ethereum/pyethapp

and this one:
https://github.com/ethereum/pyethereum

I have pyethapp running (the ipython console). What then is pyethereum?


texts:
I have both Mist and Geth installed. One note though; Mist uses (is bundled with?) Geth 1.6.0 whereas I have Geth 1.6.1 installed.

When I type > geth --testnet --fast console, I fail to sync the testnet. After some block, I start to get only messages like this (copied from here):

WARN [04-21|17:40:40] Ancestor below allowance peer=20c9ad97c081d633 number=647267 hash=000000…000000 allowance=647267 WARN [04-21|17:40:40] Synchronisation failed, dropping peer peer=20c9ad97c081d633 err="retrieved ancestor is invalid"

However, when I close this terminal (remove chain data) and start Mist and click "Use the test network", it syncs with Ropsten correctly. Is Mist passing other flags that I need to use too? Or is it just a problem with Geth 1.6.1?

Thanks,


texts: Testing in Truffle - How to create two instances of the same contract?

texts:
I am instantiating a contract to test like this:

var Test = artifacts.require("./Test.sol");

contract('Test0', function(accounts) {
  it("First test", function() {
    var thisTest
    return Test.deployed().then(function(instance) {
    thisTest = instance
    // my tests
  })

  it("Second test", function() {
    var thisTest
    return Test.deployed().then(function(instance) {
    thisTest = instance
    // thisTest still refers to the one in the previous test
    // How do I create a new one?
  })
})

The problem I'm having is that I can't isolate the different instances as I assume they're pointing to only one instance of the contract.

Is there a way to create more than one instance?


texts: All requests routed to submodule when changing its provider in web3js

texts:
Using web3.js 1.2.11, I expect the last part of the following code to route requests from the web3.eth.personal module to the IPC socket, and requests on web3.eth to TCP port 7545.
let Web3 = require('web3');
let net = require('net');

let provider_a = new Web3.providers.WebsocketProvider('ws://localhost:7545');
let w3 = new Web3(provider_a);
console.debug('root', w3.currentProvider.url);
console.debug('personal', w3.eth.personal.currentProvider.url);
w3.eth.getBlockNumber().then(function(o) {
    console.debug(o);
});

let provider_b = new Web3.providers.IpcProvider('/tmp/foo.ipc', net);
w3.eth.personal.setProvider(provider_b);
console.debug('root', w3.currentProvider.url, w3.currentProvider.path);
console.debug('personal', w3.eth.personal.currentProvider.url, w3.eth.personal.currentProvider.path);
w3.eth.getBlockNumber().then(function(o) {
    console.debug(o);
});

The output of the above, using an actual provider on 7545 and socat UNIX-LISTEN:/tmp/foo.ipc -, outputs:
root ws://localhost:7545
personal ws://localhost:7545
root ws://localhost:7545 undefined
personal undefined /tmp/foo.ipc
0

More precisely, the second getBlockNumber() call shows up on the unix
socket.
I tried using two websocket providers, this works in some cases (web3.eth.getBalance), not in others (web3.eth.Contract.methods...call..)
I tried using two http providers, same problem (but afaiu this is deprecated anyway).
Am I to understand that combining provider types is not possible?


texts:
What is the difference between these two?

 _instance.send(msg.value);

 address(_instance).send(msg.value);

both of them are giving me the same result on remix. Why?

So is this:

address(this).balance;

this.balance;

Am I missing something. Is there security consideration in using one of these?


texts: How to get all the information of a uniswap trade using web3?

texts:
I would like (if possible) to read the exact trade made in a transaction where and address interact with Uniswap (or other DEX) using web3.
Using Etherscan is quite simple to read the tokens swapped in a transaction, see for example
https://etherscan.io/tx/0x28dc4fd2364440a60a2e027de0f9b3d77cb1420ecd8662637224e5f5ecb9695a in transaction action.
My final purpose would be that for a given transaction extract the same information.
Thank you in advance!


texts: The cost of using Ethereum as a reference database

texts:
As stated in the documentation there are 3 types of storage in the Ethereum VM (EVM) The storage, the memory, and the stack

  Each account has a data area called storage, which is persistent
  between function calls and transactions. Storage is a key-value store
  that maps 256-bit words to 256-bit words. It is not possible to
  enumerate storage from within a contract and it is comparatively
  costly to read, and even more to modify storage. A contract can
  neither read nor write to any storage apart from its own.

Let's say I want to store key-values pairs of millions of records e.g cars and owners, does this mean it will be extremely costly to do so ?
Or the concept of storage is totally different of what I'm looking for ?


texts: should I use server side rendering(Next.js) for a dapp?

texts:
Recently I have been studying a lot about dapps and now working on a little complex one. So what I wanted to ask is which is better for a dapp ? SSR or CSR ?
I have read in a couple of places that we should use SSR incase if metamask is not installed on the browser and we can fetch info from the Ethereum blockchain on the server using something like infura from the server(ofcourse we still cant sign anything).

A simple setup would be like the code in the link below

An example of web3 setup

As you can see I am checking if web3 exist in the browser and use the injected one but if its not (else case), I am using infura.

My question is that cant we just use CSR because it will work even if the page is rendered in the client side.
It will simply use infura if web3 doesn't exits and we can use componentDidMount lifecycle method for fetching the data from the ethereum blockchain.
Please ask for the details if needed

Regards


texts:
I am running a full node and I noticed that the amount of disk space it takes is larger than reports online.

I use the command ./geth --syncmode full --rpcapi eth,web3,personal --rpc --rpcaddr 127.0.0.1.

The results from looking at my .ethereum file is as follows:

4.0K    .ethereum/keystore
109G    .ethereum/geth/chaindata/ancient
504G    .ethereum/geth/chaindata
11M .ethereum/geth/nodes
163M    .ethereum/geth/ethash
505G    .ethereum/geth
505G    .ethereum/


texts: How to pay gas fee for new addresses of ERC20 tokens that initially have 0 Eth balance?

texts:
I have a confusion, When we create new address/account for an ERC20 token then it have 0 Eth balance. When we send some tokens to this address and then withdraw token again from this address require a gas fee in ETH but this account don't have any ETH. So how we can send the transaction when account have 0 ETH for Gas fee. Can we use a separate address to pay ETH fee for all address of Token ?
I am developing ERC20 token wallet application in C# so kindly answer accordingly.

Thanks


texts:
So what I am trying to do is create a keccak256 of an array of structs.

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract Test
{
    struct test1 {
        address test;
        address test2;
    }

    struct test2 {
        address test3;
        test1[] test4;
    }

    function encode (test2[] test)
      external
      returns (bytes32)
    {
         return keccak256(abi.encodePacked(  ??  ));
    }
}

So I have a structure called test1 and a structure test2 that contains an array of test1.

How can I hash them?

If I do abi.encodePacked() on test2 I get an error, if I do it on an array of test2 I get an error but If I do it like:

abi.encodePacked(test.test3, test.test4)

Then it works, but I'm not sure if it produces the expected results. Since array of test2 should work as well if that is the case.

Does anyone know exactly how this works and what concept should I use for hashing an array of structs?


texts: Find deployed contract address if you loose it

texts: How do we find the address of a contract, if we loose the address that we deployed at?


texts: usedGas comparison: `push()` a struct into the array vs change all the values on the same struct that is stored in the array

texts:
[Q] When I push() a new struct into an array vs. when change all the values inside the same struct that is stored in the array, they both consume different usedGas. Regarding this difference, which path should I take, in order to use gas efficiently:

node[] array_1;
function foo(){
    array_1.push(<some_value>);
}

or

uint32 index=0;
node[<array_size>] array_2;
function foo() {
   array_2[index++].value = <some_value>;
}

[Observation] When I push() a new struct into my array, it uses much less gas than when I change all the values inside the same struct that is stored in the array.

Why do they differ on gas usage since both do the same operations? I assume, I am doing something wrong.

https://github.com/ethereum/wiki/wiki/Solidity-Features:

  .push() for Dynamic Storage Arrays
  PT Dynamically-sized storage arrays have a member function push, such
  that var l = arr.push(el); is equivalent to arr[arr.length++] = el;
  var l = arr.length;.

In this following example: you could see the different gas usage.

my_contract.transact().push_me( 30, 40, 16 ); consumes 63146 gas
my_contract.transact().change( 30, 40, 16 );  consumes 79468 gas

-

contract Example {
  struct node {
    uint32 blk_start;
    uint32 blk_end;
    uint16 core;
    uint32 next;
   }
   node[]    array_1;
   node[10]  array_2;
   uint32 index = 0;

   function push_me( uint32 blk_start_, uint32 blk_end_, uint16 core_ ) {
     array_1.push(node( { blk_start: blk_start_, blk_end: blk_end_, core: core_, next: 10 }));
   }

   function change( uint32 blk_start_, uint32 blk_end_, uint16 core_ ) {
     array_2[index].core       = core_;
     array_2[index].blk_start = blk_start_;
     array_2[index].blk_end   = blk_end_;
     array_2[index].next      = 10;
     index++;
   }
}

Thank you for your valuable time and help.


texts: How to backup contract's data in case of upgrading the contract

texts:
I'm trying to make a Dapp using solidity. I saw a few article to segregate data from codes for updating code contracts.

But what can I do if I have to upgrade data structure itself, such as adding additional fields and so on? I think the update will make a new contract and previous data will be gone.

The only way I think of is adding additional functions to retrieve all data of the data contract for future use.

Is there any other way to solve data migration needs?

Thanks in advance.


texts:
Is it possible to have the Akasha platform accessible on normal internet / intractable via simple URL?

Congratulations to all Akasha developers, I hear very positive reviews so far! : ) One possible hinderance to main stream adoption however is having to install a .exe/.dmg or program to interact. Would be great if users could access content on regular internet by registering/syncing their accounts/profiles online instead.


texts:
I need to create contracts from various accounts in a Truffle JS Test. To do so, I set:

let accounts = await web3.eth.getAccounts();
MyContract.web3.from = accounts[9];

Before creating my contract instance via:

let myContract = await MyContract.new("constructor argument");

However, the contract is still deployed by account 0 (accounts[0]).

How can I specify that that instance of MyContract shall be created using account 9?

I'm also interested in then calling functions of that contract using various accounts, so it's not just about deploying a contract using a specific account.


texts: What are the relationships between Geth's different development branches?

texts:
While looking at this question I realised that I'm not too clued up on how Geth's different branches relate to each other.

For example, the PPA pushes out v1.5.0-unstable, which doesn't contain the changes made for the hard-fork, which went into 1.4.10. (I'm thinking specifically of this commit, which introduced the --oppose-dao-fork and --support-dao-fork flags.)

What are the rebase/collapse schedules relating to the different branches (I'm thinking master, develop and versioned branches), and more specifically, how do the PPA packages pick up the changes from these branches?

I'm hoping for a lovely branch diagram in the answer, but I'll settle for anything you've got...


texts: how to create hierarchical blockchin using Geth, ethereum?

texts:
As of my plan (in the attached figure) there will be 2 levels of blockchain. The top level blockchain (yellow circles) consist of 4 participant, admin top & admins middle. The bottom levels blockchain (green circle) consists of a middle admin and some child in it. So middle admins have to participate in two blockchains.
My question,
1) how to setup two blockchain in a single node (admin middle)
2) How to deploy smart contracts here ?
3) how to get the  measures block creation time, response time and energy consumption?
I'm using Geth, Ethereum, solidity on windows.


texts:
Hello Solidity Expert,
I am working on Ethernaut challenge 8 called Vault: Ethernaut  See the contract code at the end of this post.
I feel I solved the challenge but for some reason I cannot open the vault.
Here are the steps I have taken.

I found the contract on Rinkeby and extracted the Bytes32 component from the constructor.  Contract 0x5F694fcf2767ff28c0907eEAF6b705E8456a3665

I entered the Bytes32 component into the parameter of the unlock function but the vault does not unlock?

I am not certain what I did wrong here. In my mind the Vault should open.  Any hints or insights are welcome.
Thank you.
pragma solidity ^0.6.0;

contract Vault {
  bool public locked;
  bytes32 private password;

  constructor(bytes32 _password) public {
    locked = true;
    password = _password;
  }

  function unlock(bytes32 _password) public {
    if (password == _password) {
      locked = false;
    }
  }
}


texts:
Let's say we have a contract that implements a Priority Queue in Solidity that looks like this:

pragma solidity ^0.4.23;
pragma experimental ABIEncoderV2;
contract PQ {
struct Node {
    int256 key;
    address value;
}
Node[7] private heapKeyValue;
function insert(int256 key, address addr) public {
      .. Implementation ..
}
function get_min() public view returns (int256) {
    return heapKeyValue[0].key;
}
function heapify(uint8 idx) internal {
      ..Implementation..
}
}

And another contract that uses this contract:

contract test_pq {
       function test() public returns (int256){
         PQ memory pq;
         for (uint8 i = 0; i < 10; i++)
             pq.insert(i)
         return pq.get_min();
       }
}

Then what is the gas cost for calling the test() function in test_pq contract? Intuitively, the way I see it function state does not alter any state thus it should be zero gas cost. Is this the case?

Also I would appreciate if someone could explain to me what happens under the hood when the line PQ memory pq is executed


texts:
I was wondering what is the most efficient way (and why), to use variables in memory for function calls with regards to A and B?

A) Like this:

 function checkBalance() public view returns (uint256) {
        address _payee = msg.sender;
        return balanceOf(_payee);
    }

B) Or like this:

     function checkBalance(address beneficiary) public view returns (uint256) {
            return balanceOf(beneficiary);
        }


texts: Event listening on a VPS server with limited ressources

texts: I need to listen to events on the Ethereum blockchain on a small vps server with limited ressources (1 vcore, 10go SSD, 2go of RAM). Is it possible to do so without running a full Ethereum node ? What are the different options and their drawbacks ?


texts: How to upload and download files to the blockchain?

texts: I want to create smart contract which can upload and download file from blockchain. Is that possible? If so, how?


texts: Safe way to make a payable function that accepts a ERC20 Token in a contract that didn't create that Token

texts:
I have two contracts, contract A represents Token A, contract B is its own contract.
I users to call a contract B function by paying Token A to contract B, as if they were using a payable function, but by paying Token A instead of ETH.
Is making the user call token.approve() on contract A and then token.transferFrom() on contract B a safe solution or is there a pattern I should follow?


texts: In Ethereum how to check if in mapping, the key already exists?

texts:
In this Proof of existence, integrity, and ownership contract of a file why files[fileHash].timestamp == 0 is used? why timestamp?

contract Proof

{
   struct FileDetails
   {
       uint timestamp;
       string owner;
   }

   mapping (string => FileDetails) files;
   event logFileAddedStatus(bool status, uint timestamp, string owner, string fileHash);

   //this is used to store the owner of file at the block timestamp
   function set(string owner, string fileHash)

   {

       //There is no proper way to check if a key already exists or not therefore we are checking for default value i.e., all bits are 0
       if(files[fileHash].timestamp == 0)

       {
           files[fileHash] = FileDetails(block.timestamp, owner);

           //we are triggering an event so that the frontend of our app knows that the file's existence and ownership details have been stored
           logFileAddedStatus(true, block.timestamp, owner, fileHash);
        }
else
        {//this tells to the frontend that file's existence and ownership details couldn't be stored because the file's details had already been stored earlier
           logFileAddedStatus(false, block.timestamp, owner, fileHash);
        }           }

   //this is used to get file information
   function get(string fileHash) returns (uint timestamp, string owner)
   {
       return (files[fileHash].timestamp, files[fileHash].owner);

   }
 }


texts:
I was wondering if there is any way for a smart contract to determine where a specific ERC20 transfer came from. That's to say:

Alice and Bob both send a transfer to a smart contract same amount & token and both tx mined on the same block.

Can the smart contract given the SC address of the ERC20 token and the amount determine who sent it, some how?

I know you can determine if the SC owns the fund by doing smth like this:

function sendTokens(address _tokenContract, uint _amountContributed){
      if(uniqueSwap._tokenContract.balanceOf(address(this))!=_amountContributed){revert();}
    }

Im after a bit more trace-ability than this though.

Thanks in advance!


texts: Truffle & Web3 1.0.0-beta : does it work for anyone?

texts:
I'm trying to make the latest Truffle (3.4.3) and Web3 (1.0.0-beta11) to work together in a React app.

It fails when I try to call myContractInstance.deployed()

import { default as Eth} from 'web3-eth';
import { default as Contract } from 'truffle-contract';
import myContract_artifacts from '../../build/contracts/myContract.json';
...
var eth = new Eth(Eth.givenProvider || "http://localhost:8545");
var myContractDef = Contract(myContract_artifacts);
myContractDef.setProvider( eth.currentProvider);
var myContractInstance = await myContractDef.deployed();

the last line  throws an error with localhost http provider (testrpc v4.0.1):

Uncaught (in promise) TypeError: Cannot read property 'apply' of undefined
at Provider.sendAsync (bundle.js:113598)
at RequestManager.sendAsync (bundle.js:121952)
at Object.get [as getNetwork] (bundle.js:23150)
at bundle.js:114052
at Promise (<anonymous>)
at Function.detectNetwork (bundle.js:114043)
at Function.deployed (bundle.js:113991)
at App.componentDidMount (bundle.js:60259)
at bundle.js:68136
at measureLifeCyclePerf (bundle.js:67947)
at bundle.js:68135
at CallbackQueue.notifyAll (bundle.js:39530)
at ReactReconcileTransaction.close (bundle.js:70093)
at ReactReconcileTransaction.closeAll (bundle.js:26044)
at ReactReconcileTransaction.perform (bundle.js:25991)
at batchedMountComponentIntoNode (bundle.js:41397)
at ReactDefaultBatchingStrategyTransaction.perform (bundle.js:25978)
at Object.batchedUpdates (bundle.js:69759)
at Object.batchedUpdates (bundle.js:13827)
at Object._renderNewRootComponent (bundle.js:41590)
at Object._renderSubtreeIntoContainer (bundle.js:41672)
at render (bundle.js:41693)

but also with Metamask (v3.9.0):

Uncaught (in promise) Error: MetamaskInpageProvider - sendAsync not overwritten
    at MetamaskInpageProvider.sendAsync (inpage.js:219)
    at Provider.sendAsync (bundle.js:113598)
    at RequestManager.sendAsync (bundle.js:121952)
    at Object.get [as getNetwork] (bundle.js:23150)
    at bundle.js:114052
    at Promise (<anonymous>)
    at Function.detectNetwork (bundle.js:114043)
    at Function.deployed (bundle.js:113991)
    at App.componentDidMount (bundle.js:60259)
    at bundle.js:68136
    at measureLifeCyclePerf (bundle.js:67947)
    at bundle.js:68135
    at CallbackQueue.notifyAll (bundle.js:39530)
    at ReactReconcileTransaction.close (bundle.js:70093)
    at ReactReconcileTransaction.closeAll (bundle.js:26044)
    at ReactReconcileTransaction.perform (bundle.js:25991)
    at batchedMountComponentIntoNode (bundle.js:41397)
    at ReactDefaultBatchingStrategyTransaction.perform (bundle.js:25978)
    at Object.batchedUpdates (bundle.js:69759)
    at Object.batchedUpdates (bundle.js:13827)
    at Object._renderNewRootComponent (bundle.js:41590)
    at Object._renderSubtreeIntoContainer (bundle.js:41672)

I've got the same errors when I try:

myContractDef.deployed().then( function( error, result)  { ... } )


texts: how to automatically transfer funds in geth

texts:
I am trying to find a way how to automatically transfer funds from one address to another after new block is sealed.

Scenario would look like this:

1. New block sealed
2. Check source account balance
3. Deduct tx cost from balance
4. Unlock source account
5. Send available balance (minus tx cost) from source to destination
6. Wait for new block to be sealed.

I have simplified version but it does not seem to get executed.

function transferFunds(){
  var source = 0x123456789.....
  var source_pass = "secretpassword"
  var dest = 0x567890...
  var txcost = eth.estimateGas({from: source, to: dest, value: web3.toWei(200, 'gwei')});

  var fundsAvailable = eth.getBalance(source) - txcost;

  if( fundsAvailable > 0){

    personal.unlockAccount(source, source_password, "60");
    eth.sendTransaction({from: source, to: dest, value: web3.toHex(fundsAvailable)});

    console.log("Transferred " + web3.fromWei(fundsAvailable) + " ETH");

  }
  else{

    console.log("Insufficient funds");
  }

}

transferFunds();

Here are my questions:

1. What filter should I use as "pending" block is not suitable I think
2. What am I missing in the above example so it does not execute transaction ?
3. Any other comments on how to make it better are welcome

Thanks


texts: Security of contract methods password protection. Is it a safe practice?

texts:
I want my server to modify the state of the contract. The server has the contract's secret key and a way of broadcasting signed transactions to the network using web3 ethereum provider hosted by Infura. Here's the contract code:

pragma solidity ^0.4.0;
contract Contract {
    bytes32 password;
    uint public someVar;

    function Contract(string secret){
        password = sha3(secret);
    }

    function changeSomeVar(string secret, uint someValue) passwordProtected(secret){
        someVar = someValue;
    }

    modifier passwordProtected(string secret){
        if(sha3(secret) != password) {
            throw;
        }
        _;
    }
}

What are the most vulnerable points in my setup?

Should I continue with it or use something else?


texts: How to import multiple folders into remix?

texts:
I have about 50 contracts in 10 different folders. How do I bulk import/export them?
I already tried remixd, and that doesn't work.
I already tried remix desktop, but it doesn't have any explanation of how to interact with a wallet.


texts:
I have attached a picture related to DAO attack. I got the image from the following link A Survey on Ethereum Systems Security: Vulnerabilities, Attacks and Defenses
. The image shows a code containing ‘throw’. I have a confusion about throw because it causes reversal. Had the DOA attack used ‘throw’? Some body please guide me was throw used in the DAO attack and why it did not cause reversal of all transactions (and refunding)?


texts: How to instantiate and interact with a contract in web3, metamask and drizzle, given the ABI and the address?

texts:
I have a method on a Contract A which I am calling (in my dapp). This method in turn instantiates a second Contract B and emits an event with contract B's address.

I then use this address, along with the ABI (from my source code) to create a representation of this contract to interact with - in web3. However, when I try to interact with Contract B I get the following error:

  Error: Returned error: Internal JSON-RPC error.

Unlike for my other transactions - metamask does not event attempt to open.

This is the code

const transactionObject = this.context.drizzle.contracts.FundingApplications.methods.submitApplication(name, description);
const data = await transactionObject.send({from: this.props.accounts[0], value: this.drizzle.web3.utils.toWei(String(0.004), "ether")}); // this succesfully uses metamask to make a request
const applicationAddress = data.events.ApplicationSubmitted.address;
const web3Instance = new Web3(this.context.drizzle.web3.currentProvider);
const application = new web3Instance.eth.Contract(Application.abi, applicationAddress);
const transactionalObject = application.methods.voteForApplication(1);
const gas = await transactionalObject.estimateGas(); // this is where it fails
const transaction = await transactionalObject.send({from: this.props.accounts[0], gas: gas});

When I log out transactionalObject, I see that it is indeed the transactional object required by web3 and metamask. However as soon as I call estimateGas, send or call on it, it fails with the above error. This method of interacting with contracts works for all my other contracts which are deployed and then passed into drizzle options... but this method appears not to work for this contract, the only difference being that I am insantiating this contract at runtime using web3 and passing it the metamask provider. What am I missing?


texts: If contract imports erc20 token contract, can I use functions in token contract without call or delegatecall?

texts: I thought it is required to call token contract's functions to use transfer or transferfrom when I define new contract. But if the contract inherits or imports token contract, then call is not required anymore right? Please correct me. And let me know difference between inherit and import. Thank you!


texts: Reject TransferOwnership Smart Contract Solidity

texts:
I found the following code for solidity smart contracts ownership purposes.

contract owned {
    address public owner;

    function owned() public {
        owner = msg.sender;
    }

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

    function transferOwnership(address newOwner) onlyOwner public {
        owner = newOwner;
    }
}

I would like to know if it is possible to reject ownership of a contract which is transferred by owner of that contract to your contract address(or your EOA)

The reason I'm asking this question is to prevent the following scenario

Bob is owner of contract C1 and Alice is owner of contract C2
Contract C1 can automatically withdraw ether(generally any token)from it's owner address and send it to Bob's EOA. In other words it is malicious contract at all which can do bad things
Bob calls the function transferOwnership of contract C1 and transfer the Ownership to either contract C2 address or Alice's EOA .
Contract C2 or Alice becomes the owner of contract C1
Contract C1 start to withdraw the balance of it's newowner = Contract C2 or Alice, and send it to Bob's EOA


texts: Delegate function really needed while loop(Voting example)?

texts:
I'm learning Solidity, and referring given example of Voting in a doc.
But I'm not able to understand one thing about delegate function.
Here is the Delegate method:

/// Delegate your vote to the voter `to`.
function delegate(address to) public {
    // assigns reference
    Voter storage sender = voters[msg.sender];
    require(!sender.voted, "You already voted.");

    require(to != msg.sender, "Self-delegation is disallowed.");

    // Forward the delegation as long as
    // `to` also delegated.
    // In general, such loops are very dangerous,
    // because if they run too long, they might
    // need more gas than is available in a block.
    // In this case, the delegation will not be executed,
    // but in other situations, such loops might
    // cause a contract to get "stuck" completely.
    while (voters[to].delegate != address(0)) {
        to = voters[to].delegate;

        // We found a loop in the delegation, not allowed.
        require(to != msg.sender, "Found loop in delegation.");
    }
}

What is use of while loop here? they already checked with self delegation with

require(to != msg.sender, "Self-delegation is disallowed.");

And we can check initial address condition with if condition.

  if (voters[to].delegate != address(0)) {
            to = voters[to].delegate;
  ...
  ...

What is special about While loop here?


texts:
Would you please help: When I run the below command in my nodejs console I get the below error: (I am using web3 0.20.0) on Windows 10

web3.eth.getAccounts().then(list => {accts = list})

TypeError: Cannot read property 'then' of undefined
> TypeError: callback is not a function
at c:\Users\Salam Khanji\Ether\node_modules\web3\lib\web3\property.js:119:13
at c:\Users\Salam
Khanji\Ether\node_modules\web3\lib\web3\requestmanager.js:89:9
at XMLHttpRequest.request.onreadystatechange (c:\Users\Salam
Khanji\Ether\node_modules\web3\lib\web3\httpprovider.js:119:7)
at XMLHttpRequestEventTarget.dispatchEvent (c:\Users\Salam
Khanji\Ether\node_modules\web3\node_modules\xhr2\lib\xhr2.js:64:18)
at XMLHttpRequest._setReadyState (c:\Users\Salam
Khanji\Ether\node_modules\web3\node_modules\xhr2\lib\xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (c:\Users\Salam
Khanji\Ether\node_modules\web3\node_modules\xhr2\lib\xhr2.js:509:12)


texts:
I'm trying out Batch Request provided by web3.js. In the example below I want to test making 300 transactions but i get the error log displayed below. I'm trying to figure out the error log but it seems to me that there is some kind of limit. Does anyone know if that is the case?

instance is just my contract instance.

async function multipleTx(
  TRANSACTIONS = 300,
  GAS_PRICE = 2000000000,
) {
  let accounts = await web3.eth.getAccounts()

  await instance.methods
    .addSubmissionNoCheck(6, Math.round(Date.now() / 1000))
    .send({
      from: accounts[0],
      gasPrice: GAS_PRICE,
    }) // works

  var bookingBatch = new web3.BatchRequest()
  for (let i = 0; i < TRANSACTIONS; i++) {
    bookingBatch.add(
      instance.methods
        .addSubmissionNoCheck(6, Math.round(Date.now() / 1000))
        .send.request(
          { from: accounts[i], gasPrice: GAS_PRICE, value: 1 },
          bookingCallback
        )
    )
  }
  bookingBatch.execute() //throws error
}
multipleTx()

Error Log:

Error: Invalid JSON RPC response: {}
    at Object.InvalidResponse (C:\Users\Diddi\Documents\mjukvaruteknik\examensar
bete\tqdt33\node_modules\web3-core-helpers\src\errors.js:42:16)
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\web3-core-requestmanager\src\batch.js:61:60
    at Array.forEach (<anonymous>)
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\web3-core-requestmanager\src\batch.js:54:12
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\web3-core-requestmanager\src\index.js:166:20
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\map.js:32:9
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\once.js:12:16
    at iteratorCallback (C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\t
qdt33\node_modules\async\eachOf.js:58:13)
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\onlyOnce.js:12:16
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\map.js:29:13
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\@truffle\hdwallet-provider\node_modules\web3-provider-engine\index.js:157:9
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\once.js:12:16
    at replenish (C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\n
ode_modules\async\internal\eachOfLimit.js:61:25)
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\eachOfLimit.js:71:9
    at eachLimit (C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\n
ode_modules\async\eachLimit.js:43:36)
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\async\internal\doLimit.js:9:16


texts: Invalid opcode exception when trying to resize a storage array

texts:
I wrote this function:

function removeClaim(uint256 _claimId) public returns (bool success) {
    require(msg.sender == owner || msg.sender == claims[_claimId].issuer);

    // Emit event and store burned signature before deleting to save gas for copy.
    IdentityContractLib.Claim storage claim = claims[_claimId];
    emit ClaimRemoved(_claimId, claim.topic, claim.scheme, claim.issuer, claim.signature, claim.data, claim.uri);
    burnedSignatures[claim.signature] = true; // Make sure that this same claim cannot be added again.

    // Delete entries of helper directories.
    uint256[] storage array = topics2ClaimIds[claim.topic];
    uint32 positionInArray = 0;
    while(_claimId != array[positionInArray]) {
        positionInArray++;
    }

    for(uint32 i = positionInArray; i < array.length - 1; i++) {
        array[i] = array[i+1];
    }

    array.length = array.length - 1;

    // Delete the actual directory entry.
    claim.topic = 0;
    claim.scheme = 0;
    claim.issuer = address(0);
    claim.signature = "";
    claim.data = "";
    claim.uri = "";

    return true;
}

I'm trying to reduce the size of topics2ClaimIds[claim.topic] which I aliased to array. But changing array.length = array.length - 1; to topics2ClaimIds[claim.topic].length = array.length - 1; doesn't change the problem.

If I add a return right before array.length = array.length - 1;, the function executes normally. However, if I add a return right after this line (or none at all letting the function execute till the end), I get this error:

Error: Returned error: VM Exception while processing transaction: invalid opcode

If I understand the documentation correctly, every storage array is a dynamically sized array:

  For dynamically-sized arrays (only available for storage), this member can be assigned to resize the array. Accessing elements outside the current length does not automatically resize the array and instead causes a failing assertion. Increasing the length adds new zero-initialised elements to the array. Reducing the length performs an implicit :ref:delete on each of the removed elements. If you try to resize a non-dynamic array that isn’t in storage, you receive a Value must be an lvalue error.

(https://solidity.readthedocs.io/en/v0.5.3/types.html)

In case this is wrong, please let me know.

The mapping I use and therefore the array in question is declared as follows in the header of the contract:

mapping (uint256 => uint256[]) topics2ClaimIds;

Btw. I realize that arrays are a terrible data structure for what I'm trying to do to begin with. If Solidity has better data structures available (like a binary heap for starters), please let me know.


texts:
I replace my MetaMask's web3 with web3.js 1.0.0-beta.34, and getGasPrice always returns null under every network --

window.web3 = new Web3(web3.currentProvider);
console.log('web3.version = ' + web3.version);
web3.eth.getGasPrice(gasPrice => {
    console.log('gasPrice = ' + gasPrice);
});

i.e., from mainnet to Ropsten to my private network ( ganache-cli ) log --

web3.version = 1.0.0-beta.34
gasPrice = null

Does anyone else have the same experience? What could have gone wrong?


texts: How could Compound's interest accruing every block? How's that implemented?

texts:
Here I'm referring to https://compound.finance, which is quite an awesome product.

One thing inspires me most is that the interests accrued in Compound are updated per block. How's that even possible?

From its FAQ (https://medium.com/compound-finance/faq-1a2636713b69):

  How often is interest calculated?

  The interest rates you see in the Interface and Market Overview are
  quoted as annual interest rates. Interest accrues each Ethereum block;
  every ~15 seconds, your balance will increase by (1/2102400) of the
  quoted interest rate. Really!

I still couldn't figure out how to do that, as I'm seeing exactly it works even without frontend UI - by setting requestedAmount to be 0xff...ff.

Can someone please educate me on this? Thanks.


texts: How i can call one method inside another method result?

texts:
i want to call two methods first call one method then second method after first method success below is my code please check and let me know how i can achieve this

this.state.token.methods.approve(this.state.neutralG.address, qty).send({ from: this.state.account}).
  then('receipt', (receipt)=>{

   this.state.neutralG.methods.createEscrow(intvalue, 3600, price, this.symbol, beneficiaryAddress, qty,
    this.tokenAddress).send({ from: this.state.account}).
  once('receipt', (receipt)=>{
    this.setState({loading: false})
  })

  })

this is not calling second transaction.


texts:
I'm looking to install geth 1.4.6 that syncs much faster than 1.4.5. Unfortunately doing brew upgrade ethereum only updates geth to version 1.4.5.

How can I get geth 1.4.6 for Mac OS X?


texts: Transaction dropped and replaced but still shows as pending in etherscan

texts:
I canceled a transaction by sending another 0 ETH transaction to myself customizing the nonce in Metamask. Now the canceled transaction shows as "dropped & replaced" in etherscan, but it's still pending:
https://etherscan.io/tx/0xde32215b3628d7b5e690194464898e4d187c2592d439e143d403d28ddeb6224e
If I try to send a transaction with a higher nonce it will not pass through as there is a pending transaction with a lower nonce. If I try to send another transaction with the same nonce as the canceled one, I get an "rpc error with payload" from Metamask. So basically my wallet is stuck. Is there something I can do about it?
Thanks to anyone who can help!


texts:
There's buyprice on function buy and sellprice on function sell.  I would like to set up

1 ETH =  10000 (SYMBOL)
0.1 ETH = 1000 (SYMBOL)
0.01 ETH = 100 (SYMBOL)
0.001 ETH = 10 (SYMBOL)

How can I set a number on buyprice and sellprice?  Even if i calculated it, it doesn't work at all

function buy() payable returns (uint amount) {
  amount = msg.value / buyPrice;      // calculates the amount
  require(balanceOf[this] >= amount); // checks if it has enough to sell
  balanceOf[msg.sender] += amount;    // adds the amount to buyer's balance
  balanceOf[this] -= amount;          // subtracts amount from seller's balance
  Transfer(this, msg.sender, amount); // execute an event reflecting the change
  return amount;                      // ends function and returns
}

function sell(uint amount) returns (uint revenue) {
  require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
  balanceOf[this] += amount;                // adds the amount to owner's balance
  balanceOf[msg.sender] -= amount;          // subtracts the amount from seller's balance
  revenue = amount * sellPrice;
  msg.sender.transfer(revenue);             // sends ether to the seller: it's important to do this last to prevent recursion attacks
  Transfer(msg.sender, this, amount);       // executes an event reflecting on the change
  return revenue;                           // ends function and returns
}


texts: Out of gas error when reading from blockchain?

texts:
function getPosts(address[] subscriptions, uint[] subscriptionIndexes, uint count) public view returns
            (address[], bytes32[], bytes32[], uint[]) {

            address[] storage postSenders;
            bytes32[] storage postLinks;
            bytes32[] storage postComments;
            uint[] storage postTimestamps;

            while(postSenders.length < count) {
                (uint postId, address subscription) = getNextPost(subscriptions, subscriptionIndexes);

                postSenders.push(subscription);
                postLinks.push(addressToLinks[subscription][postId]);
                postComments.push(addressToComments[subscription][postId]);
                postTimestamps.push(addressToTimestamps[subscription][postId]);
            }

            return (postSenders, postLinks, postComments, subscriptionIndexes);
        }

The above works fine when I pass an array of length 311, but returns this error when I pass an array of length 312 or greater:

Returned error: base fee exceeds gas limit at Object.ErrorResponse

I didn't realize gas was involved when just reading from the blockchain?

I've tried to increase the gas limit like this (using web3. v 1.0):

let results = await myContract.methods.getPosts(subscriptions, indexes, 3).call({gas: 1000000000});

But now I get that error every time regardless of what I put for the gas amount and regardless of how large subscriptions array is.

Any ideas on how I can make this more efficient or why its failing?

Thanks!


texts: Can my transaction be confirmed after I've cancelled it?

texts:
Title is self-explanatory. It is my understanding that the way blocks are mined, the miner takes a snapshot of a collection o transactions at time T and starts solving the puzzle. But what happens if I cancel my transaction at T+1sec? Will the snapshot of the miner be updated to exclude my transaction? If not, wouldn't that mean that my transaction would still be mined even if it was cancelled?
Thanks


texts:
In Geth, if I check my balance, it says one number.
At etherchain.org it says another number which is higher and more accurate and includes my transaction history.
I wanted to convert my balance to bitcoin so I signed up on kraken.
It gave me an address to send it to in order to 'deposit' it for me presumably into my kraken account.
It seems I then trade it for btc.
It looks like, in order to send my balance to kraken, I have to use geth, but if geth has the wrong and lower balance, how do I access and send the rest to kraken?

I know my wallet number (the 0x*****) thing and I know the password for it.

Any help would be greatly appreciated.

One more quick note, the last few transactions I received happened while geth was not syncing properly.  I had to update it for it to sync right.


texts: Event not visible on Etherscan transaction list

texts:
I have a BuyToken event when user send ether to smart contract they will receive tokens based on ether amount. For ex: 1 ETH = 1000 Token.

/// This notifies clients about the Buy Token
event BuyToken(address user, uint256 eth, uint256 token);

There is my buy() function

 /**
*  function for Buy Token
*/

function buy() payable public returns (uint amount){
      require(msg.value > 0);

      amount = ((msg.value.mul(TokenPerETHBuy)).mul( 10 ** uint256(decimals))).div(1 ether);
      balanceOf[this] -= amount;                        // adds the amount to owner's
      balanceOf[msg.sender] += amount;
      emit BuyToken(msg.sender,msg.value,amount);
      return amount;
}

It works well when user send ether user will receive tokens.

But this transaction event is not visible on Etherscan.io

For ex:
Ropsten link

I send 0.2 ether I receive 200 tokens. I can see ether transaction. But received tokens transaction not visible on "ERrc20 Token Txns" tab.

Pelase can you help ??


texts: What proof do I have that I own a token?

texts:
I bought some tokens using the mnemonic phrase of my Jaxx.io wallet through myetherwallet. I got a confirmation in the tansaction history of Jaxx and a transaction ID (etherscan)
The token is https://adshares.net/ and it ends in 14 days

How do I receive the gains from owning this token and what proof do I have that I own this?

Also, how can I send these to another wallet?

Thanks


texts: How can I get contract address from tx_hash which is contract transaction?

texts:
The following is a contract transaction. I want to get the created contract address from the tx_hash using JSON RPC or web3. Is it possible?

https://etherscan.io/tx/0xb4c93e32218f1688343334e5c1b12c2d9c523516dc3644c98865a93ec3230c73

Update 1

I found the similar question. Moe mentioned the solution. I'm looking into it right now.

Is there a way to know the contract creation Address from a the transaction?


texts:
I have a Solidity project. It has contracts folder and few subfolders. Now I have to compile it with Truffle, but it seems to me the tool doesn't support the case when contracts are not in "contracts/" folder.

I've found it could be done via solc options in truffle.js, but I can't figure out what should I place there. Could you help me? Thanks


texts: how to prevent spam block attacks in cpp ethereum?

texts: it is really annoying. I'm running a sync with eth and every 1 or 3 hours there come giant spam block attacks, which slow down syncing dramatically. I delete network.rlp, restart eth and everything is ok for 1 or 2 hours. Than the next spam block attacks occur. Is there anybody, who has an idea what to do against these attacks?


texts: How to push value of function into dynamically sized array

texts:
I am trying to capture the address of the use who has been given the "right to vote" in the giveRightToVote function.  If I use msg.sender that only captures the user invoking the function.  Any ideas?

contract FantasyLeague {
// Define address of commissioner
address public commissioner;
// Hold data of proposed number
uint[] public proposals;
address[] public members;
address[] public rightsGiven;

// Deploy contract
constructor() public payable {
    commissioner = msg.sender;
}

function giveRightToVote(address) public payable {
    require(msg.sender == commissioner);
    // Ensures that the right to vote given matches the actual voted addresses
    rightsGiven.push();
}


texts:
I am using infura and web3 0.20.0 in back-end.(nodejs, I don't want to interact with metamask(front-end))
Now, I am facing a problem.
I tried to use ERC865.

    solidity

  function recoverPreSignedHash(
    address _token,
    bytes4 _functionSig,
    address _spender,
    uint256 _value,
    uint256 _fee,
    uint256 _nonce
    )
  public pure returns (bytes32)
  {
    //return keccak256(_token, _functionSig, _spender, _value, _fee, _nonce);
    return keccak256(abi.encodePacked(_token, _functionSig, _spender, _value, _fee, _nonce));
}

  Blockquote

var Tx = require('ethereumjs-tx');
var Web3 = require('web3');
const testnet = 'https://ropsten.infura.io/';
const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var contractAddress = '0xf21BF631C...';
var contractABI = [{"constant":true,"inputs":[],"................}]
var contract = web3.eth.contract(contractABI).at(contractAddress);
var transferSig = "0x48664c16";
var to = "0x36C906644FEbA405...";
var val = 100*Math.pow(10, 18);
var fee = 20*Math.pow(10, 18);
var nonce =web3.eth.getTransactionCount("0xD0A8800973cb...");
contract.recoverPreSignedHash(contractAddress, transferSig, to, val, fee, nonce, function(error, hash) {
    if (!error) {
        web3.eth.sign("0xD0A8800973cbEF2639Eb...", hash, function(error, signature) {
        if (!error) {
            console.log(hash);
            console.log(signature);
        } else {
            console.log(error);
        }
    });
    } else {
    console.log(error);
    }
});

But it returns"Error: The method eth_sign does not exist/is not available"
Because Infura does not have private key, so it doesn't have sign method.
This problem is as same as sendTransaction so I use sendRawTransaction.
How do I solve "sign" problem? (nodejs & web 0.20.0)
How do I sign this hash Manually?(I have private key)
What is "web3.eth.sign()" machanism?


texts:
My contract stores data in a mapping like the following:

mapping(address => uint256) public data_stores;

How can I view the data on a front end with web3js?

I have managed to view a uint256 like the below example.

uint256 public tester

the javascript

myContract.tester.call(function(err,res)
{
  console.log(res)
});

If I try the above for the mapping I get an error stating I have an invalid number of arguments for the solidity function.  (I am assuming this is because I did not pass in an address for the mapping).


texts:
I'm working on an open source multi coin payment gateway.
ETH, EOS, BTC and BCH will be supported.

My plan so far:

The nodejs API runs on DigitalOcean. You send a GET request with your preferred coin and e.g. price in USD. It will send you back the Pub key to send the funds to, price in crypto and a unique memo used in the frontend: `txTransfer.data = Utils.toHex('my memo);

Web3.js on the server checks 15min for incoming transactions that are >= than the inquired price with the specific memo.

If successful, return status 200.

Did I forget something? Of course I will check my ports and not run the API as root, but is there anything else I can do so no one hacks into the server and steals all the coins?

The beginning: https://github.com/MarcelBlockchain/crypto-payment-gateway


texts: Will staking increase or decrease volatility?

texts:
I'm trying to wrap my head around the implications of locking up much of the supply of ether when proof of stake happens. It seems to me that doing so would decrease the circulating supply and increase the price.

It also seems like it might stabilize the price because staking is, in a way, proving that you will not sell your coins in the near future. By offering an incentive to stake coins, an opportunity cost of keeping coins liquid (not staked) is introduced (i.e. you could be making more eth by staking). I'm thinking this cost might pressure people to stake, therefore reducing liquidity, which might deter reactionary selloffs (due to news stories, currently ongoing selloffs, drop in price of eth, etc.) because much of people's eth is not spendable (it's staked). Data on how much is staked and for how long might also signal the intentions of eth holders, since we can assume that if an owner of some eth were intending on holding for a while (and has confidence in eth holding value), then (s)he would have that eth staked. Knowing people's intentions about spending might increase long-term confidence in the currency if enough is staked and for a long enough amount of time.

On the other hand, a decrease in liquidity might be a bad thing. I've read that in forex trading, lesser liquidity generally corresponds to higher volitility, so even if liquidity is successfully reduced, that might actually increase volatility.  It also seems possible that liquidity might not change at all. The decrease in the circulating supply and, consequently, the increase in price per eth might kind of cancel out, bringing us back to square one where the total value of all circulating coins remains about the same, regardless of how many are locked up. So price might not stabilize at all. Hell, just the action of staking and un-staking might vary effective supply enough to increase price volatility.

Is there any truth to this thought about eth prices stabilizing, or does this not make sense at all? I'm throwing around the idea of creating an erc-20-based token contact with some staking mechanism built in, but I'm not really aware of the useful properties that might arise from this mechanism. Obviously, staking an erc-20 token will not secure anything (double spends are already out of the question with an erc20 token), I'm interested in the other properties (stability, price increase, others I haven't thought of). I'm having a hard enough time trying to predict the relationship between percentage of coins staked and price, let alone stability of that price.

Does anybody have any thoughts on this? Please let me know if I can clarify anything!


texts: UniswapV2 addLiquidityETH() reverting when trying to deploy to ganache locally

texts:
I'm trying to locally deploy a contract similar to sushiswap, but I keep getting a revert from addLiquidityETH(), no message other than VM Exception while processing transaction: revert
//module.exports = function(deployer) {};
const SushiToken = artifacts.require("SushiToken");
const MasterChef = artifacts.require("MasterChef");
const SushiBar = artifacts.require("SushiBar");
const UniswapFactory = artifacts.require("UniSwapV2Factory");
const UniswapRouter = artifacts.require("UniswapV2Router02");
const MockERC20 = artifacts.require("MockERC20");
const SushiMaker = artifacts.require("SushiMaker");

const migration = async function(deployer,network,accounts) {
    await Promise.all([
        deployToken(deployer,network,accounts),
    ]);
};

module.exports = migration;

async function deployToken(deployer,network,accounts) {

    if( network === 'test' ) {

        dev_addr = accounts[9];
        account1 = accounts[8];

        await deployer.deploy(SushiToken);
        let sushiToken = await SushiToken.deployed();

        await deployer.deploy(MasterChef, SushiToken.address, dev_addr, 25, 0, 0);
        await deployer.deploy(SushiBar, SushiToken.address);

        let factory = await deployer.deploy(UniswapFactory, dev_addr);
        let wethToken = await deployer.deploy(MockERC20, "Wrapped Ether", "WETH", 1000);
        let anotherToken = await deployer.new(MockERC20, "Another Token", "AT", 1000000000000);

        let poolToken = 0x0;
        if(( (await factory.getPair(wethToken.address, anotherToken.address)).toString()) === '0x0000000000000000000000000000000000000000') {
            poolToken = await factory.createPair(wethToken.address, anotherToken.address);
        }

        let router = await deployer.deploy(UniswapRouter, UniswapFactory.address, dev_addr);

        await deployer.deploy(SushiMaker, UniswapFactory.address, SushiBar.address, SushiToken.address, wethToken.address);

        await sushiToken.approve( accounts[0], 10000000000);
        await sushiToken.mint(accounts[0], 10000000000);

        try { // the error is somewhere in here
            await router.addLiquidityETH(
                sushiToken.address,
                100,
                50,
                9000,
                accounts[0],
                ~~((Date.now() + 1000*24*60*60) / 1000), // unix date 24h into the future
                {from: accounts[0], value: 10000, gas: 6000000}
            );

        } catch(err){
            console.error(err)
        }
    }

}

I have tried different addressess too, as well as different amounts, but so far it always reverts.
// Edit:
accounts[0] through accounts[9] have roughly 100 ETH per account.


texts: Does network latency significantly affect mining rewards?

texts:
I have a slightly flakey internet connection (no good providers in the area). I can stream at reasonable speeds (Megabits) but there is a certain amount of jitter in the packet latency.

Mining is competitive. Will packet latency (on the order of tens, sometimes hundreds of milliseconds) mean that, if I start mining, other miners are likely to beat me to a block? In other words, how close is the race to mine a block?

I suspect, since a number of confirmations are required for consensus, that random delays (variance on the order of several seconds) on later blocks in competing chains, will render my personal latency insignificant, but I would like to see some hard math confirming this.

(I recall reading on the Ethereum blog some analysis of how network latency establishes lower bounds on block time, but I think this was for overall network latency, not considering one jittery miner amongst others with consistently lower latency.)


texts: JavaScript Code Required to Generate an Ethereum Address?

texts: I am aware of several tools and websites that generate addresses for you, but I'm looking for an actual JavaScript code snippet to demonstrate the steps plainly.


texts: when creating a myetherwallet, a keystore file was not created/downloaded and there isn't a private key in my wallet. Also, the system will not print  a paper wallet


texts: evm_mine in parity dev chain. Fast forward time in Development Chain

texts:
Everybody loves testrpc, except me.
So, I like to write unit test against real parity dev chain node.
The question is how to fast forward timestamp(create new blocks) ?

function advanceBlock() {
  return new Promise((resolve, reject) => {
    web3.currentProvider.sendAsync({
      jsonrpc: '2.0',
      method: 'evm_mine',
      id: Date.now(),
    }, (err, res) => {
      return err ? reject(err) : resolve(res)
    })
  })
}

Need to create similar way for
parity --chain dev

the only way that I could find right now is by overwriting now variable in MockedContract:

pragma solidity ^0.4.15;

import '../../contracts/WhitelistedCappedCrowdsale.sol';
contract WhitelistedCappedCrowdsaleMock is WhitelistedCappedCrowdsale {
    uint64 public time = now;

    function getTime() public contstant returns(uint64) {
       return time;
    }

    function setTime(uint64 _time) public {
        time = _time;
    }
}


texts: Is there any possibility to exclude one of MuliSig Wallet owners?

texts:
I mean not to exclude from already existin multi sig wallets, but create a wallet with such possibility.

For example:
   The team of 4 people want to accept temporary 5th member (give him the right to control the wallet on equal basis as others) for 2 month. But the initial group (of 4) should have a right to exclude him. Or even automaticaly after this time period this member should be excluded from the wallet owners group.

Any ideas or suggestions?


texts: How can we print anything in solidity programming language?

texts:
I started with a basic HelloWorld example.

pragma solidity ^0.4.0;
 contract HelloWorld
  {
     String str="Hello World";
  }

How can we print this str and check in remix ide?


texts: Unable to approve KNC token. Fails with error: "Error: Transaction has been reverted by the EVM"

texts:
I've tried approving with multiple different spender addresses but no luck.
Token approval works fine when I try a different token, e.g. DAI. I've made sure I have the correct KNC contract address and correct spender addresses. I'm not even able to approve the spender when it's something so standard as the Uniswap V2 Router contract.
I've also checked to ensure the tokenQty is less than or equal to the tokens I have in my account, and that it is being passed down as a BN.
Here are the contract addresses I'm using (all Ropsten):
KNC: '0x7B2810576aa1cce68F2B118CeF1F36467c648F92'
KYBER_NETWORK_PROXY_ADDRESS: '0xd719c34261e099Fdb33030ac8909d5788D3039C4'
KYBER_NETWORK_PROXY_ADDRESS_ALT: '0x818E6FECD516Ecc3849DAf6845e3EC868087B755'
UNISWAP_ROUTER_V2_ADDRESS: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'

Here is my token approval helper function:
const approveTokenTrade = async (
  tokenSymbol: string,
  tokenQty: number,
  addressToApprove: string,
  web3: Web3
) => {
  const accountAddress = getAccountAddress();
  const chainId = getChainId();
  const privateKey = getPrivateKey();

  const tokenInstance = new web3.eth.Contract(
    ERC20_TOKEN_ABI,
    TOKEN_SYMBOL_TO_ADDRESS_MAP.get(tokenSymbol)
  );

  const approveTxData = tokenInstance.methods
    .approve(addressToApprove, tokenQty)
    .encodeABI();

  const approveTxObject = {
    from: accountAddress,
    to: TOKEN_SYMBOL_TO_ADDRESS_MAP.get(tokenSymbol),
    data: approveTxData,
    chainId,
    gas: 4000000,
  };

  const signedApproveTxObject = await web3.eth.accounts.signTransaction(
    approveTxObject,
    privateKey
  );

  await web3.eth.sendSignedTransaction(
    signedApproveTxObject.rawTransaction as string
  );
};

Thank you!


texts: Solidity contract "burn from" functions not compiling?

texts:
When attempting to compile any solidity contract, errors are returned.  I find myself constantly having to restart the wallet as it gets stuck on both chains, on the test chain it got to the last block and i restarted the wallet and everything seemed to be fine, but contracts must be modified before they will work.  For example, I had to remove  this code from the create a crypto currency contract code:

function burn() payable returns (bool success) {
    if (balanceOf[_from] < _value) throw;                 // Check if the sender has enough
    balanceOf[_from] -= _value;                          // Subtract from the sender
    Burn(_from, _value);
    return true;
}

function burnFrom(address _from) payable returns (bool success) {
    if (balanceOf[_from] < _value) throw;                 // Check if the sender has enough
    if (_value > allowance[_from][msg.sender]) throw;   // Check allowance
    balanceOf[_from] -= _value;                          // Subtract from the sender
    Burn(_from, _value);
    return true;
}

If I do not delete this code, the contract will not deploy.

I thought the issue was affecting just Debian, but it's happening on Ubuntu as well.  Strangely enough on Debian, transactions were disappearing, though that's not happening here on Ubuntu, I'm wondering why this is happening.


texts:
I am interested in the Dai stable coin and have seen multiple different explanations of how the coin balances and pegs to the $1. One said it was to do with the increase or decrease in interest rates to bring the price up or down(eg. If interest goes up then demand goes down and the price falls and vice versa). The other said it was to do with supply and demand change due to people buying cheaper and selling higher for a profit(eg. when the value of dai is higher than dollar people sell for a profit, which increases supply and so the value goes down; when the value is low people buy which drives price up as supply decreases).
Which of these is correct?
I apologise if this is on the wrong page.


texts: VM jump when accessing statically set variables

texts:
Hey it seems I get a jump error when I try to access any variable not set through a parameter in the constructor. amountRaised is throwing a jump error below as I try to statically set the value.

 contract Project {
 address public fundingHub;
 address public projectCreator;
 string public title;
 string public description;
 uint256 public amountToBeRaised;
 uint256 public deadline;
 uint256 public amountRaised;

function Project(address _creator, uint256 _amountToBeRaised, uint256 _deadline, string _title, string _description) {
    if (_amountToBeRaised <= 0) { throw; }
    if (_deadline <= block.timestamp) { throw; }
    fundingHub = msg.sender;
    projectCreator = _creator;
    title = _title;
    description = _description;
    amountToBeRaised = _amountToBeRaised;
    amountRaised = 0;
    deadline = _deadline;
}
}

The javascript looks like this

            return thisProject.deadline.call();
      }).then(function(_deadline) {
          console.log("this is the deadline" + _deadline.valueOf());
          return thisProject.amountRaised.call();
        }).then(function(_amountRaised) {
          console.log(_amountRaised.valueOf());
          return thisProject.amountToBeRaised.call();
        }).then(function(_amountToBeRaised) {
          console.log(_amountToBeRaised.valueOf());
        });
  }


texts:
Sorry for (maybe redundant) question, but:
If I have a payable function, and I use msg.value, like this:

function f() payable {
    // do something with msg.value
}

Should I check msg.value for overflow? And if yes, how can overflow happen?
For example, if I do f1(0 - 1), it can go off the limit, but msg is composed by Ethereum network, and it should correspond to a real amount transfered, correct?


texts: handling block gas-limit in a large loop

texts:
I have a loop like this:

struct User {
    string name;
    uint tokens;
    uint frozenTokens;
    bool isValid;
}

mapping(address => User) users;
address[] public usersAddresses;

function freeTokens() private {

   uint reciversLength = usersAddresses.length;
   for (uint i = 0; i < reciversLength; i++) {
       User storage theUser = users[usersAddresses[i]];
       theUser.tokens += (theUser.frozenTokens * 10000);
   }
}

Well now this loop could get really large as new users sign up.

I was wondering if this would work as loop gets larger? anything i could optimize in this code?

what errors could happen? what is the potential of exceeding the block gas-limit? and how can i handle it when it hits the block gas-limit?


texts: ERC-2222 : Funds Distribution Token implementation for a fee contract

texts:
My MainCore contract is a contract who sell NFT, and all the sell and buy have a 1% fee for team developper (uint DevelopperCutTotalSupply).
I try to implement the ERC-2222 "Funds Distribution Token (FDT)" to my contract (https://github.com/atpar/funds-distribution-token) to distribute claim fee power to each member of my team with weight according to importance on project.
So, I deploy the contract
contract FDT_ERC20Extension is IFundsDistributionToken, FundsDistributionToken {...}

Wich have the capacity to set a ERC20 contract, distribute % claim, withdrawn funds AND FDT_ERC20 Extension is a contract which pay the claim with ETHER.
So now I need to send ETHER to the FET-ERC20 Extension.
I can send with ether
interface IFundsDistributionTokenOptional {

/**
 * @notice Deposits funds to this contract.
 * The deposited funds may be distributed to other accounts.
 */
function depositFunds() external payable;

But the DevelopperCutTotalSupply is on the MainCore contract, and the MainCore contract have All the Bid/sell/fee, but I want only DevelopperCutTotalSupply accessible for ERC-2222.
It's what I did :
contract MainCore is IFundsDistributionTokenOptional {
       function depositFunds(uint value) public payable {
        IFundsDistributionTokenOptional.depositFunds;}}

How to send ether with my MainCore contract to FDT_ERC20Extension ?
I'm  confused with the notion of interface contract, abstract contract...


texts: Import a token to MyEtherWallet? How do I determine `Decimal` value?

texts:
I'm new to MEW, but wanted to understand how to determine the Decimal value when adding a custom token.

I pulled the contract address from etherscan: 0xaaaf91d9b90df800df4f55c205fd6989c977e73a

The token symbol is: TKN

I'm unsure how to determine Decimal.

Where do I pull this information from?


texts: Hashrate drop when both GPUs are running

texts:
I'm just getting into mining and I've just built my first mining rig.
I'm having a problem in that when I run both of my GPUs the hashrate drops right down. If I remove either GPU it shots back up, can't seem to solve the problem. Any help would be great.
Below us the spec and the hashrates, the lower numbers being when they are both running.
Motherboard Z390-P
PSU 850w
GPU 1: 1080Ti 15 mh/s / 35-40 mh/s
GPU 2: 2070 Super 20 mh/s / 35-40 mhs
Both GPus are on risers, overclocking doesn't solve the problem they still stay low.


texts:
I started an ENS auction on ropsten, but I forgot to bid.

Now the auction date has passed. The name is listed as not available:

 > ethRegistrar.entries(web3.sha3('name'))[0]
 1

The owner, however, seems to be nobody:

 > deedContract.at(ethRegistrar.entries(web3.sha3('name'))[1]).owner();
 "0x"

The name is obscure, so I think most likely there was no bids at all as it expired. Either that, or the other bidder(s) forgot to reveal bids before the end.

I tried to finalize it, and got some transaction hash. But it doesn't change anything.

Is the name now lost forever?


texts:
In this code from Solidity documentation: inside the function 'add', what does the sentence 'type(uint).max' mean?
Has something to do with this another kind of expression: 'address(this)'?
Is it some kind of cast?
Library example
Thanks a lot for your help.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.8 <0.9.0;

struct bigint {
    uint[] limbs;
}

library BigInt {
    function fromUint(uint x) internal pure returns (bigint memory r) {
        r.limbs = new uint[](1);
        r.limbs[0] = x;
    }

    function add(bigint memory _a, bigint memory _b) internal pure returns (bigint memory r) {
        r.limbs = new uint[](max(_a.limbs.length, _b.limbs.length));
        uint carry = 0;
        for (uint i = 0; i < r.limbs.length; ++i) {
            uint a = limb(_a, i);
            uint b = limb(_b, i);
            r.limbs[i] = a + b + carry;
            if (a + b < a || (a + b == type(uint).max && carry > 0))
                carry = 1;
            else
                carry = 0;
        }
        if (carry > 0) {
            // too bad, we have to add a limb
            uint[] memory newLimbs = new uint[](r.limbs.length + 1);
            uint i;
            for (i = 0; i < r.limbs.length; ++i)
                newLimbs[i] = r.limbs[i];
            newLimbs[i] = carry;
            r.limbs = newLimbs;
        }
    }

    function limb(bigint memory _a, uint _limb) internal pure returns (uint) {
        return _limb < _a.limbs.length ? _a.limbs[_limb] : 0;
    }

    function max(uint a, uint b) private pure returns (uint) {
        return a > b ? a : b;
    }
}

contract C {
    using BigInt for bigint;

    function f() public pure {
        bigint memory x = BigInt.fromUint(7);
        bigint memory y = BigInt.fromUint(type(uint).max);
        bigint memory z = x.add(y);
        assert(z.limb(1) > 0);
    }
}


texts: bytes32 same length hex strings cost different gas why?

texts:
I can not understand the difference in gas for the following problem. I generated a sha256 hash value and the output i chose to be lowercase hexadecimal. So the output value is hexadecimal string of 64 characters.Then i saved this value to a bytes32 variable inside a smart contract. The smart contract's code is:

pragma solidity ^0.4.23;

contract Project {
    bytes32 public value;

    function addValue(bytes32 val) public {
        value = val;
    }
}

Using remix, I noticed that the operation to add a value cost 43629 for some values and other 43693. So the difference is 64 gas. Can anyone help me understand why this is happening? I tested many values and the difference was 64 gas, was it random? I also tested to store it as string. Then the cost was constant for all inputs, maybe because the values have the same length as i said the inputs values have 64 characters.


texts: Transmit array as first parameter in web3.js

texts:
When I develop in solidity combined with web3.js, I face some problem recently. I create a contract code below

//setContractDetail(index,bool isConsentItem,uint8[] detailItems)
function setContractDetail(uint8 index,bool isConsentItem,uint8[] detailItems) public checkOwner{
    consentForm.items[index].isConsent= isConsentItem;
    consentForm.items[index].itemDetail = detailItems;
    /* emit SetContractDetailEvent(msg.sender,index,isConsentItem,detailItems,now); */
}
function setContractDetail2(uint8 index,bool isConsentItem) public checkOwner{
    consentForm.items[index].isConsent = isConsentItem;
}
function setContractDetail3(uint8[] index,bool isConsentItem,uint8[] detailItems) public checkOwner{
    for(uint i=0;i<index.length;i++){
        uint pointer = index[i];
        consentForm.items[pointer].isConsent= isConsentItem;
        consentForm.items[pointer].itemDetail = detailItems;
    }
    /* emit SetContractDetailEvent(msg.sender,index,isConsentItem,detailItems,now); */
}
function setContractDetail4(bool isTest,uint8[] index,bool isConsentItem,uint8[] detailItems) public checkOwner{
    for(uint i=0;i<index.length;i++){
        uint pointer = index[i];
        consentForm.items[pointer].isConsent= isConsentItem;
        consentForm.items[pointer].itemDetail = detailItems;
    }
    /* emit SetContractDetailEvent(msg.sender,index,isConsentItem,detailItems,now); */
}

When I pass the first parameter as an array (setContractDetail3), I always get an error-message - ERROR Error: Error: gas required exceeds allowance or always failing transaction. However, when I set non-array value as first parameter, the function call will be well performed. Does anyone know what is the reason for this issue?

  p.s I could successfully compile on the remix, but after I set the contract in geth console as well as connecting with web3.js, it ultimately get fail.


texts:
I am developing an KYC dapp where I am keeping customer information like name, dob, age etc. Each customer is having an account address ( i.e Ethereum account). Basically this is a private blockchain. I can able to search into blockchin by customer's ethreum account. I can able to get the customer's details by querying with "ethereum account address". My question here is , Can we search/get details by customer's name ? Or do we need to search by only his ethereum account ?

Thank you


texts: VM error: invalid opcode resulting from array operations

texts:
pragma solidity ^0.4.18;

contract VectorTest {

   /* this runs when the contract is executed */
   function VectorTest() public {
      // initialize the variables
   }

   // returns an int array by adding to all its elements a scalar value "a"
   function addScalar(int[] self, int a) public pure returns (int[] s) {
      for (uint i = 0; i < self.length; i++)
         s[i] = self[i] + a;
  }

   // returns an int array by adding to all its elements a scalar value "a"
   function addVector(int[] self, int[] melf) public pure returns (int[] s) {
      for (uint i = 0; i < self.length; i++)
         s[i] = self[i] + melf[i];
   }

}

I have a very basic VectorTest contract as above. It compiles well in Remix but when I create and try to call its functions with some example values, Remix is giving the error below. E.g., I tried to execute addScalar([12,12,13], 5) in this error message:

call to browser/BlockChaiNergy01.sol:BlockChaiNergy01.addScalar
errored: VM error: invalid opcode.
invalid opcode  The constructor should be payable if you send value.
The execution might have thrown.
Debug the transaction to get more information.

Any ideas?

Thanks in advance,

Onder.


texts: What's the correct way to reference elements in an array?

texts:
I'm going through the Ethereum Pet Shop Truffle tutorial and found this in the test section:

address adopter = adoption.adopters(8);

A previous section had used adopters[petId] = msg.sender;

Why does one use [] and the other ()?


texts: How to tell a contract when to do an action based on time and blocks?

texts:
I have a simple contract that receives any amount of ETH. The contract keeps those ETH certain amount of time until it realeases the funds to it's original owner.

I have defined which block represents the moment of release.

The only thing that I don't know how to do is, how to tell the contract: "now we are in the specified block, release those ETH".

I mean, the contract is not reading the blockchain continuously, which is the way to tell that info to the contract automatically?


texts: How Exactly is Smart Contract Validation Performed?

texts:
I have yet to find a coherent explanation of how a smart contract - that potentially can have complex interactions with other smart contracts - is actually validated. Please no hand waving here. What I have read so far implies that each node - miners and non-miners - must execute the software - the contract. How can this possibly work? Is ever public function in the contract(s) called? Are all inter-contract message passings called?

I just don't see how this could possibly work.


texts: Remix IDE getting VM error invalid opcode

texts:
I am attempting to deploy a test contract on javascriptVM using Remix IDE in chrome. However when I try to execute the contract I receive this message in the status section.

  "transact to Notes.addNote errored: VM error: invalid opcode. invalid
  opcode        The execution might have thrown.    Debug the transaction to
  get more information. "

pl let me know if anything wrong in mycode..


texts:
How should I enable the api’s ‘personal’ and ‘admin’ over RPC on Azure ‘Ethereum Consortium Blockchain’. Is there any way by which we get direct access to the VM console (Now we SSH on to the VM to connect)

Platform – Ethereum Consortium Blockchain on Azure
We have setup ‘Ethereum Consortium Blockchain’ with 3 transaction nodes and 4 mining nodes (2 subnets – 2 nodes each) on Azure. By default ‘eth’,’net’ and ‘web3’ api’s are available over the RPC. We need the api’s ‘personal’ and ‘admin’ as well be available. I have tried to stop RPC and then start RPC with the parameters for required api’s included. But that doesn’t work.

In our on-premises Ethererum environment, we do have direct access to the VM and ‘geth’ console. So we can initialize ‘geth’ so as to open all the required api’s over RPC (which I am not able to do on Azure)

Thank you,
Anjana


texts: transaction get revert by calling view method from another contract constructor

texts:
I havae two contract Record and Register.

Register.sol looks like:

pragma solidity ^0.4.24;

contract Register {
    string private name;

    constructor(string entityname) public {
        name = entityname;
    }

    function getName() public view returns (string username) {
        return name;
    }
}

And in Record.sol:

pragma solidity ^0.4.24;

import "./Register.sol";

contract Record {
    constructor(address ownerAddr, address providerAddr) public {
        Register(ownerAddr).getName();
        Register(providerAddr).getName();
    }
}

FYI, Record just want to call getName() method of Register contract in its constructor. In the test file I want to create new Record using the following code but got this error VM Exception while processing transaction: revert.

beforeEach('create new Register and Record contract', async () => {
    providerA = await Register.new("Dr Strange", {from: accounts[0]});
    providerB = await Register.new("Maybe", {from: accounts[1]});
    record = await Record.new(providerA.address, providerB.addresss);
})

What should I do?

Truffle v4.1.14 (core: 4.1.14)
Solidity v0.4.24 (solc-js)
Ganache v1.2.2

============================ UPDATE ==============================

I think its the problem of the contract iteself, not the test script. Because using Remix, Register contract can be deployed, but Record cannot even be deployed.


texts: Why don't these transactions add up to the account's total balance?

texts:
I'm looking at the balance of this wallet address: https://etherscan.io/address/0x9a77d0900323b5f2b6cff6138569846406cf7456

There is an IN transaction from Poloniex to this wallet of ~33 ETH, then an OUT transaction to The DAO of ~33 ETH, then an IN transaction of 1 ETH. Wouldn't the balance therefore be ~1 ETH? Why does the balance on this account show as ~34 ETH?

If the DAO was refunded to this wallet and that is why the balance is higher, where is this shown?


texts: How to solve Error: Invalid JSON RPC response on DigitalOcean

texts:
I have deployed my dapp front end and backend on Digital Ocean.
On running the server.js I am getting below error

(node:30490) UnhandledPromiseRejectionWarning: Error: Invalid JSON RPC response: ""

Below settings in my server.js code use to work fine on my local Ganache,

const provider = new Web3.providers.HttpProvider("http://localhost:8545");

I suspect I need to make changes in web3 provider to make it compatible to run on DigitalOcean but cannot figure out them, please help...


texts: get Transfer events from 0x0 address for ERC20 token

texts:
I am trying to get all the events that originate from zero (0x0) address in order to capture the mint activity for my ERC20 token.

Here is my code snippet:

var instance = web3.eth.contract(abi).at(tokenContractAddress);
var blockNo = web3.eth.blockNumber;
console.log('latest block', blockNo); //able to get blockNo successfully

var result = instance.Transfer({from: '0x0000000000000000000000000000000000000000'},
            {fromBlock:4361077, toBlock:'latest'},
           (err, res) => {
             console.log(res);
        });

However i never get anything in the res object and its always undefined.


texts: Unable to debug Mainnet transaction in Remix

texts:
I am trying to debug mainnet tx with Remix debugger and I get following error in the console after I provide the tx hash in the debugger box.

Is it even possible to achieve what I'm trying to do here i.e. debug mainnet transaction with Solidity code.


texts: how to check if my testnet geth node has mined some ether?

texts:
As per the instructions detailed in this post, I've created an account:

and started running my geth node:

how can I check if it's mined any ether yet?

the answer of @lungj resulted in this:


texts:
Is there any decentralized exchange with zero trading fees for ERC-20 tokens at the moment?

All fees except gas fees should be zero. I already tried Bancor and Kyber but, as far as I can tell, they both charge fees as far so I would like to find a zero fees exchange.

Vesa


texts: I'm looking for information on setting up Ethereum trading account and possibly mining?  I got here from link on Bitcoin Meetup email. Is there another site I should use?  I'm also interested in Eth meetup.


texts:
I deploy a contract on Rinkeby using geth. I am trying to interact with it using node.

When the contract is deployed, I call a simple function that changes a value in my contract:

uint public value1;

    function changeValue(uint newValue) public {
        value1 = newValue;
    }

the problem is that I get a "Invalid address" error.

The account is unlocked
The default address of web is set to the address I want to call this function from
Even using "from" in the call method, I get the error.

http://prntscr.com/gwssrd

Can someone explain me why?

PS: By the way, I am doing the exact same manipulations as someone else (just with a different contract), and it works for my pair.


texts: Web3.js + ganache local development: Response to preflight request doesn't pass access control check, CORS error

texts:
I am fairly new to DAPP and I am trying to follow an online guide building my first smart contract. Here's the source code:

Election.sol

pragma solidity ^0.4.2;

contract Election {

    string public candidateName;

    constructor (string _candidateName) public {
        candidateName = _candidateName;
    }

    function setCandidate (string _name) public {
        candidateName = _name;
    }

}

I've deployed to to my local Ganache (latest version on windows 10) and tried to interact with it using the Web3.js from here.

Here's my JavaScript code for my client side:

// Initialise web3
if (typeof web3 !== "undefined") {
  web3 = new Web3(web3.currentProvider);
} else {
  web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
}

// Set account
web3.eth.defaultAccount = web3.eth.accounts[0];

// Set contract abi
var contractAbi = [ ... my aib here ... ];

// Set contract address
var contractAddress = "my-contract-address-here";

// Load the contract
var contract = web3.eth.contract(contractAbi).at(contractAddress);

// Display current candidate name
contract.candidateName(function(err, candidateName) {
  if (err) {
    alert("Error: " + err);
  } else {
    $("#canidateName").val(candidateName);
  }
});

// Handle candidate name update
$("#updateCandidate").on("click", function(event) {
  event.preventDefault();
  contract.setCandidate($("#canidateName").val());
});

When I run my app in the browser, I am getting the following error:

  web3.min.js:1 Failed to load http://localhost:7545/: Response to
  preflight request doesn't pass access control check: The value of the
  'Access-Control-Allow-Origin' header in the response must not be the
  wildcard '*' when the request's credentials mode is 'include'. Origin
  'null' is therefore not allowed access. The credentials mode of
  requests initiated by the XMLHttpRequest is controlled by the
  withCredentials attribute.

  Uncaught Error: CONNECTION ERROR: Couldn't connect to node
  http://localhost:7545.
      at Object.InvalidConnection (web3.min.js:1)
      at t.send (web3.min.js:1)
      at n.send (web3.min.js:1)
      at l.accounts (web3.min.js:1)
      at script.js:9 InvalidConnection @ web3.min.js:1 t.send @ web3.min.js:1 n.send @ web3.min.js:1 (anonymous) @ web3.min.js:1
  (anonymous) @ script.js:9

Any idea what I might be doing wrong here?


texts:
An individual has stated in The DAO Forum thread Has the voting began that they have been able to vote more than once on a proposal.

Can I vote more than once on each The DAO proposal?


texts: Snapshot of balances of all token holders at a particular block

texts: Is there any way to get a snapshot of balances of all the token holders or the holders list at particular block. Looking for some API or tool other than web3 way to iterate over all the Transfer events emitted by the token contract.


texts: All I see is Windows and Linux support only, why is there no guide for mining ether on a Mac? Is there a way to mine on a Mac?


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

texts: If I am writing a smart contract for some kind of (gambling) game, how can I generate a random number securely? What are the best practises and security trade-offs to be aware of?


texts:
I have the following code in a script name contract.js ( foo, pwd and id are replaced by their value in my actual script)

var web3=require('web3');
personal.unlockAccount('id', "pwd")
var aContract = web3.eth.contract([]);
var a = aContract.new(
{
    from: web3.eth.accounts[1],
    data: 'foo',
    gas: 3000000
}, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
        console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
})

I wanted to execute this code in the geth console so I typed

loadScript("/usr/username/contract.js")

But all I have is the following error:

  err: TypeError: Cannot access member 'contract' of undefined
      false

I know that I didn't define an ABI but when I type the code above directly in the geth console it just works and then I can mine this contract (in local).

So is it really possible to obtain the same result with loadscript ?


texts: Why does inserting a Struct cost 5,000 extra gas per item in the Struct?

texts:
Related to the findings in: Solidity bool size in Structs

Why does inserting a Struct cause an increase of 5,000 gas per item in the Struct?

For example:

// A Struct that, when tightly packed, is 256bits.
// In theory, should cost 1 SSTORE (20,000) to insert
//   or 5,000 to modify.
struct Struct4by64 {
    uint64 one;
    uint64 two;
    uint64 three;
    uint64 four;
}
mapping (uint=>Struct4by64) mapS4by64;
uint index = 1;

// exp gas cost: 47k:
//   - 1k (misc)
//   - 21k (tx)
//   - 5k (to increment index)
//   - 20k (to write 32bytes)
// actual gas cost: 63k
//   - 47k (above)
//   - 5k (modify 32bytes by setting two)
//   - 5k (modify 32bytes by setting three)
//   - 5k (modify 32bytes by setting four)
function insert4by64() public {
    mapS4by64[index++] = Struct4by64({
        one: 1,
        two: 1,
        three: 1,
        four: 1
    });
}

Shouldn't the compiler pack the items in the Struct to a single 256bit write? Why does it waste 15k more gas by updating the Struct value for each items two, three, and four?

Likewise, I've found that reading structs from storage takes 200 gas per item in the struct. What, exactly, is the point of tightly packing the items? Just to save ONE write on creating the Struct?

This makes no sense to me. I'd be better off by storing a single 256bit uint and managing it myself via & and | bitmasks... but that's what the compiler is for, isn't it?


texts: admin.addPeer returns true while admin.peers is blank[]

texts:
I have initialized genesis file in my system, this is my genesis.json file-

    {
"alloc": {
     "790a2dc4ea3aa44eb27cbb430cf4e1cff989706790":  {"balance": "9999999999999999999999999999999999"}
  },
"coinbase": "0x0000000000000000000000000000000000000000",
"difficulty": "0x20000",
"extraData": "",
"gasLimit": "21000",
"nonce": "0x0000000000000042",
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "0x00",
"config": {
"chainId":89822 ,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
 }
}

Than I have launched the network using the following command :

    geth --rpc --rpcaddr 0.0.0.0 --rpcport 8549 --rpccorsdomain "*" --rpcvhosts "*" --rpcapi "web3,network,admin,personal" --datadir /home/ethereum --networkid 89822 console

Same file I have initialized in my AWS linux client. Then i have launched the network using the same command as above except I have changed the port to 30304 which was 30303 by default in the 1st client:

    geth --rpc --rpcaddr 0.0.0.0 --rpcport 8549 --rpccorsdomain "*" --rpcvhosts "*" --rpcapi "web3,network,admin,personal" --datadir /home/private --networkid 89822 --port 30304 console

now I am adding AWS client as peer to the 1st client using the following command:

    admin.addPeer("enode://4b1a3942568e227d169ffd68b6733ef6f40e4cb77df7de819e63e6cc521c5dbd48c458799696edd0fa711f74f3752f43e81a4babad122fa6d58bddb4eaf7ef85@192.168.0.175:30304");

Whose IP address should I give after @? Here I am using the IP of the 1st client. It is giving true, but when I type admin.peers it shows null:

    > admin.peers
    []


texts: Is it possible to send ERC-20 tokens with the gas from another account?

texts:
I'm creating a DApp platform which allows customers to send and receive USDT (ERC-20 Token). The problem I have is that if customer want to send some Tethers out, he should have enough ETH too as the gas, while he might did not receive any ETH on his account.
I have 3 different ideas about this.

Charge the customer's ETH by myself, and send USDT directly from his account.
Move customer's USDT to my account (in someway without transaction fee), and send the desired USDT to final recipient using the ETH provided in my own account.
Send USDT from customer's account, but using my own account to provide the fee for transaction instead of using customer's one.

For some reasons, I need to implement the way 2 or 3, but I don't know how? Are they practical at all? If so, how can I do them?


texts:
I'm reading the white paper, more specific about scaling.

I'm stuck on the second strategy.

  Second and more importantly, however, we will include an
  intermediate state tree root in the blockchain after processing each
  transaction. Even if block validation is centralized, as long as one
  honest verifying node exists, the centralization problem can be
  circumvented via a verification protocol. If a miner publishes an
  invalid block, that block must either be badly formatted, or the state
  S[n] is incorrect. Since S[0] is known to be correct, there must be
  some first state S[i] that is incorrect where S[i-1] is correct. The
  verifying node would provide the index i, along with a "proof of
  invalidity" consisting of the subset of Patricia tree nodes needing to
  process APPLY(S[i-1],TX[i]) -> S[i]. Nodes would be able to use those
  nodes to run that part of the computation, and see that the S[i]
  generated does not match the S[i] provided.

Is this the same as sharding?


texts: See the contract code in Meta Mask or/and Ganache

texts:
I have set up Ganache and Meta Mask on my browser and I have deployed a sample contract in it.
Just follow the steps mentioned in
https://truffleframework.com/tutorials/pet-shop.

As far as I found out I (as Ethereum user) I should be able to see the contract before confirm any transaction.

Now back to tutorial environment ( Ganche and Meta Mask):

Is it possible to use Meta Mask to see the actual contract?
Is it possible to use Ganache to see the actual contract?


texts: How can I setup up Ethereum Wallet to launch geth with flags for ethminer?

texts:
I see that Ethereum Wallet uses its own geth.exe binary which it looks for in %AppData%\Roaming\Ethereum Wallet\binaries\Geth\unpacked, on Windows.

It seems this is only one of the processes that are launched when starting the wallet. Is there anyway to tell the wallet to add some flags such as --rpc --rpccorsdomain localhost?

Or am I supposed to start geth before starting the wallet or starting ethminer?


texts:
I have a very similar problem as https://github.com/paritytech/parity-ethereum/issues/8788

When I use web3.eth.getBlock for the first 1 million and latest 50,000 blocks (approximately), I get the desired output, while for blocks number 1,000,000 to latest-50,000 it returns null.

I'm using Parity v1.10.8-stable on Windows 10. My node is connected to Ethereum mainnet and fully synchronized. web3 version 0.20.6.

Is this a bug and I can't do anything or can it be fixed?

My script:

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

const run  = async () => {
    const latestBlock = 6039000
    console.log('+100', !!(await web3.eth.getBlock(100)))
    console.log('+1000', !!(await web3.eth.getBlock(1000)))
    console.log('+10000', !!(await web3.eth.getBlock(10000)))
    console.log('+100000', !!(await web3.eth.getBlock(100000)))
    console.log('+1000000', !!(await web3.eth.getBlock(100000)))
    console.log('+2500000', !!(await web3.eth.getBlock(2500000)))
    console.log('-2500000', !!(await web3.eth.getBlock(latestBlock-2500000)))
    console.log('-1000000', !!(await web3.eth.getBlock(latestBlock-100000)))
    console.log('-100000', !!(await web3.eth.getBlock(latestBlock-100000)))
    console.log('-10000', !!(await web3.eth.getBlock(latestBlock-10000)))
    console.log('-1000', !!(await web3.eth.getBlock(latestBlock-1000)))
    console.log('-100', !!(await web3.eth.getBlock(latestBlock-100)))
}

run()

Output:

+100 true
+1000 true
+10000 true
+100000 true
+1000000 true
+2500000 false
-2500000 false
-1000000 false
-100000 false
-10000 true
-1000 true
-100 true


texts: Is there a decompiler that will convert Solidity byte code back into source code? I am wondering how to verify code of contracts that are published to the blockchain.


texts:
Can someone explain why a year ago mining with a difficulty of 2Ph, a rig with a 240Mh/s hash rate gave 1eth per month, but now (complexity 5Ph) gives 0.8, that is, the dependence is clearly not linear.
Also, some calculators show that such a rig should give about 0.45 eth (https://www.mycryptobuddy.com/EthereumMiningCalculator, https://www.coinwarz.com/mining/ethereum/calculator)
And other calculators show about 0.8 eth, which one to trust? (https://whattomine.com/coins, https://www.cryptocompare.com/mining/calculator/eth)


texts:
I'm trying to upload a simple image file to IPFS using ipfs.files.add(). However, I can't seem to figure out why the promise throws an error.

Here's the code:

$(function() {
  $(window).load(function() {

    const IPFS = require("ipfs-api");
    const ipfs = IPFS("localhost", "5001", {protocol: "http"});

    var fileBuffer;
    var imageUpload = document.getElementById("input");
    imageUpload.addEventListener("change", handleFiles, false);

    function handleFiles() {
      console.log("File Chosen!");
      const reader = new FileReader;
      reader.readAsArrayBuffer(imageUpload.files[0]);
      console.log("Buffering...")
      reader.onload = function() {
        var arrayBuffer = reader.result;
        fileBuffer = new Uint8Array(arrayBuffer);
        console.log("Buffer: ", fileBuffer);
        ipfsUpload();
      }
    }

    function ipfsUpload() {
      console.log("Uploading...");
      ipfs.files.add(fileBuffer, (error, result) => {
        if (error || !result) {
          console.log("Error!");
        }
        else {
          console.log("Success!");
        }

      });
    }

  });
});

At first I thought I wasn't properly connected to my IPFS node. However, I did the whole process in the terminal window with node.js and it worked. So I'm thinking this might have something to do with the browser (Chrome) or some dependency?

"dependencies": {
    "bootstrap": "^4.1.3",
    "browserify": "^16.2.2",
    "buffer": "^5.2.0",
    "ipfs": "^0.31.6",
    "ipfs-api": "^24.0.0",
    "jquery": "^3.3.1",
    "popper": "^1.0.1",
    "truffle": "^4.1.14",
    "web3": "^0.20.7"
  }

Note: I'm using Browserify to bundle all my dependencies.

EDIT: After printing the actual error, I get the following:

TypeError: content.once is not a function
    at Multipart._pushFile (bundle.js:29092)
    at Multipart._maybeDrain (bundle.js:29056)
    at Multipart._transform (bundle.js:29048)
    at Multipart.Transform._read (bundle.js:107644)
    at Multipart.Transform._write (bundle.js:107632)
    at doWrite (bundle.js:108104)
    at writeOrBuffer (bundle.js:108093)
    at Multipart.Writable.write (bundle.js:108010)
    at eachSeries (bundle.js:29443)
    at bundle.js:23065