texts: Same contract created twice (0xfec94608dea1f3609e4a93e56e01477d8a86de46)

texts:
While browsing traces generated by parity I encountered an interesting case:

Contract 0xfec94608dea1f3609e4a93e56e01477d8a86de46 has been created twice.

First time, in the transaction: 0xc0d8d11c5da64e025ac0bb0cc286ede65c2a0b7afeeb455f04d6479cc98edb7a. The transaction failed with Out of gas but the contract was successfuly created.

Second time, the same contract with the same code has been created in transaction: 0x9c3ef34611bd24e254b2b6f339e2f196a57042e8261c069af944248d982c67b4.

From what I understand the contract got the same address because it was created within another contract. The contract address is generated from the creator contract address and its nonce. Since the previous creator contract transaction ended up with Out of gas the nonce was not increased and thus the same contract address.

What really happened? Was the contract really created in the first transaction? Shouldn't it be reverted? Does Etherscan show it correctly? What would happen if in the second transaction the contract is generated with a different code?

EDIT: I reported the issue to the Parity GitHub issues


texts: Upload a full directory to IPFS using ipfs (js-ipfs-http-client)

texts:
I want to upload a directory to ipfs on my browser using (js-ipfs-http-client) module.
I found this old issue. https://github.com/ipfs/js-ipfs/issues/277 So I decided to use recursive way to add files and get only one hash for it.

ipfs.addFromFs('path', { recursive: true, ignore: ['subfolder/to/ignore/**'] }, (err, result) => {
            if (err) { throw err }
            console.log(result)
        })

But it gave me this error.

I need to upload a directory to ipfs using javascript but all resources I had found upload only one file.Or a lot of files with array of hashes. I need a way to upload all files of directory and get the with only one hash. Thanks in advance.


texts: Are Solidity numbers little endian, or big endian padded left?

texts:
Solidity says it stores numbers as little endian... but I don't understand how thats possible given that they are left padded.

const a = new Bn(256)
const b = new Bn(256 * 256)

a.toArray('le')
>> [0, 1]
b.toArray('le')
>> [0, 0, 1]

That makes sense. The little byte is first.

However, integers are left padded in Solidity.

If you left pad both to 32 bytes, they'll both be

[0, 0, ..., 1]

What am I missing or misunderstanding? Maybe it would be more accurate to say solidity numbers are big endian and padded left?


texts: What caused the Ethereum flash crash on GDAX?

texts:
At around 16:00 EST, there was a brief but massive flash-crash visible on GDAX:

http://www.cnbc.com/2017/06/22/ethereum-price-crash-10-cents-gdax-exchange-after-multimillion-dollar-trade.html

People who had buy orders for Ether at low prices made spectacular gains in the ensuing rebound, while those who had sell orders for low prices had terrible losses.

Why/how did this occur?


texts: Metamask doesn't show token value on erc20 contract interaction

texts:
Why using the Transfer method is showing the value of the erc20 that I want to transfer while with a custom method is always showing 0 ETH on metamask instead of the token that I'm transferring via the contract? Is there a way to show the value of the erc20 that the users are transferring using my custom function and isn't it dangerous to let user transfers all their erc20 tokens while they only see 0 ETH on metamask...

Please note that with transfer method I mean transaction data is contract.methods.transfer(...
and with custom method I mean data is contract.methods.mycustomcontractfunction(...


texts:
I sent Ether to a contract but the transaction failed due to "out of gas".

How do I complete the transaction I am trying to make? I sent the ether from my NanoS wallet to the XYO contract.


texts: What is the value add of _msgSender helper in openzeppelin

texts:
I have a question about openzeppelin _msgSender helper:
function _msgSender() internal view virtual returns (address payable) {
    return msg.sender;
}

(https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol)
They say this function is able to give us the real sender, when we use a GSN. But this function contains msg.sender so i do not understand how it works, to detect a GSN usage.
I do not see the value add of this function because the only thing it does is returning msg.sender.
I think i miss something...
Thanks a lot


texts: Division and floor rounding with 18 decimals

texts:
I am recreating a UNISWAP-like AMM and have encountered problems anytime I want to divide the balances of tokens in my pool. For example: I want to require() that tokens are deposited in the correct ratio (Total number of token 1/Total number of token 2). If I do this I can encounter 2 problems:

either the result is 0<x<1 and I get 0 which stops all further calculations
or the result is rounded down to an integer which is a significant calculation error

I hoped using larger numbers (18 decimals) would solve this problem but it hasn't, I also don't want to use external libraries, other than safeMath. What can I do to solve these problems? Thanks!


texts: testRegistrar is failing with error (ReferenceError: 'testRegistrar' is not defined at :1:1)

texts:
I am trying to host my own website of Swarm. But I am getting the following error (the last line in bold) when trying to register:

  >eth.accounts

  ["0x090c84e3ae32dcd38be0525223e87ac3393a763e"]

  >web3.fromWei(eth.getBalance(eth.coinbase), "ether")

  1

  >loadScript('/home/hadoopcd/ensutils.js')

  true

  >personal.unlockAccount(eth.accounts[0])

  Unlock account 0x090c84e3ae32dcd38be0525223e87ac3393a763e

  >testRegistrar.register(web3.sha3('argo'), eth.accounts[0],{from: eth.accounts[0]})

  ReferenceError: 'testRegistrar' is not defined
      at :1:1

I downloaded the ensutils.js from 'https://raw.githubusercontent.com/ethereum/ens/master/ensutils.js'.

Any help is appreciated


texts: Solidity get return variable from a send method in React

texts:
I'm trying to call a method that pushes data to my Blockchain and then returns back the ID of the new struct I created. This is how I'm calling the method in my React code:

const documentId = await storehash.methods.sendDocument(this.state.IPFSlink, newDate).send({from: this.state.account}).call()

And here is my smart contract method:

function sendDocument(
    string memory _ipfsLocation,
    uint256 _uploadDate
)
public
returns (uint256)
{
    documentCount ++;
    ListOfDocuments[documentCount] = documentStore(documentCount, _ipfsLocation, msg.sender, _uploadDate);
    return documentCount ;
}

So it should created the new struct and return back the ID. However, it causes the following error:

  Unhandled Rejection (Error): invalid tuple value (coderType="tuple", value="QmStXLfxUJuc4xTtSGQxmF1PXrjVmsosqL6Wyi5EuQiYNH", version=4.0.26)

Can anyone help me understand what I'm doing wrong?

p.s sorry if I've formatted this badly, it's my first time using a stackexchange.


texts: TypeError: Type uint256 is not implicitly convertible to expected type bool

texts:
function allowance (address _owner, address _spender) constant returns (uint remaining )
      if **(__allowances[_owner][msg.sender])**{
          **^-------------------------------^**
            return __allowances[_owner][msg.sender];
      }
            return 0;
   }


texts: I need to find a company or trusted cryptocurrency professional to review my smartcontract

texts: I have been searching to find someone to review a smartcontract for my companies up and coming ICO.  I have only found companies that hope to do this in the future but no real business that reviews the code.  After some research it seems an individual that is very known in the crypto space is the way to go.  Any help on this would be great!


texts: What does the extraData field of a block represent?

texts:
I am trying to save some data into a block.
The extraData field has a constant value since block 1.
Also where does the data parameter of sendTransaction() function get stored?


texts: Vyper Smart Contract deployment using web3.py, Clique PoA

texts:
I am new to Blockchain Dapp development so bear with me if I sound a bit out of court.
Coming from a Python background, I am trying to use web3.py to create, deploy and interact with vyper ^0.2.0 smart contracts.
I used Puppet to start a new network consisting of 2 PoA nodes on the same LAN. Although I am currently testing on 1 node to confirm contract deployment before I initialize the 2nd node.
However using web3.py, I can't seem to deploy a contract to obtain the contract address required to transact. It timed out after 120 seconds. (I waited longer to see if the pending transactions will be registered but to no avail)
I also tried to deploy the same contract using Remix, but I keep getting " creation of  pending...". I am using POA, I checked gas and nonce and they are good. Please can someone assist with a working sample code that would guide me through?


texts: Why do contracts have an account? I mean, their code is entered to the blockchain and their balance can be computed by previous transactions, so why is there an account of it?


texts: Geth remote central server with local keystores

texts:
We are running multiple wallets and each wallet is connected to local geth. Because of high usage we created one central geth and we connected our wallets to this remote geth.
Our issue here is that the keystores are stored on remote geth and we want them to be saved on the machine from where we're sending this requests to our central geth.
How we can manage to connect our wallets to one central geth but to save keystores locally on server from where we are sending this requests to central geth?
Is there any documentation available? Tried different setup using ssh tunnels but it seems keystores are still generated on remote central geth server.
Thank you.


texts: Is it possible to pay gas for other account?

texts:
Is it possible to transfer tokens from account 1 to account 2 but pay the gas price from account 3?
I don't want to spend gas deploying codes to do that, Is it possible to do that w/o any code?


texts: Is it possible to spend from multiple addresses and broadcast just one tx?

texts: In bitcoin I can combine UTXO from multiple addresses into a single transaction. In Ethereum it seems that if I want to spend from multiple addresses I need to do N transactions. This makes HD wallets a bit expensive and impractical. Is there any tricks I am missing here?


texts:
https://thegraph.com/ seems to rely on the assumption that events will last forever.

But this post: https://www.reddit.com/r/ethereum/comments/a2ocy6/full_notes_from_fridays_eth_1x_sync_call/
seems to imply that logs dont last forever due to pruning.

Is the Graph doomed to fail?


texts: Trying to set a new value to storage contract through another contract

texts:
I'm having a problem of setting a value to storage contract through another contract. Below is the code:

StorageContract.sol

pragma solidity ^0.5.8;

contract StorageContract {
    constructor () public {
       userStruct[msg.sender].userId = msg.sender;
       userStruct[msg.sender].userName = 'Jack';
       userStruct[msg.sender].isUser = true;
    }

    mapping(address => User) public userStruct;

    struct User {
        address userId;
        string userName;
        uint userRegistrationDate;
        bool isUser;
    }

    function setNewUser(address _userId, string memory _userName) public returns(address){
        require(userStruct[msg.sender].isUser == true, "Error (setNewUser)");
        User storage u = userStruct[_userId];
        u.userName = _userName;
        u.userRegistrationDate = now;
        u.isUser = true;
        return _userId;
    }
}

UserContract.sol

pragma solidity ^0.5.8;

import "./StorageContract.sol";

contract UserContract {
    StorageContract storages;
    constructor (address _storageAddress) public {
        storages = StorageContract(_storageAddress);
    }

    function userSetNewUser(address _userId, string memory _userName) public returns(address){
        require(msg.sender != address(0));
        address userId = storages.setNewUser(_userId, _userName);
        return userId;
    }
}

The problem I face here is that I cannot set a new user through UserContract, since it does not satisfy the require statement at setNewUser and I cannot understand why. Would highly appreciate your help.


texts: eth-lightwallet: what is the difference between a functionTx and a valueTx?

texts:
In eth-lightwallet, there are two types of Tx creation functions;
txutils.valueTx(txObject)

and
txutils.functionTx(abi, functionName, args, txObject)

My guess is; although their inputs are very different, they both result in a Tx object that looks like this:
tx = {
  nonce: '..',
  gasPrice: '..',
  gasLimit: '..',
  to: '..',
  value: '..',
  data: '...'
}

and the only difference is that data is empty in valueTx, and it's the hex-encoded version of the function call in functionTx. Is this correct? Is data the only difference between two?
Also, how can I compute data myself, given that I know the contract address, abi and the function name/parameters? Is there another library for this?
Thanks,


texts: Verification of externally-created ECDSA signatures in Solidity

texts:
I have ECDSA signatures created using Golang without using web3 or anything related to Ethereum, and I want to verify these in Solidity.

Step 1: Signing the message in Golang

My Go code to create signatures:

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "fmt"

    "github.com/ethereum/go-ethereum/common/math"
    "github.com/ethereum/go-ethereum/crypto/secp256k1"
    "crypto/rand"
    "github.com/miguelmota/go-solidity-sha3"
    "encoding/hex"
    "strconv"
)

