texts: Could not transfer ether to smart contract

texts:
I'm testing one smart contract and need to send some ether to it, but when I try to do it I get error "It seems this transaction will fail. If you submit it, it may consume all the gas you provide". Could anybody suggest how to solve it?

Here is source code, base Oraclize class omitted cause I think it does not matters but still lot of Oraclize related stuff, sorry:

contract AdContractTest3 is usingOraclize {
    string public calc_script_base_url = "http://5.45.80.18/ad-price-calculator.php";
    uint public total_price_in_szabo;
    uint public szabo_per_placement;
    uint public szabo_per_view;
    address public client;
    address public blogger;

    event LogPriceUpdated(string price);
    event LogNewOraclizeQuery(string description);
    event LogNotEnoughEther();
    event LogEtherSent();
    event LogOnDeposit(address sender, uint amount);

    function AdContractTest3(uint price_in_szabo_per_placement, uint price_in_szabo_per_view, address client_address, address blogger_address) public payable {
        szabo_per_placement = price_in_szabo_per_placement;
        szabo_per_view = price_in_szabo_per_view;
        client = client_address;
        blogger = blogger_address;
    }

    function strConcat(string s1, string s2, string s3, string s4, string s5, string s6, string s7) internal pure returns (string)
    {
        return strConcat(strConcat(s1, s2, s3, s4), strConcat(s5, s6, s7));
    }

    function __callback(bytes32 myid, string result) public {
        require(msg.sender == oraclize_cbAddress());
        myid; // Silence compiler warnings
        total_price_in_szabo = parseInt(result);
        LogPriceUpdated(result);
    }

    function updatePrice(string video_url) public payable returns(string) {
        if (oraclize_getPrice("URL") > this.balance) {
            LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
        } else {
            var url = strConcat(calc_script_base_url, "?price_in_szabo_per_placement=", uint2str(szabo_per_placement), "&price_in_szabo_per_view=", uint2str(szabo_per_view), "&video_url=", video_url);
            oraclize_query("URL", strConcat("json(", url, ").total_price_in_szabo"));
            var log_msg = strConcat("Oraclize query '", url, "' was sent, standing by for the answer...");
            LogNewOraclizeQuery(log_msg);
        }
    }

    function payForWork() public {
        if (total_price_in_szabo * 1 szabo > this.balance) {
            LogNotEnoughEther();
        } else {
            blogger.transfer(total_price_in_szabo * 1 szabo);
            LogEtherSent();
        }
    }

    function onDeposit() public payable {
        LogOnDeposit(msg.sender, msg.value);
    }
}


texts: How to create a consortium network on geth?

texts: I have a dapp which is build using truffle.i want to create a consortium network and connect that with my truffle dapp? is that possible and how can i do that?


texts: I'd like to be able to execute an ETH transaction on chain based on a change in price of an asset.  This seems like a job for an Oracle, but aside from an app that's not on chain that watches for price changes, I'm not sure how to go about doing this the "block chain way."


texts:
For a school project I am making an ethereum Dapp on ionicwith banck-end on Nodejs. I Cannot find a way to use metamask on my mobile Dapp because it is not a web3 dapp. Any suggestions, is there any other options besides metamask ?
I've searched all over the web but could not find anything relevant to my situation.


texts: Is it possible to see the event log when using eth_call?

texts:
I want to perform a transaction locally (with the call method in web3 which perform a eth_call RPC call). It returns only the return value of the function called and I want to see the event log.

I considered sending a transaction with a 0 gas price, then reading logs from the transaction receipt. According to parity documentation :

  Note That the receipt is available even for pending transactions.

In my case the receipt is null until the transaction is mined, so that solution does not work.

To sum up my question, how to read the event log when executing a transaction locally ?


texts:
How do information sites like CoinMarketCap get tokens/coins trading volume?
Is it just from exchanges?
Do they take into account tokens transferred between wallets and smart contracts? Are those transactions considered trading?


texts: Parity RPC eth_newFilter not returning pending events

texts:
I'm trying to create a listener for new pending TXs on the network using Parity RPC's eth_newFilter method.

I'm sending the request using the following parameters, expecting to get pending transactions back when I call eth_getFilterChanges. However, I only get transactions as they are mined into a block.

Shouldn't this give me pending transactions (not yet mined)? Any idea what I'm doing wrong?

parameters_to_send = {
    "jsonrpc":"2.0",
    "method":"eth_newFilter",
    "params":[{
        "fromBlock": "pending",
        "toBlock": "pending"
    }],
    "id":1
}

I know there is a method for eth_newPendingTransactionFilter, but the data returned using a custom eth_newFilter is a bit better for my purposes.

Thanks!


texts: What is "could not unlock signer account" error when sending tokens to an ERC20 token contract using transferFrom()?

texts:
I'm using testrpc -u 0 -u 1 to start the local testnet, deploying my OpenZeppelin Standard Token smart contract with truffle migrate, and using web3 in my dapp.

