texts:
there
I have a contract that I want to work just in a specific period and then stop working I wrote these two function but they didn't seem correct, this contract is called multiple times and I just want it works 10 min after the first call can anyone help?

    contract MyContract {
     uint start;
    mapping (uint => uint) public blockTime;
function addBlock public (){
   uint num++;
    blockTime[num]=block.timestamp;
// I want to know when is the first time this contract is called (from another contract)
    start=blockTime[1];

}
    function specificTime(uint event) public {
     // just work for 10 min
    require (block.timestamp <= start + 10 minutes);

        // some event will happen
        myEvent(event);
    }
}```


texts: I've been mining with geth but my balance is still 0. Why?


texts: How do I get a list of accounts from my Ledger Nano S wallet, including unused accounts?

texts:
geth lists the non-zero balance accounts and the next zero balance account from your Ledger Nano.

How can I get a list of accounts from my Ledger Nano S wallet, including the next block of unused accounts?


texts: Uniswap V2 Contract question: Stack too deep

texts:
Could someone explain how this line of code (linked below) properly circumvents the "stack too deep" error? I was under the assumption that the "stack too deep" error meant the method needed to be broken up into smaller sub-methods, as it has too many local variables. Though in the swap method it looks like defining a new block scope gets around that? is this a recommended way to go about doing things?
https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.sol#L166


texts: What is the beginning nonce on the Rinkeby Testnet?

texts: I know that the nonce is representative of how many transfers an account has made and is 0 at the start on the mainnet. However, on testnets, such as the now decommissioned Morden where it was 2^20 I believe, the beginning nonce is different. Right now I am working with the Rinkeby Testnet, however I am having issues setting the nonce correctly. Does anyone know what the beginning nonce on Rinkeby is?


texts:
Deployed contract from https://github.com/BitGo/eth-multisig-v2/blob/master/contracts/Forwarder.sol , got contract address 0xa07946aac9e905b2d0bfc71d9aaa78694d889815.

But after sending coins to this address, nothing happened.
1st time thought that there was not enough gas for this transaction, but if address received coins so 2nd time my coins will be forwarded to creator address, but nothing happened again. Who knows what is the problem?

Debug in ether.camp showed me that contract is good and everything should work as planned

pragma solidity ^0.4.2;
/**
 * Contract that will forward any incoming Ether to its creator
 */
contract Forwarder {
  // Address to which any funds sent to this contract will be forwarded
  address public destinationAddress;

  /**
   * Create the contract, and set the destination address to that of the creator
   */
  function Forwarder() {
    destinationAddress = msg.sender;
  }

  /**
   * Default function; Gets called when Ether is deposited, and forwards it to the destination address
   */
  function() payable {
        if (!destinationAddress.send(msg.value))
            throw;
  }

  /**
   * It is possible that funds were sent to this address before the contract was deployed.
   * We can flush those funds to the destination address.
   */
  function flush() {
    if (!destinationAddress.send(this.balance))
          throw;
  }
}


texts: Is it better to store my MyEtherWallet password in a password manager or memorize a less secure one?

texts: I figure I could either use a secure password manager to generate a long, randomly generated password for my keystore file, or could come up with a less secure passphrase that I memorize. Which method would be better, both in terms of safety and risk of losing access to my wallet?


texts: Mist 0.9 Using Private Node on Local g0-Ethereum Wallet - How to start without an Internet connection

texts:
Mist 0.9 Using Private Node on Local Ethereum Wallet -
How to start without an Internet connection

Windows 10 - go-Ethereum Wallet starts up and mines
Mist 0.9 will not start without an internet connection ie points to  URL -
 https://wallet.ethereum.org/

So I can work offline on the train for Solidity Dev


texts: Mapping of address => uint256 in Struct returning wrong value after transaction in test

texts:
Here is my contract:

pragma solidity ^0.4.4;

import "./SafeMath.sol";

contract TestContract is SafeMath {
    struct Result {
        bytes32 name;
        uint256 balance;
        mapping (address => uint256) betBalances;
    }

    function TestContract(bytes32[] _resultNames) {
        for (uint i = 0; i < _resultNames.length; i++) {
            results.push(Result({
            name: _resultNames[i],
            balance: 0
            }));
        }
    }

    function getBetBalance(uint resultIndex) public validResultIndex(resultIndex) constant returns (uint256) {
        return results[resultIndex].betBalances[msg.sender];
    }

    function bet(uint resultIndex) public hasNotEnded payable {
        Result storage result = results[resultIndex];
        result.balance = safeAdd(result.balance, msg.value);
        result.betBalances[msg.sender] = safeAdd(result.betBalances[msg.sender], msg.value);
    }
}

Here is my testing code:

const web3 = global.web3;
const TestContract = artifacts.require("./TestContract.sol");

contract('TestContract', function(accounts) {
    const params = {
        _owner: accounts[0],
        _name: "test",
        _resultNames: ["first", "second", "third"],
        _bettingEndBlock: 1000
    };

    let testContract;

    it("allows users to bet if the betting end block has not been reached", async function() {
        testContract = await TestContract.new(...Object.values(params));

        testContract.BetAccepted().watch((error, response) => {
            if (error) {
                console.log("Event Error: " + error);
            } else {
                console.log("Event Triggered: " + JSON.stringify(response.event));
                console.log("resultIndex: " + JSON.stringify(response.args._resultIndex));
                console.log("betAmount: " + JSON.stringify(response.args._betAmount));
                console.log("betBalance: " + JSON.stringify(response.args._betBalance));
            }
        });

        let initialBalance = web3.eth.getBalance(testContract.address).toNumber();
        let betAmount = web3.toWei(1, 'ether');
        let betResultIndex = 0;

        await testContract.bet(betResultIndex, { from: accounts[1], value: betAmount });
        let newBalance = web3.eth.getBalance(testContract.address).toNumber();
        let difference = newBalance - initialBalance;
        assert.equal(difference, betAmount, "New result balance does not match added bet.");

        let resultBalance = await testContract.getResultBalance(betResultIndex);
        assert.equal(resultBalance, betAmount, "Result balance does not match.");

        let betBalance = await testContract.getBetBalance(betResultIndex);
        assert.equal(betBalance.toString(), betAmount, "Bet balance does not match.");
    });

And here is the console error:

/Users/xxx/.config/yarn/global/node_modules/truffle/build/cli.bundled.js:213982
        throw reason;
        ^
AssertionError: Bet balance does not match.: expected '0' to equal '1000000000000000000'
    at /Users/xxx/coding/xxx/test/topic.js:75:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

I have confirmed the bet method works by adding an Event and that the betBalance is as it should be (not included in this code). But it is returning as 0 on the testing side. Why is this happening?

I know that transactions aren't able to return values, but is my call to get the resultBalance considered a transaction since I am chaining the call?


texts:
I want Solidity code to define a function f that would map two Ethereum addresses A, B into a new address X = f(A,B) such that there is nearly zero probability that X is an already taken address (an address of an existing wallet or an address equal to f(C,D) where C!=A or D!=B.

I will explain why I want this. I want to create a token COURT that would represent decisions of several courts, each court denoted by an address. A party may endorse or not endorse the court decision. If a court B decision is enforced on a wallet A then f(A,B) is considered as a valid reservoir of money, otherwise not.


texts: How is Ethereum Plasma different from Ardor's Parent Child chain feature?

texts:
From my understanding Ethereum's plasma is similar to Ardor's parent child chain feature, but what are the main differences from these two technologies?

Ardor is fully proof of stake and it lets you mine/stake its child coins within the system, does plasma have this feature of mining/staking its child tokens?


texts: Geth PoA Clique and 100% transaction finality

texts:
In Bitcoin and Ethereum PoW, we have probabilistic BFT. I.e., the transaction finality will never reach 100%, but it will be very close to that with every further confirmation.

How about Geth POA Clique or Paritiy POA Aura? Is there a point in time where a transaction can be considered as 100% final.

For instance, in a Clique network with 3 sealers (S1, S2, S3), with the following block structure:

...
Block #100 [TX1], sealed by: S1 (in-order -> block-difficulty:2)
Block #101 [], sealed by: S2 (in-order -> block-difficulty:2)
...

At Block #102: can I consider TX1 as being 100% final in a setting with 3 sealers?

At this point, it is impossible to present an alternative chain as long as 50%+1 sealers are honest (?)

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


texts: Can not start mining on parity kovan testnet

texts:
I have been setting up node with parity kovan testnet on cloud instance.I want to start mining with ethminer.

When I start mining with:

ethminer -C -F "http://127.0.0.1:8545"

gives error as:

miner  06:39:47.443|ethminer  Getting work package...
JSON-RPC problem. Probably couldn't connect. Retrying in 1...

And starting with:

ethminer -G -F "http://127.0.0.1:8545"

gives error as:

[OPENCL]:No OpenCL platforms found
No GPU device with sufficient memory was found. Can't GPU mine. Remove the -G argument

With geth I can successfully start mining on same cloud instance but can't with parity.

Starting parity with:

parity --jsonrpc-port "8545" --jsonrpc-apis "all" --port "30303" --chain=kovan --author (address of coinbase)

How could I fix the error I am facing?Thanks in advance.


texts: Use function return variable of smart contract in web3.py

texts:
since im new to solidity programming i have some problem with executing my Contract.

My Contract looks like this:

# Solidity source code
contract_source_code = '''
pragma solidity ^0.4.1;

contract Identities {

event existProduction(bool);
address private owner;
mapping(address => bool) private production;

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

function setProduction(address id, bool include) public {
    require(msg.sender == owner);
    production[id] = include;
}

function proofProduction(address id) public constant returns (bool) {
    existProduction(production[id]);
    return production[id];
}

I want to save an address of a production and want to set it 'TRUE' or 'FALSE' from another instance.

My web3.py code looks like this where i try to find out the boolean variable of an existing or not existing member:

compiled_sol = compile_source(contract_source_code)  # Compiled source code
contract_interface = compiled_sol[':Greeter']
contract_interface_identities = compiled_sol[':Identities']

# web3.py instance
provider = HTTPProvider('http://127.0.0.1:8000')
w3 = Web3(provider)
w3.middleware_stack.inject(geth_poa_middleware, layer=0)
identitiescontract = w3.eth.contract(abi=contract_interface_identities['abi'],
                                     bytecode=contract_interface_identities['bin'])
tx_hash_identities = identitiescontract.deploy(transaction={'from': w3.eth.accounts[0]
w3.eth.waitForTransactionReceipt(tx_hash_identities)
account2 = w3.toChecksumAddress('0x1200f5a866b0889a816d808a82b4f3be30ba6ba2')
identitiescontract.functions.setProduction(account2, True)
proof = identitiescontract.functions.proofProduction(account2)
exist = identitiescontract.eventFilter('existProduction', {'fromBlock': 0, 'toBlock': 'latest'})

My EventFilter is empty and i cannot read out the events and also the proof variable dont give me some information like bool as i want to

Output is like this

  Function proofProduction(address) bound to
  ('0x1200F5A866b0889A816D808A82B4f3bE30bA6bA2',)

Can someone help me how i get the return value out of a smart contract function ?


texts: Different errors while deploying with geth console and truffle

texts:
I'm trying to deploy a contract by two different ways, I can't succeed in any.
First way:
 1. geth console —rinkeby —rpc —rpcapi db,eth,net,web3,personal —unlock="0x..." 2>>geth.log
I have ether on my account, I enter my password correctly, I'm sure that account is on eth.accounts list
 2. I compile my contract with solc, it gives me binary code and abi, which I put into variables bin and abi. I put 0x before binary code.
 3. var contract = web3.eth.contract(abi)
 4. var token = myContract.new( {from: eth.coinbase, data: bin, gas: 1000000}, function(e, myContract) { if (e) { console.log(e); } else { if (myContract.address) { console.log ("mined " +myCcontract.address);  } } })

And it says that

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

Second way is by using Truffle. I've succeeded in deploying contract to rinkeby lots of times already, but now I'm stuck on this error.
 1. I run geth and unlock account
 2. There is my truffle.js :

  module.exports = {
    networks: {
      development: {
        host: "localhost",
        port: 8545,
        network_id: "*",
      gas: 900000
      },
  rinkeby: {
        host: '127.0.0.1',
        port: 8545,
        network_id: 4,
        gas: 4612388, // Gas limit used for deploys
        from: "0xeb1eb48fc3c2756cde3dce8a53472e437062f976"
      }
    }
  };

3.truffle migrate --reset --network rinkeby
And it says

  Error encountered, bailing. Network state unknown. Review successful transactions manually.
  TypeError: contract.detectNetwork is not a function
      at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:201861:21
      at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:326484:15
      at

My purpose was to learn how to interact with contract's functions by geth or truffle console. But smth went wrong. Please, help me fix it.
If you made it to the end of this question, thanks already


texts:
To run a node on my vps,

--rpccorsdomain "mydomain.com" and set maxconnection, can be set at the same time so that only my own website can send rpc call for security, also I use max connection to limit the bandwidth?
What is the correct geth command for init node and start node? Do I still need the file CustomGenesis.json?
Usually how big the node is? and how long to download?

also, I created some demo account by script lightwallet, I cannot find which one is the private keys from the keystore object:

  {"salt":"FneDYAPZOTF4f4Gdylm3wMlJv7QLMcvGB1+upxjQvE8=","hdPathString":"m/0'/0'/0'","encSeed":{"encStr":"ruohZV2xykidwTOmM0GtijnhaMGP2dMSUGdBJ/Teh8KIO4JvTa5cOgKxpYEoKKVmZwzzpzfsAw3XehDlNUYnYwE+J6jgB2N8JGxbBVufz5IMMjS0QOw0y8ILf35TMxbRcQFkEstcDACfOWrn0B98xzuvnAwNmh4lC0iLSTm8SV8t/HQn/hbfbQ==","nonce":"Ia3VbewxYFRHr1HfFJgGl4VElo80xGE9"},"encHdRootPriv":{"encStr":"nxB7ElsU/VIP7fSHmGwIjPrEEC2HY7XFbnrIW1+NPrpmBr/LduWwR7Rc7l2BcK5P3yGh6ZtTo+Z+aGyuH4smZnFLM+cwKqMhMZGQrkZxeeIEUjosLqhs2iwAaF8BHW5Pb4zzfE0DeX2UuRoJAE70KrdE0Ed22u9v1tv2zF6Clg==","nonce":"BTYyIsI1Oq4tGXBOl4Qvok7E0DXbxa3o"},"version":3,"hdIndex":3,"encPrivKeys":{"14ad302bf56a84cc48a553fb83f703a996f184c0":{"key":"BfZzyE1PsJ14f4ONi7CcBkNmWBx71QlDeNFj8MIBXzv9plyRUka/GaxMzKr60Y8D","nonce":"NcImsJ2MbIjZJEIK8Ho6p3SgawFJk/LR"},"648c78407bf7392de7153515e7b2714cec103709":{"key":"lPpTSyRrIxi16lRiZMIlk2CzPctYTUkZOPkmMNz3U5Qus3zko0SwjLRKo9iKAlLf","nonce":"+JhVJtdKKhnvAvdPEeFYem5IBIBsFZpx"},"cf69e4be058fbdc03f921654cc14b865c9c8cbbe":{"key":"8KVDtJ6cQZ39XKwJqB3QfwZPbJjw9a6JA2gVnHQOdOqMaIGxfgsQYg8N9HY9DLQX","nonce":"7yF0LSgUB+88gaC/kGK+1TkFrSE63WEc"}},"addresses":["14ad302bf56a84cc48a553fb83f703a996f184c0","648c78407bf7392de7153515e7b2714cec103709","cf69e4be058fbdc03f921654cc14b865c9c8cbbe"]}

How can I find the private key for each account? This is just for testing


texts: how to hook up web3 injected by metamask in angularjs

texts: i need to connect to ropsten testnet through metamask but the problem is i wrote the code in node js and it works fine . but how to hook up the web3 into the angularjs 1.


texts:
I have a question about the gas charge. I want the user to pay.

How do I get it. There are certain wallet addresses. They'll send 0 ether.

the tokens they earn will be uploaded to their accounts.

what is the code of it.

I'm sorry about my little English.


texts: Compiled solidity contract run out of gas on deployment

texts:
I have a solidity contract that compiles ok (0.5.1 compiler version), but it runs out of gas if I deploy the whole of it. If I comment some of the external methods of the contract, it compiles and deploys ok. I think the problem is not in the methods theirselves as I can comment any of them separately and it works.

I'm doing all this with truffle on a local network with ganache:

truffle migrate --network development --reset

The error:

Error:  *** Deployment Failed ***

"PPA" ran out of gas (using a value you set in your network config or deployment parameters.)
   * Block limit:  0x6691b7
   * Gas sent:     6721975

My truffle-config.js:

[...]
module.exports = {
  networks: {
    development: {
      provider: function() {
        return new HDWalletProvider(mnemonic, "http://127.0.0.1:7545")
      },
      network_id: 5777
    }
  },
  compilers: {
    solc: {
      version: "0.5.1"
    }
  }
};

Any clue what's going on?


texts:
So I have an old version of the mist wallet 0.3.7.

How do I update it? I have a few hundred $ worth of coins in there and I don't want to lose them.

I don't see any way to back up the wallet or extract the private keys.


texts:
The following compiles in 0.4.26, but not 0.5.0. The error is "Type contract CustList is not implicitly convertible to expected type address." I figure it's something with address payable, but I have tried ever casting permutation and can't get this to work in 0.5.0.

pragma solidity ^0.5.0;

contract CustTest {
    mapping(address  => address) public customers;
    function createProfile()
        public
    {
    customers[msg.sender] = new CustList();
    }
}

contract CustList { uint x;}


texts: RangeError: private key length is invalid (In New ETH Transaction pragmatically)

texts:
Followed this Ans
Ans1 and Ans2 but no solution got.

const web3 = new Web3('https://ropsten.infura.io/v3/3c52917848e945229c0d33d632b10490');

const account1 = '0x0982081d5a2bba0a9da9fe722c92edc0cb0e9b6a'
const account2 = '0xabc46ddc17a0c37ef70e8a153d4724f199705e8b'

const ac1_pvtkey =Buffer.from('XXXX9F79B587B1DE553E2ADCA3DC8D49BE3E2840083D970C41D83F7FD471XXXX');

const ac2_pvtkey =Buffer.from('XXXXC15FBDB4634400B7F8FA17C9491B2E346AEC1BC86A493B18F5759042XXXX');

  //build transaction here ---------------------------

 `web3.eth.getTransactionCount(account2, (err, txCount) => {
    const txObject = {
    nonce: web3.utils.toHex(txCount),
    to: account2,
    value: web3.utils.toHex(web3.utils.toWei('0.2','ether')),
    gaslimit: web3.utils.toHex(2100),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
    }

console.log(txObject)

  //signing transaction here ---------------------------

const tx = new Tx(txObject);
tx.sign(ac2_pvtkey); //using account2 private key

  ------------------------- ERROR GIVING ------------------------

var sig = secp256k1.sign(msgHash, privateKey);
                    ^
RangeError: private key length is invalid `


texts: Getting error invalid command: "networkid=15"

texts:
geth --rpcapi eth,web3,personal --rpc networkid=15 2>&1 | tee -a blockchain.log

while running the above command i get following error

  invalid command: "networkid=15"

And the same command works on another server so i guess am missing something configuration wise.


texts:
I want send a data on a transaction.
_data is storing my message..
Here's my code:

const Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://rinkeby.infura.io/v3/9ce80a86c6c54d22aa821d0486a1a47d')

var account1 = '0xa00c70B72150D627cf53872eefD077079116B6a6'
var account2 = '0xD2a8aa318Fbc56995Db8C415BE6E40329DB1C56C'

const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1, 'hex')
var _data = '0x6d79206e616d65206973206872697368616268'

const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2, 'hex')

web3.eth.getTransactionCount(account1, (err, txCount) => {
    const txObject = {
        nonce: web3.utils.toHex(txCount),
        to: account2,
        value: web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
        gasLimit: web3.utils.toHex(21000),
        gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
        data: _data,
    }
    console.log(txObject)
    const tx = new Tx(txObject)
    tx.sign(privateKey1)

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

    web3.eth.sendSignedTransaction(raw, (err, txHash) => {
        console.log(txHash)
    })
})

The transaction is processed successfully, But the input data message is not the _data value in the etherscan.io


texts: Warning! Error encountered during contract execution [Reverted please someone help me with this

texts:
i attached link code on etherscan. and error code also

error:
https://etherscan.io/tx/0x90d0d39a127e0693066cbc9a8a42fab20250753ead52724ab1760d7b4b458009

code:
 https://etherscan.io/address/0xfecf0e91a193e8511ac83d8effda34ae4278f491#code


texts:
I am studying Smart Contract with solidity.
I can't understand something, so I want to get expert advice.

I logged in to the Upbit exchange to trade the golem's token.
The Upbit exchange gave me a token deposit address.
That address was a contract address(0x27c6769A0549fa03DafEd89d555C7E71B21Dd35E)

After depositing the golem's token, something happened that I could not understand.
There is no ether to pay for the gas at the deposit address, but the golem's token was transferred to another address.

Q1] To transfer tokens without Ether, how to implement smart contract?

Q2] If you know where to find the sample code to reference, I would like to know the url


texts: I want to create a token using smart contract. Before deploying it on the blockchain, do I have to get the smart contract verified from the third party or can I directly deploy the contract?


texts: Can smart contract sate copy from one private blockchain to another?

texts:
I'm working with private blockchain(PoA), and we're looking for a disaster recovery plan for the chain.
Currently, we have two instances 1) one is running API(node + web3) and interacts with the 2) private blockchain instance.
Copy the chain folder to another machine, and run gives an updated block counts. However, I can't retrieve the smart contract data that has been stored from the first machine.
Is there any way to retrieve the SC data?


texts: Algorithm used for symmetric key encryption by quorum

texts: What are the symmetric key encryption techniques used by the enclave in quorum to encrypt the payload? The documentation of quorum mentions that the enclave uses a symmetric key to encrypt the payload but there is no mention of the algorithm that is used. Any leads would be highly appreciated.


texts: Can Ethereum be used to tokenize bandwidth?

texts:
Decentralizing internet bandwidth usage, by allowing blockchain users to act as server nodes using their desktop computers and be paid for it, would fix the problem of running massive server rooms where data must be centralized.
Why isn't Ethereum directed towards solving this problem, whereas Theta token does? (a separate blockchain that is no longer ERC20)
Wouldn't gas fees or their equivalent  be astronomically even more high for this sort of data-heavy use case where a blockchain is trying to decentralize bandwidth?


texts: Recovering of Parity 1.7.8 wallet - integrating to Open Ethereum

texts:
I last used Parity in 2018 - having a wallet with different coins.
As I did a Windows Inplace-Upgrade I saved my C: drive and hoped at that time, that this should be enough to backup my account and wallet.
Since the reignited hype around crypto currency, I tried to access my wallet again with the old 1.7.8 client, but saw that Parity is outdated and was replaced with Open Ethereum. My client won't even start and downloading the blockchain does also not work, so I tried Open Ethereum. It seems that there is no GUI in the browser and everything is done with a CLI, so I'm a little bit confused how to restore or see my wallet.
What I have:
Parity Recovery Phrase for my account (account=wallet?)
Data from old_C:%appdata%\roaming\parity\ethereum\ (dapps, keys, network, signer)
How can I integrate the given data to the new Open Ethereum Client and have an insight to my wallet? If not possible with the Open Ethereum client - do I have other possibilities for extracting my data?


texts:
Quick introduction:I send arrays of strings from a python script to a js script.
The data sent are of these type:

and are stored in a var "data".So I have this object("data") which contains 12 "blocks",evry of which contains ID_utent=...Xacc=..Yacc=...Zacc=..Date=..Time=..(as shown in the image)
(here there is the JS code if you want to see:

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 10001;

net.createServer(function(sock) {

console.log('__________');

sock.on('data', function(data) {

    console.log('DATI:\r' + data);

});

sock.on('close', function(data) {
    console.log('__________');
});

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

I want these data saved on blockchain.
I thought to use a smart contract like this

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) {
        storedData = x;
    }

    function get() constant returns (uint) {
        return storedData;
    }
}

So my question is: Could I save these data passing directly "data" as an object parameter?? like this:

pragma solidity ^0.4.0;
contract SimpleStorage {
    object storedData;

    function set(object x) {
        storedData = x;
    }

    function get() constant returns (object) {
        return storedData;
    }
}


texts: What is the economically efficient hardware setup for proof-of-stake mining?

texts:
As I understand it, if/when proof-of-stake is fully adopted, all those GPUs will become practically worthless for mining. (Presumably they'll be dumped onto the secondhand market or redeployed for POW mining on competing currencies.

If I was to build a good POS mining rig from scratch, what are the priority requirements? Where is the advantage? Would I want many cores, or lots of RAM, or will the computation hardware be rendered moot by network latency? Or will a "good enough" computer perform as well as any bigger/faster machine, assuming that blocks don't normally contain gas-hungry calculations?

In a nutshell: what are the hardware requirements for POS mining, and to what extent is it worthwhile to build a bigger/faster machine?


texts:
I'm thinking about a particular use case where a smart contract in a private chain could send txs to the public chain (in my case txs would be functions calls of a smart contract in the public network).
In my knowledge it may not possible without passing through a server side interaction acting as a proxy between the two networks(too much centralized) but I hope that there's some implementation that I still don't know.

thank you for your help


texts:
When running my chain my gas limit drops drastically from the set limit of the genesis block "gasLimit": "0x3B9AC9FF" due to large gaps both in time and frequency between the transactions that require the high gas price, I attempted to correct this by reducing the "gasLimitBoundDivisor": "0x0400" to zero, however parity expects a non-zero value, how can I set a high ceiling on my gas limit that wont drop below a certain level without requiring any of my low gas transactions to push up drastically by putting an equally high floor as with minGasLimit.

{
    "name": "ItemChain",
    "engine": {
            "authorityRound": {
                    "params": {
                            "stepDuration": "5",
                                "validators" : {
                                                "multi": {
                                                            "0": {
                                                                "list": ["0xc742f517c1ee50425ca257c46f4232w17e2fa8b"]
                                            }
                                    }
                            }
                    }
            }
    },
    "params": {
        "gasLimitBoundDivisor": "0x0400",
        "accountStartNonce": "0x0",
        "maximumExtraDataSize": "0x32",
        "minGasLimit": "0x3B9AC9FF",
        "maxTransactionSize": 307200,
        "eip150Transition": "0x0",
        "eip160Transition": "0x0",
        "eip161abcTransition": "0x0",
        "eip155Transition": "0x0",
        "maxCodeSize": 24576,
        "maxCodeSizeTransition": "0x0",
        "eip140Transition": "0x0",
        "eip211Transition": "0x0",
        "eip214Transition": "0x0",
    },
    "genesis": {
            "seal": {
                    "authorityRound": {
                            "step": "0x0",
                            "signature": "0x0000000000000000000000000000000000000000000000000000000000000000"
                    }
            },
            "difficulty": "0x100000",
            "gasLimit": "0x3B9AC9FF"
    },
    "accounts": {
        "0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
        "0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
        "0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
        "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
       "0xc742f517c1ee50425ca257c46f4232w17e2fa8b": { "balance" : "100000000000000000"}
    }
}


texts:
I logged into my metamask after a week, just to realize it was drained. I don't know how this could have happened, I just want to make sure I prevent this from happening in the future, should I completely stop using the metamask extension? Anyone knows how this could happen? I can't think of anyway someone could have gotten access to my private keys. I didn't send or save them anywhere. Thank you.
https://etherscan.io/address/0x4dc1dd1facd67247a7dfa3caf725eb1579338223
the last transaction is the unknown one.


texts: Do I pay any fee to the miner if I call a non-constant function, when no state variable is changed?

texts:
Suppose I have a non-constant function which changes a state variable under some condition.

In other words, the function may sometimes change this variable and sometimes leave it as is.

Will I pay any gas fee to the miner when the function doesn't change the variable?

I wrote a small Truffle test which shows the gas cost when the function doesn't change the variable:

File MyContract.sol:

pragma solidity 0.4.24;

contract MyContract {
    uint private x;

    constructor(uint _x) public {
        x = _x;
    }

    function set() external {
        if (x >= 42)
            x += 42;
    }

    function get() external view returns (uint) {
        return x;
    }
}

File MyContract.js:

contract("MyContractTest", function(accounts) {
    it("set", async function() {
        let myContract = await artifacts.require("MyContract.sol").new(41);
        let estimateGas = await myContract.set.estimateGas();
        console.log(estimateGas);
    });
    it("get", async function() {
        let myContract = await artifacts.require("MyContract.sol").new(41);
        let estimateGas = await myContract.get.estimateGas();
        console.log(estimateGas);
    });
});

The Printout:

Contract: MyContractTest set: 21647
Contract: MyContractTest get: 21656

I then realized that estimateGas runs under the assumption that the tested function is called from the on-chain (i.e., by some other contract) and not from the off-chain, because the gas cost of the constant function get was also larger than 0.

So as in the title of my question:

Will I pay any fee to the miner if I call function set and it doesn't change variable x?

Thank you!

CLARIFICATION:

My question is about the gas cost of a non-constant function (can it be zero in some cases). The question suggested as a duplicate is about the gas cost of a constant function (can it be larger than zero in some cases). So these are essentially two different questions.


texts: How does one go about implementing the ContractTransactor interface from the bind package in go-ethereum?

texts:
Hey guys thanks in advance!

Here is the interface provided by the go-ethereum library in the bin package.  I need an example on how to implement this interface please :)

// ContractTransactor defines the methods needed to allow operating with contract
// on a write only basis. Beside the transacting method, the remainder are helpers
// used when the user does not provide some needed values, but rather leaves it up
// to the transactor to decide.
type ContractTransactor interface {
    // PendingCodeAt returns the code of the given account in the pending state.
    PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
    // PendingNonceAt retrieves the current pending nonce associated with an account.
    PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
    // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
    // execution of a transaction.
    SuggestGasPrice(ctx context.Context) (*big.Int, error)
    // EstimateGas tries to estimate the gas needed to execute a specific
    // transaction based on the current pending state of the backend blockchain.
    // There is no guarantee that this is the true gas limit requirement as other
    // transactions may be added or removed by miners, but it should provide a basis
    // for setting a reasonable default.
    EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error)
    // SendTransaction injects the transaction into the pending pool for execution.
    SendTransaction(ctx context.Context, tx *types.Transaction) error
}

I have some basic starter code here, so that people can see where I need the interface applied.

package main

import (
    "MyProject/constants"
    "MyProject/contracts"
    "fmt"
    "github.com/ethereum/go-ethereum/accounts/abi"
    "github.com/ethereum/go-ethereum/accounts/abi/bind"
    "github.com/ethereum/go-ethereum/common"
    "math/big"
    "strings"
)

func main() {
    contractAddress,err:=common.NewMixedcaseAddressFromString("hexFun")
    if err != nil {
        panic(err)
    }
    userAddress,err:=common.NewMixedcaseAddressFromString("hexFun")

    if err != nil {
        panic(err)
    }

    userMainAddress := userAddress.Address()
    mainConctractAddress := contractAddress.Address()
    if err != nil {
        panic(err)
    }
    fmt.Println(abiObj)
    //LOOOOOOOK HERE PEOPLE THANK YOU --------------------------------------

    var one bind.ContractTransactor
    transactor, err:=contracts.NewERC721Transactor(mainConctractAddress,one)
    if err != nil {
        panic(err)
    }
    auth, err := bind.NewTransactor(strings.NewReader(constants.GetEthKey()),constants.GetEthParaphrase())
    trans, err:=transactor.Mint(auth,userMainAddress,big.NewInt(123))

    if err != nil {
        panic(err)
    }
    fmt.Println(trans.Hash())

}


texts:
I am new to Ethereum. I tried getting some wei from the faucets referenced here, in particular, from zerogox and morden.ether.camp. It says on these websites that I have been sent wei (see e.g., screenshot below). That was more than a day ago.

However, I see no change in my balance on my Ethereum wallet (see second screenshot). My wallet tells me about 1 minutes passed since the last block (i.e., fully sync as far as I as understand).

Have I received the wei, but cannot see it?

Am I seeing the correct balance, and I have not received the wei?

Why?

Thank you.


texts: Metamask (and other wallets) don't show tokens on balance despite of transactions are in blockchain

texts: I've generated thousands of addresses with my seed phrase and deposited some USDT tokens to one of them (m/44'/60'/0'/267) and ensured that I'm able to spend that tokens. But after I've imported this seed phrase to Metamask and Trust wallet, I see no tokens on the balance.


texts: Unaffordable gas limit for my Ethereum based crypto-coin

texts:
The gas limit for single send transaction is about 21000 gas.

Now I am creating my own Ethereum based crypto-coin, and I want to keep its conversion rate as 1 coin = 1 US$ and about 0.02 US$ as transaction fees.

But if my traders send 1 or just half coin, then also for this transaction, if they have to pay the whole gass limit then it will be of no use as it will be more of a loss.

So, my question is, is there any other way to avoid this much fee? Or instead, can we combine multiple transactions up to a limit and then send it as a 'single transaction' to miners??

Thanks in advance.


texts: Designing web site page for accepting Ethereum

texts:
Currently, I'm looking for a way to start accepting Ethereums on a website.

The following topic encourages usage of smart contracts for keeping a track of all transactions coming to a specific ETH address, with possibility to add a custom order ID for identifying an order in my database:
Accepting Ethereum on a website

However, I'm really wondering how should a SmartContract-enabled payment page look like. Is there any way to include the SmartContract code mentioned above in Ethereum payment URL and QR code in the way understandeable by major desktop & mobile clients, or I should take another approach?


texts: How are web3 contract function calls and transactions carried out?

texts:
Sorry if this sounds like a beginner question but after reading through a lot of material I have some questions.

Firstly, if a contract has already been created can I call its functions if I know its ABI & address? I think contract(ABI).at(contractAddress) does this but I found the description rather ambiguous.

Secondly, if I am running web3 by direct library import without MetaMask or Mist when I initiate a function call who is the msg.sender? If MetaMask or Mist are running is the msg.sender the currently signed in wallet?

Finally, if I want to create a browser Dapp, how do I ensure some functions can only be invoked by the Dapp and no one else (Not even the owner)?

Thanks in advance!


texts: Where does Ethereum node store its variant?

texts:
It's known to all that once the smart contract is deployed to the Ethereum network, it won't be modified. But what about the value of a contact's variant? Say a smart contract looks like:

...
contract Hello{
      uint256 var1 = 10;
      function changeVar1() public{
             var1 = 100;
      }
}
...

So my question is where is the variant var1 stored in Ethereum? Is it a part bytecode of the smart contract?(I guess it is stored this way) If so, its value exists in memory of EVM when you run the contract and each time you run the smart contract again the value of var1 is initialized as 10. If not, where is it stored exactly ? And can I see the value of var1 changed by the previous transaction which called the function changeVar1()?


texts: use the caller of the wrapper function to call the inner function

texts:
Suppose, I have 2 contracts A and B:

contract A{
    function someMethod() public{
         // Something happens here
    }
}

And contract B containing its instance and its wrapper function

contract B{
     A instance = new A();

     function wrapper_someMethod() public{
          instance.someMethod();
     }
}

Now, what I want here is, whenever I call function wrapper_someMethod() using some address 0xABCDEF, the call to the someMethod() function goes from this address only (0xABCDEF), and not from the address(contract B).

How can I do so? Tell if there some other strategy to do it.

Thanks.


texts: Solidity: Contract Inheritance and upgrade

texts:
This might have been answered somewhere else, but I couldn't find a 100% satisfying answer. I have the following contracts:

Contract One {}

Contract Two is One{}

Contract Three is Two {}

All the contracts are in separate files, being imported. I fail to understand the concept of upgrades in this case, since when I compile the contract Three in Truffle, everything else is imported and compiled at that point.

Assuming I have functions in contract Three that set the new addresses of contracts One and Two, what is the procedure of upgrading? I fail to understand the complete logic, and would appreciate a detailed description of this process. Basically, what I want is to be able to change contracts One and Two later (adding more functions, changing stuff) without affecting data structs that are on contract Three.


texts: How does Transactions work in Ethereum Virtual Machine?

texts:
While reading the transactions sections of EVM documentation many questions raised in my head:

  If the target account is not set (the transaction does not have a
  recipient or the recipient is set to null), the transaction creates a
  new contract (The payload should be the code of the contract,
  correct ? ).  As already mentioned, the address of that contract is
  not the zero address but an address derived from the sender and its
  number of transactions sent (the “nonce”) (But Doesn't the nonce
  represent a number that combined with block data provides the hash of
  the next block ? ) . The payload of such a contract creation
  transaction is taken to be EVM bytecode and executed (Do they mean
  the compiled bytecode of the contract ? and what do they mean by "and
  executed" ? ) . The output data of this execution is permanently
  stored as the code of the contract. This means that in order to create
  a contract, you do not send the actual code of the contract, but in
  fact code that returns that code when executed (Which code returns
  what ? We have contract code and the compiled contract I missed this
  one entirely ) .

Sorry for embedding the question the quote but I think this is for better understanding what I really when asking the questions.


texts: How do I find the amount of Ether the deployed contract on Remix IDE holds?

texts: Assuming I have successfully deployed a contract on the online Remix IDE and sent Ether to the address the contract is deployed to; how do I find the amount of Ether that the contract/address now holds?


texts:
If I want to burn ether, is it safe to send it to 0x0000000000000000000000000000000000000000 - safe in the sense that there is provably no way (other than cracking encryption or bruteforce) that this ether could return back into circulation?

There are a few articles out regarding how the black hole address holds some 500m$ worth of ether and tokens, but these articles lack technical depth.

I'm curious to know if there exists any party that knows or could know (by other means than bruteforce) the private key of this address or if the system has been explicitely designed such that such a private key can't be known by anyone or such that transfers from this address are invalid by definition?

If that's not the case - is there a way I can create an ethereum address of which provably no one knows the private key?


texts: Is it possible to console(In nodejs) the transaction hash from metamask?

texts: I am running rinkeby testnet ethereum node in my local. I created one address in my local node using "personal.newAccount()" in geth console.Now I deposited some ethers to my local address through metamask account.Now point is "Is it possible to console(In nodejs) the transaction hash from metamask while depositing the ethers from metamask account to local rinkeby address in nodejs console" Thanks


texts: TDD Solidity: expect internal struct state

texts:
I'm a big fan of TDD/BDD so I figured hardhat and chai/waffle are a good start to learning smart contract development.
I've run into an issue though where I'm wondering what best practice would be to expect the state of a mapped, nested struct?
Minimal example:
contract MyContract {
    struct Inner{uint foo;}
    struct Outer{Inner bar;}

    uint idx;
    mapping (uint => Outer) mapped;

    function doSomething(uint _val) public {
        mapped[idx] = Outer(Inner(_val));
    }
}

How would I go about testing that Inner.foo has the correct value after the call to doSomething(123) ?
The only solution I've found so far is creating a function getOuter(uint _idx) public view returns (Outer memory) and use that to retrieve the value to expect in the test.
This however would mean adding a function to the contract that is only needed for testing as well as using pragma experimental ABIEncoderV2; which - well, sounds kinda experimental.
What's the correct way to solve this?


texts: ETH2 Atomic Composability and Sharding: What does it really mean for DeFi users?

texts:
In the following post, Vitalik Buterin claimed that ETH2-Sharding will not break DeFi composablity:
[1] https://ethresear.ch/t/cross-shard-defi-composability/6268
However, I am not at all convinced by his arguments.
Let's look at the following example from Vitalik [1]:

Composability example 1: Uniswap <-> Tokens Nearly all DeFi
applications are uses of composability, because tokens are a type of
application and so any DeFi application that uses tokens is an
application that interacts with another application. Let us look at
Uniswap as an example. In Uniswap, a user sends some quantity of token
A to a Uniswap contract, which sends some quantity of token token B
back to the user. Uniswap requires strict dependency between all
transactions that interact with it: the Nth transaction must be aware
of the output of the N-1’th transaction, because this is how the price
updating algorithm works.
Hence, the Uniswap contract would need to live on a single shard
(there are designs for multi-shard Uniswap, but they are more
complex). Users looking to trade would perform a 2-step procedure:
Send their token A to the shard that Uniswap is on. Perform a trade
with Uniswap as before (the transaction doing this would be combined
with the transaction “claiming” the receipt from step (1), so it’s a
single step) [Optional] If desired, move the token B that Uniswap gave
them to some other shard.

Now this is a very simple use case.
Since Uniswap acts as an automated market maker, it seems pretty obvious that Uniswap wants to run on a single shard.
However, sending token from one shard to another shard seems to be very tedious for DeFi users.
If I want to trade with DeFi-assets, then I don't want to care about moving ETH between shards.
I just want to invoke a smart contract, and I don't want to care about where a particular smart contract is sharded.
For me, this seems like a lot of needless technical complexity for the average DeFi-trader.
But this is just one aspect that I am concerned about.
The other aspect is that Vitalik's Uniswap example does not explain at all how atomic composability is still supposed to work.
For example, let's consider the use case of flash loans. Flash loans are uncollaterized loans that succeed only if they are paid back within the same transaction. In contrast, with asynchronous messages between shards, flash loans would probably be infeasible.
And flash loans are just one advanced example, I am pretty sure that we could find many more advanced DeFi use cases.
So what do you think, do you believe that Vitalik did not even realize what "atomic DeFi composability" actually means?


texts: Truffle for Windows: I can't make it work

texts:
I've installed Truffle v3.2.1 for Windows. If I try to run:

truffle console

  Could not find suitable configuration file.

If I run:

truffle create:contract MyContract

I get nothing but command list.

Any ideas?


texts:
i want to setup an ethereum node for my website to use. What is the min space I need? To save space do I need to use light node? Or even Better idea?
How much space I need for light node or full node? Or some other node I can only keep the transactions related to myself?
Thanks


texts:
Suppose you received 250 HELLOCoins and you want to burn them. Unfortunately, HELLOCoins uses OpenZeppelin ERC20 which implements the following function:

  function _transfer(address from, address to, uint256 value) internal {
        require(to != address(0));

        _balances[from] = _balances[from].sub(value);
        _balances[to] = _balances[to].add(value);
        emit Transfer(from, to, value);
    }

The require "to" to be different from 0x0 means that you can't send any ERC20 to 0x0, therefore not burn HELLOCoins.

Which of the following alternatives are better and would the second option ever work?

Send to 0x0000000000000000000000000000000000000001 (the first address after 0x0. Does someone own this address? There is nothing on the internet about it)
Create another smart contract which reads the ERC20 address of HELLOCoins. The smart contract calls a sendTo function which does not implement the "require(to != address(0))" part. I am skeptic this would work but I would like to know.
Any other solution to burn HELLOCoins?


texts: Getting "replacement transaction underpriced" though not trying to replace a transaction

texts:
I'm running an airdrop script which essentially loops a database of recipients and invokes a batchTransfer function each time with 80 different recipients and amounts.
After about 10 successful submissions, each new submission is rejected with "replacement transaction underpriced" - though the data of the request is different!
The stack is web3|infura|rinkeby

I read the answer here but not sure it applies. Will changing the nonce solve it? Where do I do it anyway? is nonce a param I add to the json array along with gas and gasPrice? And anyway, why doesn't the network see the data is different in each transaction I try to submit?


texts: Calling external contract leads to infinite gas need

texts:
I'm trying to implement this pattern:

contract Producer {
  uint8 public SOME_VALUE=12;
}
contract Consumer {
  Producter currentProducer;
  function setProducer(address addr) { currentProducer = Producer(addr); }
  function getSome() returns (uint8) { return currentProducer.SOME_VALUE(); }
}

It compiles, I can deploy my Consumer, and I can it bind a producer.

But I want to ensure addr is really a Producer when I bind it to my Consumer:

function setProducer(address addr) {
    Producer newProducer = Producer(addr);
    require(newProducer.SOME_VALUE() > 0);
    currentProducer =newProducer;
}

This way, I'm sure I'm linking a Producer and not anything else (I don't like the way I do this, but that's the best solution I found yet)

But by just adding this require, I'm no more able to deploy. The gas needed is sky rocketing... may be infinite as, no matter how high I put it, the transaction fails after reaching the limit (Same behavior on Remix or on a local testnet). Please note that, a the time of deployment, the setProducer() function is not called.

Is this a bug? Or most probable: am I missing something?

Thanks for your help


texts:
We all know a smart contract is a normal piece of code which can have intended and unintended bugs. DAO attack is such an example where a bug has led to a heavy loss. Suppose I want to check what all properties can be there which a smart contract should satisfy in order to call it as safe. I have seen that there are many projects already going on where FORMAL VERIFICATION is being used to achieve the exact specification but I am not talking about those things. I am asking for some safe properties which can ensure this safety.

For example, we know that using CALL function to transfer ethers to a contract address can be a potential vulnerability that can be exploited if not handled properly.

So what all these properties can be?


texts: Ganache and truffle - how to set zero deployment fees

texts:
I am running a local ganache-cli node on my machine and would like to have zero transaction fees. For this reason I am starting the node using

  ganache-cli -g 0

which sets the gas price to zero. My initial migration file of truffle looks like this:

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

module.exports = function(deployer) {
  deployer.deploy(Migrations, {
      gas: 0
  });
};

Upon running

  truffle migrate

I get an error saying: base fee exceeds gas limit

What could be the problem? Thanks!


texts: How can I create an ethereum wallet which can show many addresses balance?

texts:
I'm looking for a wallet which can scan many ethereum addresses balance,(like electrum for bitcoin).
I need to import 200 (or more) eth addresses and scan their balances include their tokens(if funded).
I've already used electrum for bitcoin and now I want something like that for ethereum.
It's appreciated if someone guide me?
I'm even ready to pay someone who can write a code for this reason. A customised ethereum wallet just for scan the balances, not for send & receive ethereum.


texts: Can i post a data to the url in Ethereum smart contract

texts:
Actually i want to create a smart contract in ethereum for handling the api requests. creating a proxy kind of contract which makes note of the number of requests in the contract.
Is it possible, any material available for me to refer...


texts:
I am developing a Dapp, which has a smart contract in solidity and uses truffle framework. My smart contract has a constructor that takes a value as an argument
I want to initialize this smart contract from truffle framework in node.js
But the value that I need to pass to initialize has to be fetched from a database(mongoDB). How can this be done?
Can we write fetching this code logic in 2_deploy_contracts.js?
Thank you in advance


texts: What is the best way to encrypt and decrypt a variable in Solidity so only the msg.sender and contract can see that variable?


texts: Interacting with a deployed contract: How can I mint a token based on the Open Zeppelin Standard

texts:
Please excuse what seems to me a basic question, as I am very new to this:

I'm using the truffle framework to deploy a smart contract. Playing around with Open zeppelin standard tokens, I've issued the SampleCrowdsale.sol contract: Link

I've successfully got it on the Ropsten blockchain, but that's as far as my knowledge goes. How can I interact with the contract, other than sending ether to it?

As an owner, how can I call the mint function that's part of the MintableToken.sol contract?

Thank you.


texts: What does TheDAO counter-attack by spamming actually do? (suggested by Stephan Tual)

texts:
TheDAO is currently under attack and a counter-attack by spam has been suggested by Stephan Tual https://blog.slock.it/dao-security-advisory-live-updates-2a0a42a2d07b#.r3wg8cxlw

What does this code actually do?

for (var i = 0; i < 100; i++) {
    eth.sendTransaction({from: eth.accounts[0], gas: 2300000,
      gasPrice: web3.toWei(20, “shannon”),
      data: “0x5b620186a05a131560135760016020526000565b600080601f600039601f565b6000f3”}) }
}

I figured that it sends 100 transactions from account 0 with some data. But what is that data and how does it help the DAO from getting drained?


texts: Please confirm units in this sendTransaction are reasonable

texts:
Can you please double-check this command for me and tell me if I screwed up the units?

eth.sendTransaction({ from: "blah", to: "blah", value:20000000000000000, nonce:5, gas:120000, gasPrice:80000000000 })

I had a little panic attack afterward about whether I was supposed to put gasPrice in wei or gwei.  I checked the documentation and it says wei, but nevertheless I'd like the peace of mind of a second set of eyes.

If one screws it up and puts in a ridiculously high gas price beyond the available funds, will that burn up all of what's remaining in the account before it fails?


texts:
How do I get my own address into a variable when I use HDWallet as provider for Web3?
const HDWalletProvider = require("@truffle/hdwallet-provider");
Web3 = require("web3");
let provider = new HDWalletProvider('claim .. ... ... .. .. blah','https://sandbox.truffleteams.com/blah/blah')

web3 = new Web3(provider);

I have tried:
web3.eth.accounts[0] is empty
web3.currentProvider.selectedAddress is empty
web3.eth.getAccounts(accounts => console.log(accounts[0])) is empty

Nothing seems to work.


texts: How to ensure that a string parameter to a function is not empty?

texts:
Lets say that I have a function which needs two string parameter ,
function data(string memory _firstname, string memory _lastname) public {
buyer[msg.sender] = Buyer(_firstname, _lastname);
}

Now, I want to ensure that user has not left either of the two fields empty. How do I do it ?


texts:
I have a scenario where I need to store N no. of document hashes in a smart contract with some key(id). And also fetch the particular document hash by it's key. Any help on designing the structure for storing would be appreciated.
Thanks


texts:
I'm trying to setup personal full node in archive mode (whole history) on server with this parameters:

Intel i3 3.4GHz
8GB DDR3 1333 MHz
2TB HDD
100 Mbps / 128

I was expecting issues with HDD speed (despite HDD is quite solid) but I got that ETH node needs some random seeks - unfortunately after renting server.

But now node stopped syncing - my parity logged stopped on

  2018-01-24 12:38:59 UTC Syncing #2422928 7d9a…cc9e     0 blk/s    0
  tx/s   0 Mgas/s      0+ 7089 Qed  #2430018   49/50 peers     12 MiB
  chain   11 MiB db   42 MiB queue

If I'm getting this right node is on block #2430018 - now its ~5M blocks in ETH blockchain.

I run parity with these flags:

parity --fat-db on --db-compaction hdd --base-path /home/eth_chain/ --mode active --pruning archive --tracing on --logging INFO --log-file /var/log/parity/proc.log

Disk is not full

Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           788M   17M  771M   3% /run
/dev/sda2        20G  2.9G   16G  16% /
tmpfs           3.9G     0  3.9G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/loop0       21M   21M     0 100% /snap/parity/7572
/dev/loop2       84M   84M     0 100% /snap/core/3748
/dev/loop3       21M   21M     0 100% /snap/parity/7576
/dev/loop4       82M   82M     0 100% /snap/core/3887
/dev/sda3       1.8T   43G  1.7T   3% /home
/dev/sda1       487M   69M  389M  15% /boot
/dev/loop5       21M   21M     0 100% /snap/parity/7596
tmpfs           788M     0  788M   0% /run/user/0

I'd allow parity to use more of my hw - its entirely dedicated to this purpose

Have you any advice? Is running ETH full node in archive mode on HDD complete nonsense? - even in --db-compaction hdd mode? With 8GB RAM?


texts: DeclarationError: Uninitialized storage pointer. Struct error when running truffle tests

texts:
I've seen other similar questions but they don't explain why this error happens and/or they are case specific questions. So, I have this code:
pragma solidity >=0.4.22 <0.7.0;

contract MagicIdeas {

    struct IdeaCard {
        address owner;
        string title;
        string text;
        string img_url;
        string card_id;
    }

    ....

    function update_card_data(string memory _card_id,
                            string memory _new_title,
                            string memory _new_text,
                            string memory _new_img_url) public {
        IdeaCard storage updatedCard; // ERROR HERE
        updatedCard = IdCardMap[_card_id];
        if(bytes(_new_title).length>0){
            updatedCard.title = _new_title;
        }
        if(bytes(_new_text).length>0){
            updatedCard.text = _new_text;
        }
        if(bytes(_new_img_url).length>0){
            updatedCard.img_url = _new_img_url;
        }
    }

Whe I run truffle test I get the following:
DeclarationError: Uninitialized storage pointer.
        IdeaCard storage updatedCard;
        ^--------------------------^

Why does this happen? How can I solve it?
Extra: The same code compiles correctly on remix.


texts: Can I modify a struct property and send it back to the contract?

texts:
we are experiencing an issue dealing with structs.
We expect to modify a struct property after getting it from an event in web3js, but, it seems that the modify does not apply.

Any ideas?

Contract code:

pragma solidity ^0.5.3;
pragma experimental ABIEncoderV2;

contract Example {
  struct Structure {
    uint value;
  }

  event Created(
    Structure structure
  );

  event Modified(
    Structure structure
  );

  constructor() public {}

  function create() public {
    emit Created(Structure(42));
  }

  function modify(Structure memory structure) public {
    emit Modified(structure);
  }
}

web3js code:

  let Example = artifacts.require('Example')
  let accounts = await web3.eth.getAccounts()

  Example.deployed()
    .then(instance => {
      instance.Created(async (err, evt) => {
        let structure = evt.returnValues.structure
        console.log('Created: ' + structure.value)
        structure.value = 21
        console.log('Modify: ' + structure.value)
        await instance.modify(structure, { from: accounts[0] })
      })

      instance.Modified((err, evt) => {
        let structure = evt.returnValues.structure
        console.log('Modified: ' + structure.value)
        callback()
      })

      instance.create({ from: accounts[0] })
    })

log:

Created: 42
Modify: 21
Modified: 42

We expected the modified value equals to 21


texts:
I have a test function:

function test(uint[400] subscriptions, uint[400] subscriptionIndexes) public view returns
      (uint[4000], uint[4000], uint[400]) {

        uint[4000] memory postSenders;
        uint[4000] memory postIds;

        for (uint i = 0; i < 4000; i++) {

            postSenders[i] = 1;
            postIds[i] = 1;
        }

        return (postSenders, postIds, subscriptionIndexes);
    }

If I connect Remix to Ganache, and call the function by copy pasting the parameters into the Remix IDE blue function box then it runs fine. If I try to call the same contract on the same Ganache network using web3 v 1.0 I get an out of gas error.

 let subs = [1,1, ... ,1]
  let indexes = [1,1, ... ,1]
  let results = await contract.methods.test(subs, indexes).call()

If I reduce the number of loops in the test function eventually it will stop giving the out of gas error. Does anyone know what might be causing the problem?

The function also runs fine on Rinkeby via Remix.

Thanks!


texts: What's the reason all tokens have decimals?

texts:
All of tokens have decimals property, e.g. WBNB token has 18 decimals.
If there was a dex pair using different decimals, then we would first need to divide both sides before we  calculate rates.
(token0 / pow(10, decimals0)) / (token1 / pow(10, decimals1))

What's the reason we need decimals as opposed to just having all tokens use the same base?
Is this is a limitation / optimization of solidity?


texts: send transaction and handling events in web3 1.0

texts:
I have created a contract which has a function like this:

function transfer(address _to, uint256 _value, bytes _data) internal returns (bool) {
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    emit Transfer(msg.sender, _to, _value, _data);
    return true;
}

but now when I want to test contract in web3 1.0.0 using following code:

var balance = await baxToken.methods.balanceOf(user1).call({from:owner, gas:gasEstimate})
console.log(balance)

await baxToken.methods.transfer(user1, 50000).send({from:owner, gas:gasEstimate}).on('event', console.log)

var balance = await baxToken.methods.balanceOf(user1).call({from:owner, gas:gasEstimate})
console.log('balance')

while the first 2 lines of code works however the code stops then. I realized that if I comment the emit Transfer(...) from my contract it works fine.


texts: web.eth.call() returns a revert even when the transaction is success

texts:
I have this snippet to test if web3.eth.call() can check if a pending transaction will revert in advance.
web3.eth.call(tx, "pending")
.then(result => { console.log(count, "Passed!") })
.catch(revertReason => console.log(count, "Reason: ", revertReason ))

Then there are some calls on transactions that return revert error like
{code: -32000, message: "err: insufficient funds for gas * price + value (supplied gas 164340)"}
or
Fail with error 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT
When I check into etherscan they were success.
Why does it happen?


texts: Calling a smart-contract fallback function from another contract

texts:
contract A {
   function one() public {
      //transfer to B to call its fallback function
      B(addressB).transfer(value);
   }

contract B {
   function() external payable {
       someaddress.transfer(msg.value);
   }

In reality, is it impossible to do so?
Otherwise, if I create an empty B's fallback function then it works. Or if I create simple function with someaddress.transfer(msg.value); and call this function from contract A as B(address).someFunction.value(value)() then it also works.


texts: What is an example of a require-style exception when receiving ether via a public getter?

texts:
In the Solidity documentation it is stated that:

A require-style exception is generated in the following situations:
...

If your contract receives Ether via a public getter function.

...

What is an example of that and why does it raise the exception?


texts:
I would like to write a contract, that fetches a data from oracle in a specific point of time (or later) Is there any option to pop up an event in some point in the future in Ethereum contract?
The naïve approach is that any time the user opens a dapp, to try to call a function, and check if it met its due, or has already been called. But I wonder if there is another way.


texts: UnhandledPromiseRejectionWarning: Error: nonce generation function failed or private key is invalid in Ganache

texts:
In Go I am using go-ethereum to read data from the ethereum smart contract. My smart contract is maintained with truffle.
I am trying to fetch candidate information based on candidate id. I have a modifier in the solidity that checks if given id exists or not as
    /**
     *  Check if candidate exists
     */
    modifier candidateExists(uint256 candidateId) {
        require(candidates[candidateId].exists, "No Candidate.");

        _;
    }

Everything works perfectly fine if I pass valid candidateId. But exception occurs if candidates don't exist and revert.
Following is the error recorded in ganache-cli console
(node:31528) UnhandledPromiseRejectionWarning: Error: nonce generation function failed or private key is invalid
    at Object.t.sign (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:37:75864)
    at Object.sign (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:37:64863)
    at Object.t.ecsign (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:37:185991)
    at e.sign (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:17:104733)
    at e.sign (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:10:92594)
    at e.t.hash (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:37:243491)
    at e.u [as hash] (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:10:89447)
    at c.combine (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:2:159323)
    at new c (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:2:158990)
    at Function.c.fromResults (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:2:160122)
    at readyCall (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:17:120626)
(node:31528) 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: 26)
(node:31528) [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.


texts:
I am working on a ethereum dapp and am struck with the following errors, concerned code pieces have been attached.
App.js
  async loadBlockchainData() {
    const web3 = window.web3
    const networkId = await web3.eth.net.getId()
    const networkData = DStock.networks[networkId]
    if(networkData) {
      const dstock = new web3.eth.Contract(DStock.abi, networkData.address)
      this.setState({ dstock })

     //const myId = await dstock.getMyId[this.state.account].call().call()
     const myId  = await dstock.methods.getMyId[this.state.account].call()
    }

Solidity code
mapping (address=> uint256) public getMyId;

Error recieved
Unhandled Rejection (TypeError): Cannot read property '0x14677494C6Dc1E83122A942E07fE79C3cba33D27' of undefined
and
Unhandled Rejection (TypeError): Cannot read property 'call' of undefined
respectively on uncommenting the last two lines of the javascript code


texts:
May I know why I can't do additional in uint for solidity 4.24?

function ToUint(bytes memory value) internal pure returns (uint) {
    uint r;
    for (uint i = value.length - 1; i >= 0; i--)
        r = (r << 8) + uint(value[i]);
    return r;
}

I might have over simplified my code and it doesn't exhibit the problem. The original code was above. As soon as I took out (r << 8) +, every thing works.

The << 8 is not an issue. Because it failed even when I have r + uint(value[I])

The length of bytes array is only 6, and all bytes value are < 0x7F


texts: an alternate way to get all products from dynamic array?

texts:
I'm newbie with Solidity and trying to make some smart contract for eCommerce :D basically.

Here is code of that:

pragma solidity ^0.4.16;

contract ecommerce{

    event OnProductAdd(uint, string, uint);
    event UserInfo(User);

    struct User{
        address _address;
        bytes32 name;
        uint balance;
    }

    struct Product{
        uint id;
        string name;
        uint price;
    }

    address _owner;

    mapping(address => User) public user;

    Product[] public products;

    modifier isAdmin() {
        require(msg.sender == _owner, "you don't have admin access");
        _;
    }

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

    function addProduct(uint _id, string _name, uint _price) isAdmin public {

        products.push(Product({
            id: _id,
            name : _name,
            price : _price
        }));

        emit OnProductAdd(_id, _name, _price);
    }

    function getAllProducts() view public{

       //TODO: return all products
    }

}

Now, what I want is to get all products, but it's a dynamic array..and we cannot return dynamic array directly in Solidity.
So, what alternate way I can use to get all products?


texts: What is the wallet password if you press skip when installing

texts:
In the "Protect your account" installer screen there is a "SKIP" link. What is the wallet's password when setting a password is skipped?

(picture from this guide: https://medium.com/@attores/step-by-step-guide-getting-started-with-ethereum-mist-wallet-772a3cc99af4)


texts: Private Network: Blocktime become over 1 minute when peer number increases

texts:
I have a small private ethereum network.

There is only one miner at most. All nodes are connected to miner node and publicly opened another node; always sync. Please note that miner's port is publicly open. You can see an example as follows.

Current Difficulty: 11.73 MH

I do observe that,  when network has more than 5 peers or more block time gets larger, which is usually might be over a minute.

For example
I observe these block times in a row.

414 seconds, 189 seconds, 363 seconds, 121 seconds, 400 seconds and so on. And even there is in total one submitted transaction. So if I submit multiple transactions and few contract deployment to the network, block time increases over one minutes.

Here is an example of block time most are red.

I have a MacPro, which I used as a miner:

2,5 GHz Intel Core i7
16 GB 1600 MHz DDR3

It used to mine having hash-rate over 4MH/s and now at most 258.4 KH/s after the update on Geth v1.6.2, where I could not find and valid answer related to the issue: Geth 6.2: miner.start() returns null and miner's hash-rate drop for all miners down due to the update .

[Q] What should I do to make my network stable to have block times smaller than 1 minute?

Please note that I can provide and additional information requested.
Thank you for your valuable time and help.


texts: solidity, how to send eth to a contract in the same tx you create it

texts:
actually i'm creating a new contract with new Contract(params)
but how to send eth in the same time (in the same tx like geth does) ?


texts:
I understand that ethers.js is an alternative to web3js.

I have used web3js with ethers.js with quorum. Does anyone used ether.js with quorum before?


texts: web3.eth.personal.newAccount + JSON RPC error connected to ropsten in metamask

texts:
Updated:

I have a function where I init web3 and included web3.eth.personal.newAccount at the bottom of the function to create a new account.

initWeb3: function() {
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }

    web3.eth.personal.newAccount('abc123').then(function(data) {
      console.log(data);
    });
  },

When connected to localhost:8545(ganache) in metamask and test this, it generates a new account, but when connected to ropsten, I get the following error:

  inpage.js:1 MetaMask - RPC Error: Internal JSON-RPC error. {code: -32603, message: "Internal JSON-RPC error."}

Why can't I generate a new account if I'm connected to Ropsten? I use web3 1.0 btw.


texts:
If _tois left empty, and bytecode is a new contract, should _to.call(bytecode) create a new contract ? Or is it so that when a _to address is included in the transaction then the EVM processes it as a non-contract-creating transaction ?

EDIT: I'm trying to create a new contract via a proposal on the http://ethereum.org/dao framework. This article said that its possible, but it does not work. So my question is, is it possible to create a new contract using .call() ?


texts: Is there a way to use A Smart Contract to Read Memory and Write to the blockchain?

texts: Could someone create a smart contract where the target would be to read kernel memory (using some exploit) and then at the end of the smart contact it would write the kernel memory to the blockchain?


texts: sent 500 lend tokens to my ETH crypto wallet in error

texts:
Hi there I hope you can help. I have mistakenly sent 500 Aave (Lend) tokens to my ETH wallet address on crypto.com. Please can you advise what I can do to get back into my orginal wallet?
Below is the transaction on etherscan:
https://etherscan.io/token/0x80fb784b7ed66730e8b1dbd9820afd29931aab03?a=0xb30b3304d979a06f02fee7d304b109dafd5ba9d7
Regards
Kevin


texts:
I know, the practical reasons behind it is just to add additional security layer.

But why does EVM even need it? Asm doesn't have it and works great.


texts: Solidity says my function can by marked as view but my code changes state?

texts:
Given the code below, when I compile the code with Remix it says the function processBandPayments() can be marked as view.  This concerns me greatly since in my mind, the code is changing state by altering the content of one or the other storage variables; in this case the claims or escrow storage variable.

So either this is a Solc/Remix bug (doubtful) or my code doesn't do what I think it does and doesn't really record payments or escrow assignments to the blockchain.  Can anyone shed some light on this?

// The map that maps a game ID to a specific game.
mapping(uint256 => structGame) public s_mapGameIdToGame;

// The map that maps a request nonce to a game ID.
mapping (address => uint256) public s_mapRequestNonceToGameId;

// The map that tracks how much Ether is due to a particular address, whether that
//  address is a player or a band.
mapping (address => uint256) public s_mapAddressToClaimAmount;

// The map that tracks how much Ether is due to a paritcular owner ID.  This is the
//  "escrow" storage.
mapping (bytes32 => uint256) public s_mapOwnerIdToEscrowAmount;

// The round of each play in a game is stored here.
mapping (uint256 => structGameRoundResults[]) public s_mapGameIdToGameResults;

/**
 * @notice Process the payments to the band using the results of the game given
 *  to us earlier by multiple calls to addGameRoundResult().
 *
 * NOTE: If an address is not found in the band addresses array, the amount due that
 *  band is stored in the escrow map instead of the claims map.
 *
 * param _perBandPayment - The amount to pay each band.
 */
function processBandPayments(
        uint256 _gameId,
        uint256 _perBandPayment
    )
        private
        onlyIfValidGameId(_gameId) onlyIfPlayingState(_gameId) {

    // We should have at least one game round result or something is
    //  very wrong.
    require(s_mapGameIdToGameResults[_gameId].length > 0, "(processBandPayments) The game round results array is empty.");

    // If the band donation percentage is 0, then this method should not have been called.
    require(_perBandPayment > 0, "(processBandPayments) The payment for each band is 0.");

    // Process each band payment by iterating the game round results.
    for (uint i = 0; i < s_mapGameIdToGameResults[_gameId].length; i++)
    {
        require(s_mapGameIdToGameResults[_gameId][i].ownerId.length > 0, "(processBandPayments) An owner ID was not set.");

        // Do we have a band address?
        if (s_mapGameIdToGameResults[_gameId][i].bandAddr == address(0)) {
            // No.  Aggregate the payment amount in escrow.
            s_mapOwnerIdToEscrowAmount[s_mapGameIdToGameResults[_gameId][i].ownerId].add(_perBandPayment);
        }
        else {
            // Yes.  Aggregate the payment.
            s_mapAddressToClaimAmount[s_mapGameIdToGameResults[_gameId][i].bandAddr].add(_perBandPayment);
        }
    }
}


texts:
I had an unfinished block since i stopped farming in 2019, and with the current price i thought i will start again, right now i have 2162.472 t credits (not sure if that's 2.1 Ethereum) problem is that it says 43.54% work done.
So that means that if i finish it i will get like +4 Ethereum? I'm using just 2 rigs since my others rig have 4gb cards, need to know how much i will get to know if it will worth to add some more rigs, right now it estimates around 5 months.
Thanks.


texts: How to call a function from an already deployed contract?

texts:
I tried to use the function "Call", as described here: Calling function from deployed contract

But seems it is not working at all.

How can I call a function from an existing deployed smart contract?

I'm trying to call a simple function from an existing address that receives an address as parameter.

This is the code I'm using to call the external function:

Contract A:

function CallExternalFunction(address externalContractAddress)
{
    externalContractAddress.call(bytes4(sha3("FunctionX(address)")),0xfffff);
    //sends 0xfffff as input parameter to the external contract
}

The source code of the already deployed contract is like this:

Contract B:

contract test {

mapping (address => uint256) public balanceOf;

function test() {

}

function FunctionX(address _address)
{
    balanceOf[_address] = 50000;
}
}


texts: Was the function called before from a specific address?

texts:
Consider a function definition as below -

function checkForUpvote() external returns(bool){

Here I would first like to check, if the external account invoking this function
: has invoked this function before ?. If yes, exit. Else Continue.

// ......
// ......<function definition follows>
}

Question: how can I check that checkForUpvote() is invoked only once by one account. ?


texts: Please, how can I remove ether that's stuck in a contract? If it's impossible to do that, what then is the function that will enable me remove ether from a contract I created?


texts:
I am trying to do a simple test on Truffle, but it seems that the deployed() promise is never being executed.

var MyContract = artifacts.require('MyContract')

contract('MyContract', function(accounts) {

    it('My Test', function () {
        MyContract.deployed().then(function (instance) {
            console.log('Deployed');
            assert.equal(1, 2, "This should fail");
        }).catch(function (e) {
            console.log(e);
            })
    })
})

When I do truffle.cmd test --network ganache the test just executes and doesn't log anything to the console.  It seems that no code in the deployed() promise is being executed.  If I do console.log(MyContract) I can see the contract, so it seems that it is being found by the Truffle test.

Any idea what could be wrong?


texts: How to call my contract's function using sendRawTransaction?

texts:
I am trying to call my contract's method using sendRawTransaction. I have a function in my contract

updateReading(address consumerAddress,
            uint32 consumerMeterId,
            uint64 consumedReadingValue,
            address producerAddress,
            uint32 producerMeterId,
            uint64 producedReadingValue)

which I want to call using sendRawTransaction. The updateReading function updates the contract state of the contract. How can I make a call to this function using sendRawTransaction?

I am using truffle framework for the development.I have written the following code in my js to call the function using sendRawTransaction.

        var privateKey = new Buffer(password,'hex')
        var setData;
        var contractAddress;
        EnergyTrade.deployed().then(function (instance) {
              contractAddress=instance.address;
              setData=instance.updateReading(consumerAddress,consumerMeterId,consumedReadingValue,producerAddress,producerMeterId,producedReadingValue);

              var rawTx = {
                    to:contractAddress,
                    from:consumerAddress,
                    data: setData
                  }

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

              var serializedTx = tx.serialize();
              web3.eth.sendRawTransaction(serializedTx.toString('hex'), function(err, hash) {
                    if (!err)
                      console.log(hash);
              });

        })

It returns the following error in my console.

    (node:23336) UnhandledPromiseRejectionWarning: Error: invalid type
at Object.exports.toBuffer (/home/maria/Desktop/12-Energy/node_modules/ethereumjs-util/dist/index.js:177:13)
at Transaction.setter [as data] (/home/maria/Desktop/12-Energy/node_modules/ethereumjs-util/dist/index.js:625:19)
at /home/maria/Desktop/12-Energy/node_modules/ethereumjs-util/dist/index.js:685:63
at Array.forEach (<anonymous>)

Another issue is

   (node:23336) UnhandledPromiseRejectionWarning: Error: invalid address
at inputAddressFormatter (/home/maria/Desktop/12-Energy/node_modules/truffle-contract/node_modules/web3/lib/web3/formatters.js:271:11)
at inputTransactionFormatter (/home/maria/Desktop/12-Energy/node_modules/truffle-contract/node_modules/web3/lib/web3/formatters.js:97:20)
at /home/maria/Desktop/12-Energy/node_modules/truffle-contract/node_modules/web3/lib/web3/method.js:89:28
at Array.map (<anonymous>)

How can I make sendRawTransaction possible in my js using truffle framework?


texts: web3.eth.getAccounts() never give any output

texts:
const deploy = async () => {
    **var acct = await web3.eth.getAccounts();**
    console.log("ac", acct);
}
deploy();

even the console is not getting printed,what could be the reason?
any possible solution would be grateful.


texts: Iterating through an array in JS and simple promises (web3/pudding)

texts:
This might be more to do with my lack of understanding some JS basics however it's in ethereum/web3 context so here it goes.

I have a public array posts in my contract and a global variable in JS of the same name.

Using truffle/pudding framework on the frontend I am then trying to iterate through the array doing something like this:

length = 3;
posts = new Array(length);
for(i = 0; i < length; i++ ){
  social.posts.call(i).then(function(v){
    posts[i] = v;
  });
}

However by debugging I found out that the anonymous function gets executed only once and with i equal to 3. posts[3] gets set and nothing else. I must be doing something silly here. Please help.

Edit: So I understand now that the problem is because of the promises but is there another way to easily retrieve array values from the contract? Pudding was meant to help with this.


texts: Could we call a constant function without spending any gas inside a transaction function?

texts:
I have a sorted linked list that contains around 1000 items. When I receive a new item my goal is to push the item to the list keeping the sorted order. So if I receive very small value, I am required to iterate all the list to find the tail of the list.

Constant function's goal is to return the index location for transaction function to push into.

Iteration(iterateListToFindPushIndex()) might look like this:

struct Interval {
  uint32 num;  //contained value.
  uint32 next; //points to next node on the linkedlist.
}

prevNode     = self.list[self.head]; //head of the list, largest value.
currentNode  = self.list[prevNode.next];
while( true ) {
  if( s > currentNode.num ){
    //self.list.push(Interval( { num: s, next: prevNode.next }) );
    //prevNode.next = uint32(self.list.length - 1);
    return prevNode.next;
//returned indexed would be use in transaction function to insert intem into the correct location.
  }
  prevNode         = currentNode;
  currentNode      = self.list[currentNode.next];
}

As we know when we call a constant function, it does not cost any gas and its free to use. So when I find the index location via a constant function, it won't cost me any gas.

function iterateListToFindPushIndex() constant returns(uint index){}
function func(intervalNode storage self) {
  index = iterateListToFindPushIndex();
  self.list.push(Interval( { num: s, next: index }) )
}

Inside a transaction function, when I iterate through my list even though I don't change any memory storage, it cost me additional gas.

So is it possible to call a constant function without spending any gas inside a transaction function.

Thank you for your valuable time and help.


texts: Contract deployment out of gas, but was created anyway?

texts:
I have deployed a contract with Parity on Kovan, which did not show up in the contracts menu after contract deployment was done. I had to watch it manually to be able to see it in the contracts menu.

When I check the contract on Etherscan, it tells me Contract Creation Out of Gas, but the contract was deployed anyway!?

My questions are:

How could it be deployed if it was out of gas?
If errors were encountered during contract creation, is it still fully functional?


texts: How does a fallback function rejecting ether work?

texts:
A contract in Solidity can have a fallback function like:

// This contract rejects any Ether sent to it. It is good
// practise to include such a function for every contract
// in order not to loose Ether.
contract Rejector {
    function() { throw; }
}

What underlying mechanism in the EVM allows for this?


texts: Hash of address pair combination where order is irrelevant

texts:
I have a contract where I often set stuff for a combination of 2 addresses. Because the parameters addressA and addressB are interchangeable I currently save the information redundantly.

Example:

    mapping ( address => mapping ( address => uint256 )) public maxNextUpdateInBlocks;

    function configureCurrencyPair(address _currencyA, address _currencyB, uint256 maxNextUpdateInBlocks) public onlyOwner {
        maxNextUpdateInBlocks[_currencyA][_currencyB] = maxNextUpdateInBlocks;
        maxNextUpdateInBlocks[_currencyB][_currencyA] = maxNextUpdateInBlocks;
    }

Can this be improved? I am thinking about a hash of the address combination where it doesn't matter if I hash currencyA+currencyB or currencyB+currencyA

And just set in one line:

maxNextUpdateInBlocks[currencyAB] = maxNextUpdateInBlocks;


texts: Executing custom script through non-interactive is different from executing through console

texts:
I have a private ethereum blockchain with a script, filename.js.

miner.stop();
debug.verbosity(4)
loadScript("path to FileStorage.js");
var DataStorageContract = web3.eth.contract(JSON.parse(FileOutput.contracts["FileContract.sol:D
ataStorage"].abi));
var f = 'QmaFDzPfZKwKchNNPBKKVHDz7msc6PTtkYjkWudyKnvF8B'
var d = 'dc2e26b90098aef8457c24bde1ffd5fda15667cf98697fe0c2f77d6be3b6726d'
var fileStorage = DataStorageContract.new(f, d, { from: web3.eth.accounts[0], data: "0x" + File
Output.contracts["FileContract.sol:DataStorage"].bin, gas: '1000000'},  function (e, contract)
{
    if(!e) {
        if(!contract.address) {
            console.log("Contract transaction send: TransactionHash: " + contract.transactionHa
sh + " waiting to be mined...");
            console.log('Error1: ' + e);
        } else {
            console.log("Contract mined! Address: " + contract.address); console.log(contract);
            console.log('Error2: ' + e);
        }
        console.log('Error3: ' + e);
    }
    console.log('Error4: ' + e);
});
miner.start(8);
admin.sleep(10);
miner.stop();

When I attach to the blockchain

  geth --attach "path to ipc"

it returns a console. When I ran

  loadScript("path to filename.js")

I got an output

  Contract transaction send: TransactionHash:
  0x92a875d52660c659ccf0e8fbb1b9d8be109f632db22b1c017 978cdee406cdf18
  waiting to be mined... true

  Contract mined! Address:
  0xbfb5b63dacbd32833919c54da763be85d55f26e3 [object Object]

However, when I run it non-interactive using

  geth --exec 'loadScript("path to filename.js")' attach "path to ipc"

I get an output

  Contract transaction send: TransactionHash:
  0x5e3d9ccfcf3b19d25e8c1dcd662606de10418320270679d8e086e93f04630d1c
  waiting to be mined...

  true

It does not show the "Contract Mined" section in the non-interactive. How do I correct this?


texts: How to understand supplies from smart contracts

texts:
I would like to understand how is total supply calculated and how could I know how much is circulating for particular token.
I will just use random token for example
https://etherscan.io/address/0xd15ecdcf5ea68e3995b2d0527a0ae0a3258302f8#code
has
contract MachiXToken is StandardToken, Ownable {
    string public constant name = "MachiX Token";
    string public constant symbol = "MCX";
    uint8 public constant decimals = 18;
    uint256 public totalSupply = 1000000000 ether;

and etherscan shows https://etherscan.io/token/0xd15ecdcf5ea68e3995b2d0527a0ae0a3258302f8
1,000,000,000 MCX
How is this calculated and how could I get if all is in circulation or some parts are locked and will be distributed later? (someone showing me some examples of locked tokens in smart contract would be useful)


texts: Decentralized Time server to get time in Dapps?

texts:
So basically i want to ask that how can we programmatically get the accurate, exact and current time in a DApp, without relying on the system's time or a centralized time server ?

Is there a decentralized serivce which keeps track of time, so it would be easier to query time from there without having to rely on centralized, single point of failure and potentially vulnerable time servers ?

Maybe a decentralized timestamping service can help here, but i am not aware of any.

please let me know !


texts: How is it possible for Centre and the like to blacklist Ethereum addresses when they themselves are not miners/validators?

texts:
There is no shortage of the news on stablecoin censorship, in particular blacklisting of Ethereum addresses:

Tether has been blacklisting Ethereum addresses that hold USDT for a couple of years now—this year alone,
Tether has blacklisted 24 addresses that hold a total of $5.51 million USDT in summation.
[...]
Tether has blacklisted a total of 39 out of the 1.47 million Tether addresses that exist,
which represents a total of 0.00002% of all tether addresses.
When a tether address is blacklisted, it can’t send, receive, or redeem USDT.

Assuming that the said stablecoin issuers are not miners/validators, how are they able to do censor sending and receiving? Does such censorship involve also NFTs, Eth, and other erc-20 tokens? Could similar censorship be done by MakerDao?


texts:
When i try to deploy any contract using quorum local node in remix browser with solidity version higher than 0.5.0, the contract gets deployed but any transaction to interact (fetch / update) the contract shows an error.

  Quorum Node:

  Version: quorum-v2.4.0

  Solidity:

  Solc version: 0.6.1 / 0.5.16

Contract:

pragma solidity ^0.6.1;

contract Sample{

    struct Structure{
        uint a;
        string b;
    }

    mapping(string => Structure) public s;

    function add(uint a, string memory b)public {
        s[b] = Structure(a,b);
    }
}

Can anybody please tell me how to solve this issue.


texts:
I created an Ethereum paper wallet using the files from myetherwallet.com on an airgapped computer. But I don't understand how the wallet can be generated and integrated into the blockchain to be able to receive ETHs without the generator ever establishing a connection to the internet and thus the Ethereum network.

The only solution I see right now is that somehow all possible Ethereum addresses are already available for sending ether to and only the private key is generated to a untouched Ethereum address which I can access then.


texts: truffle migrate --network ropsten issues

texts:
When i run truffle migrate --network ropsten i don't see the contract deployment but just

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

i don't know why but also deleting ./build i can't see the deploying of my migrations files but only

Compiling your contracts...
===========================
> Compiling ./contracts/A.sol
> Compiling ./contracts/B.sol
> Artifacts written to /Users/........./build/contracts
> Compiled successfully using:
   - solc: 0.5.0+commit.1d4f565a.Emscripten.clang

A lot of guides show a code like this:

Running migration: 1_initial_migration.js
Deploying Migrations…
… 0xd01dd7...
Migrations: 0xf741...
Saving successful migration to network…
… 0x78ed...
Saving artifacts…
Running migration: 2_deploy_contracts.js
Deploying HelloWorld…
… 0x0aa9...
HelloWorld: [SAVE THIS ADDRESS!!]
Saving successful migration to network…
… 0xee95...
Saving artifacts…

And here my truffle.js code:

var HDWalletProvider = require("truffle-hdwallet-provider");
const MNEMONIC = 'my mnemonic words from metamask'

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // for more about customizing your Truffle configuration!
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    },

    ropsten: {
      provider: function() {
        return new HDWalletProvider(MNEMONIC, "ropsten.infura.io/v3/my-key")
      },
      network_id: 3,
      gas: 4000000      //make sure this gas allocation isn't over 4M, which is the max
    }
  }
};

So how can i solve this problem?


texts: Remix not importing all the necassary files

texts:
I am trying to use the ERC20PresentMinterPauser contract from openzeppelin in remix but Remix is not importing all the files that are necessay!
The code I pasted in a .sol file is given below
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol";

What can be done to get all the files from github to remix for this to compile?


texts: How to charge all gas fee to a General Master Wallet

texts:
We are currently developing a blockchain platform that deals with sending of tokens from users to users, and as you know, ETH is required as a gas fee to be paid for any ERC20 token transfer from a Wallet.

But we don't want our users to pay this gas fee when sending tokens to each others, instead we want all these gas fee to be charged to a general 'Master Wallet’.

Our team has been having problems in developing a master wallet that pays gas charges for all child-wallet under it. Is this something anyone can help us with?

We would appreciate any help we get.

Thanks.


texts: How to get signature parameters from a transaction?

texts:
In my application I have to manually verify certain transaction signatures on the ethereum blockchain. Atm I am running geth and parity nodes and query transaction information via the rpc interface but it seems to be missing the ecdsa sig params.

From what I see, both geth and parity do not seem to expose signature parameters via the rpc interface like bitcoind does (it exposes the input and output scripts with get_rawtransaction). Is there an easy way to access them or do both geth and parity strip signatures in their local blockchain caches once signatures were verified for some reason? I am wondering because even ecp only seems to parse the raw transactions from blocks into txhash,rcpt,from,amount,price,gaslimit,payload (=data), blockid missing the signature params (or are they hidden in the payload field?).

What would be an option to get complete raw transaction information as if I'd just signed it with web3.eth.sign()?