func KeyGen() (pubkey []byte, privkey []byte) {
    key, err := ecdsa.GenerateKey(S256(), rand.Reader)
    if err != nil {
        panic(err)
    }

    pubkey = elliptic.Marshal(S256(), key.X, key.Y)
    return pubkey, math.PaddedBigBytes(key.D, 32)
}

func Sign(message string, sk []byte) ([]byte) {
    hash := solsha3.SoliditySHA3(solsha3.String("\x19Ethereum Signed Message:\n"+strconv.FormatInt(int64(len(message)),10)+message))
    signature, _ := secp256k1.Sign(hash, sk)
    return signature
}

Basically, in the Sign method, I take the hash of

  "\x19Ethereum Signed Message:\n" + message.length + message

and sign the hash.

My main method is:

//Create keypair and signature
pk, sk := KeyGen()
message := "TEST"
sig := Sign(message, sk)

//Print public key and sig in hex notation
fmt.Println("PK", hex.EncodeToString(pk))
fmt.Println("Sig", hex.EncodeToString(sig))

//Print hash
hash := solsha3.SoliditySHA3(solsha3.String("\x19Ethereum Signed Message:\n"+strconv.FormatInt(int64(len(message)),10)+message))
fmt.Println("hash", hex.EncodeToString(hash[:]))

Step 2: Verification in Solidity

In Solidity, I use a library by openzeppelin found at https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol to recover the public key. I put the three values printed in Go (hash, publickey, signature) as attributes of the contract and attempt to verify the signature:

contract ECDSA {

    bytes32 hash = hex"fb96181ff706848b10a93f4028537caf17026e28ce5c0cce90af46b4d3ad04c6";
    bytes sig = hex"cd044278098c2e5e36cc716423638509bbc818b0daadd7b7bba6322a99de67373255201bac6634b6adeb29d4c3bd9b3a6a14363c4e5b5eb3087c7882c7ebca6800";
    bytes publickey = hex"0485d169380f762e82da692c4b50c8873b1ef9820f15ae6cd96d0d4741056a1b9c828f4f027d0374f22311cba8ceb5845232549e6e4df7ae490b6903a5ee1447be";

    function verifysignature() returns (bool)
    {
        return recover(hash, sig) == address(keccak256(publickey));
    }
}

Question

The above does not return 'true' when given a valid signature. What am I doing wrong?

A few things I think could be wrong:

Is it even possible to use ecrecover to validate signatures that were not created by web3.eth.sign?
Do I use the right prefix for the message before hashing it?
Is address(keccak256(publickey)) the right way to convert public key to the corresponding address?

UPDATE

I created a gist of the full working solution based on the answer by smarx. The gist is found here.


texts: What is the current DAG size? When do we expect to hit GPU limits?

texts:
I have two mining rigs running, one with 2GB GPUs and one with 8GB cards. Recently, the rig with the 2GB cards failed due to the inability to upload the DAG to the GPU.

What's the current DAG size for miners and when do we expect to hit GPU-relevant limits, e.g. 2GB, 3GB, 4GB and so on. Are there any precalculations available/possible?


texts: How to transfer erc20 coin multiple to single wallet

texts: I have many eth adress with ERC20 tokens. How can i transfer to single wallet all of them?


texts: How to Convert ERC-20 tokens back to Ether[eum]

texts:
From my understanding, Ether is converted to an ERC-20 token (like BAT), via a smart contract. Ether is assigned to that contract by sending Ether to the smart contract's address. Please correct me if I'm wrong in any of that.

My question though is, how does one convert an ERC-20 token (like BAT) back to Ether? If the smart contract holds the relationship between Ether that I sent to it, how do I convert the ERC-20 token back to Ether if I no longer want it? Instead, I'd just like Ether to use for other purposes.

Thank you for helping me understand this.


texts:
I start geth without setting gcmode=archive at the beginning.
But when i realized that if i want to get all the internal transactions in ethereum blockchain, geth has synced at the blockheight of 9300000.
I restart geth adding gcmode=archive. But i could only get internal transaction after that with debug.traceTransaction.
Is restarting geth from genesis with syncmode=full and gcmode=archive the only way to get internal transaction with debug.traceTransaction in the old block?

Can I avoid synchronizing from blockheight 0?
Will setting gcmode=archive begin to get old block state after syncing the highest block?


texts: No event after a struct push in solidity

texts:
I am testing a contract with Truffle, which code is :

Contribution[] public contributions;

struct Contribution {
    address participantAddress;
    string name;
    uint timestamp;
    uint amount;
    bool refunded;
}

function() {
    contributions.push(Contribution({
            participantAddress: tx.origin,
            name: "anonymous",
            timestamp: block.timestamp,
            amount: msg.value,
            refunded: false
        })
    );
    NewContribution(tx.origin);
}

My test code is :

it.only('should contribute to the pot', function (done) {
  var pot = Pot.deployed()
  var event = pot.NewContribution()

  web3.eth.sendTransaction({from: owner, to: pot.address, value: web3.toWei(1, 'ether')}).then(new Promise(function (resolve, reject) {
    event.watch(function (error, log) {
      if (error) {
        return reject(error)
      }
      console.log(log)
      return resolve(log)
    })
  }).then((log) => {
    assert.equal(log.args.contributor, owner, 'contributor address is wrong')
  }).then(done).catch(done))
})

With this code, I get no events in my test, but if I comment the push like this, I get the expected event :

function() {
    /*contributions.push(Contribution({
            participantAddress: tx.origin,
            name: "anonymous",
            timestamp: block.timestamp,
            amount: msg.value,
            refunded: false
        })
    );*/
    NewContribution(tx.origin);
}

Note that it compile, and both codes are working fine on testrpc, but the first one is failing with a private network or with the testnet network.

Any idea ?

Thank you


texts: Do I need different ethereum adresses for every airdrop?

texts:
I want to register in some airdrops.
I need to type same ethereum address in all airdrops or I need to create new account in metamask so I have different ethereum address for every airdrop ?


texts: Largest possible Supply an Ethereum token that can be created?

texts: What is the largest possible token supply an ERC-20 that can be created?


texts: Tracing back tripped require() to a source code line

texts:
What would be the process to map failed transactions (require, throw, etc.) back to the source code line where they occurred?

Any examples of such yet?


texts:
Variables used in contracts do they get stored in Blockchain?

If so does it require ether?
If not how is persistent where is it stored?


texts: Ethereum project has become a victime of Ddos attack, slowing down the transactions and giving priviliges to attackers to mine blocks. So instead correcting bugs in geth or parity  is there any robust solution (increase opcode cost, or hardfork)?


texts: When calling my Get function, Remix is giving me the current value and geth+parity is giving null

texts:
I have a contract that holds hashes of files and different versions of those files inside a struct.

//
// Structure which holds information about an entry and the versions that entry contains.
//
struct Entry {
    mapping (uint8 => EntryVersion) hashVersions;
}

struct EntryVersion {
    bytes32 hash;
    bool published;

}

// objectIDs that map to entries.
mapping (uint => Entry) entryMap;

//
// Given a entry and a version, a hash of that entry is returned.
//
function getEntry(uint entryID, uint8 version) public constant returns(bytes32 hashEntry, bool entryExists) {

    // If user doesn't have permissions, return blank and false.
    if ( !_hasPermissions() )
        return ("", false);

    // Fetch the current entry and its version hash.
    Entry currEntry = entryMap[entryID];

    // If entry and version were found return hash and true.
    return (currEntry.hashVersions[version].hash, currEntry.hashVersions[version].published);

}

When I deploy the contract from Remix, all goes well I get the entries correctly such as:

getEntry( 5,5 )
Value: "0x45323541374646313033463944314137354436313543383337423333323944390000000000000000000000000000000000000000000000000000000000000001"
Decoded:
bytes32 hashEntry:

0x4532354137464631303346394431413735443631354338333742333332394439

bool entryExists:

true

But when I used GETH's Javascript console attached to parity, I get:

var sol_truebase = web3.eth.contract([{"constant":false,"inputs":[{"name":"entryID","type":"uint256"},{"name":"version","type":"uint8"},{"name":"entryHash","type":"bytes32"}],"name":"addEntry","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"_hasPermissions","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"entryID","type":"uint256"},{"name":"version","type":"uint8"}],"name":"getEntry","outputs":[{"name":"hashEntry","type":"bytes32"},{"name":"entryExists","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newAddress","type":"address"},{"name":"access","type":"bool"}],"name":"_setPermissions","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]);
var activeContract = sol_truebase.at("0x4c522cce483acd799617464083287eee2a31ea44")
activeContract.getEntry.call(5,5)
["0x0000000000000000000000000000000000000000000000000000000000000000", false]

PS.
This is on the Kovan Testnet, my block is up to date and I am used the archive pruning mode.


texts: How can one determine where remix exits?

texts:
In something like this, how can I tell which require the contract exits on?

pragma solidity ^0.4.19;

contract Demo {
    uint _a;
    function Demo(uint a) public {
        _a = a;
    }

    function demo() public view {
        require(_a == 1);
        require(_a == 2);
    }
}

All that's logged in the console is:

[call] from:0xca35b7d915458ef540ade6068dfe2f44e8fa733c, to:Demo.demo(), data:01725...25a0b, return:
Details
Debug
{}
 from   0xca35b7d915458ef540ade6068dfe2f44e8fa733c
 to     Demo.demo() 0xcd021ffd464dc40614c4dd7e7826b3d91a21ab12
 transaction cost   21854 gas (Cost only applies when called by a contract)
 execution cost     582 gas (Cost only applies when called by a contract)
 input  01725a0b
 decoded input  {}
 decoded output     {}
 logs   []
call to Demo.demo errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value.  Debug the transaction to get more information.
creation of Demo pending...


texts: Very strange glitch in Mist (Provide maximum fee < estimated fee consumption)

texts:
Okay I really didn't want to have to format my OS, it's like the fifth time now!

My OS: Ubuntu 14

Anyways, I've deployed dozens of Ethereum contracts without problem.  Then, after updatting to newest Ethereum I've been unable to deploy anything since.  This is what happens:

No matter how much ether I send, or slide the bar up and down, nothing changes the provided fee being less than what is required.

I would try "hacking" Mist by editing the source code to manually change values, but so far I haven't been able to do that.

No problem creating wallets by the way..  Except it says it will consume 0 gas (I don't believe it did that before)  Any ideas what I should do?  I'll accept "format" as an answer


texts: GETH "nodiscover " and addPeer behaviour

texts:
I built a database with Ethereum node addresses.  Now I'm trying to add some of those nodes to my GETH node.
Problems that I'm experiencing:

I'm initializing the geth node with --nodiscover.  My expected behaviour is for the GETH node NOT to add any peers or receive blocks.  This in fact is not happening.  It starts to connect with nodes before I'm manually adding nodes.
When adding nodes through addPeer(), the nodes are added as 'static'.  They never end up being nodes used.  Even if I add 500 nodes, the network slowly adds node as if it was disovering them.  There is no difference is node accumulation speed between synching normally (self discovery) or using --nodiscover with addPeer().

Any idea why I'm seeing this behaviour?


texts:
There are a number of well known undesirable effects of mining pool centralization, primarily:

increased risk of collusion
a small set of pools effectively gain veto power on the evolution of the main net
a big proportion of hash power may fall victim of targeted attacks, and possibly hijacking (of the mining pool, and ultimately, if the pool is large enough, the entire network)

This issue was acknowledged for example in this blog post. It is therefore rather surprising to see that the Ethereum blockchain is no less centralised (approx 50% hashrate controlled by the top 2 mining pools over the past 24hrs, for example) than the Bitcoin counterpart.

Other than the eventual transition to proof of stake, what actions is the Ethereum community taking to counter the mining pool centralization trend?


texts: Problem with understanding web3.eth.accounts.create()

texts:
I am trying to use this function in order to create keypairs for users via frontend, and these pairs are associated with username and password.

However, I noticed, that this:

var account = new Web3EthAccounts('ws://localhost:8545');

console.log(account.create());

works always, no matter if on that port something is running or not. And for that reason I am not so sure anymore, if the web3.eth.accounts-library is even interacting with my running blockchain. I also am not even sure anymore if thats even necessary, or if the keypair just doesn't need that connection.


texts:
Using Windows, when I started Geth with:

geth --rpc --rpcaddr 192.168.1.9 --rpcport 8545 --rpcapi "eth,net,web3,personal" --datadir C:\Users\BulldogBud\AppData\Roaming\Ethereum\testnet\chaindata --networkid 3 console

Receiving:

  I1206 11:55:12.857903 node/node.go:410] HTTP endpoint opened: http://192.168.1.9:8545

I opened another Console typing:

curl -X POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":1}' http://192.168.1.9:8545

Receiving :

  {"jsonrpc":"2.0","error":{"code":-32600,"message":"invalid character '\'' looking for beginning of value"}}

How can I fix this issue? Thank you in advance!

EDIT
after several attempts, giving:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":1}' http://localhost:8545

the new error message is:

  curl: (7) Failed to connect to localhost port 8545: Connection refused

Any suggestion?


texts: Are underscores `_` in modifiers code or are they just meant to look cool?

texts:
I often see _ in modifiers

modifier onlyOwner() {
    if (msg.sender != owner) throw;
    _
}

Does it execute any code or is it meant to make the code easier to read ?


texts: How might you identify eth addresses with the same owner?

texts:
Given an ethereum address, how might you identify (or make a good guess) as to which other ethereum addresses belong to the same owner?

Note: I'd come across some content that somewhat answers this question in the context of bitcoin but not ethereum.  The bitcoin approaches I'd come across were mostly bitcoin-specific (eg take advantage of bitcoin's input/output transaction structure).


texts: Truffle Flattener creates empty flat file

texts: Using trufffle-flattener, I am trying to create a flat file merging all the related solidity based codes. After executing the flattening scripts, I see only the empty flat file getting created. Could you please assist me in resolving this issue ?


texts: ethminer fails to allocate DAG buffer -only- when connecting to a pool

texts:
When I run ethminer -G it starts the miner as expected. It takes around 60 seconds to allocate the DAG, and then it starts pumping out hashes on the GPU (at a dismal 1MH/s but that's besides the point.)

 cl  09:49:13|cl-0      DAG 93 %
 cl  09:49:13|cl-0      Switch time 52536 ms / 49530777 us
  m  09:49:13|main      Speed   0.00 Mh/s    gpu/0  0.00  [A0+0:R0+0:F0] Time: 00:00
  m  09:49:14|main      Speed   1.04 Mh/s    gpu/0  1.04  [A0+0:R0+0:F0] Time: 00:00
  m  09:49:14|main      Speed   1.04 Mh/s    gpu/0  1.04  [A0+0:R0+0:F0] Time: 00:00

However, when I attempt to connect to a pool, for example ethminer -F http://eth1.nanopool.org:8888/0xddb296fbb8882e35e500747bf684f63687437431 -G then it sputters with

 X  09:52:39|cl-0      Creating DAG buffer failed: clCreateBuffer -61
 X  09:52:39|cl-0      OpenCL Error: clEnqueueWriteBuffer -38

If it wasn't working with just the -G I would understand it and have some debugging to do. But I fail to see why having the payload come from a pool instead of locally would cause it to fail so.

I notice the buffer sizes are different - on the non-pool version, I get cl  09:48:27|cl-0      Creating DAG buffer, size 1073739904 but on the pool version I get cl  09:52:39|cl-0      Creating DAG buffer, size 2298476672 so this is likely the cause of the problem - but I still don't see why it exists.

If I try a different pool will that change things? What options do I have?


texts:
Can I make new cryptocurrency on top of ethereum blockchain tech.?
How can i make new cryptocurrency on top of ethereum blockchain tech.?
Any api or platform? Process? Answer will be appreciated...
Thank You in advance.


texts:
In Ethereum yellowpaper the gas cost to create a contract is equal 32000. But what is the cost to validate and keep the contract operating until it is executed?

Edit:

Imagine the following situation: I want to transfer an amount of ether from wallet X to wallet Y. I will use a smart contract to do the validation of the transfer. By my understanding the cost would be:

32 000 gas to create a new contract;
After the contract was validated, 21000 gas would be added to the cost of the contract because the transaction would be validated.

My questions are: is this analogy correct?

Anything I do in the Ethereum blockchain can be considered a transaction? (If I just want to store a value in the blockchain (i.e. 256 bit value has a cost of 20 000 gas) I would have to pay the gas for store the value and also the gas cost of a transaction?


texts: How to check if a transaction is still in the blockchain?

texts:
Say we want to confirm that a value transaction tx has reached certain finality, which we define as waiting for 12 block confirmations. We do this to drop the probability of tx getting lost due a fork or it getting included in an uncle block.

The examples I've seen use getBlock and/or getTransaction first to make sure tx was mined in a block.

They then wait until 12 new blocks have been mined and seem to use getTransactionReceipt to check if tx is still in the blockchain.

Is there some functional difference in this context between using getTransaction and getTransactionReceipt to check if tx still has blockNumber? The implementations don't seem to use any of the additional data returned by getTransactionReceipt making it slightly confusing.
Lets say a fork happened or tx got into an orphaned block before 12 confirmations. Does this mean that getTransaction and getTransactionReceipt will return null for the transaction or how is this reflected in these calls?


texts: I have created a contract, minted some tokens, and I see I have the option to set the Sell and Buy price, but if I do that, Etherscan.io will still show $ 0.00 as the value of my token. How do I actually set Sell and Buy prices? I use 18 decimals


texts: Error when I set compilers! need a little help

texts:
when I run

  web3.eth.getCompilers()

I found that Solidity is not my geth compiler. I try to set it by

  admin.setSolc("/usr/local/bin/solc")
  An error that

Error:solc:exit status 1
      at web3.js:3119:20
      at web3.js:6023:15
      at web3.js:4995:36
      at <anonymous>:1:2

so I try to use solcjs and it worked.
But when i compile with contract,the same ERROR happend.Someone know what's wrong?thx very much.


texts: How can we retrieve the evolution of the state of an smart contract variable?

texts:
I have a simple smart contract with a variable color which stores a string.

If I unterstand correctly, each transaction can change the state of this variable and is stored permanently into the blockchain. Let's say tx#1 changes it to red, tx#1 changes it to blue, and tx#2 to red, tx#3 to green.

I want to have red, blue and green, and not just the last state of this variable color.

How can I achieve this?

Thanks


texts: can raiden network be used on ethereum PoA(proof of Authority)?

texts:
https://github.com/raiden-network/raiden

can raiden network be used on ethereum PoA(proof of Authority) ? If it can , how to use it?

Please help.


texts:
This line of code returns a new address.
web3.eth.personal.newAccount('!@superpassword').then(console.log);

but how is it possible to get this address in a variable, So it can be used for inserting into database


texts: Ropsten rejects my sendSignedTransaction function

texts:
This is my code:

    contractNoEvents.methods.myMethod().call(function(err,foo){
           if (foo.length > n) {
             contractNoEvents.methods.myOtherMethod().call(async function(er, bar){
               if (bar.length > 10){

                var nonce = await web3.eth.getTransactionCount(account);
                const encoded_tx = contractNoEvents.methods.mySendMethod(Math.floor(n).encodeABI();
                const rawTx = {
                     nonce: nonce,
                     gasLimit: 3000000,
                     gasPrice: web3.utils.toHex(utils.toWei('20', 'gwei')),
                     data: encoded_tx,
                     from: account,
                     to: contractAddress
                }

                let tx = new Tx(rawTx);
                tx.sign(pvtKey);
                let serializedTx = tx.serialize();
                console.log(serializedTx);
                web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
                .on('receipt', console.log)
                .on('error', console.log);
               }
              });
           }
        });

I get the following error on Ropsten:

connection not open on send()
(node:1983) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 13): Error: connection not open

I've been looking around but could not find anything I'm absolutely clueless if anyone has any solutions please =)


texts: Deploy multiple truffle contracts with dependency

texts:
Suppose I would like to migrate 2 contracts that are dependent on each other. This can can be done with
var contract1 = artifacts.require("contract1");
var contract2 = artifacts.require("contract2");

module.exports = function(deployer) {
  deployer.deploy(contract1).then(function(){
        return deployer.deploy(contract2, contract1.address)
});
};

However, if I try and nest a 3rd contract that has dependencies on the first two, with the following code :
var contract1 = artifacts.require("contract1");
var contract2 = artifacts.require("contract2");
var contract3 = artifacts.require("contract3");

module.exports = function(deployer) {
  deployer.deploy(contract1).then(function(){
        deployer.deploy(contract1, contract2.address).then(function(){
        return deployer.deploy(contract3, contract1.address, contract2.address)
        })
})};

Then running truffle deploy on this migration file only deploys the first contract and not the remaining two. What is the correct syntax for deploying 3, or even up to n contracts? Is there a nicer way than doing it than this ugly nesting?
Another question, say an additional argument else needs to be calculated for contract 3, what is the correct syntax for this? eg. I want to do something like
var contract1 = artifacts.require("contract1");
var contract2 = artifacts.require("contract2");
var contract3 = artifacts.require("contract3");
var someSol = artifacts.require("someSol.sol");

module.exports = function(deployer) {
  deployer.deploy(contract1).then(function(){
        deployer.deploy(contract1, contract2.address).then(function(){

        const someAddress = await someSol.foo(contract1.address, contract2.address);
        return deployer.deploy(contract3, contract1.address, contract2.address, someAddress)
        })
})};

Any help greatly appreciated


texts: How to calculate average of some numbers in the secret contract of Enigma?

texts:
I want to calculate the average of the Millionaires based on this article.
https://blog.enigma.co/getting-started-with-the-enigma-protocol-a-complete-developers-guide-170b7dfa5c0f

And this is my code.

// CALLABLE FUNCTION to calculate the average assets
function computeAverage(address[] _addresses, uint[] _netWorths)
    public
    pure
    returns (uint)
{
    uint average;
    uint sum = 0;
    for (uint i = 0; i < _netWorths.length; i++) {
        sum += _netWorths[i];
    }
    average = sum / _netWorths.length;
    return average;
}

// CALLBACK FUNCTION to change contract state
function averageAssets(uint _uint) public onlyEnigma() {
    averageAssetsResult = _uint;
    emit CallbackFinished();
}

This average becomes some big number like 52576064 (when the actual number is 125), 52573696 (when the actual number is 100).

I think this is natural because in secret contract we need to hide the actual number. Is there some built-in average function?


texts: Is there a database that lists GPU models and their approximate mining hashrates?


texts: Error: Returned values aren't valid, did it run Out of Gas? during deployment of huge number of contracts

texts:
I am trying to deploy very large number of contracts (more than 300 thousands) with automine option at Ganache GUI .. Is it possible to do such experiments ? when i want to deploy such huge number of contracts, then i am facing following error;

Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
    at ABICoder.decodeParameters (C:\Users\aa\node_modules\web3-eth-abi\src\index.js:226:15)
    at extractingParams (C:\Users\aa\Desktop\temp\deploy - NewfromsFuzz.js:185:42)
    at main (C:\Users\aa\Desktop\temp\deploy - NewfromsFuzz.js:334:7)
    at Object.<anonymous> (C:\Users\aa\Desktop\temp\deploy - NewfromsFuzz.js:381:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
(node:14280) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:14280) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

UPDATE: here is my code

async function finalDeploy(r){

  for(i=0; i<constructorParams.length; i++) {

    const options = {
      data: '0x' + myBin[r]+constructorParams[i],
      gas: 5000000,
  };
  const signed = await web3.eth.accounts.signTransaction(options, privateKey1);
  const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
  console.log("Contract: " +r+" is deployed at  " +receipt.contractAddress);
  contractAddressess.push(receipt.contractAddress)

  }

}

note: above code is valid to deploy 500+ smart contracts

UPDATE 2: Also it should be noted that i have only one contract and one ABI. but i am just trying to deploy that contract with millions different values for its constructor. That's why I am saying i want to deploy millions contract.
For every contract, in my each constructorParams there is value like 0x00ff0040f5020000000000000000001d00000000000002ff37ff4a1f00000b00. this value is encoded for my following constructor (and for every contract this is the same constructor) ...

  constructor(address _wallet) public payable {
        totalSupply = 6;
        owner = _wallet;
    }

As pointed out in comments that there may be some wrong value for your constructor. To answer this point; if i try my above code to deploy my contract with first 500 different values for constructor, then there is no problem.. but if i try the same code with 600 or above values, then at least first 500 values should deploy 500 contracts, but i have received above mentioned error without deploying even a single contract.


texts: How to distinguish uint and int types during evm execution (via opcode)

texts:
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this Orz.

I'm doing some security-related attempts on Ethereum EVM (very immature, just an interesting attempt), and now I need to distinguish between int and uint types in EVM.

pragma solidity >=0.4.22 <0.6.0;
contract calc256{
    uint uresult;
    int result;

    function uadd(uint _a,uint _b) public returns(uint){
        uresult = _a + _b;
        return uresult;
    }

    function iadd(int _a, int _b) public returns(int){
        result = _a + _b;
        return result;
    }
}

For example, the func uadd() and iadd() produce exactly the same opcode. So I can't distinguish between the two data types inside evm

For uadd () function, input _a = 0xfff .... fe, _b = 3, the actual input in evm is (0xfff .... fe, 3) (actually caused an overflow)
For the iadd () function, input _a = -2, _b = 3, and the actual input in evm is also (0xfff .... fe, 3) (correct).

That is, the unsigned positive integers 0xfff...fe and the negative number -2 are represented both as 0xfff...fe when calculating in evm.
I know that Ethereum relies on two's complement to represent signed numbers, but is there any way to make evm distinguish between 0xfff...fe and -2?

Thanks in advance.


texts: Are receiving address and contract address the same thing?

texts:
I've Googled this, but none helped.

I have a wallet, in there I've got a receiving address by which I can receive cryptocurrency from others.

But could this address also be called contract address?
I know a little bit smart contract, and some ICO projects also use contract addresses to receiving funding coins, but are they basically same thing?

Thanks in advance.


texts:
I can't get free testnet ether. I tried already the faucet, I tried mining, it all does not work. Could someone maybe just send me some for some testing?

0x769d1Aab08dCF3F27289194896c0A41F7d51d412

Sorry for begging, but after 3 hours of testing around to find the error, I am giving up.

Thanks.


texts: How can I make sense of solidity-coverage reports

texts:
I'm trying to check the coverage of an entire ERC20 set of openzeppelin tests. I'm using openzeppelin/test-environment and solidity-coverage v0.7.4 as plugins in truffle. The tests went fine but I get odd results for coverage.

Contract      | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines
Context.sol   | 0       | 100      | 0       | 0       | 20,24,25       |
ERC20.sol     | 0       | 0        | 0       | 0       |... 217,227,228 |
ERC20Mock.sol | 0       | 100      | 0       | 0       |... 16,20,24,28 |
IERC20.sol    | 100     | 100      | 100     | 100     |                |
SafeMath.sol  | 0       | 0        | 0       | 0       |... 136,153,154 |

As you can see, only IERC20 got entirely covered, and ERC20 got nothing despite of this contract being the implementation of the IERC20 itself. SafeMath should have some coverage as well. Does anyone can explain this? This is my first time using solidity-coverage, any help is much appreciated.


texts: Soldity: += not compatible with int type

texts:
Trying to run the following code in solidity 0.5.3 with similar compiler in Remix:

function deposit() public payable {
        Maker storage depM = addressToMaker[msg.sender];
        depM.contributionBalance += msg.value;
}

With contributionBalance being a int type in the Maker struct.

And get the following error:

browser/PHBacon.sol:33:9: TypeError: Operator += not compatible with types int256 and uint256
        depM.contributionBalance += msg.value;
        ^-----------------------------------^

If I set it to uint it compiles with no errors. Any thoughts?


texts: Ethereumjs testrpc getting 400 Bad Request when navigating to localhost:8545

texts:
I've followed the instructions for installing ethereumjs testrpc (https://github.com/ethereumjs/testrpc)

I have Node v.6.9.1

I'm on macOS so I have XCode Command Line Tools installed.

Running npm install -g ethereumjs-testrpc completed without error.

Running which testrpc returns /usr/local/bin/testrpc

Then I run testrpc and no error occurs and it states Listening on localhost:8545

When I navigate to localhost:8545 I get 400 Bad Request.

I haven't done anything yet and I'm not sure why this is happening. Has anyone else come up against this issue when installing ethereumjs testrpc


texts:
This is from the Casper FFG document on Arxiv.

Is a higher than b? If so how is b the target checkpoint if it is lower?
If a' is a descendant of a (which I take means a previous checkpoint) how does h(a') = h(b) + 1 look like?


texts: What does Vlad Zamfir mean by 'the fork-choice rule is stateful'?

texts:
Does he mean the rule to determine the next blockchain requires knowing the state of currently bonded validators?

  This “out-of-band authentication only necessarily once” property is
  what Vitalik calls weak subjectivity. In this context information is
  said to be “objective” if it can be verified in a protocol-defined
  manner, while it is “subjective” if it must be authenticated via
  extra-protocol means. In weakly subjective consensus protocols, the
  fork-choice rule is stateful, and clients must initialize (and
  possibly sometimes renew) the information that their fork-choice rule
  uses to authenticate the consensus. In our case, this entails
  identifying the currently bonded validators (or, more probably a
  cryptographic hash of the validator list).


texts:
I'm working on a DAO and I need to make some kind of lottery on who get's the earnings for a certain round. To make this as honest of possible I was thinking about making a lottery where the probability is based on the number of DAO tokens the user has.

So lets say 3 users take part in the round. Let's call them Alice, Bob and Charlie. Alice has 100 DAO tokens, Bob has 50 and Charlie has 10;

Would I just pick a random number in the range of 1 to 160(the total amount in the round) and give Alice the round if it is 1-100 Bob if it is 101-150 and charlie if it is 151-160.

How do I get the DAO token balance from my seperate token contract?

And can this method handle large numbers of users without hitting the gas limit?


texts: Full Archive Node Compaction Performance

texts:
We're currently syncing a Full Archive Node (--gcmode archive --sync full --mainnet) and are experiencing a relatively odd behavior:

As you can see, the node seems to "pause" its processing of new blocks regularily. After a bit of investigation, we noticed that it seems to be linked to database compaction:
{"database":"/var/lib/geth/geth/chaindata","lvl":"warn","msg":"Database compacting, degraded performance","t":"2021-04-14T09:19:35.407752222Z"}

I've found some older resources talking about this behavior:

https://github.com/ethereum/go-ethereum/issues/16871
https://github.com/ethereum/go-ethereum/issues/17020

We're running 1.10.2 Kepler Verge with comfortable hardware (2x NVMe disks on RAID-0, 1gbps link, 16 4.5Ghz cores and 64GB RAM) with an average of 4000 peers and a sustained ingress of about 20mbps.
CPU usage sits around 50%, iowait is < 0.1, load average is normal ; geth process doesn't seem to be starving at all.
My questions are relatively simple : is this an expected behavior ? if yes, can we improve resource consumption to speed up the compaction process ?
Thanks a lot.


texts:
I am trying to create a system using blockchain for a "firm". What I am looking to do is for an employee to enter some data into the system but before it is uploaded have a manager sign off on it being true. Is there a way to make it so that everybody can enter data but it has to be verified by specific people before it is okay?
Thank you in advance.


texts: How exactly can we deploy a contract on a button click from a front end when we are using nodejs and running testrpc?

texts: I want to deploy my contract by taking in parameters from the webpage and they serve as parameters for my contract's constructor and when I click on a button I should be able to deploy the contract on testrpc


texts: How to get the Error Message from revert and require on a solidity contract with Nethereum

texts: Is there a way on Nethereum to get the string messages returned from  arevert or require are executed on solidity contract?


texts:
Previously was able to do the setup successfully, today it didnt work.

alex@alex-Inspiron-3558:/media/alex/Y/Blockchain/assignment_1$ **geth --datadir=./chaindata init genesis.json**

INFO [11-07|11:18:50] Allocated cache and file handles         database=/media/alex/Y/Blockchain/assignment_1/chaindata/geth/chaindata cache=16 handles=16
Fatal: Failed to open database: open /media/alex/Y/Blockchain/assignment_1/chaindata/geth/chaindata/LOCK: read-only file system.

Scanned various forum and the common reason stated was geth is already runing in the background, hence the error.

command: **lsof -i tcp:30303** didnt

gave any result. so no listening was happening on port 30303

Ran the command ps faux | grep geth, found the geth process that is active, killed it still the issue remains.

alex@alex-Inspiron-3558:/media/alex/Y/Blockchain/assignment_1$ **ps faux | grep geth**

alex      3506  0.0  0.0  14224   972 pts/8    S+   11:30   0:00          |       \_ grep --color=auto geth
alex      2839  2.5  1.8 1693852 74916 ?       Sl   11:07   0:35          |   \_ /home/alex/.config/Mist/swarmjs/bin/swarm --bzzaccount /home/alex/.config/Mist/swarmjs/swarmKey --datadir /home/alex/.config/Mist/swarmjs --ens-api /home/alex/.ethereum/geth.ipc

alex@alex-Inspiron-3558:/media/alex/Y/Blockchain/assignment_1$ k**ill -QUIT 3506**

bash: kill: (3506) - No such process

alex@alex-Inspiron-3558:/media/alex/Y/Blockchain/assignment_1$ **kill -QUIT 2839**

alex@alex-Inspiron-3558:/media/alex/Y/Blockchain/assignment_1$ **ps faux | grep geth**

alex      3512  0.0  0.0  14224   968 pts/8    S+   11:30   0:00          |       \_ grep --color=auto geth

alex      2839  2.5  1.9 1693852 75164 ?       Sl   11:07   0:35          |   \_ /home/alex/.config/Mist/swarmjs/bin/swarm --bzzaccount /home/alex/.config/Mist/swarmjs/swarmKey --datadir /home/alex/.config/Mist/swarmjs --ens-api /home/alex/.ethereum/geth.ipc.

let me know if you need further logs on this. Meanwhile I will try finding a solution for this.


texts:
I want to find documentation about how to develop my own sidechain.
I have been trying to research the code of xDai github but I don't completely understand how it works exactly and how to implement a sidechain.
Thanks


texts: Hi Guys I sent nearly 1000 $ to a contract address the the project didn't take off. To get a refund i was told to send 0 ether to the contract address with some data in the data field. But I used Wirex wallet and that wallet doesn't have to option to send 0 ether and no option for hex Data. Is there another way that I can send 0 ether and the data manually to this ether address and then the contract will refund me the 1000 $ ? Any help would be much appreciated.


texts: Solidity. Pushing a struct to an array. But that struct contains an array. Copying of type struct memory[] memory to storage not yet supported

texts:
Here is my code. I need to have a "checkpoint" object that stores some information including an array of "delegations" which is another object.
struct delegation{
    uint256 percent;
    address delegator;
}

struct checkpoint{
    uint256 blockNumber;
    uint256 balance;
    delegation[] delegationTable;
}

mapping(address => delegation[]) votePower;
mapping(address => uint256) balance;
mapping(address => checkpoint[]) checkpoints;

function _setCheckpoint(address _who) private{
        checkpoints[_who].push(
            checkpoint(
                uint256(block.number),
                balance[_who],
                votePower[_who]
            )
        );
}

Solidity seems to have some issues with pushing dynamic arrays around. But I can't find another way for me to store that delegation array that's in votePower inside the checkpoint object.


texts: How to transfer ETH from contract to external address after crowsale?

texts:
I am trying to learn creating smart contracts. For practice, I created token and crowdsale contracts by following the examples on ethereum.org and deployed it. Token distribution is working as expected, but when the contract deadline is met(Funding goal is also achieved), the funds from contract account are not transferred to Beneficiary account.

Here is the code:

pragma solidity ^0.4.11;
contract token { function transfer(address, uint){  } }

contract Crowdsale {
    address public beneficiary;
    uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price;
    token public tokenReward;
    mapping(address => uint256) public balanceOf;
    bool fundingGoalReached = false;
    event GoalReached(address beneficiary, uint amountRaised);
    event FundTransfer(address backer, uint amount, bool isContribution);
    bool crowdsaleClosed = false;

    /* data structure to hold information about campaign contributors */

    /*  at initialization, setup the owner */
    function Crowdsale(
        address ifSuccessfulSendTo,
        uint fundingGoalInEthers,
        uint durationInMinutes,
        uint etherCostOfEachToken,
        token addressOfTokenUsedAsReward
    ) {
        beneficiary = ifSuccessfulSendTo;
        fundingGoal = fundingGoalInEthers * 1 ether;
        deadline = now + durationInMinutes * 1 minutes;
        price = etherCostOfEachToken * 1 ether;
        tokenReward = token(addressOfTokenUsedAsReward);
    }

    /* The function without name is the default function that is called whenever anyone sends funds to a contract */
    function () payable {
        if (crowdsaleClosed) revert();
        uint amount = msg.value;
        balanceOf[msg.sender] = amount;
        amountRaised += amount;
        tokenReward.transfer(msg.sender, amount / price);
        FundTransfer(msg.sender, amount, true);
    }

    modifier afterDeadline() { if (now >= deadline) _; }

    /* checks if the goal or time limit has been reached and ends the campaign */
    function checkGoalReached() afterDeadline {
        if (amountRaised >= fundingGoal){
            fundingGoalReached = true;
            GoalReached(beneficiary, amountRaised);
        }
        crowdsaleClosed = true;
    }

    function safeWithdrawal() afterDeadline {
        if (!fundingGoalReached) {
            uint amount = balanceOf[msg.sender];
            balanceOf[msg.sender] = 0;
            if (amount > 0) {
                if (msg.sender.send(amount)) {
                    FundTransfer(msg.sender, amount, false);
                } else {
                    balanceOf[msg.sender] = amount;
                }
            }
        }

        if (fundingGoalReached && beneficiary == msg.sender) {
            if (beneficiary.send(amountRaised)) {
                FundTransfer(beneficiary, amountRaised, false);
            } else {
                //If we fail to send the funds to beneficiary, unlock funders balance
                fundingGoalReached = false;
            }
        }
    }
}

Am I missing something?


texts: How many nodes are there on the Ethereum network?

texts: When looking on the Ethereum Network Status site, only a limited number of nodes are listed. How can I discover how many nodes there are currently running in total?


texts:
I'm fooling around on the testnet, and I made a contract with an "owner", input manually (not necessarily the sender) that has admin-like privileges.

When I deployed my contract I pasted my main address, but when the contract was deployed the address was different by 1 character! See for yourself, this image shows the owner attribute and my account address.

This happened twice, with the same owner icon, and the same different character. I pasted and I know I did it right, it displayed my icon and everything.

What is the cause of this, and how do I fix it? Because I'm not the owner I can't do anything on my contract. It's not just having permissions, it includes functions that automatically sending tokens to the owner, etc.

The contract is an extension of the token tutorial, here is the contructor:

function MyToken(
    uint256 initialSupply,
    string tokenName,
    uint8 decimalUnits,
    string tokenSymbol,
    address contractOwner
) {
      balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
      totalSupply = initialSupply;          // Update total supply
      name = tokenName;                    // Set the name for display purposes
      symbol = tokenSymbol;               // Set the symbol for display purposes
      decimals = decimalUnits;           // Amount of decimals for display purposes
      owner = contractOwner;
}


texts: How to get the price of a pair using only its symbol?

texts:
Is it possible to get the price of a pair using graphql for uniswap without knowing its id?
I use this website to try things out: https://thegraph.com/explorer/subgraph/uniswap/uniswap-v2
For example, this query allows me to get 5 pairs and their ids and symbols:
{
  pairs(first: 5) {
    id
    token0 {
      symbol
    }
    token1 {
      symbol
    }
  }
}

But what if i only have the symbol and want to get the id?
example:

symbol: ETH / WBTCid: ??

What query do i have to send?


texts: Is there any website which shows tx and deploy fee in fiat price?

texts: I'd like to estimate how much deploying a contract and sending a transaction costs. It would be nice if there is a website which displays the transaction fee history.


texts: Need help understanding — web3.eth.getStorageAt

texts:
Let's say I have three state variables in my contract

contract A {
    uint private x = 255;
    uint[] y;
    uint z;
}

As I understand it, x will have index 0, y index 1 and z index 2? Is it that simple?

How many indexes there are?

Are there special indexes?

Does index point to a single storage cell holding one variable(irrespective of its size) or does it point to a cell with a limit(like 32 bytes)?

I'm just trying to access private state variables at contract addresses and have no idea how. I believe it's done through this app method. Thank you!


texts: When I use personal.unlockAccount(), there is an option to pass a parameter for duration. What is the maximum duration to which i can unlock the account? I have searched through its documentation. It only tells me that the duration is in seconds. And if i pass 0 as a duration parameter, the account unlocks permanently. But I want to know what is the maximum duration i can set.


texts: Version Compatibility Issues Solidity v0.4 to 0.5 | Identity Contracts ERC 725 | abi.encodePacked not working

texts:
This is in reference to ERC 725 Identity Contracts. I am updating the contract to version 0.5. The issue arise in a specific function where it requires a single argument to the call method which I have provided using abi.encodePacked but receiving the following error
2 arguments given but expected 1. This function requires a single bytes argument. If all your arguments are value types, you can use abi.encode(...) to properly generate it.
For reference, I have added the code snippets
 struct Execution {
        address to;
        uint256 value;
        bytes data;
        bool approved;
        bool executed;
    }

function approve(uint256 _id, bool _approve) public returns (bool success) {
        require(
            keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 2),
            "Sender does not have action key"
        );

        emit Approved(_id, _approve);

        if (_approve == true) {
            executions[_id].approved = true;
            success = executions[_id].to.call(executions[_id].data, 0);
            if (success) {
                executions[_id].executed = true;
                emit Executed(
                    _id,
                    executions[_id].to,
                    executions[_id].value,
                    executions[_id].data
                );
                return;
            } else {
                emit ExecutionFailed(
                    _id,
                    executions[_id].to,
                    executions[_id].value,
                    executions[_id].data
                );
                return;
            }
        } else {
            executions[_id].approved = false;
        }
        return true;
    }

Getting the following error on this line of code
success = executions[_id].to.call(executions[_id].data, 0);

TypeError: Wrong argument count for function call: 2 arguments given but expected 1. This function requires a single bytes argument. If all your arguments are value types, you can use abi.encode(...) to properly generate it.

I have already tried the following solution
success = executions[_id].to.call(abi.encodePacked(executions[_id].data, 0))
But the issue still persists


texts:
I understand concepts about how consensus is important to record data into the blockchain such that it is accurate and not tampered with.

But, suppose a client queries the balance of an account, and a malicious node decides to return bogus data? In other words even though the blockchain is immutable what if the malicious node forks the codebase and modifies data after it reads the state of the blockchain? Then for the client requesting the data wouldn’t it see incorrect data in this case when checking an account balance?

I’m sure there is a means to prevent this...but I cant find the right literature.


texts: Configuration settings for launching your own local Geth node for smart contract deployment & execution?

texts:
I need to know how to configure a Geth node that I am running locally for the purpose of deploying smart contracts to in a test net context.  I have the Geth source project setup successfully in JetBrains GoLand IDE on Linux.  When I run the project, it compiles successfully, executes, but immediately exits with a 0 exit code instead of staying resident, ready to accept smart contract deployments and execution.

How do I configure my Geth node node for proper execution on Ubuntu Linux (14.04) and so I can deploy smart contracts to it from Truffle?  Are there any web pages or resources that discuss this issue directly (Geth node configuration, launch, and smart contract deployment?)


texts: Ethereum Wallet testnet not synching when mining

texts:
I am trying to mine on the testnet. Unfortunately, my Ethereum Wallet (latest version using Geth 1.5.3) kind of gives up doing anything when I click on start Mining on testnet. The time counts up is displayed in red, but nothing gets synchronized anymore.

In the "normal" non-mining mode, i've got up to 25 peers and actual blocks get synched from time to time (every ~20-40sec).

What could go wrong here? And how can I find out?


texts: ether faucet error whenever i am trying to get ethers for rinkeby testnet from https://faucet.rinkeby.io/

texts:
when ever i am trying to get ethers (rinkeby) from https://faucet.rinkeby.io/  it is giving me this error.

Faucet offline: context deadline exceeded

even without entry my url it is giving the error.

help pls


texts: Checking if address previously sent token to adddress

texts:
I am developing a function that allows a user to mark another one as a scammer, this will be later displayed in a webapp.
To do this, i need to know if the user (address) previously interacted (sent tokens) with the address it's trying to mark as a scammer.


texts: Why is Etherscan's "Pending transactions" count so huge?

texts:
Etherscan's pending-transactions count has been in the 60k-80k range for a few days. Why is this?

If I look at etherscan's current pending-transactions list, sorted by gas price, I see transaction 0xb3fc7559712e7f95919b6faea, which has a gas price of 2,311.44 GWei, and a 21-minute-old timestamp. Why is this juicy transaction not being picked up by miners? If it's an invalid transaction, somehow, why is it sticking around in the pending transactions list? Does a node's mempool tend to carry tens of thounsands of transactions like this?


texts: Manipulate smart contract functionalities

texts: Let's say I have a Dapp which uses some specific smart contracts to setup connections between different entities. Do I need to care if nodes behave maliciously or does the smart contract guarantee me that connections will be setup only in the way I intend?


texts: Are there any public/free nodes to connect a Dapp front end?

texts:
I have a small Dapp written in Meteor (client only) that reads some contract and account info from the blockchain.  I can deploy my front-end code for free on meteor.com (or a variety of other places), but I still need a node to connect to.

Do I need to host my own node?  If so, any recommendations? I'm using Digital Ocean $5 VPS now, and it's really, really slow.

If not, are there free/public options?


texts:
I'm having trouble implementing a time out factor in my election. Lets say when the contract is deployed the timer kicks off, after the timer runs out the election ends and it announces the results of the election.

How can I generate reports in solidity?


texts: How to use smtp protocol in solidity smart contract via chainlink Oracle

texts:
i had developed a external adapter that make a http get request to cryptocompare api
and get latest eth-usd price for me.
from bridge import Bridge

class Adapter:
    base_url = 'https://min-api.cryptocompare.com/data/price'
    from_params = ['base', 'from', 'coin']
    to_params = ['quote', 'to', 'market']

    def __init__(self, input):
        self.id = input.get('id', '1')
        self.request_data = input.get('data')
        if self.validate_request_data():
            self.bridge = Bridge()
            self.set_params()
            self.create_request()
        else:
            self.result_error('No data provided')

    def validate_request_data(self):
        if self.request_data is None:
            return False
        if self.request_data == {}:
            return False
        return True

    def set_params(self):
        for param in self.from_params:
            self.from_param = self.request_data.get(param)
            if self.from_param is not None:
                break
        for param in self.to_params:
            self.to_param = self.request_data.get(param)
            if self.to_param is not None:
                break

    def create_request(self):
        try:
            params = {
                'fsym': self.from_param,
                'tsyms': self.to_param,
            }
            response = self.bridge.request(self.base_url, params)
            data = response.json()
            self.result = data[self.to_param]
            data['result'] = self.result
            self.result_success(data)
        except Exception as e:
            self.result_error(e)
        finally:
            self.bridge.close()

    def result_success(self, data):
        self.result = {
            'jobRunID': self.id,
            'data': data,
            'result': self.result,
            'statusCode': 200,
        }

    def result_error(self, error):
        self.result = {
            'jobRunID': self.id,
            'status': 'errored',
            'error': f'There was an error: {error}',
            'statusCode': 500,
        }

i was successful in getting eth-usd price.
Here is the question that  can i use smtp protocol in smart contract?
smtp mail sending code
# the first step is always the same: import all necessary components:
import smtplib
from socket import gaierror

# now you can play with your code. Let’s define the SMTP server separately here:
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "1a2b3c4d5e6f7g" # paste your login generated by Mailtrap
password = "1a2b3c4d5e6f7g" # paste your password generated by Mailtrap

# specify the sender’s and receiver’s email addresses
sender = "from@example.com"
receiver = "mailtrap@example.com"

# type your message: use two newlines (\n) to separate the subject from the message body, and use 'f' to  automatically insert variables in the text
message = f"""\
Subject: Hi Mailtrap
To: {receiver}
From: {sender}

This is my first message with Python."""

try:
    #send your message with credentials specified above
    with smtplib.SMTP(smtp_server, port) as server:
        server.login(login, password)
        server.sendmail(sender, receiver, message)

    # tell the script to report if your message was sent or which errors need to be fixed
    print('Sent')
except (gaierror, ConnectionRefusedError):
    print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
    print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
    print('SMTP error occurred: ' + str(e))


texts: How to use eth_newFilter to get pending incoming transactions to a contract?

texts:
I'm trying to get pending transactions to a certain contract using Infura.
Is it possible to do that using eth_newFilter? Since apparently these filters only "trigger" from contract events, does that mean this idea is doomed? As in, when I get a tx from the filter, it can no longer be pending as it must be finished in order to trigger the filter?

If so, is it a suitable option to host my own full node instead and parse trough all pending transactions on my own? Doing that on Infura would result in a crapload of requests that I wouldn't want to burden their service with.

Any help is much appreciated.


texts: What is an efficient way to return multiple pieces of information off-chain?

texts:
I have a contract where an ID of type uint can be owned by an address through mapping (uint => address) owner. I have another mapping that keeps tabs of which IDs a particular address might own: mapping(address=> uint[]). I'd like to create a function that returns all the IDs a certain address might own to an off-chain call. What is a good way I can achieve this? I considered creating a string that appends all the IDs that are separated by some delimiter, but that seems inefficient.

Thank you for any help in advance.


texts:
I have a dapp node which uses web3js to send transactions to quorum geth node. The html pages shows the http provider and the ports. In theory anyone can use these ip and public address in the html to do postman rpc json calls to transfer assets away.

How can someone secure these ports when they are required to be opened for web3js to send transactions to? By openiny these ports anyone can connect to.

Of course one can firewall to allow only the dapp instance to connect to. But the dapp static html page will still hold thr connection details. One can also use an active directory or nginx to secure the access to the dapp and/or json rpc api.

Are there any other solutions on top of the above mentioned to secure quorum geth nodes?


texts: deploy contract on privavte blockchain using truffle

texts:
I setup a private blockchain on local using geth.What I did :

create genesis.json
geth init
geth attach
create account , unlock account and mining start
truffle init, write contract, migrations and update truffle.js

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*",
    }
  }
};