As the user, I perform an action that calls approve(myContractAddress, amount, {from: myAddress). Then I perform another action that calls transferFrom(myAccount, myContractAddress, amount, {from: myContractAddress}) gives this error:

Error: could not unlock signer account
    at StateManager.queueTransaction
(/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:84996:21)
    at GethApiDouble.eth_sendTransaction
(/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:85804:14)
    at GethApiDouble.handleRequest (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:85620:10)
    at next (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:113129:18)
    at VmSubprovider.handleRequest (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:113829:12)
    at next (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:113129:18)
    at GethDefaults.handleRequest (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:85935:12)
    at next (/usr/local/lib/node_modules/ethereumjs-
testrpc/build/cli.node.js:113129:18)
    at FilterSubprovider.handleRequest
(/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:113388:7)
    at next (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:113129:18)

Essentially I want to have the contract transfer my funds to itself, on my behalf. It is almost working except for this error!

This would work:
transferFrom(myAccount, someOtherAccount, amount, {from: someOtherAccount}), but I need to be able to send to a contract.


texts: Get contract address from contract creation transaction

texts:
I'm trying to detect the creation of new ERC20 tokens.  My current idea is to scan all transactions in a block, and look for transactions where the "to" address is null.  This is normally contract creation transactions.
The problem that I'm having currently is how to get the newly created contract address from the contract creation transaction details?  If I can get the newly created contract address, I can then check if the contract adheres to ERC20 standard and then parse it as ERC20 contract.
I normally get transaction details using the following code:
let tx = await web3.eth.getTransaction('0x46af5890c8ab51af8eeba255ad920f74e258218bdfd28951b6795fb0afa61ee6');


texts: Refund function in solidity smart contract not working

texts:
I'm trying to implement a HelloWorld smart contract to change 1:1 Ether into a Token (stored in balances) and vice versa - I can call the pay function and everything works out nicely but the refund function doesn't work. Although ethers and tokens (stored in balances) are deducted from the contract, ethers are not sent back to the caller when refund is called - so they disappear. I'm working on the Reopten test net:

So as you can see the contract currently has 0.0088 ether because I've called refund twice with 0.0011, but as you can see the contract doesn't send out ether - so they disapear

https://ropsten.etherscan.io/address/0xaa394f1d64d6193b3189826a7b58e40a56703227

You can also see that there have been two calls to refund from an address where no ethers have been transferred to...

https://ropsten.etherscan.io/address/0x90a700898b596115c03bb9b99b639ad811d792ff

What am I doing wrong?

pragma solidity ^0.4.23;

contract EtherSwap {
mapping(address => uint) balances;

/* Define variable owner of the type address */
address owner;

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

function() public payable {
    balances[msg.sender] += msg.value;
}

function query() public constant returns (uint balance) {
    return balances[msg.sender];
}

function query(address id) public constant returns (uint balance) {
    return balances[id];
}

function refund(uint amountRequested) public {
    require(amountRequested > 0 && amountRequested <= balances[msg.sender]);

    balances[msg.sender] -= amountRequested;

    msg.sender.transfer(amountRequested);
}

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

}

RAW refund transaction:

  {"nonce":"0x19","gasPrice":"0x098bca5a00","gasLimit":"0x923a","to":"0xAA394f1d64D6193B3189826A7B58e40a56703227","value":"0x00","data":"0x278ecde10000000000000000000000000000000000000000000000000003e871b540c000","chainId":3}

Signed refund transaction:

  {"from":"0x90a700898b596115c03bb9b99b639ad811d792ff","nonce":"0x19","gasPrice":"0x098bca5a00","gasLimit":"0x923a","to":"0xAA394f1d64D6193B3189826A7B58e40a56703227","value":"0x00","data":"0x278ecde10000000000000000000000000000000000000000000000000003e871b540c000","chainId":3}

ABI:

  [{"constant":false,"inputs":[{"name":"amountRequested","type":"uint256"}],"name":"refund","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"query","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"kill","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"id","type":"address"}],"name":"query","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]


texts:
I call a contract over geth RPC using sendTransaction and get a transaction hash. Is there a way to verify over the geth RPC interface if this transaction failed due to a VM abort (Solidity throw statement, similar)?

The transaction receipt doesn't seem to offer any variables telling this.


texts: Web3: How to get price of ETH at time of transaction?

texts:
Example transaction:
https://etherscan.io/tx/0x2edfb0bf11355a48bbb93c567a8c6de39f80de515ceb8b26dbcbf4729bd8a217

In code given a transaction object, how would I fetch the price of ETH at the time of the transaction?

Using the example transaction, it's sending 4.1 ETH, at an estimate value of $4253.18. How did it know that the price of ETH was $1037 at the time?


texts: Can we upload Keystore file to Metamask?

texts: I created a geth Full Node. Through this I created a new account and a Keystore file was created. Can I import this Keystore file to Metamask so that I can transfer funds?


texts: How do i retrieve Eth from a contact that i created?

texts:
New to blockchain.. havent a clue.. I managed to create a new contract with Eth. I moved money from MyEtherum Wallet to Metamask and into a contract, somehow? I have no coding experience but need someone to help with getting my Eth back out of the contract.. From looking around myetherwallet i found a ABI/JSON interface and now wondering if this is where the withdrawal code goes. If so anyone any idea what it might be? I created the contract on mainnet.
Is this the correct way to withdraw Eth from a contract to a wallet?
Im new at this.. have no clue.
Using 'MyEtherwallet' and 'Metamask' Also have the address of the contract.
Many thanks


texts:
I thought that I had an error similar to this one, that the default account was not set (I was getting method undefined errors for all methods called in my contract).I've set it both in the geth console

eth.defaultAccount = eth.accounts[0]

as well as the js code using geth:

web3 = new Web3(new Web3.providers.HttpProvider(`http://${gethServer.host}:${gethServer.port}`));
/*
    Strange bug. Need to specify the account the transactions are made from.
*/
web3.eth.defaultAccount = web3.eth.accounts[0];

When calling the methods of this contract:

contract C {

     uint[] numbers;

     function initNumbers() {
         numbers.push(1);
         numbers.push(2);
     }

     function stateChanger(uint a) {
         numbers.push(a);
     }

     function getNumber(uint index) returns (uint) {
         if(index >= numbers.length)
            return 0;
         else
            return numbers[index];
     }
}

I get the following output in the geth console:

> c.initNumbers({from:web3.eth.accounts[0],gas:4000000000});
"0x76a1882128d64d94a7bad34e656cd83d57d2a1aefc51b99ba5893f8521a1a79e"
> c.stateChanger(3, {from:web3.eth.accounts[0],gas:400000000});
"0x1b7d5ef5d19a553af756790796a094d2ba213454ab056b7696e2f18e636d8ffc"
> c.stateChanger(4, {from:web3.eth.accounts[0],gas:400000000});
"0xd342a49323b7280e1954a9d33ac9bc457a3015768d5059801d2edf1d16585b9b"
> c.getNumber(0);
"0x31295a2a7ea20cee58e6a144039ae46b835110583b6d1b9517228627eb50999c"
> c.getNumber(1);
"0xce4dba582f37c72d58c767a2b9371a9a8ddbc1e63bc6c96eb5f61cc779168f64"
> c.getNumber(3);
"0x065bd993c4c8e86b2046a53f626619020ad550958dca955a40c839bbc9a1d0c7"

Why does geth return transaction hashes instead of integers as defined by the contract interface? Is it broken?


texts: Is there a startup option in Mist to specify a blockchain folder?

texts:
I'd like to move my blockchain folder (Windows) from C to E drive. Can I start Mist with an option to use a different folder for blockchain data? If not, can I just make a BAT file with

geth.exe --datadir "E:\Ethereum\data\"
Ethereum-Wallet.exe

and Mist will use that folder?

Why the hell the Mist devs didn't support the same command line option in Mist?


texts: Invalid shares? using Dualminer through Nanopool

texts: So, i have just started using Dual Miner V8.0 and i have been in email contact with nanopool support and it seems i am mining alot of invalid shares. In my code i am not seeing any notification for an invalid share only a green text pop up when i do indeed find shares. I have update my GPUs drivers to its most recent update drivers (gpu is ,MSI GAMING Radeon RX 480 GDDR5 4GB CrossFire VR Ready FinFET DirectX 12 Graphics Card (RX 480 ARMOR 4G OC), driver Radeon Software Crimson ReLive Edition 17.2.1), i also have corrected any abnormalities in my config.txt file and epool.txt file. I have registered 1 single share on nanopools website but since have not had another one pop up. EVEN THOUGH i have logs stating ive found over 200 shares now running my computer periodically over the last two days. If anyone could shed some light on why i am not getting any shares to validate it would be much appreciated. if pictures are needed i can post what ever else in comments.


texts: Ganache launch unexpected token in JSON: Syntax Error

texts:
After launching Ganache on my Windows 10 laptop. Ganache was working fine but one day, while running Ganache, my laptop shut down because of some problem with the battery. After opening the laptop again, this error came up and  I was asked to relaunch Ganache. But relaunching it didn't work.
SyntaxError: Unexpected token I in JSON at position 0
    at JSON.parse (<anonymous>)
    at JsonStorage_JsonStorage.getFromStorage (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\json\JsonStorage.js:18:23)
    at JsonStorage_JsonStorage.get (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\json\JsonStorage.js:30:12)
    at WorkspaceSettings_WorkspaceSettings._getRaw (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\settings\Settings.js:23:26)
    at WorkspaceSettings_WorkspaceSettings.get (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\settings\Settings.js:18:22)
    at flatMap (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\workspaces\WorkspaceManager.js:26:41)
    at Array.flatMap (<anonymous>)
    at WorkspaceManager_WorkspaceManager.enumerateWorkspaces (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\workspaces\WorkspaceManager.js:17:10)
    at WorkspaceManager_WorkspaceManager.bootstrap (C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\types\workspaces\WorkspaceManager.js:61:10)
    at C:\Program Files\WindowsApps\GanacheUI_2.4.0.0_x64__5dg5pnz03psnj\app\resources\app.asar\webpack:\src\main\index.js:230:22


texts:
I'm testing my smart contract on ropsten and I have written an async function that lets me send TRANSACTION transactions from TRANSACTION different accounts. For some reason when TRANSACTION > 20 i get caught in the catch statment with a gas exceeds allowance error and i can't figure out why. I have similarly written a function to fund an arbitrary amount of accounts with eth. Litterally all that is done on the smart contract when invoking instance.methods.addSubmission... is push a uint256 into an array in a mapping(uint256 => uint256[])
async function multipleTx() {
  let accounts = await web3.eth.getAccounts()
  console.log('Issuing Transactions...')
  let totalGasUsed = 0
  const promisesArr = []
  const sendBlockNumber = await web3.eth.getBlockNumber()
  const sendTimeStamp = Date.now()

  for (let i = 0; i < TRANSACTIONS; i++) {
    console.log('account', i, 'is', accounts[i])
    promisesArr.push(
      instance.methods.addSubmissionNoCheck(1, 139).send({
        from: accounts[i],
        gasPrice: 10000000000,
      })
    )
  }
  await Promise.all(promisesArr)
    .then(async (receipts) => {
      let lastBlock = receipts[0].blockNumber
      receipts.forEach((receipt) => {
        totalGasUsed += receipt.gasUsed
        lastBlock =
          receipt.blockNumber > lastBlock ? receipt.blockNumber : lastBlock
      })
      await outputResults(
        sendTimeStamp,
        totalGasUsed,
        sendBlockNumber,
        lastBlock
      )
    })
    .catch((error) => {
      console.log('multipleTX():', error)
    })
}

console output:
multipleTX(): Error: gas required exceeds allowance (8000029) or always failing
transaction
    at C:\Users\Diddi\Documents\mjukvaruteknik\examensarbete\tqdt33\node_modules
\@truffle\hdwallet-provider\node_modules\web3-provider-engine\subproviders\provi
der.js:18:36
    at XMLHttpRequest.request.onreadystatechange (C:\Users\Diddi\Documents\mjukv
aruteknik\examensarbete\tqdt33\node_modules\web3-providers-http\src\index.js:96:
13)
    at XMLHttpRequestEventTarget.dispatchEvent (C:\Users\Diddi\Documents\mjukvar
uteknik\examensarbete\tqdt33\node_modules\xhr2-cookies\xml-http-request-event-ta
rget.ts:44:13)
    at XMLHttpRequest._setReadyState (C:\Users\Diddi\Documents\mjukvaruteknik\ex
amensarbete\tqdt33\node_modules\xhr2-cookies\xml-http-request.ts:219:8)
    at XMLHttpRequest._onHttpResponseEnd (C:\Users\Diddi\Documents\mjukvarutekni
k\examensarbete\tqdt33\node_modules\xhr2-cookies\xml-http-request.ts:345:8)
    at IncomingMessage.<anonymous> (C:\Users\Diddi\Documents\mjukvaruteknik\exam
ensarbete\tqdt33\node_modules\xhr2-cookies\xml-http-request.ts:311:39)
    at IncomingMessage.emit (events.js:228:7)
    at endReadableNT (_stream_readable.js:1185:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:21)

smart contract function
mapping(uint256 => uint256[]) public submissions;

function addSubmissionNoCheck(uint256 key, uint256 timeAtLocation) external {
  submissions[key].push(timeAtLocation);
}

Update:
I have removed the gas limit specification as per my own solution below and instead and overfunded the accounts and it seems to work now. I've ran multiple times doing 20 transactions from 20 different accounts. However i feel like if the problem was insufficent funds in the accounts i should receive the Insufficient funds for gas * price + value error.


texts: Prevent Remix from recompiling in real time?

texts:
How do I prevent online Solidity Compiler called "Remix" from recompiling my code real-time?

When using features like Oraclize, the recompilation takes long and happens all the time, making the overall IDE non responsive.


texts: Ethereum:Smart Contract: How much ether should I send initially

texts:
There is an option to send Ether while deploying smart contract(creating ERC20 token)

How much Ether should one send to be able to successfully do transactions with ERC20 Token ?

Is there any relation or formula to calculate the amount of Ether that you need to send on the basis of total supply ?

For Example:- You have created one ERC20 Token and initializes total supply with 9999999000000000000000000.

Then, how much ether you have to send ?


texts:
I have the following function:

pragma solidity ^0.4.18;

contract PromoContract {
      uint256 public promoCreatedCount;

      function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {
        require(promoCreatedCount < 5000);

        address personOwner = _owner;
        if (personOwner == address(0)) {
          personOwner = cooAddress;
        }

        if (_price <= 0) {
          _price = startingPrice;
        }

        promoCreatedCount++;
        _createPerson(_name, personOwner, _price);
      }
}

I started the following Test Contract:

pragma solidity ^0.4.18;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/PromoContract .sol";

contract TestCryptoSportsToken {
    PromoContract promoContract = PromoContract (DeployedAddresses.PromoContract ());
    //check for events

    // Testing the adopt() function
    function testCreatePromoPerson() public {
      promoContract.createPromoPerson("0xf7ca47eabf0e98af942fa45a5e8cdc05b7100eb4", "Test Person", 1);

//check for ?
    }
}

Any suggestion how to test the contract function createPromoPerson. I appreciate your replies!


texts: How can I inject a custom web3 provider into the drizzle app when using Nightwatch e2e tests?

texts:
I have setup a basic e2e test with a Drizzle VueJS app. It appears that when the tests run drizzle uses the fallback option for connecting to the blockchain using web sockets (ws://127.0.0.1:8545).

I want to use a custom PrivateKeyProvider for the tests so that the test run will commit transactions to the blockchain without running out of gas.

How can I tell drizzle to use this custom provider when I run the e2e Nightwatch tests? I've tried setting window.web3 using the following browser execute script but Drizzle continues to use the direct web sockets fallback option.

// In the Nightwatch JS tests/e2e folder:
browser.init();

browser.execute(function() {
  return window.web3;
}, [], function(result) {
  const provider = new PrivateKeyProvider(
    "ACCOUNT_PRIVATE_KEY",
    "http://localhost:8545"
  );
  result.value = new Web3(provider);
})

browser.waitForElementVisible('#app')

// Fill out a form and submit to blockchain
// Get out of gas error because drizzle is still using the fallback option
// and not the custom PrivateKeyProvider as needed

Any help would be greatly appreciated.


texts: I do not see my testnet transactions and Ether

texts:
I installed MetaMask, connected to Ropsten TestNet, clicked "Buy", then clicked "Ropsten Test Faucet".  There, I clicked "request 1 ether from facuet", waited several seconds, and saw a transaction id "0xb3840f20b3c9b781347edf7e0d1b633fb60fa8a5a4808032db224e9deb33ae9a".
But, clicking the link brought me to this page which says "Unable to locate Transaction entry". Indeed, even after waiting several hours and clicking several more times, my balance (as I see in MetaMask) is still 0.

I tried another faucet but it did not help - my balance in Ropsten TestNet is still 0 and I see no transactions. What am I doing wrong?


texts:
The model that contracts can only accept and process data, instead of also being able to retrieve data from the Internet, seems limiting (even if not, it's less direct).
If a concern is that data or the Internet is unreliable, couldn't a contract be programmed to handle such cases?

Are there fundamental technical limitations that led to Ethereum contracts not being able to "access the Internet" directly?


texts:
I have created a test token and deployed it on the ropsten test network. I have the full balance in my ether wallet. My question is how can I transfer this token to other wallets? How can I configure the token on other wallets using the rospsten test network?
Thank you


texts: getting error web3.toWei is not a function when testing

texts:
i have installed web3 latest version 1.0.0-beta.36. i am using helper libraries which i used from openzeppelin when i am running the test cases using truffle test it shows error as

  TypeError: web3.toWei is not a function

it's not just web3.toWei also i am also not able to use bignumber .i don't know why i am not able to use helpers from openzeppelin
this is the file with the name of ether.js in helper folder

function ether (n) {
  return new web3.BigNumber(web3.toWei(n, 'ether'));
}

module.exports = {
  ether,
};

and for big number the code which shows error is

require('chai')
  .use(require('chai-bignumber')(BigNumber))
  .should();

const RefundableCrowdsale = artifacts.require('RefundableCrowdsaleImpl');
const SimpleToken = artifacts.require('SimpleToken');

contract('RefundableCrowdsale', function ([_, wallet, investor, purchaser, anyone]) {
  const rate = new BigNumber(1);
  const goal = ether(48);
  const lessThanGoal = ether(45);
  const tokenSupply = new BigNumber('1e22');

i have installed chai-bignumber and web3


texts: Drizzle - accessing array items from a getter

texts:
In my contract I have a getter function that returns a full array of addresses:

function getDeployedCampaigns() public view returns(address[] memory) {
    return deployedCampaigns;
}

Using drizzle I have the following code for my component that returns the content of that array:

import React, { Component } from "react";

class ReadCampaigns extends Component {

  state = { dataKey: null};

  componentDidMount() {
    const { drizzle, drizzleState } = this.props;

    const contract = drizzle.contracts.CampaignFactory;

      const dataKey = contract.methods["getDeployedCampaigns"].cacheCall({from: drizzleState.accounts[1], gas: 3000000});

    this.setState({ dataKey });
  }

  render() {
    const { CampaignFactory } = this.props.drizzleState.contracts;

    const campaigns = CampaignFactory.getDeployedCampaigns[this.state.dataKey];
    console.log(campaigns);
    return <p> Campaigns: {campaigns && campaigns.value}</p>;
  }
}

export default ReadCampaigns;

And the following:

console.log(campaigns);

returns this to the console:

{args: Arguments(0), fnIndex: 3, value: Array(2)}
args: Arguments [callee: (...), Symbol(Symbol.iterator): ƒ]
fnIndex: 3
value: Array(2)
0: "0x6aA54653EEE943cb0a9DF41ee890A9c25f8b9210"
1: "0x2Fc343d40c0a643B30401A0A1788ec6F55e0EdD0"
length: 2
__proto__: Array(0)
__proto__: Object

Now, my expectation was that I would be able to map through campaigns.value, however:

console.log(campaigns.value)

returns undefined.

Seems like I am missing something, because the following statement:

{campaigns && campaigns.value}

produces a list of all addresses as expected, however they are concatenated.

Could somebody kindly explain what I am missing in my thinking process?
Thanks


texts: Can I put the inline assembly code as function argument string?

texts:
Assume there is an example as below:
pragma solidity >=0.4.11 <0.6.0;

contract C {
    uint b;
    function f(uint x) public view returns (uint r) {
        assembly {
            r := mul(x, sload(b_slot)) // ignore the offset, we know it is zero
        }
    }
}

Can I move the "r := mul(x, sload(b_slot))" as an input string of a function?
something like
pragma solidity >=0.4.11 <0.6.0;

contract C {
    uint b;
    function f(uint x, string memory assembly_code) public view returns (uint r) {
        assembly {
            string_to_assembly_code(assembly_code);
        }
    }
}

Call the function like C.f(3, "r := mul(x, sload(b_slot))")
Because I cannot determine what calculation method I would use when deploy the contract, I would like to send the required calculation formula to the contract code for simple calculation. Is it possible to do it?


texts: Downloading Mist Chaindata to a New Storage Device

texts:
The computer I am working on has an SSD and HDD. The Chaindata was originally set to download to the SSD, but the SSD has run out of storage. The computer is running Mist; how can I either

(1) move the entire Mist directory to the HDD or

(2) direct the Chaindata to specifically download to the HDD?


texts: What makes the blockchain immutable in Proof-of-Stake?

texts: In Proof-of-Work, it's difficult to edit/delete data on the blockchain because of the millions of hashes performed before generating a block. It would be impossible for a single attacker to have 51% of the computational capacity of the whole network which makes it difficult for him/her to tamper with the data. How is immutability achieved in Proof-of-Stake?


texts: How to bypass account unlock prompt in geth console private testnet

texts:
How to bypass account unlock in private testnet, i want to transfer randomly between address.
Is this possible, if yes how?

I am looking forward to bypass the prompt in console so that i can transfer to and fro by account index.


texts: Quorum how to decode result returned by eth_getQuorumPayload api?

texts:
I've read the post How to get decrypted transaction data in quorum?

I followed the api document and got the result by calling eth_getQuorumPayload

curl -H "Content-Type: application/json" -X POST http://127.0.0.1:22000 --data '{"jsonrpc":"2.0", "method":"eth_getQuorumPayload", "params":["0x0904cbd975e6fd2444c6f029e951be0af68cf60af603070a561b46d683d754a08a0986c842b7d9468cc2be05c9e7afcab972ea3034ac48aaebb032629e6970cf"], "id":67}'

Result:

{"jsonrpc":"2.0","id":67,"result":"0x60fe47b10000000000000000000000000000000000000000000000000000000000000010"}

How to decode "0x60fe47b10000000000000000000000000000000000000000000000000000000000000010" into a readable string?
I set the 'storedData' in private contract to 16, so I got '0x10' in the last byte in result, is it right?
What does the first few bytes '0x60fe47b1' mean?


texts: Im working on something and I need to get a price from uniswap for some tokens eg eth or chainlink but from uniswap router contract, anyone knows how to calculate the price.


texts: Change a Checksum Address to Its Normal Hex Value

texts: I know there are functions to convert hex address -> checksum address, but are there any to convert checksum address -> hex address?


texts:
I'm looking to run a private Ethereum blockchain. But I wanted to check first, is it possible for an account to hold multiple custom tokens?

For example, can an account hold tokens that denote very simple points(e.g. 100 tokens = 100 points), and another token that is unique (e.g. collectable once only). This is an example with 2 kinds of tokens, but there could be more.


texts: Need some help with Solidity Contract error

texts:
Warning! Error encountered during contract execution [Bad instruction]

Here's the solidity code. Can anyone please help me find the problem in the code?

https://ropsten.etherscan.io/address/0xa2ba735e2ff51fbaf9a3e12543bcd86be40e3a3d#code

Remix doesn't give any error while creating contract. The contract is deployed without any problem. When I try to send ether to get tokens it displays the error; Warning! Error encountered during contract execution [Bad instruction]


texts: join an array of strings and map, filter, reduce functions in solidity

texts: I want to concatenate an array of strings into a single string using solidity, just like the array join function in javascript and python. Also I want to do map/filter/reduce functions in an array. Is there any cost-effective methods available?


texts: GETH Error on personal_sendTransaction/eth_sendTransaction

texts:
Been trying to use personal_sendTransaction / eth_sendTransaction for days but I cannot get pass this error. I have tried different combination of gas/gasprice/value but I cannot make it work.

PS. My Go ETH Server is fully synced

Last combination I tried:

"gas":"0x51DAC207A000" // 90000000000000 Wei
"gasPrice":"0x218711A00" // 9000000000 Wei
"value":"0x38D7EA4C68000" // 1000000000000000 Wei


texts: i cannt confirm request in Parity I Can't locate local key file asked by parity to sign a transaction

texts:
How to confirm request in Parity
I have POA chain from this tutorial https://github.com/paritytech/parity-poa-tutorial
and as you can see it ask me to select local key and click confirm


texts: Failed to install Truffle on MacOS Mojave

texts:
I am currently really struggling in getting Truffle up and running. I am running MacOS Mojave and have Node (v.10.16.0) and NPM (6.9.0) and have tried

  npm install -g truffle

and have gotten:

  npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules

  npm ERR! path /usr/local/lib/node_modules

  npm ERR! code EACCES

  npm ERR! errno -13

  npm ERR! syscall access

  npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

  npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']

  npm ERR!   stack:

  npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',

  npm ERR!   errno: -13,

  npm ERR!   code: 'EACCES',

  npm ERR!   syscall: 'access',

  npm ERR!   path: '/usr/local/lib/node_modules' }

  npm ERR!

  npm ERR! The operation was rejected by your operating system.

  npm ERR! It is likely you do not have the permissions to access this file as the current user

  npm ERR!

  npm ERR! If you believe this might be a permissions issue, please double-check the

  npm ERR! permissions of the file and its containing directories, or try running

  npm ERR! the command again as root/Administrator (though this is not recommended).

  npm ERR! A complete log of this run can be found in:

  npm ERR!     /Users/myname/.npm/_logs/2019-07-09T21_08_31_313Z-debug.log

And when I try

  sudo npm install -g truffle

I get:

  Password:

  npm ERR! path /usr/local/bin/truffle

  npm ERR! code EEXIST

  npm ERR! Refusing to delete /usr/local/bin/truffle: /Users/vikas/.nvm/versions/node/v9.11.2/bin/truffle symlink target is not controlled by npm /usr/local/bin

  npm ERR! File exists: /usr/local/bin/truffle

  npm ERR! Move it away, and try again.

  npm ERR! A complete log of this run can be found in:

  npm ERR!     /Users/robertocantu/.npm/_logs/2019-07-09T21_13_07_178Z-debug.log

If you know what I can do, please explain it as simple as possible. I am not too well versed in doing things in Terminal; I'm just trying to learn how to program smart contracts and I can't seem to even set up my computer to do so.


texts: How can I write a contract for non-financial transactions

texts:
I am using azure etehereum consortium blockcahin, As of now I have created a contract using solidity, which deals with transfer of ether from sender account to receiver account, but If I want to store a records which don't have any financial information `

  lets say inventory records where person X gives 2 keyboards to person Y

how can I store this transaction in ethereum blockchain and if this record is stored how can I retrieve this information


texts:
I am trying to create a smart contract or a combination of contracts thereof whereby one could set permissions to view variables that can be set in a contract on a private network.

Consider an account that has deployed a contract with 2 variables:

name
address

In addition lets say there are 2 functions:

getDetails
setDetails

These can be set by the caller of the contract calling the setDetails function which can set these variables to values passed in during the invocation of the function.
They can be fetched by getDetails which provides the values of these variables.

At this point, lets say an address has set the variables to

name = John
address = 1 Smith St.

How do I make sure other users/addresses calling the get function or reading the variables that have been set can retrieve the variable values only if they have the correct permissions?

I was following the Eris Industries based tutorials and noticed that permissions can be set for token transfer based on the fund manager example. Can this be extended to read variables that have been set by a previous interaction with the contract?


texts: How can I change the gas price or the gas limit when testing with pyethereum?

texts:
I've got some code that's ultimately destined to run on a private network. I'm testing it with the lovely pyethereum, doing things like:

from ethereum import tester as t

class testMyContract(TestCase):
   def setUp(self):
      self.s = t.state()
      code = open('../mycontract.sol').read()
      self.mycontract = self.s.abi_contract(code, language='solidity', sender=t.k0)

   def testExpensiveThing(self):
     mydata = [1000, 3000, 2000, 8000]
     self.mycontract.doExpensiveThing(mydata)

This blows up with

  File "/usr/local/lib/python2.7/dist-packages/ethereum/tester.py", line 201, in _send
    raise TransactionFailed()
TransactionFailed

It doesn't blow up when I pass it less data, and the contract looks quite expensive, so I'm assuming it's breaking because it's running out of gas. Is there a way to pass pyethereum some settings that will allow the transaction to use more gas?


texts: How to join strings with numbers in Solidity

texts:
I'd like to format url with number parameters as following:

http://someurl.com/?param1=100&param2=200

The problem is, it's always truncated after first number parameter e.g:

http://someurl.com/?param1=100. Not sure why.

In my contract I'm using strings library https://github.com/Arachnid/solidity-stringutils

contract code:

import "strings.sol";

contract MyContract {
    using strings for *;

    function bytes32ToString (bytes32 data) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        for (uint j=0; j<32; j++) {
            byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[j] = char;
            }
        }
        return string(bytesString);
    }

    function uintToBytes(uint v) constant private returns (bytes32 ret) {
        if (v == 0) {
            ret = '0';
        }
        else {
            while (v > 0) {
                ret = bytes32(uint(ret) / (2 ** 8));
                ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
                v /= 10;
            }
        }
        return ret;
    }

    function uintToString(uint v) constant private returns (string ret) {
        return bytes32ToString(uintToBytes(v));
    }

    function formatUrl(uint param1, uint param2) constant returns(string) {
        var parts = new strings.slice[](4);
        parts[0] = "http://someurl.com/?param1=".toSlice();
        parts[1] = uintToString(param1).toSlice();
        parts[2] = "&?param2=".toSlice();
        parts[3] = uintToString(param2).toSlice();

        return "".toSlice().join(parts);
    }
}

So calling formatUrl(100, 200) returns "http://someurl.com/?param1=100"

If I changed function like this:

function formatUrl(uint param1, uint param2) constant returns(string) {
        var parts = new strings.slice[](4);
        parts[0] = "http://someurl.com/?param1=".toSlice();
        parts[3] = uintToString(param1).toSlice();
        parts[1] = "&?param2=".toSlice();
        parts[2] = uintToString(param2).toSlice();

        return "".toSlice().join(parts);
    }

I get output: "http://someurl.com/?param1=&?param2=200"

It always ends after inserting first number converted to string.


texts: Why a length-1024 string of RLP encoding is \xb9\x04\x00?

texts:
In the Ethereum wiki RLP page,

  If a string is more than 55 bytes long, the RLP encoding consists of a single byte with value 0xb7 plus the length in bytes of the length of the string in binary form, followed by the length of the string, followed by the string. For example, a length-1024 string would be encoded as \xb9\x04\x00 followed by the string. The range of the first byte is thus [0xb8, 0xbf].

First of all, how 'dog' is over 55 bytes in python3?
I test 'dog' and python 3 show me it is 56 bytes so I can understand 'dog' is 0x83. The funny thing for me is cat&dog is still 56 bytes.

The second thing is, in python3, len('string...') = 1024 shows 1080 bytes. I have no idea how it encoded to \xb9\x04\x00.

Could you explain how it becomes \xb9\x04\x00?


texts: Syncing filled all my space, where is the data and how do I remove everything as clean as possible?

texts:
I'm running geth on a distant linux Ubuntu machine, I have a total of 12Gb disk space, I thought that would be enough, but it wasn't. I only had the minimal LAMP settings, I installed Geth with these instructions, (I didn't check then but I'm not sure it took that much space). I started syncing and tried installing solC at the same time, and I reached size limit.

This is more of an open question because I can't seem to find convincing answer about WHERE the files are located when I run geth console or geth --testnet console. The chaindata folders are way too small, the whole .ethereum directory is only 2.1Gb. What is the difference between .ethereum/chaindata and .ethereum/geth/chaindata ?

Bottomline is is there plan of the geth file architecture for linux ? It seems to be everywhere and I have no idea how to delete everything. I'd also like to know why /usr/ got filled 5 Gb while all the blockchain data is in /<username>/.ethereum.


texts: How to use local reference type storage variable in Solidity 0.5.0

texts:
I'm trying to understand value type and reference type concept in Solidity as per new changes. I'm trying understand local reference types with following example.

pragma solidity ^0.5.0;

contract Locations {

  function doSomething() public  {

    uint[] storage localArray;

  }
}

It gives me an error of array initialization. However after doing something like uint[] storage localArray = new uint[]; (which might also wrong) I found strange error

  Type function (uint256) pure returns (uint256[] memory) is not
  implicitly convertible to expected type uint256[] storage pointer

Any thought?


texts: Can't access swarm 8500 port from outside

texts:
I run local swarm node, so I can access it from localhost:8500. RPC request works fine locally.
But when I try to send requests to swarm rpc from another server, it is not accessible. I see port 8500 is only open locally.

Seems very strange. Are there any options to open it for the network?


texts: Issue with using "this" statement to get current value

texts:
I am trying to get the current value for my int variable counterforindex in the check function. However this doesn't seem to happen.

uint public counterforindex;

function Check(string hdata, string dtime) returns(bool out1)

{

    uint C1 = 0;
    C1 = this.counterforindex; //The error occurs here
......
}

The error is as follows

Error: Type function () returns (uint256) is not implicitly convertible to expected type uint256.
        C1 = this.counterforindex;

Any solution guys?????


texts:
I'm trying to encode some parameters and I've noticed all the encoders in the ABI project.
Essentially, I want the equivalent to abi.encodeParameter(type, value) in Nethereum? Is there an easy solution to obtaining this with the parameter attributes on the model?


texts: Please enable network time synchronisation in system settings geth windows 8.1

texts:
I'm learning Ethereum and following this tutorial to setup private chain on local machine.
All works fine, however when I try to run the node(s) it displaying me an warring Please enable network time synchronisation in system settings

If I run commands w32tm /resync and  net time /domain then warring goes away for time being, and then again comes unexpectedly.

Is there any permanent solution for that?


texts: What is considered as a "state" in ethereum?

texts:
I am reading the Ethereum white paper and I am frequently seeing this word "state". The meaning of
state is ambiguous to me.
What does it mean?

Does it mean the previous block?

Does it mean the current block?

Does it mean the entire blockchain?

Does it mean a single transaction(may be the last transaction?)?

Or any other thing?

Please help me. One example where he uses this word is:

I am currently reading this part of the white paper: "https://ethereum.org/en/whitepaper/#blockchain-and-mining"
Thank You!


texts: I need to test a DAPP which will run in Mist, but I don't want to run it in TestNet or MainNet, I want to run it in a ethereum-js testrpc instance.  Is it possible to do that?  Does anybody has tried it?


texts:
I have two different files which are Project1.sol and Project2.sol
Project2.sol is like:
import "./Project1.sol";

contract Project2{
    address newProject1Address =address(new Project1());
}

Project1.sol is like:
import "./Project2.sol";

contract Project1 is Project2{

}

I wanted to deploy Project1 in Project2.sol. And also I have been using a struct which is in Project2 from Project1.sol file. That's why I used "is" in the code.
However, I got an error which is "definition of base has to precede definition of derived contract." for this line: contract Project1 is Project2{
After I checked the error on the internet, there were solutions for two contracts and one file. However, I had two files.
I merged these two contracts in a file.
This is what I did:
pragma solidity >=0.7.0 <0.9.0;

contract Project2{

        Apple[] public applepies;

        struct Apple{
             string name;
             mapping (address => bool) applepie;
        }

        function createProject() external{

             address newProject1Address =address(new Project1(msg.sender));

             uint idx = applepies.length;
             applepies.push();
             Apple storage newProject = applepies[idx];
        }

    }

contract Project1 is Project2{
        address public creator;

        constructor (address creator1){

             creator= creator1;
        }

        function getDetails(uint index) public{
             Apple storage newv= applepies[index];
             //require(newv.applepie = msg.sender);
        }
}

Then, I could not deploy Project1 from Project2. When I do that, this the error which I got, "circular reference for contract creation(cannot create instance of derived or same contract)" on this part address newProject1Address =address(new Project1());
What should I do? What is your suggestions?


texts: Transactions are failing despite high gas fee?

texts:
So, I'm sending a transaction on Ethereum network using Metamask even with a high gas fee but the transactions are failing. I'm transferring ETH from Metamask to another wallet.
What I found strange is, usually the error message on etherscan.io displays:
Fail with error 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'

But in my case, it is just displaying "Fail" and no additional information.
Another strange thing I observed is, the "Input Data" field of the transaction on etherscan.io is empty.
I would expect the binary data corresponding to the transaction to be present there even if it failed.
It does give a warning message:
" Warning! Error encountered during contract execution [Out of gas] "
But I'm curious why the failed message doesn't have the details and the input data section is also empty.


texts: call wont work in order to update another contract's storage

texts:
Storage(variable n) of E won't get updated when I use call from contract D.

addressOfE = "0x13fac93069c10e977204b9b64502439740cbe46a"; //Contract E's address that exist on my private chain.

call does not update E's storage:

D.callSetN(addressOfE, 100); //I have waited transaction to be deployed.
D.getN(); //returns 0;
E.getN(); //returns 0;

delegatecall seems working:

D.delcallCfunc(addressOfE, 101);  //I have waited transaction to be deployed.
D.getN(); //returns 101;
E.getN(); //returns 0;

callcode seems working:

D.callcodeSetN(addressOfE, 102);  //I have waited transaction to be deployed.
D.getN(); //returns 102;
E.getN(); //returns 0;

[Q] What should I do to update E's storage by calling contract D's function? Is it possible?

I have tried the exact same tutorial on the following guide: https://ethereum.stackexchange.com/a/3672/4575

contract D {
  uint public n;
  address public sender;
  function callSetN(address _e, uint _n) {
    _e.call(bytes4(sha3("setN(uint256)")), _n); // E's storage is set, D is not modified
  }

  function callcodeSetN(address _e, uint _n) {
    _e.callcode(bytes4(sha3("setN(uint256)")), _n); // D's storage is set, E is not modified
  }

  function delegatecallSetN(address _e, uint _n) {
    _e.delegatecall(bytes4(sha3("setN(uint256)")), _n); // D's storage is set, E is not modified
  }
  function getN() constant returns(uint){
      return n;
  }
  function getSender() constant returns(address){
       return sender;
   }
}

contract E {
  uint public n;
  address public sender;
  function setN(uint _n) {
    n = _n;
    sender = msg.sender;
    // msg.sender is D if invoked by D's callcodeSetN. None of E's storage is updated
    // msg.sender is C if invoked by C.foo(). None of E's storage is updated
  }
  function getN() constant returns(uint){
      return n;
  }
    function getSender() constant returns(address){
       return sender;
   }
}

Thank you for your valuable time and help.


texts:
Browsing through the Ethereum docs I came across this modifier:

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

I am not familiar with usage of _. What does it mean in this context?


texts: Getting Method ID "Keccak hash" in Python

texts:
I am trying to derive the Method ID, the Keccak (SHA-3) hash, in Python so that I may call the functions of my contracts once they are deployed as detailed in the ABI documentation: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

This details that 0xcdcd77c0 should be the ID derived for the function with the signature baz(uint32,bool)

I have tried to replicate this using the python sha3 module (https://pypi.python.org/pypi/pysha3):

>>> import sys
>>> import hashlib
>>> import sha3
>>> s = hashlib.sha3_512()
>>> s.update(b"baz(uint32,bool)")
>>>s.hexdigest()
'f1bb0cbc152d49505684ee7d2a37a860af1820ff8052ed6b32eddd3d82f97e89b24aac5ef334f94474264795cb7672339aecfc2cd2dc1cd0b87adccada2e7bc1'

How can I get the first four bytes from this in the correct format to use as a method signature in a transaction? Converting this digest to hex doesn't seem to give the correct signature.


texts:
I'm trying to save some space so I tried a geth removedb and then a --fast resync.

But while browsing my .ethereum folder I saw this one which looks like a chaindata folder given its contents and is massive, 10Gb, what is its use ?

The geth removedb doesn't remove it, is it safe to delete it ?


texts: String validation solidity: alpha numeric and length

texts:
What is best practice in solidity for testing that an input string contains only alpha numeric characters and is not longer then x amount of chars?

   function testStr(string str) constant returns (bool){
        bytes memory b = bytes(str);
        if(b.length > 13) return false;

        for(uint i; i < b.length; i++){
            //test if is tring only contains 1234567890abcdefghijklmnopqrstuvwxyz and . char

        }

        return true;
    }


texts:
What is the significance of uncle rate?

Some Ethereum sites show an uncle rate in decimal, another shows the uncle count per 25 blocks.  If there are many or few uncles, how important is that to the network?  Are there "warning" signs that it suggests?


texts: eth_call to a constant field in contract returns "0x" on Rinkeby

texts:
I'm trying out Micro Raiden on Rinkeby testnet, but a call to 'token' field in a contract returns empty value (0x) when using infura.io directly or geth, but not on MEW connected to infura.io.

This fails: (I checked that 0xfc0c546a is correctly a hash of 'token()')

{
    "jsonrpc": "2.0",
    "method": "eth_call",
    "params": [
        {
            "data": "0xfc0c546a",
            "to": "0x568a0d52a173f584d4a286a22b2a876911079e15"
        },
        "latest"
    ],
    "id": 1
}

returns:

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": "0x"
}

But MEW connected to rinkeby via infura works as intended:

What could be wrong in the raw request?


texts: I recently started using TurboGeth and I have a question. Where does Turbo Geth store its data files?


texts:
I am very new to Solidity, and playing around with testrpc and truffle.

One of the thing I would like to do is the self-destruct a contract. Because I do wish to be able to remote my contract during development phase, until it is stable.

contract HelloWorld {
    function sayHello() public pure returns (string) {
        return ("Hello World!");
    }

    function kill()  public {
        selfdestruct(address(this));
    }
}

I am manage to call sayHello() and kill() using truffle console. But the self-destruct doesn't seem to do anything. I am still able to call sayHello().

Wish this question is not too newbie.


texts: Geth/Remix Error: gas required exceeds allowance or always failing transaction.How to solve this issue?

texts:
I have tried to deploy the example given in the following link(using remix and geth).While deploying, an error occurred in both geth and remix. And I found that the usage of "require" causes the problem.How to solve this issue without removing the "require"?

Smart contract Example


texts: Does web3.js have deserialization methods?

texts:
Looking at the code of web.js's utils.toHex():

/**
 * Auto converts any given value into it's hex representation.
 *
 * And even stringifys objects before.
 *
 * @method toHex
 * @param {String|Number|BigNumber|Object}
 * @return {String}
 */
var toHex = function (val) {
    /*jshint maxcomplexity: 8 */

    if (isBoolean(val))
        return fromDecimal(+val);

    if (isBigNumber(val))
        return fromDecimal(val);

    if (isObject(val))
        return fromUtf8(JSON.stringify(val));

    // if its a negative number, pass it through fromDecimal
    if (isString(val)) {
        if (val.indexOf('-0x') === 0)
            return fromDecimal(val);
        else if(val.indexOf('0x') === 0)
            return val;
        else if (!isFinite(val))
            return fromAscii(val);
    }

    return fromDecimal(val);
};

/**
 * Should be called to get hex representation (prefixed by 0x) of utf8 string
 *
 * @method fromUtf8
 * @param {String} string
 * @param {Number} optional padding
 * @returns {String} hex representation of input string
 */
var fromUtf8 = function(str) {
    str = utf8.encode(str);
    var hex = "";
    for(var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i);
        if (code === 0)
            break;
        var n = code.toString(16);
        hex += n.length < 2 ? '0' + n : n;
    }

    return "0x" + hex;
};

it returns a JSON serialized object when given an object but I can't seem to find an inverse function of fromUtf8(toHex()), the "unhex" function.

Does web3.js have one?


texts: Run "truffle test" command with auto set custom balances

texts:
I know how to set custom balance accounts on testrpc.
It could be like $ testrpc --account="0x627306090abab3a6e1400e9345bc60c78a8bef57,100000000000000000000".
But I don't figure out how to do that with "truffle test".
Are there any way to configure account balances?


texts:
I have a ticket system where you can buy some tickets to an given price. I want to set the amount to the method and send it back to the contract. For this I'm using metamask but I don't really get, how to set the price in my transaction.

import Web3, { utils } from 'web3'

this.contracts = context.drizzle.contracts
const web3 = new Web3(this.contracts.Ticketmarket.givenProvider)
const { abi, address } = this.contracts.Ticketmarket
this.Ticketmarket = new web3.eth.Contract(abi, address)

 buyTicket(id) {
const connectionID = id
this.stackId = this.contracts.Ticketmarket.methods.buyTicket.cacheSend(
  connectionID ,
  { from: this.props.accounts[0], value: (2,"ether")}
  )
}

and my funtion in the contract looks like this.

contract Ticketmarket is usingOraclize, Ownable{

struct Connection{
    string start;
    string destination;
    uint desttime;
    uint price;
    uint contingent;
    uint soldTickets;
    address[] buyers;
}

uint public connectioncount = 0;

mapping (uint => Connection) public connectionList;

Connection[] public connectionArray;

function buyTicket(uint _connectionID) public payable returns (uint, uint){
    Connection storage connection = connectionList[_connectionID];

    require(_connectionID < connectioncount && connection.soldTickets<connection.contingent && msg.value >= connection.price);

    connection.buyers[connection.soldTickets] = msg.sender;
    connection.soldTickets++;
    uint passengerNumber= (connection.soldTickets)-1;
    return (_connectionID, passengerNumber);
}

Trying mu code fail with:

takeEvery has been cancelled
utils.js:240
callListenForContractEvent has been cancelled
utils.js:240
takeEvery has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
getAccounts has been cancelled
utils.js:240
callCreateAccountsPollChannel has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
accountsSaga has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
accountBalancesSaga has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
takeEvery has been cancelled
utils.js:240
callCreateBlockPollChannel has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
takeEvery has been cancelled
utils.js:240
blocksSaga has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
drizzleStatusSaga has been cancelled
utils.js:240
takeLatest has been cancelled
utils.js:240
takeEvery has been cancelled
utils.js:240
web3Saga has been cancelled

uncaught at root
 at contractsSaga
 at takeEvery
 at callSendContractTx
 numberToHex

Could someone help me?


texts: General practice on updating contracts on a blockchain?

texts:
I have been searching around a lot but couldn't find the answer to this.

My understanding is that one a Ethereum blockchain, there should be one/multiple types contracts. Once live, those contract being immutable, no one can add another type of contract. If needing to create another type of contract, a fork should happen in the chain.

Is this true?

In such case, what would be the general recommendation on handling a business which has contracts that often change or that often has new products? Should we spin a new blockchain each time?


texts: How can I encapsulate data in ethereum transactions?

texts:
How can data be encapsulated in an Ethereum transaction so that the block chain can record state of external system? Am I limited to using JavaScript type protocols?

Are tools provided for storing this sort of data?


texts: What algorithm ethereum uses to generate wallets?

texts: The wallet string is the public key, while the private key is used to unlock the account and should be kept in secret. What algorithm is used to generate this pair?


texts:
Following Q/A (What datatype should I use for an IPFS address hash?) recommend us to use bytes to store IPFS hash.

I was using following example(https://github.com/AdrianClv/ethereum-ipfs/blob/master/NotSoSimpleStorage.sol), which uses string to store IPFS hash that costs around 110,000 gas price, which seems pretty expensive.

[Q] Does using bytes instead of string in order to store IPFS hash cost cheaper? I observe that storing bytes instead of string costs very close to string (110,000 gas). Since both datatypes storage seems expensive should I use events to store them?

Is there any example/tutorial related to store IPFS hash using bytes?

Would this work:

myContract.insertHash("QmWmyoMoctfbAaiEs2G46gpeUmhqFRDW6KWo64y5r581Vz");

contract Example_bytes {
    bytes[] list;
    function insertHash(bytes ipfsHash) {
       list.push(ipfsHash); //costs around 110,000 gas.
    }
}

contract Example_string {
    struct hashes{
         string hash;
    }

    hashes[] list;
    function insertHash(string ipfsHash) {
       list.push(hashes{hash: ipfsHash); //costs around 110,000 gas.
    }
}


texts: Getting hex instead of uint through mapping

texts:
I have a simple method where I count how many times certain address has called method of smart contract. Here is code:

mapping (address => uint) countTotal;

function countSends() public returns(uint retClicks) {
    clicksTotal[msg.sender]++;
    return countTotal[msg.sender];
}

Obviously I expect that on first send I'll get 1, then 2, then 3...

But for some reason what I get back through web3js is hexadecimal value like 0xea6166fd3f8249c3dd3ed1dcbb3af9989aebdcf9f5eb079fc6d570296e6f4509. How can I get regular unsigned integer?

EDIT: Duplicate nannies linked to theoretical discussion... this much better explains what you need to do: How to get values returned by non constant transaction functions?


texts: Quorum/DApp Running in Secure Enclaves Such as Google Asylo

texts:
To secure the geth nodes and the keystores, can we run constellation and geth nodes within secure enclaves such as Google Asylo?

Or perhaps the DApp or Smart Contract could run in the secure enclaves.

How can this be achieved?

Nathan Aw


texts: Calling Transfer event causes infinite gas estimation solc

texts:
solc estimates an infinite gas usage from _transfer and I am unsure why. I did find that if I comment out the Transfer(_from, _to, _amount) line, the gas usage becomes finite.

Here is the minimum code to reproduce the issue:

pragma solidity ^0.4.19;

contract Token {

    event Transfer(address indexed _from, address indexed _to, uint _value);

    struct Balance {
        uint amount;
        uint lastUpdated;
    }

    mapping (address => Balance) public balances;

    function _transfer(address _from, address _to, uint _amount) internal returns (bool success) {

            // check if sender has sufficient balance
            require(balances[_from].amount >= _amount);
            //check for uint overflow
            require(balances[_to].amount + _amount > balances[_to].amount);

            balances[_from].amount -= _amount;
            balances[_to].amount += _amount;

            Transfer(_from, _to, _amount);
            return true;
        }
}

Using solc version 0.4.19+commit.c4cbbb05.Darwin.appleclang


texts: How can I redeploy my ico/erc20 token from Rinkeby to the main Ethereum network?

texts:
If you know and have a tutorial please attach the link in this thread.

My token on Rinkeby looks like this:

https://dappuniversity.github.io/dapp_token/


texts: Same Block Received More Than Once With Same Block Parameters

texts:
Use Case:
I am implementing a deposit system where I will get a block as it is mined and parse transactions to check for a deposit of Ether or a specific token. Getting the same block twice will result in same transactions parsed twice and that eventually might result in wrong credits etc.

To listen to blocks, I have implemented two scenarios but facing the same issue in both of them.

Scenario 1:
web3 version 0.19.0
Node Version 8.12.0
Ethereum Node: Geth Rinkeby Node Running on AWS

I use web3.eth.filter to listen to the latest block hashes and print the latest block info. For some blocks, I get the same block number twice.

var filter = web3.eth.filter('latest');
filter.watch(function(error, result) {
  if (!error) {
    web3.eth.getBlock(result, true, function(error, data) {
      if(!error)
      {
        console.log('Block: '+data.number+' Transactions Count: ',data.transactions.length);
      }
    });
  }
});

Output:

/* Notice the Block Number 3205025 Fired Twice with the same txn count */
Block:  3205023 Transactions: 39
Block:  3205024 Transactions: 24
Block:  3205024 Transactions: 24
Block:  3205025 Transactions: 17

Scenario 2:
web3 version 1.0.0 beta 36
Node Version 8.12.0
Ethereum Node Node: Infura Rinkeby Websocket

I used web3.eth.subscribe to subscribe to latest block headers and as a result, I get exactly same block headers emitted more than once from the emitter.

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.WebsocketProvider('wss://rinkeby.infura.io/ws'))

const subscription = web3.eth.subscribe('newBlockHeaders');

subscription.subscribe((error, result) => {
  if (error) console.log(error)
})
.on('data', async (block) => {
  console.log(block.number);
});

Output:

3215743
3215743
3215744
3215744
3215744
3215744

Am I doing anything wrong or is it the usual behavior or is there any way to handle the duplication of the exact same block.


texts: Contract method returns a Promise instead of a value

texts:
I am trying to store a unit from my smart contract in a variable. My code currently looks like this:

var variable = this.contractInstance.methods.myMethod().call({from: account, gas: 5000000});

^myMethod returns a uint

But instead of saving the uint, I save a promise. How can I save the uint instead?


texts: Whats the difference between hash generated and hash generated after mine

texts:
I am seeing this portal

https://anders.com/blockchain/block.html

When i type some data hash changes and when i click on mine button, hash changes again. I guess hash after mine is final one. Whats the logic for mine hash?


texts: How to make password with mnemonic words?

texts:
i'm new on blockchain development and i'm trying to make a login like metamask in vuejs. Can someone teach me how to make 13 mnemonics word, where the last mnemonic is the password value get from an input using bip39?

            async createWallet(){
        const mnemonic = await generateMnemonic();
        // const entropy = await entropyToMnemonic();
        // this.passphraseCreated = entropy

        if(this.selectLang == 'english'){
             this.mnemonic = await setDefaultWordlist('english')
        } else if (this.selectLang == 'chinese'){
             this.mnemonic = await setDefaultWordlist('chinese_traditional')
        }

        const seed = await mnemonicToSeed(this.mnemonic, this.createPassword || "");
        const root = hdkey.fromMasterSeed(seed);
        const masterPrivateKey = root.privateKey.toString('hex');

        const addrNode = root.derive("m/44'/60'/0'/0/0");
        const pubKey = privateToPublic(addrNode._privateKey);
        const addr = publicToAddress(pubKey).toString('hex');
        const address = toChecksumAddress(addr);

        console.log(mnemonic)

    async login() {

        const seed = await mnemonicToSeed(this.mnWrited, this.passLogin || "")

        if(validateMnemonic(this.mnWrited || this.passLogin))
        {
            const root = hdkey.fromMasterSeed(seed)
            const addrNode = root.derive("m/44'/60'/0'/0/0")
            const pubKey = privateToPublic(addrNode._privateKey)
            const addr = publicToAddress(pubKey).toString('hex')
            const address = toChecksumAddress(addr)
            this.address = address

            console.log(address)
            fetch('https://api.etherscan.io/api?module=account&action=balance&address=' + address + '&tag=latest&apikey=R5AABKRFH5HMXBA9IBQ5G44HS84B8YJWFI')
            .then(response => response.json())
            .then(response => {
                if(response.status == '0'){
                    // console.log(response.message)
                    // this.logged = true;
                }
                else {
                    // console.log(response)
                    this.logged = true;
                }
            })
        }
        else
        {
            console.log("Wrong Words")
            this.showResponse = true;
        }

        // if(this.mnWrited.length < 12 && this.mnWrited.length > 12){
        //     console.log('Digite as 12 palavras.')
        // }
    },


texts: How to get events from latest to older with then array of 10 log

texts:
I want to bring latest 10 logs  from my events . and rest logs  will load  when I click on load more button then next latest logs  (11 to 20 )  should be loaded .
plz help me in this
logs = await window.newInstance.queryFilter(
        window.newManagerInstance.filters.StakingTransfer(
          ethers.constants.AddressZero,
          null,
          null
        ))


texts: How to check last block in which storage variable was modified?

texts:
I am looking for method to quick chceck in which block variable was modified last.
Assuming I have geth database synced in archive mode, that means I have all previous world states tries and accounts storages tries.
How can I check this fast. Is there a way to do this not checking previous worldstates states and storage tries?
Can I determine this block number looking only on bloom filters or whatever, more efficient than checking tries?


texts:
Curently minimal transaction cost is around 0.1$. And it's VERY high for most of IoT applications, where service price is less than 0,1$.

Is there any solutions, works, startups anything about it?


texts:
I would like to approx the max amounts of peers my box can handle and whether this max could be too much. Therefore:

a) What is the main machine resource consumed by more peers besides network? CPU? RAM?

b) Is there a downside to having a lot of peers?

Parity//v1.7.0-beta-5f2cabd-20170727/x86_64-linux-gnu/rustc1.18.0


texts: How to determine if an internal transaction creates a new contract?

texts:
I'm working on programmatically analyzing smart contracts and I need a way to determine if an internal transaction is creating a new contract. Can this be done by looking at the event logs? Anyone know how to approach this?

example: https://etherscan.io/txsInternal?block=4752011


texts: DeclarationError: Identifier already declared. when writing in solidity

texts:
DeclarationError: Identifier already declared near function

pragma solidity ^0.5.1;
contract Timestamp{
   uint start;
   uint end;
   function start() public{
      start = block.timestamp;
   }
   function end() public {
      end = block.timestamp;
   }
   function getTimeDif() view public returns(uint) {
      return end - start;
   }
}


texts: Indexed Event with string not getting logged

texts:
I am facing a strange issue in my solidity smart contract using events. I created the event in 2 ways as below:-

1. event Event1(string assetName, address toAdd);
2. event Event1(string indexed assetName, address indexed toAdd);

Now if I run my smart contract and I have specified approach 1, then the event gets printed in the console logs whereas if I use approach 2, then the event is not printed in the console logs.

Can someone clarify on this?

Note: Not pasting the whole contract code


texts: Is there a way to manually import a private key into Mist?

texts: I want to move Ether between different wallets. I have a private key and want to move it to the Mist wallet. Any way I can do that?


texts:
I have a fast node running on a raspberry pi+SSD, I want to transfert it to a raspbery pi+SD card (512GB).
If I install the same os, with the exact same packages, then make geth.
Can I just copy the datadir of my geth node to get a fully synchonized fast node?
Thanks.


texts: Geth automining includes only 1 transaction per block

texts: I am trying to perform a heavy load and scalability tests on a smart contract. However, the test takes a lot of time because only 1 transaction is added per block. I read that this might be due to gasLimit of the block but currently my blocks have a limit of 3877440195466 gas and the transaction that is processed take s "txs=1 gas=36544". I am wondering how can I fix that and also if there is a way to change my mining code so that more transactions are added per block?


texts: Get addLiquidityTransaction on a specific contract on ethers.js

texts:
I'am trying to get an addLiquidityETH event in ethers.js with a WebSocket on a specific contract but got nothing, can someone tell me what am i missing ?
const filter = {
address: ' TOKEN ADDRESS ',
topics: [

  // This one below retrieves Transfer TX
  // ethers.utils.id("Transfer(address,address,uint256)")

  // This one does not show liquidity transactions
  ethers.utils.id("addLiquidityETH(address,uint256,uint256,uint256,address,uint256)")
]
}

this.provider.on(filter, (tx) => {
  console.log(tx.transactionHash);
})

Any ideas ?


texts:
Solidity Browser doesn't load anymore.

Here is a screenshot with the Chrome Developer open.

on Chrome Version 52.0.2743.116 m

It's stuck on loading and I see in developer some error messages.
It worked fine just a few minutes ago. Even Internet Explorer fails.

Do you have any idea about what is wrong?

EDIT:
I see that in an older site it still works

EDIT2:
Now even the current version works

EDIT3:
After a couple of hours it doesn't work again

EDIT4:
It might have been a network issue as I haven't experienced that any more


texts: Why are ICO startups claiming to build blockchains with different functionality, but yet are using Ethereum?

texts:
I've been researching the top blockchain startups by market cap on https://etherscan.io/tokens.

For example:

EOS (EOS)

Tronix (TRX)

VeChain (VEN)

etc.

And I'm just not understanding what they are all trying to do?

They all seem so similar, and so basic; with nothing new being introduced at all (or is there?).

Many are claiming to be building a better blockchain service, but yet are using Ethereum?

Or are they just using Ethereum as a crowdfunding source?

To me this is just screaming illegitimate to every one of these startups.

Like I don't even understand what innovation any are bringing to the table.

For example Tronix (TRX) has a market cap of $4,775,337,947 (as of 5/14/2018),

Like this snippet of code right here (the contract on the Ethereum blockchain):

pragma solidity ^0.4.11;

contract TronToken {

    string public name = "Tronix";      //  token name
    string public symbol = "TRX";           //  token symbol
    uint256 public decimals = 6;            //  token digit

    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    uint256 public totalSupply = 0;
    bool public stopped = false;

    uint256 constant valueFounder = 100000000000000000;
    address owner = 0x0;

    modifier isOwner {
        assert(owner == msg.sender);
        _;
    }

    modifier isRunning {
        assert (!stopped);
        _;
    }

    modifier validAddress {
        assert(0x0 != msg.sender);
        _;
    }

    function TronToken(address _addressFounder) {
        owner = msg.sender;
        totalSupply = valueFounder;
        balanceOf[_addressFounder] = valueFounder;
        Transfer(0x0, _addressFounder, valueFounder);
    }

    function transfer(address _to, uint256 _value) isRunning validAddress returns (bool success) {
        require(balanceOf[msg.sender] >= _value);
        require(balanceOf[_to] + _value >= balanceOf[_to]);
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        Transfer(msg.sender, _to, _value);
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress returns (bool success) {
        require(balanceOf[_from] >= _value);
        require(balanceOf[_to] + _value >= balanceOf[_to]);
        require(allowance[_from][msg.sender] >= _value);
        balanceOf[_to] += _value;
        balanceOf[_from] -= _value;
        allowance[_from][msg.sender] -= _value;
        Transfer(_from, _to, _value);
        return true;
    }

    function approve(address _spender, uint256 _value) isRunning validAddress returns (bool success) {
        require(_value == 0 || allowance[msg.sender][_spender] == 0);
        allowance[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function stop() isOwner {
        stopped = true;
    }

    function start() isOwner {
        stopped = false;
    }

    function setName(string _name) isOwner {
        name = _name;
    }

    function burn(uint256 _value) {
        require(balanceOf[msg.sender] >= _value);
        balanceOf[msg.sender] -= _value;
        balanceOf[0x0] += _value;
        Transfer(msg.sender, 0x0, _value);
    }

    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

Is worth $4,775,337,947?!

I understand how there is a lot of speculation going on, so the prices are probably very inflated.

But still, how are these startups worth anything?

Like, what am I missing or not seeing?


texts:
How can i read symbol and name of the token in transaction?
I tried to decode input data from transaction, but it wasn't success.
the latest Web3j does not have toAscii method in java.
Should i use parity tracer for this?
What advantages of tracing? Internal transactions?

Thanks


texts: Where does the mist browser store the node log files?

texts:
Mist uses to launch it's own client (geth or eth) in the background.

Does it store the node's logs? If so, where?


texts: Reverting invalid blocks in Plasma chains?

texts:
Plasma white paper (page 19):

"The fraud proofs ensure that a coalition of participants are not able to create fraudulent
blocks without getting penalized. In the event a fraudulent block is detected and proven
on the root blockchain (or parent Plasma chains), the invalid block is rolled back."

How can a block in an independent chain (Plasma chain) be reverted? If I'm a Plasma operator, how can Ethereum main chain make me revert a block, how is that enforced?

And what if there are valid blocks already built on top of the invalid one?


texts: Truffle test seems to succeed, but then 'transaction wasn't processed in 240 seconds! '

texts:
I have 5 smart contract functions and 26 unit tests for them. If I run the tests together, they run green, however, in the end, I get a timeout error:

The error message wasn't quite informative for me, so I started to comment out the tests one by one, and all of my tests seem to be good together until I add a particular one (see below).

The relevant smart contract function:

mapping(uint256=>bytes32[]) idRowArrayMapping;

event QueryResultStored(
    uint256 queryId,
    uint256 resultId
);
event RowStored();
event Error(string errorMessage);

enum ViewResultCodes { Success, NoMatchFound, IntegerNotPositive, StringEmpty }
ViewResultCodes public viewResultCode;

function validateRow(uint256 _resultId, string _rowString) external view returns (ViewResultCodes result) {
    if (_resultId <= 0) {
      return ViewResultCodes.IntegerNotPositive;
    }
    if (bytes(_rowString).length == 0) {
      return ViewResultCodes.StringEmpty;
    }

    bytes32 rowHash = keccak256(_rowString);
    bytes32[] storage dataSet = idRowArrayMapping[_resultId];

    for (uint i = 0; i < dataSet.length; i++) {
      if (dataSet[i] == rowHash) {
        return ViewResultCodes.Success;
      }
    }
    return ViewResultCodes.NoMatchFound;
  }

And the unit test for it:

'use strict';

const QueryResultHandler = artifacts.require("./QueryResultHandler");
const ViewResultCodes = {
  Success: 0,
  NoMatchFound: 1,
  IntegerNotPositive: 2,
  StringEmpty: 3
};

let instance;

contract('validateRow() function test', function() {
  beforeEach('Setup contract for each test', async function() {
    instance = await QueryResultHandler.deployed();
  });

  it("(0,'a'): Should return the StringEmpty code", async () => {
    instance.validateRow.call(0,'a').then(function(viewResultCode) {
      assert.equal(viewResultCode, ViewResultCodes.IntegerNotPositive, "Returned code was: " + viewResultCode);
    });
  })
})

Also, if I run the test alone, there is no timeout and it works fine. I would be grateful for any ideas, what can be the problem.


texts:
I'm building Dapp on Ethereum. The main feature of this Dapp is Register/Login logic. I Don't want to use Metamask, but I want to make Login system like MyEtherWallet without any chrome extention. What's the best way of doing so?

should I use centralized Database? because Dapp won't be decentralized anymore.


texts:
I want to know if calling selfdestruct clears/removes data from blockchain or it still remains there.
Looking at this link, CLICK HERE it says that data doesn't get removed. (first answer)
Looking at this link, CLICK HERE it says that it frees up the data. (first answer)
Question 1) So, which one is right ? Does the data get removed or not ? what gets removed exactly ?
Question 2) If I send the ether directly or transfer,  to the contract that already used selfdestruct, will it return false and my ether coming back to me or ether will get burn ? if it burns and gets lost, then the idea that

" selfdestruct exists because no one can interact it with it anymore
so that no dangerous thing could happen "

seems to be a little bit wrong...


texts: Give tokens back to owner and get ethers to own account

texts:
I am working on a smart contract in which requirement is if someone purchases tokens by ether and after the purchase if he/she wants to return the token and get ether balance back. As in my requirement, I need to calculate the price of ether at run time after his/her purchase. So when I do code like this, here 1000000000000000000 is hardcoded but in my case, it calculated on runtime to return ether balance to the customer.

function sell(uint256 amount) payable public  {
   msg.sender.transfer(1000000000000000000);        /// sends ether to the seller.
 }

This throw following error

transact to Scalifyt5Token.sell errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value.  Debug the transaction to get more information.

If I do in this way enter ether amount from input in ether that is working fine. but that is not my requirement as I need to calculate wei value at runtime.

function sell(uint256 amount) payable public  {
   msg.sender.transfer(msg.value);        /// sends ether to the seller.
}

Any help will be appreciated.

Thanks in advance.


texts: How do I encode address field when creating new instance of a contract?

texts:
when I query my accounts on my local test rpc, I get this:

> web3.eth.accounts[0]

'0x8a39ab283fb500e3be48a68f6c9d90371bfaa345'

All good, but when I try to create an instance of a contract I created, I get this:

> deployedContract = VotingContract.new(['Larry','Curly','Moe'], { data: contract.bytecode, from: web3.eth.accounts[0], gas: 4700000})

Error: invalid argument 0: missing 0x prefix for hex data
    at Object.InvalidResponse (C:\Users\dude\AppData\Roaming\npm\node_modules\web3\lib\web3\errors.js:38:16)
    at RequestManager.send (C:\Users\dude\AppData\Roaming\npm\node_modules\web3\lib\web3\requestmanager.js:61:22)
    at Eth.send [as sendTransaction] (C:\Users\dude\AppData\Roaming\npm\node_modules\web3\lib\web3\method.js:145:58)
    at ContractFactory.new (C:\Users\dude\AppData\Roaming\npm\node_modules\web3\lib\web3\contract.js:228:33)
    at repl:1:38
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)
    at bound (domain.js:280:14)
>

What is the correct format for the address in this case?


texts: while calling an contract method using web3j returns null.Deployed in Remix ,getting response and deployed in geth console ,got response.


texts: Syncing geth 1.9.15 took too long on HDD raid-0

texts:
I've been running full node on a server with this config:

Centos 7
11 Tb hdd raid-0
32 Gb ram

and I'm using geth 1.9.15-stable-0f77f34b
I'm trying to be archive node but syncing took over 1 months despite I had database dumps since january but after one month I still stucked in january blocks. So I don't think that I could ever finish syncing. I even tried --syncmode = full and that did not help neither.
Status of HDDs:

And it's R/W speed:
command:
    hdparm -Tt /dev/sda4

result:

  /dev/sda4:
  Timing cached reads:   25122 MB in  1.99 seconds = 12633.44 MB/sec
  Timing buffered disk reads: 786 MB in  3.00 seconds = 261.86 MB/sec
———————————
command:
  sync; dd if=/dev/zero of=tempfile bs=1M count=1024; sync

result:
   1024+0 records in
   1024+0 records out
   1073741824 bytes (1.1 GB) copied, 0.648344 s, 1.7 GB/s

Also .ethereum folder size is about 3.6T right now.
How can I speed up this or is it ever possible to finish syncing with this server?


texts:
What is the process to get Dollar or Euro from Ether to my bank account?

The easiest is to sell ETH into BTC on Poloniex, then I transfer my BTC to Kraken and on Kraken I sell BTC into Euro and the next step is withdraw Euro to my bank account?

Is there any simpler way to do this?


texts: Deploying smart contracts with truffle and geth in windows

texts:
I'm trying to deploy a contract. When running: truffle.cmd migrate network --ropsten I get the following error:

  No network specified. Cannot determine current network.

Please help! Details are below

I've connected & unlocked my account in geth with:
geth --fast --cache=1048 --testnet --unlock "mycontractaddress" --rpc --rpcapi "eth,net,web3" --rpccorsdomain '' --rpcaddr localhost --rpcport 8545 Previously, I have synced with the entire blockchain*

My truffle.js file is:

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


texts:
Say I wanted to create a system on the Ethereum network to place bets on a prize pool that was under the current block reward say 2.5 ETH.

Would these steps be a reasonably fair way to make sure players couldn't game the system?

1) Have 100 possible entries into the game

2) Gather all the player's address and XOR them together

3) On the 99th entry make sure that this person doesn't have a majority of the entries(multiple entries are allowed)

4) When the last person enters use the block.timestamp function as a sort of seed to add to the number from the XOR'd addresses

5) do modulus division by 100 to find the winning number and hand out the prize