when I try to migrate the contract I am getting the following error :

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

using this command to start a node with geth :

geth --port 3000 --networkid 58342 --nodiscover --datadir="privchain" --maxpeers=0 autodag --rpc --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3" --ipcapi "eth,net,web3"

This is my genesis.json file :

{
  "config": {
    "chainId": 58342,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
  },
  "nonce": "0x0000000000000033",
  "timestamp": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x8000000",
  "difficulty": "0x100",
  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x3333333333333333333333333333333333333333",
  "alloc": {}
}


texts: How to add multiple smart contracts to remix? i have a project including several smart contracts such that they are inherited from each other. The question is how to add all of them to remix and then test each of them?


texts: Detected type of solidity contract in Remix: TokenFactory example

texts:
I am new to solidity and I am playing around with a sample "Factory Contracts" as
 in this git:
https://gist.github.com/carolplay/b547d54f39c7d4d35f9a6aa71a1df1e3

I was able to deploy a Token contract, or deploy a TokenFactory contract.
But after calling the createToken method of the deployed TokenFactory, which is supposed to deploy a new Token contract, and I loaded the returned address, the recognized type is TokenFactory instead of Token in Remix.

I wonder if I messed up something or the remix IDE because this example is not that complicated.


texts:
I am trying to sign transactions using the Web3 HDWalletProvider package and an infura API. I am using the following code:

const Web3 = require('web3');
const Web3HDWalletProvider = require("web3-hdwallet-provider");
const mnemonic = "12 words"

var httpProvider = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/[API]');
var provider = new Web3HDWalletProvider(mnemonic, httpProvider);

I get the error

Uncaught ReferenceError: require is not defined

I have a Dapp that I compile in Remix and I have been using Metamask to confirm transactions but I want to upload several thousands smart contracts in a batch and confirming individually is not a practical option. I would rather not convert my project to truffle if possible. Can anyone help me with this?

Thanks!

Phil


texts:
I'm working on ethers npm package and after instantiating wallet, I'm trying to transfer some tokens to the address. but it is throwing out an error missing-signer.

Do anyone know, what mistake I might have done?

My Code :

var ethers = require('ethers');
var providers = require('ethers').providers;
var utils = require('ethers').utils;
var p = new providers.JsonRpcProvider('http://xxx.xx.xxx.xx:8545', false, 5);
ethers.Wallet.provider=p;

const contractAddress = '0x contract address here';
var contractInterface = 'contract interface here';

var data = 'wallet json from keystore';

var walletJson = JSON.stringify(data);
var wPassword='keystore account password';
ethers.Wallet.fromEncryptedWallet(walletJson, wPassword).then(function(wallet) {
    console.log("Address: " + wallet.address);

    var address = 'adress to transfer to';
    // //var payout =  ethers.utils.parseEther('10.0');
    var payout =  1000000000;
    var contract = new ethers.Contract(contractAddress, contractInterface, wallet);

    try {
        var promise = contract.functions.transfer(address, payout);
        console.log(promise);

        promise
        .then(function(result) {
          console.log(result);
        })
        .catch(function(err) {
          console.log("Promise Rejected "+ err);
        });
    } catch (e) {
      console.log(e); process.exit();
    }
}).
catch(function(err){
    console.log(err);
});

Is there anything I'm doing wrong with the account address or password(contract address)?

What might the mistake be? Any ideas?


texts: Why do some functions from my contract end up in the ABI while others don't?

texts:
Using the greeter example, The original contracts is written with 4 methods: mortal(), kill(), greeter(), and greet().

Why then when I look at the mined contract does it show me an ABI of:

{
  address: "0xaa159b9af634c040e1853fee9dcff12bd6f58772",
  allEvents: function(),
  greet: function(),
  kill: function()
}

Are some of these just special built in keywords that act differently? 'mortal()' and 'kill()' seem to have the exact same semantic structure.


texts: Won't making Ether more deflationary, make it less useful?

texts:
Won't deflation simply make the network more expensive to use, for any new arrivals who aren't already sitting on deflationary gains?
If there is deflation in Ether and at the same time transaction costs can go down, how does that work?


texts: Can you create fungible tokens out of a single non-fungible token?

texts:
As you are aware, ERC20 tokens are fungible tokens and ERC721 are non-fungible tokens. Click here for details if you want to read about them.
Assuming you have a non-fungible digital asset such as art tokenized as 1 token. Can I further tokenize that art to many fungible tokens so I can start selling it fractionally to many users? Something like the concept of crowdfunding.


texts: Solidity: Initialize struct containing string array