I understand that the block time can be manipulated by miners but if the prize pool is smaller than the block reward this is a feasible option, no?


texts: Getting pending transactions for a past block

texts:
I want to get historical list of pending transactions. For example, for a block number 1,000,000 is it possible to get this list?

Right now I have downloaded blockchain data up to block 1,600,000 , however if I execute this:

> eth.getBlock('pending', true).transactions
[]
>

I get no pending transactions.

Does this mean geth doesn't store pending transactions per block in its database? If geth does not, maybe Parity does it ???


texts: Why chainid is done in assembly in UniswapV2ERC20

texts:
I am studying uniswap solidity source code and there is something i do not understand in UniswapV2ERC20 constructor:
uint chainId;
assembly {
    chainId := chainid
}

(pasted from https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
My question is why this affectation is done in an assembly section ?
Thanks


texts:
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Users\Hp\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Windows_NT 10.0.18363
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Hp\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd D:\assign\client\node_modules\sha3
gyp ERR! node -v v14.2.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sha3@1.2.3 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sha3@1.2.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Hp\AppData\Roaming\npm-cache\_logs\2020-05-08T14_35_30_250Z-debug.log
√ cleaning up temporary files


texts: Hierarchial deterministic wallets on Android

texts: Is there some implementation which lets me create Hierarchical Deterministic Wallets for Ethereum on Android ? I am looking for some library which lets me create the same.


texts: Failure to call 1inch getExpectedReturn function from the Solidity contract

texts:
I am trying to test 1inch getExpectedReturn function from my Solidity contract. I deploy my contract on the Mainnet forked with Ganache via Remix. The entire contract is pretty simple and looks as follows:
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract IOneSplit {
    function getExpectedReturn(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amount,
        uint256 parts,
        uint256 disableFlags
    )
        public
        view
        returns(
            uint256 returnAmount,
            uint256[] memory distribution
        );
}

contract TradingBot  {

    // OneSplit Config
    address ONE_SPLIT_ADDRESS = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
    uint256 PARTS = 10;
    uint256 FLAGS = 0;

    // Allow the contract to receive Ether
    function () external payable  {}

    function getreturn (address _from, address _to, uint256 _amount) public view returns(uint returnAmount, uint[] memory distribution) {
        IERC20 _fromIERC20 = IERC20(_from);
        IERC20 _toIERC20 = IERC20(_to);
        IOneSplit _oneSplitContract = IOneSplit(ONE_SPLIT_ADDRESS);
        (returnAmount, distribution) = _oneSplitContract.getExpectedReturn(_fromIERC20, _toIERC20, _amount, PARTS, FLAGS);
    }
}

The contract compiles well but after deployment and running the getreturn function I always get the cryptic "VM Exception while processing transaction: revert" error. I also tried to use the call function:
function getreturn_test () public {

    ONE_SPLIT_ADDRESS.call(abi.encodeWithSignature(
                                "getExpectedReturn(address,address,uint256,uint256,uint256)",
                                                    0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48,
                                                    0x6B175474E89094C44Da98b954EedeAC495271d0F,
                                                    uint(100), uint(10), uint(0)));
    }

It does not work either. I can't find any explanation why this does not work in my contract. Could anyone see any reasons?


texts: how to format contract params expecting bytes32?

texts:
I have a contract that expects a bytes32 parameter called "topic" which I pass in like this:

web3.utils.hexToBytes(web3.utils.stringToHex("Weather"));

I also tried

web3.utils.stringToHex("Weather")

and just passing it in as "Weather" and that didn't work.

I'm getting this error:

Error: invalid bytes32 value (arg="_topic", coderType="bytes32", value=[87,101,97,116,104,101,114], version=4.0.27)


texts: Using a token deployed separately in zeppelin-solidity Crowdsale.sol contructor

texts:
How to bring already deployed token into zeppelin-solidity Crowdsale.sol contructor? The owner is the same. What should I use instead of the "Mintable _token" below?

function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public {
  require(_startTime >= now);
  require(_endTime >= _startTime);
  require(_rate > 0);
  require(_wallet != address(0));
  require(_token != address(0));

  startTime = _startTime;
  endTime = _endTime;
  rate = _rate;
  wallet = _wallet;
  token = _token;
}


texts: Can a hash of all input addresses be used as a source of randomness?

texts:
So I want to create a casino contract. Can I use a hash of all addresses that participate in the casino as a source of randomness?

I'd think yes, as there would be lots of users that have played the casino and an attacker would need to make lots and lots of accounts to be able to influence the hash to a predictable value (and no other users may join or he will need to restart his attack.

As I am not a security expert, I would like to know your opinion on the security of my idea.

I was also thinking of adding some kind of stake requirement to the hashing, like only hash the addresses that are in the top 25% of investments. Then the attacker would need to have quite some stake in the casino before trying to game the system.


texts: what is the cheapest way for sending ethereum from 10 account addresses to 10 account addresses?

texts: What is the cheapest way to send ether to 10 addresses? By using smart contract or using externally owned account to send one by one...? I know that the gas limit of a normal transaction is 21,000...so 10 of this transaction costs 210,000 gas. I think send ether to 10 addresses by using smart contract has cost more than 210,000 gas, correct?


texts:
Here is my contract code:

$.getJSON('Adoption.json', function(data) {
  // Get the necessary contract artifact file and instantiate it with truffle-contract
  var AdoptionArtifact = data;
  App.contracts.Adoption = TruffleContract(AdoptionArtifact);

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

  // Use our contract to retrieve and mark the adopted pets
  return App.markAdopted();
});

I use the contract by calling a method like the below

          var petsRow = $('#petsRow');
          var petTemplate = $('#petTemplate');

          petTemplate.remove("");

            App.contracts.Adoption.deployed().then(function(instance) {
              adoptionInstance = instance;
              // Execute adopt as a transaction

              for(var i = 0; i < 5; i++)
              {
                return adoptionInstance.getEntity(i);
              }

            }).then(function(result) {

            console.log(result);
             petTemplate.find('.panel-title').text(result[1]);
             petTemplate.find('img').attr('src', result[2]);
             petTemplate.find('.pet-breed').text();
             petTemplate.find('.pet-age').text();
             petTemplate.find('.pet-location').text();
             petTemplate.find('.price').text(result[3]);
             petTemplate.find('.price').attr('data-id', result[0]);

             //petTemplate.find('.panel-pet').eq(i).find('button').text('Sold').attr('disabled', true);
             petTemplate.find('.btn-adopt').attr('data-id', result[0]);

             petsRow.append(petTemplate.html());

          }).catch(function(err) {
            console.log(err.message);
          });

Problem I am having is when I try to create a for loop it doesn't work as it's async. Im trying to retreive each entity. It just returns the promise once.


texts: How should we benchmark transaction per sec?

texts:
I'd like to compare the transaction speed of private Ethereum(ex. PoA), Eris and HydraChain.

How should we benchmark them?


texts: How to connect two nodes on two different networks

texts:
I'm trying to create my own chain so I have a VM which is the main node that will mine all the time, so that I don't lose the chain if all the nodes are off. I want also to make my friends able to mine and send transactions on this chain, but the problem appears when I try add a new node using admin.addPeer() and this node is on a different network from the VM network. I am able to connect two nodes if they are on the same network but I'm not able to connect two different nodes if they are on different networks.
How can I achieve that?
I think my problem is when I make  the full URL using the enode, because I'm using the IP address of the node which is an internal IP, how can I make a full URL using external and internal IP address. Also, I don't have any access to the router, so I cannot configure it.


texts: How can I split part of a number always in 2 numbers

texts:
In solidity how can i retrieve always 2 numbers from an int?

For example in the first funcion the result is 78 and the result of the second function

function returnNumberTest1() public returns(uint) {
    uint256 n = 85055054;

    return n & 0xff;
}

function returnNumberTest2() public returns(uint) {
    uint256 n = 55058618935774054120265983768542913389624544203505105799354858217531716133001;

    return n & 0xff;
}

How can I always retrieve 2 numbers indepentende of the size of the n variable?


texts: At the end of February I did a transfer of my Etherums. I sent them from my Ledger hard wallet to Metamask. Apparently they never ended up there. I do have the wallet addresses. How can I find the exchange account with these addresses?