texts:
I do not seem to be able to initialize a struct containing a string array. This is what I tried:

contract testStruct {
    struct stru{
        string[] s;
    }

    stru myStru;

    /*
    function add(string s) {
        string[] strAr; // Uninitialized storage pointer. Did you mean ' memory strAr'?
        strAr.push(s);
        myStru = stru(strAr);
    }
    */

    function add(string s) {
        string[] memory strAr; // just doesnt do anything, exception?
        strAr[0] = s;
        myStru = stru(strAr);
    }

    function getFirst(uint i) constant returns (string s) {
        s = myStru.s[0];
    }
}

The first version (commented out) gives me the compiler warning and does not seem to write anything to storage. The second one seems to run into an exception (I assume that looking at the gas consumption). Thus my question is: How do I initialize a structure containing a string array?


texts: Tried to send ethereum to contract address, get error in etherscan (gethdebugtrace)

texts:
I sent ethereum to a contract address I made and I always get this error:
An error occurred during contract execution: exception

What is going wrong here? I used the exact same code provided on https://www.ethereum.org/crowdsale#the-code and I deployed it from my mist desktop wallet.


texts: Can I buy Ether directly to Ledger Nano S?

texts: Is it possible to buy Ether directly to Ledger Nano S? Because I don't want to download Mist, then create account there, and then wait for the entire blockchain to sync, mainly because while syncing, Malwarebytes is going crazy blocking many outbound IPs! I hope that they're not there to steal my Ether! That's why I want to directly buy Ether to the Ledger, or that would not be possible?


texts: Contract calling a function in another contract : TypeError

texts:
I have three contracts Ignition.sol  , Factory.sol, Cookie.sol , Ignition should call the function 'factoryStart()' in the Factory contract. newCookie() creates new Cookie.sol contracts depending on the passed arguments.
Parts of code has been omitted for readability.
Ignition.sol:
pragma solidity ^0.7.0;

contract Ignition {

 uint256 attr1;
 uint256 attr2;

 constructor(uint256 _attr1, uint256 _attr2){
   attr1 = _attr1;
   attr2 = _attr2;
 }

 // do stuff...

    function factoryStart() public {

     Factory.newCookie( attr1, attr2 );
    }

}

Factory.sol :
pragma solidity ^0.7.0;

contract Factory {

 uint256 attr1;
 uint256 attr2;

 constructor(uint256 _attr1, uint256 _attr2){
 attr1 = _attr1;
 attr2 = _attr2;
 }

 // do stuff...

 function newCookie() public {

 Cookie newCookie = new Cookie(attr1, attr2);
 }

}

Right now, I get a compilation error;
TypeError: Cannot call function via contract type name.
I know my solution must be wrong somehow because I need the ABI/Address of Factory in Ignition so that interaction can happen but I couldn't figure out how.
Any help is appreciated.


texts: When to use metamask and ethereum wallet

texts:
I am confused with metamask and ethereum wallet and Truffle.
I used metamask in Truffle Petshop tutorial.
Then I am using now ethereum wallet with first voting dapp.
I m confused totally


texts:
I am using geth and ethminer on Windows.

Looking at geth, I can see that it is up to date because it is very slowing showing that it is importing new chain segment.  I think that means that geth is caught up and it is only adding new transactions as they come.

I am using ethminer to mine and so I think that geth is fairly busy with the mining.

I also have a Ethereum wallet, pointing to the same exact path that geth is using (C:\Users\frank\AppData\Roaming\Ethereum Wallet\binaries\Geth\unpacked) and using geth I made 100% sure that it is using the same ethereum account as the wallet.

As a matter of fact, when I open the wallet and geth is running, the wallet shows that it is not using geth.  So, I think that somehow the wallet figured out that geth was already running and connects to it, rather than trying to run another instance.

My question is, why does the wallet always says that it is syncing and it has downloaded 2 million of 4+ million blocks?  The wallet always appear to be stuck around the same number, although geth appears to be up-to-date.

so, my question, if geth is busy mining and the wallet does not work, how else can I check if I have any ether?  Can geth mine while it is in console mode?  Can I access some web interface to see my wallet status?

Thanks!


texts: Accessing transactions from EOS in Ethereum smart contract

texts:
I would like to find a way to access transaction information from other blockchains such as EOS in an Ethereum smart contract and vice versa.

Would the way to implement this be by using an oracle which provides EOS transaction data?

Also how could I be able to do this vice versa, access Ethereum transaction data from an EOS smart contract?


texts: How to replicate Bitcoin's OP_RETURN functionality on Ethereum?

texts:
I know Ethereum is more advanced, and allows for more interesting things than associating data to a transaction. But let's say I have a legacy system that uses Bitcoin's OP_RETURN. What options do I have to move from the Bitcoin blockchain, to the Ethereum blockchain?

To put it another way, I need to add data, and then be able to look up that data by some unique id. (like Bitcoin's tx id). Also I need to be able to verify who placed the data. Can I just associate data to a tx? Or should I build a contract with a key-value field for the data, and add some way to verify authorship?


texts: Do we need to create raw transaction for every UTXO that we use during a transaction?

texts: Let say I have 2 UTXOs, one has  value = 0.0001 and another one has value = 0.00005. Now I want to send 0.00014. SO now I have to use both UTXO to perform transaction. So do I have to create 2 raw transaction in order to perform this transaction or one raw transaction? If one transaction, then which txid we will use?


texts:
I am trying to follow a tutorial to deploy a smart contrat on Ropsten Testnet. I am in part 4. Deploy the contract to Ropsten test network:

https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-2-30b3d335aa1f

However, I am stuck at the point when creating a new account with truffle. The  line:
truffle(default)> web3.personal.newAccount('verystrongpassword')

Should create a new account and give me the adress. But there is a 800A138F problem coming up.

I tried changing truffle.js to another name. The error doesn't come up but in the comand line what happens is that truffle opens up again like nothing has happened and in the folder there is a new web3.personal.newAccount('testpassword1234') file created.

Thanks in advance


texts: Add Number to Item in all Struct Members

texts:
I have a struct where I want to increment an item across all struct members. For example, say there is a struct 'Contract', and new customers get their own bytes32 ID, which points to their own struct:

mapping(bytes32 => Contract) public contracts;
bytes32[] public idList;
struct Contract {
        uint data;
        uint vintage;
}

I want to increment each struct contract item vintage by +1 at some time. One way to do this would be to loop through the ID array, pull out their contract, and increment the item.

for (uint i = 0; i < idList.length; i++) {
        Contract storage k = contracts[idList[i]];
          k.vintage += 1;
      }

Is there a way to effectively invoke

*.vintage += 1;

So all the contracts structs have the element vintage incremented in one swoop?


texts:
I managed to setup Quorum IBFT nodes on my MacOS. So far it works - deploying smart contracts, submitting transactions and etc using Metamask using RPC URL localhost:22000- as expected on the local machine (IP 192.168.0.102).
However, on other machine (different IP address) I got error in Metamask "Could not fetch chain ID. Is your RPC URL correct?" when I tried to add a new network the RPC URL of http://192.168.0.102:22000.
Thank you for your help!


texts: Parity account addresses all having prefix 0x00

texts: After creating multiple new accounts with the Parity wallet (v1.6.6), I notice they all have the address prefix 0x00 (the 0x part being the obvious hexadecimal prefix), for example 0x00A85d2d62E1851ad5702e31619B10c7E4308522. What is the reason behind this address scheme?


texts: C++ (or generally OOP) inheritance in Solidity

texts:
In Solidity, when one does inheritance, the two contracts share state. Some pseudocode,

contract A {
uint myVar = 1
setVar() {myVar = 3}
}

contract B is A {
myVar = 2
}

If I deploy A, A.myVar = 1. If I deploy B and then call A.setVar(), B.myVar = 3 (and not 2).

So clearly, inherited contracts share state in Solidity.

In C++, inherited classes do not share state. If you want this kind of shared state functionality, you would need to use the "virtual" key word to reference data in memory (independent of classes).

How can I get "C++ inheritance" functionality in Solidity? For example, if I deploy A, then deploy B, B inherits the functionality of A (namely setVar()) but they do not share state, so A.myVar = 1 and B.myVar = 2 after deployment of both contracts. If I called A.setVar(), B.myVar would still be 2.


texts: I am having access denied to generate a new bootkey

texts:
When I try to run the command to bootnode -genkey bootnode.key

it would say:

  Fatal: open bootnode.key: Access is denied.


texts: Who will run the network after proof of stake?

texts:
Currently miners act as 'servers' for the Ethereum network, by doing all the needed work for Dapps to run, calculating, saving data etc..

Am I correct?

My question is this:
who will run all of this after move to Proof of Stake?


texts: How is this address a contract in kovan and address in mainnet

texts: 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa  is the address for kovan DAI. However this is an actual address on the ethereum mainnet. How is this possible? How is the private key for this address accessible by an address holder?


texts: best practice for airdrops and gas usage

texts:
I tried to write an airdrop contract which takes a list of recipients and a list of balances and then can be commanded to airdrop all at once. With code below I can launch a single transaction able to drop tokens to 100 addresses at once. It cost around 3.5M gas, which is huge and close to the maximum per transaction. Launching a single transfer with my particular token costs around 58k gas. So the batch is more efficient using only 60% of the gas needed by multiple transactions yet I'm bit disappointed because I expected a much bigger saving. I'm looking for a better strategy if any.

pragma solidity ^0.4.17;

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

contract Airdrop{
    address[] public recipients;
    uint256[] public balances;
    ERC20Basic public token;
  address owner;

    function Airdrop(address _token) public{
        require(_token != address(0));
        token = ERC20Basic(_token);
    owner = msg.sender;
    }

    function setRecipientsAndBalances(address[] _recipients, uint256[] _balances) public {
        require(_recipients.length == _balances.length);
    require(msg.sender == owner);
        recipients = _recipients;
        balances = _balances;
    }

    function doAirdrop() public returns(uint){
      require(msg.sender == owner);
        require(recipients.length>0);
        for(uint i=0; i < recipients.length; i++){
            if(token.balanceOf(this)>=balances[i]){
                token.transfer(recipients[i],balances[i]);
            }
            else{
                return i;
            }
        }
        return recipients.length;
    }

}

Then I tried to launch with a script like this (code is not complete)

  it('should do massive airdrop to cause gas issues', async function () {

    //an empty array
    var a = [];

    //generate 100 integers and push in a
    for (i=100;i<200;i++) a.push(i);

    //generate 100 0x addresses appending the integers
    const addr = a.map(x => "0x0000000000000000000000000000000000000" + x );

    console.log(addr);

    //generate an array of balances all equal to 1000
    let balances = addr.map(x => 1000);
    console.log(balances);

    //call the airdrop contract to set the recipients and balances
    await this.airdrop.setRecipientsAndBalances(addr,balances).should.be.fulfilled;

    //call the airdrop to finally airdrop
    let result = await this.airdrop.doAirdrop();

    //write gas on the console
    console.log("gasUsed:"+result.receipt.gasUsed);

  });

I get a gas usage of 3.5ml gas


texts: Deploying contract with parameters using web3.js and Node.js

texts:
I try to deploy a ERC721 contract.
Which is from OpenZeppelin.

My contract constructor wants two input string fields.

constructor(string _name, string _symbol) public {
    name_ = _name;
    symbol_ = _symbol;

    // register the supported interfaces to conform to ERC721 via ERC165
    _registerInterface(InterfaceId_ERC721Enumerable);
    _registerInterface(InterfaceId_ERC721Metadata);
}

However, when I'm deploying the contract, it tells me that the parameters I set must be HEX encoded data.

This is the error message i got:
/Users/amos_mac/721_server/node_modules/solc/soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!

Error: The data field must be HEX encoded data.

So I used web3.utils.asciiToHex(), but it doesn't help.

Here is my code of deploying contract:

MyToken.deploy({
    arguments: [[web3.utils.asciiToHex('Top 10 Students')],[web3.utils.asciiToHex('Top10')]]
}).send({
    from: address,
    gasPrice: gasPrice,
    gas: gas + 500000
}).then((instance) => {
    console.log("Contract mined at " + instance.options.address);
});

Please help!
Thanks a lot!

After checking my code, I realized I added additional '0x' to my bytecode.
Thats what cause the bug.


texts:
I am creating a presale for a new ERC20 token. I have seen various methods and I would like more details about the data field.

Example
    1. Bitjob

Address: 0x5e87EDE65d71218d710c6F94b9bfCD9017FB292A
Gas Limit: 250000
GWEI (Gas Price): 25
Data:     0x1fb00cdc00000000000000000000000000000000464de6625dfe4f2d83ad09b4886000e6

Target Coin

https://medium.com/@TargetCoin/contribute-to-target-coin-ico-83ba469f0b8a

They state -

Using the Target Coin Coin Smart-contract: ETH only.
0xe9e1E3414800886d5210a3F726947387F662ba2A

But there is no data field. I am a little confused by this.

Has anyone more details about the data field and how this should be used in a presale?


texts: How to subscribe to transaction with a smart contract in web3js?

texts:
I am trying to write a web3js code. I have already written it using web3j (java) and now i want to do exactly same thing but using web3js. I have seen documentation and stuff, but i am not able to subscribe to events in web3js.
Below is my code written using web3j :-
        web3j =  Web3j.build(webSocketService);
        Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
        ClientTransactionManager transactionManager = new ClientTransactionManager(web3j, RTKContractAddress);

        EthFilter RTKContractFilter = new EthFilter(DefaultBlockParameterName.LATEST, DefaultBlockParameterName.LATEST, RTKContractAddress);

        disposable = web3j.ethLogFlowable(RTKContractFilter).subscribe(log -> {

                String hash = log.getTransactionHash(); // Here we obtain transaction hash of transaction from the log that we get from subscribe
                String prevHash = flowableTransactionLog.get(numberOfTransactionsFetched.get() - 1).getTransactionHash();

                if(!hash.equals(prevHash)) {
                    flowableTransactionLog.add(log);
                    System.out.println("Chat ID : " + chat_id + " - Trx :  " + log.getTransactionHash());
                    Optional<Transaction> trx = web3j.ethGetTransactionByHash(hash).send().getTransaction();
                    trx.ifPresent(transaction -> allRTKTransactions.add(transaction));
                    numberOfTransactionsFetched.getAndIncrement();
                }
        }, throwable -> {
            throwable.printStackTrace();
            webSocketService.close();
            webSocketService.connect();
        });

In the above code, whenever there is a new trx with the smart contract, my code gets executed, and in that code, i add the received LOG in a ArrayList. Later, i read them when it becomes necessary.
So, in java subscribing to a smart contract was super easy. All i needed was the contract address. Using the contract address, i made a filter and using the filter, i subscribe to all the logs that will be made after the Latest block. Using the logs, I also fetched the transaction details.
But i am not able to do the same in web3js. One things i saw is that, to make a filter in web3js, i need to have the ABI of the contract, but the contract which i want to subscribe to is not open source and the ABI of the contract is not available online.
This is that token :- CRTS TOMO Token
What is the equivalent web3js code? Three problems/questions that i am facing are :-

I don't have contact ABI
Without ABI, how to make a filter
How to subscribe to the smart contract.


texts: Contract calling own function emit event?

texts:
Does a contract calling a function defined within itself cause an Event to be emitted?
Etherscan is not showing events emitted when a function is called using sendSignedTransaction(), despite the fact an Event is within that function.


texts:
I am using this code for implementing Forwarder in my Contract.
contract Forward {

  address public destinationAddress;
  event LogForwarded(address indexed sender, uint amount);
  event LogFlushed(address indexed sender, uint amount);

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

  function() payable public {
    emit LogForwarded(msg.sender, msg.value);
    destinationAddress.transfer(msg.value);
  }

  function flush() public {
    emit LogFlushed(msg.sender, address(this).balance);
    destinationAddress.transfer(address(this).balance);
  }

}

But it's showing me some errors as I am using Compiler 0.6.0 and this code is of 0.4.23 and I am not able to convert it to latest version. Can someone help me with it?
Here is a preview of the error: