texts:
Pardon the n00b question!

I am trying to do some simple math in solidity using USD values.

For example, say the start price of a token offering is $0.50 USD and the contribution is $10.00 USD, then the number of tokens issued should be 20 tokens.

I am having trouble with the numbers with solidity.

Since Solidity doesn't use decimal places, I was assuming:

$0.50 USD would be represented as 0500000000000000000;
//0.500000000000000000

$10.00 USD would be represented as 10000000000000000000;
//10.000000000000000000000000

If I lead any unit values with zeros, Remix reports Expected primary expression. as the error.

What's the best way to do math if you need to account for decimal places in Solidity?

I am not looking to way any ETH, WEI math, just USD math accounting for at least 4 decimal places.

Thank you in advance!!!


texts: Account nonce -- Incremental, i.e., Deterministic or Arbitrary

texts:
In cryptography, a nonce is an arbitrary number that can be used just once.

But in Ethereum, the account nonce is deterministic. Deterministic vs Arbitrary -- How can both be true at the same time?


texts: I would like to warp a token and inherit its methods in a wrapper without declaring them in a wrapper. Can I do this?

texts:
The reason why I am asking this is to create something that is closely related to mutability. So, instead of creating a different token every time there is a code-change, I would like to simply use a wrapper and then wrap another token/contract that has the updated code.
Was anything like this done before, and if yes, where can I learn more about this approach ?


texts: msg.sender 'spoofing' when function is public or external

texts:
I have a Smart contract where I want only the onwer to call a specific function, for example:

function getInfo() view public onlyOwner() returns (address) {
  return msg.sender;
}
.....
modifier onlyOwner ()  {
  require ( msg.sender== my_owner);
}

I can build a web3 call slaiming to be (calling from) any address, in this case the owner of the contract, for example:

web3 = new Web3(App.web3Provider);

......
if(directAccessMode)
    web3.eth.defaultAccount =   '0x1111111111111111111111111111111111111111';
......

and be able to geth the required information without any check from EVM that I am really the 'owner' of the address I am claiming to be even avoiding using the address' access details.

I am aware that smart contract data is public nevertheless I do not understnad why there is no control on caller's address validity.

Thanks


texts:
How to create multi forwarder address (contract)?

my code https://pastebin.com/raw/ADwPtz8q

error InternalCompilerError: Compiled contract not found.

pragma solidity 0.4.25;

contract Factory {

address[] public WubaContracts;
event LogCreatedWubaContract(address sender, address WubaContract);

function createWubaContracts() public returns(bool success) {
    require(WubaContracts.length==0, "3 contracts, please.");
    for(uint i=0; i<3; i++) {
        Wuba v = new Wuba();
        WubaContracts.push(address(v));
        emit LogCreatedWubaContract(msg.sender, address(v));
    }
    return true;
}

function setupWubaContracts() public returns(bool success) {
    for(uint i=0; i<3; i++) {
        Wuba v = Wuba(WubaContracts[i]);
        v.oke();
    }
    WubaContracts.length=0;
    return true;
}

}

contract Wuba {
function transfer(address _to, uint256 _value) returns (bool success);
function balanceOf(address _owner) constant returns (uint256 balance);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);

  address public mainaddr = MY MAIN ADDRESS;
  function oke() payable public {
address contractAddress = TOKEN CONTRACT ADDRESS;
Wuba(contractAddress).transfer(mainaddr,msg.value);
  }
}


texts: :Contract has not been deployed to detected network (network/artifact mismatch) tried all the links but did not help

texts:
my APP.js code

App = {
  web3Provider: null,
  contracts: {},
  account: 0x0,

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    web3.eth.defaultAccount=web3.eth.accounts[0]
    // Initialize web3 and set the provider to the testRPC.
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // set the provider you want from Web3.providers
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }
    App.displayAccountInfo();
    return App.initContract();
  },

  displayAccountInfo: function() {
    web3.eth.getCoinbase(function(err, account) {
      if (err === null) {
        App.account = account;
        $("#account").text(account);
        web3.eth.getBalance(account, function(err, balance) {
          if (err === null) {
            $("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
          }
        });
      }
    });
  },

  initContract: function() {
    $.getJSON('ChainList.json', function(chainListArtifact) {
      // Get the necessary contract artifact file and use it to instantiate a truffle contract abstraction.
      App.contracts.ChainList = TruffleContract(chainListArtifact);

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

      // Retrieve the article from the smart contract
      return App.reloadArticles();
    });
  },

  reloadArticles: function() {
    // refresh account information because the balance may have changed
    App.displayAccountInfo();

    App.contracts.ChainList.deployed().then(function(instance) {
      return instance.getArticle.call();
    }).then(function(article) {
      if (article[0] == 0x0) {
        // no article
        return;
      }

      // Retrieve and clear the article placeholder
      var articlesRow = $('#articlesRow');
      articlesRow.empty();

      // Retrieve and fill the article template
      var articleTemplate = $('#articleTemplate');
      articleTemplate.find('.panel-title').text(article[1]);
      articleTemplate.find('.article-description').text(article[2]);
      articleTemplate.find('.article-price').text(web3.fromWei(article[3], "ether"));

      var seller = article[0];
      if (seller == App.account) {
        seller = "You";
      }

      articleTemplate.find('.article-seller').text(seller);

      // add this new article
      articlesRow.append(articleTemplate.html());
    }).catch(function(err) {
      console.log(err.message);
    });
  },

  sellArticle: function() {
    // retrieve details of the article
    var _article_name = $("#article_name").val();
    var _description = $("#article_description").val();
    var _price = web3.toWei(parseInt($("#article_price").val() || 0), "ether");

    if ((_article_name.trim() == '') || (_price == 0)) {
      // nothing to sell
      return false;
    }

    App.contracts.ChainList.deployed().then(function(instance) {
      return instance.sellArticle(_article_name, _description, _price, {
        from: App.account,
        gas: 500000
      });
    }).then(function(result) {
      App.reloadArticles();
    }).catch(function(err) {
      console.error(err);
    });
  },
};

$(function() {
  $(window).load(function() {
    App.init();
  });
});

My Truffle.js code

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" // Match any network id
    }
  }
};

i Tried following thigs no use

1) we deleted the build folder completly and

and rerun the

    truffle migrate --reset

(not succeded )

2) I have used the two commands to check for re compile and deploy no use

    truffle compile
    truffle migrate

(no use)

3) Can anyone explain what this error is saying ? what are artifacts in etherium
nothing helped me plese help me


texts: Uncaught Error: Cannot find module 'web3-eth-personal'

texts:
I have these two lines of code to unlock the default account,
But i keep on getting error , tough the require path points to proper directory of web3-eth-personal,

var personal = require('./node_modules/web3-eth-personal/');
personal.unlockAccount(web3.eth.defaultAccount)

The Error:

  web3.min.js:1 Uncaught Error: Cannot find module
  './node_modules/web3-eth-personal/'
          at o (web3.min.js:1)
          at o (web3.min.js:1)
          at Index2.html:49

The thing is that iam able to call a function which reads value from contract, but trying to set value in contract is problem. my contract is on Ropsten test network.

Please guide.


texts: How does web3.js work out the types of the arguments you feed it?

texts:
Suppose I have a contract with a function name overloaded to take different types:

contract MyContract {
    event LogString(string str);
    event LogAddress(address addr);

    function logData(string str) {
        LogString(str);
    }
    function logData(address addr) {
        LogAddress(addr);
    }
}

These two functions will have different function signatures depending on the data I pass in. However, (I think) I would normally pass in an address from JavaScript as something like:

mycontract.logData("0xdeadbeef")

How does web3.js decide whether I intended the argument "0xdeadbeef" to be an address or a string? If this turns out to contain traps for the unwary, what's the best practice for naming the functions? Should I drop the overloading and give the functions different names depending on their expected data types?


texts: Is there a max number of websocket connections that geth can support?

texts: I realize that it depends on my machine, RAM, etc, but is there a general guide of how many WS connections geth can support?


texts: Problem verifying source code on Etherscan

texts:
This is really annoying I have tried putting in the ABI. Keep getting a constructor error. I have tried many combinations, nothing seems to work.

Following is the source code I deployed to Testnet 0x34a03193f88ceb2b3ac3ea32b47f7d25544d5f5e:

pragma solidity 0.4.8;
contract mortal {
    /* Define variable owner of the type address*/
    address owner;

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

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

contract greeter is mortal {
    /* define variable greeting of the type string */
    string greeting;

    /* this runs when the contract is executed */
    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* main function */
    function greet() constant returns (string) {
        return greeting;
    }
}


texts: What is the measured distribution of block times since Homestead?

texts:
The variance of block times should arguably follow a Poisson distribution. But by casual observation I've seen blocks fast as 4 s or 1 m 15 s. The average is around 14 s since Homestead.
If it follows a Poisson distribution it would have not that huge variance I observe:

What is the true distribution of block times in Homestead, derived from empirical observation?


texts: I understand that every transaction is visible on the blockchain but would it be possible to create a DApp that allows people to vote in disguise? not showcasing their vote till the votingprocess is over?


texts: Setting the initial balance of an account in ganache-cli

texts:
How can I set the initial balance of an account when launching ganache-cli (aka testrpc)?

There's nothing in ganache-cli --help to indicate that this is possible.

However, when I launch ganache-cli --acctKeys=accounts.txt, I can clearly see that each account has a balance.

Thank you.


texts: Listening to Events from another smart contract

texts:
I want to listen to an event from inside another (deployed) smart contract.

I am a complete noob to Ethereum and Solidity. So please excuse me for stupid questions, I might have misunderstood everything.

I want to listen to an event inside a deployed contract C1. And when a certain event takes place a want to call a function on another contract C2.

For example, there is a token called Matryx Token, Solidity code can be found here at EtherScan.io

In the Solidity code there is a contract MintableToken is ReleasableToken, inside that contract there is an event event MintFinished();.

How can I listen to this event and then call a function on another contract C2?

I am an experienced Swift developer. So I was thinking of writing this as a macOS app or iOS app. I found Geth, Go Ethereum, mobile client but it is a bit unclear how I can listen to events.

So maybe the easiest way would be to develop my own Solidity "program" (dApp?) and deploy it as a smart contract?

Where I would make most functions private or onlyOwner?

Is it possible to call a non constant nor public function on a smart contract (C2)?

I do not understand the answer given for this question (possible duplicate)
Can a contract listen to events of another contract?


texts: Pass specific address in Web3J send method

texts:
How to pass specific  address in send method in Web3J?

For example, using web3 javascript library, we can pass from address like below.

contract.someMethod().send({ from: this.props.accounts[0] })

But in the Java wrapper, there are no parameters defined for send() method.

Is there a way to pass specific address in web3j?


texts: Sending ether from list of addresses with web3.js

texts:
I would like to read the csv text file and make a transaction via web3.js like what I did with web3.py

Here is my python code

#!/usr/bin/python3.7
import os
import time
import pandas as pd

from pathlib import Path

from web3 import Web3, IPCProvider
from pathlib import Path

ipc_file = os.path.join('IPC')

sending_account = "ACC"
private_key = 'PRI'

web3 = Web3(IPCProvider(ipc_file))

addresses_df = pd.read_csv(
    'test.txt',
    header=None, names=['id', 'address', 'balance']
)

nonce_count = web3.eth.getTransactionCount(sending_account)

for row in addresses_df.itertuples():
    nonce_cnt = int(nonce_count)
    transaction = {
        'to': row.address,
        'value': int(row.balance),
        'gas': 21000,
        'gasPrice': 1000000000,
        'nonce': nonce_cnt
    }
    signed = web3.eth.account.signTransaction(transaction, private_key)
    TxHash = web3.eth.sendRawTransaction(signed.rawTransaction)
    print("Address:",row.address,"Nonce:",nonce_cnt,"TX:",TxHash.hex())
    nonce_count += 1
    time.sleep(1)

and here is my csv file

0,0x843fd22c88d59e57ae1856a871a5d95e95b0a656,52500000000000

Thanks in advance.


texts: Read Events from Blockchain using Infura.io instead of parity

texts:
I have a Script that is reading events from the Ethereum blockchain and want to use infura.io instead of my full parity client. Unfortunately I get the following error as soon as I change the 127.0.0.1:8545 in this code to my Infura.io Access link.

 var fs = require("fs");
var Web3 = require('web3');

var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://127.0.0.1:8545'));

Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (/Users/moritzhubel/node_modules/web3/lib/web3/errors.js:38:16)
at XMLHttpRequest.request.onreadystatechange (/Users/moritzhubel/node_modules/web3/lib/web3/httpprovider.js:116:24)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/moritzhubel/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/Users/moritzhubel/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpRequestError (/Users/moritzhubel/node_modules/xhr2/lib/xhr2.js:544:12)
at ClientRequest.<anonymous> (/Users/moritzhubel/node_modules/xhr2/lib/xhr2.js:414:24)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at Socket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)

Is there anyone who can help?


texts: Can not access quorum's contract from webpage *CORS*

texts:
I am getting following error on browser's console while accessing contracts.

  Failed to load http://localhost:22000/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

How can I fix it?

Following is code:

    var output = web3.eth.coinbase;
    $('#candidateName').text(output);


texts: The constructor should be payable if you send value ? It seems no error on my code

texts:
I am a student who studies solidity now. I am following the tutorial now to study how to write solidity code on Remix. But I think below code does not have any problem, but it keeps making an error.

pragma solidity ^0.4.24;

contract Receive {
    uint256 public balance;
    function pay() public payable {

    }
}

contract Send {
    Receive public r;

    constructor() public {
        r = new Receive();
    }

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

The error is:

The constructor should be payable if you send value

But if I remove the name of payable fallback function in Receive contract like below:

function () public payable {

}

It works. but why this happens ..? and the tutorial says that payable fallback function can have its name and also the statements in it, too.


texts: i am sending to an array of addresses but it is showing error on transfer function

texts:
pragma solidity ^0.4.16;

contract init {
    address[] public userAddresses;
    function addStudent(address _user) public {
       userAddresses.push(_user);
     }

     function sendToken(uint value) payable{
         for (uint i=0; i<userAddresses.length; i++) {
             userAddresses.send(value);
        }
     }

}

  i have used both send and transfer but nothing worked out. i have also
  added "payable" keyword when initialising addresses array but it also
  shows error.


texts: Is it possible to run bsc node with minimal config (especially low disk storage)?

texts:
I have a vps with 8vCPU, 16GB RAM and 160GB SSD. Is it possible to setup a bsc mainet node even if the official documentation (https://docs.binance.org/smart-chain/developer/fullnode.html#fullnodes-functions) got way higher minimal config.
I might try anyway but i've never set up a node and wanted to know if it was dumb to even try ?


texts: Keep getting the error "BigNumber Error: new BigNumber() not a base 16 number"

texts:
I am trying to call a getter function to return me a string but after hours of debugging I am not able to solve the problem.
I have tested the contract in remix and it does work, I have tested returning an uint works but for returning a string I keep getting the error in the title.

Here is the contract function:

pragma solidity ^0.5.1;

contract FreeSpeech{

address owner;
struct Message{
    string Message;
    int Vote;
    uint timeSubmit;
    bool isImportant;
    uint senderId;
}

mapping(address=>uint) public addressId;
mapping(address=> uint) addressMessageCount;

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

Message[] messageArr;
constructor() public{
    owner = msg.sender;
}

function addMessage(string memory _message/*, bool _MessageImportant*/) public {
    if(addressId[msg.sender] == 0){
       addressId[msg.sender] = uint(keccak256(abi.encodePacked(msg.sender)));
    }
    addressMessageCount[msg.sender]++;
    messageArr.push(Message(_message,0, now, true/*_MessageImportant*/, addressId[msg.sender]));
}

function getMessageCount() public view returns(uint){
    return addressMessageCount[msg.sender];
}

function getAddressId() public view returns(uint){
    return addressId[msg.sender];
}

function getMessageString() public view returns(string memory){
    return (messageArr[1].Message);
}

function upvoteMessage(uint _messageId) public {
    messageArr[_messageId].Vote += 1;
}

function downvoteMessage(uint _messageId) public {
    messageArr[_messageId].Vote -= 1;
}

function getMyMessageUpvoted() public view returns(string memory){
    int largest = 0;
    uint idLargest = 0;
    for(uint i = 0; i<addressMessageCount[msg.sender]; i++){
        if(messageArr[i].Vote > largest){
            largest = messageArr[i].Vote;
            idLargest = i;
        }
    }
    return messageArr[idLargest].Message;
}
}

And here is the web3 code:

function testString() { contractInstance.getMessageString.call().then(console.log) }

The thing that I don't get is that if I try to return a string it gives me the error specified in the title but if I return a uint it doesn't give me any problem and the console.log works fine.
Foe example if I try to call the the function getMessagesCount() it does return me the correct values because it returns a uint.
The contract is deployed at: 0xA8c44C88Db7b0E34d7a2fC0A1718dfA00CBcbE3C in the ROPSTEN network.


texts:
Should i have ether in contract account in order to call oraclize_query (firtst call is free) or it discounts from the main account?
Thanks!


texts: Metamask Error messages shows only revert

texts:
I have a little problem with the error messages I receive from MetaMask. In my dApp I have a modifiers which should throw an error with an error message. However, in MetaMask I only receive the RPC error message:
"{code: -32603, message: "Error: Error: [ethjs-rpc] rpc error with payload {…VM Exception while processing transaction: revert"}"

Is it possible to extract the error in some other way?
Also, could that be linked to the usage of inheritance?
Because the modifiers are in a separate contract.
To my knowledge, after compilation there should only be one contract (even if inheritance was used).

Thanks! :)


texts: Deploy contracts without deploying Migrations

texts:
I would like to deploy my contracts to mainnet using truffle. I figure it's the easiest and safest way to do it since I already deploy to testnet using truffle. The problem is I don't want to deploy the Migrations contract for every repository I have because it adds up to too much money. At today's ETH prices it's about $1.60 per deploy, I'd rather pay 0. How do I deploy my contracts to mainnet using truffle without deploying the Migrations contract?
Actually it looks like I can simply comment out the deployment of Migrations.sol in 1_initial_migration.js. What are the consequences of doing this? Will I run into problems by doing this?


texts:
I need to send eth to accounts that have erc20 tokens:

foreth.forEach(function(item,i){
    const balance = contractInstance.methods.balanceOf(item).call(function(err, result) {
       console.log(result)
    if (result>0) {
    console.log("success")
    web3.eth.getTransactionCount(fromAddress)
  .then((count) => {
    let rawTransaction = {
      'from': fromAddress,
      'gasPrice': web3.utils.toHex(10 * 1e9),
      'gasLimit': web3.utils.toHex(21000),
      'to': item,
      'value': web3.utils.toHex(web3.utils.toWei("0.0002")),
      'nonce': web3.utils.toHex(count)+i
    }
    let transaction = new Tx(rawTransaction)
    transaction.sign(privateKey)
    web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
      .on('transactionHash', console.log)

  })

    }
    })
    })

But when executing the code, 2 caches are generated for me, which are not on etherscan. Account transactions are also not visible, what's the problem?
Some later i get error:

Transaction was not mined w
ithin 750 seconds, please make sure your transaction was properly sent. Be aware
 that it might still be mined!

any1 can help me?


texts:
I can't get web3.js to work with Angular. I got the exact same problem as the person here.
I used method 2 from the answer on that question, and it seems to work as it now compiles, but I'm getting the following error in the console:

Basically all solutions on the internet on this problem that I have tried lead to this error for me.
How do I fix this?


texts: TypeError: Name has to refer to a struct, enum or contract when compiling a contract

texts:
I'm getting a weird error while compiling a contract in Solidity, I think it's because I'm using Solidity v0.5.0 and it was written with a previous version. Here's the code:

pragma solidity ^0.4.2;

contract Migrations {
    address public owner;
    uint public last_completed_migration;

    modifier restricted() {
        if (msg.sender == owner) _;
    }

    function Migrations() {
         owner = msg.sender;
    }

    function setCompleted(uint completed) restricted {
        last_completed_migration = completed;
    }

    function upgrade(address new_address) public restricted {
        Migrations upgraded = Migrations(new_address);
        upgraded.setCompleted(last_completed_migration);
    }
}

To be specific the compiler returns:

TypeError: Name has to refer to a struct, enum or contract.
    Migrations upgraded = Migrations(new_address);

underling the first appearance of Migrations.

Where's the problem in this?


texts: Is a contract 'kinda' equivalent to a table or a row in a traditional database?

texts:
Following the analogy that a blockchain is a kind of database, I'm trying to understand how my data should be structured and stored on the blockchain.

I've read about writing contracts in solidity and I see that contracts can contain complex data types such as mappings, arrays and struts, etc.

Should I store database type table data, inside one of these inside a contract, or should I create many contracts of the same type and store a row of data in each?

Perhaps an example will help explain, say I want to store relationships between user accounts, would I create a 'table' contract as follows:

pragma solidity ^0.4.0;

/// @title Company roles.
contract CompanyRole {

    mapping(address => address) public directors;
}

or a 'row' contract:

pragma solidity ^0.4.0;

/// @title Company roles.
contract CompanyRole {

    address person; // company the role is valid for
    address company; // company the role is valid for
    uint type;   // the type of role
}

It would be helpful to know the pros and cons of both approaches, or others, including cost implications.

Basically my question is where should table data be stored?


texts:
According to the official doc, a contract can create a new contract using the new keyword. But it does not work when I test the code from this post. My dev environment is truffle 2.1.1 and testrpc (or geth).

pragma solidity ^0.4.2;

contract MyContract {
    bytes32 public Name;

    function MyContract (bytes32 name) {
        Name = name;
    }
}

contract Factory {
    bytes32[] public Names;
    address[] public newContracts;

    function createContract(bytes32 name) returns(address) {
        address newContract = new MyContract(name);
        newContracts.push(newContract);
        return newContract;
    }

    function getName(uint i) {
        MyContract con = MyContract(newContracts[i]);
        Names[i] = con.Name();
    }
}

When calling Factory.createContract, it sends a new transaction and returns the tx hash instead of contract address.

Factory.deployed().createContract("1234")
// or
Factory.deployed().createContract("1234", {from:web3.eth.accounts[0], gas:200000})

  Transaction: 0x7f92f8bfa88c5707879ca0b8a93e53dbb7919c55fc90d352fb00269d70fd0fdb
  Gas usage: 0x5418
  Block Number: 0x0a
  Block Time: Fri Jan 20 2017 15:16:25 GMT+0800 (CST)

But calling Contract.New gets a new transaction with contract address.

Contract.new("12345")

  Transaction: 0x7275b47ac3712fd26c46b41b1e3f5f2ccbbb638a736e759a48103e08dfccda2a
  Contract created: 0x1787b9e9e99802c2c1a580ae7e2bcef045e5b7e7
  Gas usage: 0x019d5f
  Block Number: 0x09
  Block Time: Fri Jan 20 2017 15:14:43 GMT+0800 (CST)

What's the correct way to make Factory.createContract work? Any help will be welcomed.

Even tried compiling the contracts in browser-solidity and loading in geth console. But got the same result, a transaction with contractAddress=null.

factory.createContract("1234", {from:eth.accounts[0], gas:200000})

> eth.getTransactionReceipt("0x31cc7dc3b36fa9c4c524fa672f4537d19b5ac8459cc9f8232a073b9607f6d54e")
{
  blockHash: "0x026ecdfec95100d0322bff322c16a3f9df35fac9b6e21106dba1cd6d8c6c7ff5",
  blockNumber: 3029,
  contractAddress: null,
  cumulativeGasUsed: 144490,
  from: "0x5fae6ee92e44ddbf09bc5a9602c14decad10f235",
  gasUsed: 144490,
  logs: [],
  logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  root: "0x5481a645efdb0c07d4be3c137e9ef053b3fdb7695a96ce5b6ad92fca1b2edc0e",
  to: "0x2c978a345ed2fe0fc8ecf10b5e00737973f9a07a",
  transactionHash: "0x31cc7dc3b36fa9c4c524fa672f4537d19b5ac8459cc9f8232a073b9607f6d54e",
  transactionIndex: 0
}

Thank @Rob Hitchens for the code. Though the contractAddress is null, but getContractAddressAtIndex returns a valid contract address.

> factory.createContract("hello1", {from:eth.accounts[0], gas:200000})
"0x8e3d1b7d743f935bf4f88fa567292247f583ff22dea4e07ab21806e5546aeacb"
> xx = factory.getContractAddressAtIndex(0)
"0x93936cdf4fcc383679cf0305fb314e18fef620d0"
> eth.getTransactionReceipt("0x8e3d1b7d743f935bf4f88fa567292247f583ff22dea4e07ab21806e5546aeacb")
{
  blockHash: "0x951a2081ba61618820b5def8bec249eb52f829d9932d68555d03a5d4f70b4d42",
  blockNumber: 5,
  contractAddress: null,
  cumulativeGasUsed: 129810,
  gasUsed: 129810,
  logs: [],
  transactionHash: "0x8e3d1b7d743f935bf4f88fa567292247f583ff22dea4e07ab21806e5546aeacb",
  transactionIndex: 0
}

Another issue is it doesn't work in truffle console.

truffle(default)> f = Factory.at(Factory.address)
truffle(default)> f.createContract("hello", {from:web3.eth.accounts[0], gas:200000})
'0xe505daa028d408a800681fba1733777b8ea788cd47f45d28f36a0ff589e12356'
truffle(default)> f.getContractAddressAtIndex(0)
'0x'


texts: Which are the operations providing gas refund available immediatly for the current running transaction?

texts:
Most of gas refund operation aren’t available immediately, but instead increase the refund counter (which if I understand correctly is refunded not after the end of contract creation or call by contract but is instead refunded after the full end of the transaction).

I already found the 2300 stipend given for a transaction transferring funds… But is there anything else ?


texts: Ethereum wallets that support "Custom RPC URL" like Metamask

texts: I'm running a private blockchain and I've been using Metamask connected to my custom RPC URL with no issues.. I'm curious if there's any other Ethereum wallet that let's you add and connect to a custom RPC URL.


texts: API resource for determining all address holders of a contract

texts:
I would like a RESTful API for viewing all addresses which holds a balance of a specific contract.

It seems that etherscan.io deprecated this feature, or I'm looking at the wrong endpoints

Are there any services that do this? Other block explorers with APIs?


texts: Geth current block number update latency

texts:
With a fully synced fast node, logs are printed every ~8s seconds or so:
"Imported new chain segment" with how many blocks, and how long has elapsed between the last chain segment.

How can we decrease the time elapsed in order to keep the most synchronized blockchain at all times?


texts:
I'm trying to send 12 integer as bytes to a contract function. If I use

web3.utils.toHex(12)

the variable will become 0xc

The problem is that when contract function parses bytes, it reads uint256, so the result is revert.

How can I generate a hex with specific length? Like uint256, 128, 64, 32?

Edit: just tested manually and the variable I need is
0x000000000000000000000000000000000000000000000000000000000000000c
There must be a way to generate it somehow.


texts: How to know the amount of ETH in the liquidity pool

texts:
I'm currently trying to find a way to know the amount of ETH inside the liquidity pool. That would be by using Uniswap V2. A pair would be ETH/Some other ERC20 token.
My idea was about using IUniswapV2Pair Interface and then i'm just not sure. Maybe there is a better way even ? (https://github.com/Uniswap/uniswap-v2-core/blob/4dd59067c76dea4a0e8e4bfdda41877a6b16dedc/contracts/interfaces/IUniswapV2Pair.sol)
I would appreciate any help or to see any examples of something similar implemented in a contract, thanks.


texts: In solidity, how to copy a string or pass it by value?

texts:
In this example I only modify string a, but both a and b are changed. It seems like the string wasn't copied. I only want to change a. How do you copy a string and how do you pass a string by value to another function?
function test() public view returns (string memory, string memory)
{
    string memory a = "Hello?";
    string memory b = a;
    bytes(a)[5] = '!'; // modify string a
    return (a, b);
}


texts: Executing functions from a contract address

texts:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L57
Line #57 of Address.sol is used to execute a transaction that transfers ether from the contract address to destination address.
Similarly I would like the contract address to execute contract functions. How can I do it in Solidity or Vyper?


texts: Get a balance of an address at a certain block

texts: We are facing a problem with the web3.eth.getBalance(address [, defaultBlock] [, callback]) ( here the doc ). The function works well for last block, or for a small number of blocks in the past, but it does not returns ( it apparently hangs ) for block deeper in the history. What's the reason of this behavior?


texts:
I've recently been running into issues with contract deployment (receiving "Error: VM Exception while processing transaction: out of gas" during migration). It's been my understanding that the deployment cost of a contract is directly related to the size of the contract bytecode. I'm using Truffle and in my 2_deploy_contracts.js file I've been logging contract bytecode size in an attempt to investigate:

const Contract1 = artifacts.require("Contract1");
const Contract2 = artifacts.require("Contract2");
const Contract3 = artifacts.require("Contract3");

async function doDeploy(deployer, network) {
    console.log("Contract1 bytecode size: ", Contract1.deployedBytecode.length);
    console.log("Contract2 bytecode size: ", Contract2.deployedBytecode.length);
    console.log("Contract3 bytecode size: ", Contract3.deployedBytecode.length);

    await deployer.deploy(Contract1);
    await deployer.deploy(Contract2);
    await deployer.deploy(Contract3);
}

module.exports = function(deployer, network) {
    deployer.then(async () => {
        await doDeploy(deployer, network);
    });
};

The results of these logs show that the contract which I know to be causing the problem has a deployedBytecode size of only 24078 bytes, while the others (which are not causing issues) have sizes approaching 40000 bytes. I don't understand why its not the largest bytecode contract causing the out of gas error. Is my understanding of deployment costs incorrect?

(FYI this example has been simplified and the actual situation includes far more than 3 contracts. The contract causing issues also uses a couple different libraries... could this contribute to the problem?)


texts: How it is possible to login in ethereum wallet account only with private key?

texts:
I was playing with web3.eth.accounts.create([entropy]) function and I can easily create a new Ethereum account and get the address and the private key.
I created a simple address/private key pair and accessed to My Ether Wallet to try accessing to the address wallet. I can access with no problems, but I noticed that I was only asked to introduce the private key, no need to access the address.
How can it figure out my Ethereum address only based on the private key? Sorry if the answer is very basic but I cannot find a good explanation to that. I know that Ethereum wallet is based on the public/private key (assymetric) cryptography, but I thought that you need to provide both to login.


texts:
I have come across statements like uint256(0) and address(0). What is the meaning of that?

For example this statement in solidity docs
uint256(0) - uint256(1) == 2**256 - 1


texts:
I'm thinking of storing some data in logs by emitting events but I cannot easily find the answers to the following questions:

What is the total size limit of one event?
Can I store lots of string32 in event log data and what encoding is used for them?
How much would it cost?

The flow would be: send transaction to a contract with a string included -> contract does its job -> contract emits an event with job results + the passed string.

General advices on this idea are also welcome.


texts: Is functional programming possible on the EVM?

texts:
Is there a technical limitation preventing functional programming on the EVM? For instance the cost of computation?

I have heard that FP is "too costly". Is that correct? If it is, why?

Because "functional programming" is a broad category, this is a bit of a broad question. But knowing if FP is possible could inspire people to explore either creating a functional language or even integrating some functional programming concepts into Solidity.


texts: Struct array uninitialised storage pointer

texts:
Hi I'm having a struct

struct Participants{
        address participantAddress;
        uint amount;
        bool isPresent;
    }

I created an array like Participants[] participants;

But first it shows warning "Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning." So I added storage keyword as like Participants[] storage participants;. No it is showing "Uninitialised storage pointer". I google and I haven't found solution to silence this warning. Can anyone help to solve this problem. Thank you.


texts: How can I prevent a 51% attack on my Ethereum based blockchain

texts:
I am intending at some point to open up access to an Ethereum based blockchain.  I don't want to call it a private blockchain as I want it to be public.

Is there some best practice to prevent a 51% attack when it goes live.

Is controlled mining an approach, meaning control at the start which peers can connect and mine until there is a sizable mining community.


texts: Data privacy with block chain in health care?

texts:
I'm new to the concept of block chain and have only been reading about it the past four hours.  I hear a lot of marketing and business folks tell me that block chain is the way of the future for data security in the healthcare sector, and since I'm interested in working the IT sector of healthcare in the future, I thought I'd read a bit about this.

From cursory reading I've done, I still don't see how block chain is inherently better at managing patient data privacy over more traditional approaches of silo-ed data management solutions.

For example, if a healthcare institution has one database storing all my information as a patient of their facility, at least I can hope they have taken the security measures to prevent other people from accessing my medical files.

When I did my cursory reading about block chain, it seems to advertise the benefits of immutability of the data, difficulty and validation associated with create new blocks of data through proof of work methodology, and the distributed nature of data storage.  Blog articles speaking on cryptocurrency advertise how all financial transactions are transparent for all people in the block chain network to read.   In the world of healthcare, I most certainly DO NOT want the entire world to read my medical history, but I don't see much laymen literature on how block chain addresses the issue of data privacy.

So my question is, does block chain technology inherently address data privacy in any way?  Does it inherently perform better than traditional database management solutions in terms of data privacy?  Especially in the space of health care where patient data must be private and accessible by only a few individuals.


texts:
Issue
I ran the official example code: truffle migrate,and stuck there for a long long time:
truffle migrate
Running migration: 1_initial_migration.js
Deploying Migrations...

Steps to Reproduce
I started my geth using command:
geth --port 3000 --networkid 58343 --nodiscover --datadir=./datadir --maxpeers=0  --rpc --rpcport 8543 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner"

myGenesis.json
{
"config": {
"chainId": 16,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0
},
"difficulty": "400",
"gasLimit": "2000000",
"alloc": {
"f953e0323e6ef6fabe74a2a16ca633cdf512203a":{
"balance":"1000000000000000000000000"
}
}
}

truffle.js
module.exports = {
rpc: {
host:"localhost",
port:8543
},
networks: {
development: {
host: "localhost", //our network is running on localhost
port: 8543, // port where your blockchain is running
network_id: "*",
from: "0xf953e0323e6ef6fabe74a2a16ca633cdf512203a", // use the
account-id generated during the setup process
gas: 1900000
        }
    }
};

Note: I unlocked the 0th account from geth console  and  did start mining at the time of  deploying . I checked the statuus using personal.listWallets() and found that rest all accounts are locked except the first one.
Expected Behavior
Truffle migration should be have completed succeesfully
Actual Results
Then I redeployed and I got this output
Using network 'development'.
`Running migration: 1_initial_migration.js
 Deploying Migrations...
 0x313ee101eb7b3f3e9eb49c08a3d45b926e68ff3c55f3f5bdc7b0359be75f5bef
 Migrations: 0x61ccc18e4e1e66086c0e9ceea8e45471b471d7f5
 Saving successful migration to network...
 ... undefined
 Error encountered, bailing. Network state unknown. Review successful
 transactions manually.
 Error: authentication needed: password or unlock
 at Object.InvalidResponse (/usr/local/share/packages/node-v8.9.4-
 linux-x64/ lib/node_modules/truffle/
 build/webpack:/~/web3/lib/web3/errors.js:38:1)
 at /usr/local/share/packages/node-v8.9.4-linux-
 x64/lib/node_modules/truffle/build
 /webpack:/~/web3/lib/web3/requestmanager.js:86:1
 at /usr/local/share/packages/node-v8.9.4-linux-
 x64/lib/node_modules/truffle/build/webpack:/packages/truffle-
 migrate/index.js:225:1
at /usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
at XMLHttpRequest.request.onreadystatechange (/usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
at XMLHttpRequest._setReadyState (/usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
at XMLHttpRequest._onHttpResponseEnd (/usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
at IncomingMessage.<anonymous> (/usr/local/share/packages/node-v8.9.4-linux-x64/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

Environment

Operating System: Ubuntu
Ethereum client: Geth 1.8.14-stable-316fc7ec
Truffle version (truffle version): v4.1.14 (core: 4.1.14)
node version (node --version):v8.9.4
npm version (npm --version): 5.6.0


texts: How to validate my mnemonic before my hardware wallet is broken? (SafePal)

texts:
I just bought a SafePal wallet, I really like it.
But I am pretty sure that it will get broken at some point.
So I started to get afraid what if I broke my SafePal, bought another one, and turned out I did not write the mnemonic correctly.
So before my SafePal is broken, I would like to test if I really wrote it correctly.
Is there any way to do this? such as writing some codes by using some JS library or something?


texts:
I want to send some eth from within a contract to an address. According to the docs there are two possibilities:

  address.transfer(uint256 amount):
  send given amount of Wei to Address, throws on failure

and

  address.send(uint256 amount) returns (bool):
  send given amount of Wei to Address, returns false on failure

It seems easier to use .transfer, as this will automaticall throw an exception and revert any change performed within the transaction. But the compiler says the method is not available:

  Error: Member "transfer" not found or not visible after argument-dependent lookup in address

I have a feeling I'm missing something obvious, but can't figure it out, probably related to the "argument-dependent lookup". Any ideas?


texts:
Im trying to retrieve the current difficulty value via api and parse the value only using JQ. In this example it is etherchains api. Currently my output is

curl 'https://etherchain.org/api/difficulty' | jq '.data'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    52  100    52    0     0    129      0 --:--:-- --:--:-- --:--:--   129
[
  {
    "difficulty": 666836759051894
  }
]

and I would like it to be

666836759051894

When I look at the jq manual https://stedolan.github.io/jq/manual/#Basicfilters it shows

    jq '.foo'
Input   {"foo": 42, "bar": "less interesting data"}
Output  42

What am I doing wrong?


texts: Possibility of transferring "real funds" and "real ether" on " testnet "?

texts:
According to THIS ANSWER (by user "eth") :

  (1) Testnets are "play money" so that you can try out applications
  without spending real money.

And According to THIS WEBSITE :

  (2) Tobalaba blockchain is a Public test network, codenamed "Tobalaba." AND "It is based on Ethereum."

Now, according to (1) and (2):

Can we transfer "real funds" and "real ether" on Tobalaba blockchain like Ethereum? For example, can we pay the salary of someone using Tobalaba blockchain ? or it is only a testnet to be able to only test smart contract before deploying on the main Ethereum blockchain ?

And also (2) means that "Tobalaba blockchain" is a testnet (like "Ropsten")?

Note: I asked this question here, since Tobalaba blockchain is based on Ethereum network and so Inherits the Ethereum properties like supporting smart contract etc.


texts:
sorry this may be a dumb question but I need to be sure before I mess things up.
I have a bare metal server with virtualization software. I made a VM and it's running my geth node. I wanted to make another VM so I can sync a backup node since i have plenty of space, memory and CPU, but I know the critical thing for running the node is the disk writing speed, I have 6GB/s SSD on RAID 10, now the dumb question... if I run the second node even that it's on a separate VM, it's in the same physical server... will the writing speed maintain 6GB/s for both nodes or would I be reduced like 3GB/s for each node?


texts:
Need help restoring my account. Briefly:

I had to delete my geth folder as it was getting to 400gb.
I DO HAVE a my original keystore folder and password.
I upgraded to MIST v10 which syncs to 99% & 72 blocks then stops.
If I try to import my account by drag & drop my keystore file it says
importing but nothing happens.
I'm also trying to use my keystore file name to access my ethereum via Exodus but just getting error messages. I'm not sure how much of the keystore info I should be using - all incl UTC-2017 etc or just the last 40 or so letters/numbers after the last - ???

Suggestions please.

Thanks in  advance


texts: Solidity 0.6.x - when is it mandatory to use assembly (with examples)?

texts: Solidity's development is very active and, if compared to several other codes, stable releases are updated quite frequently. Which cases need assembly as mandatory feature for Solidity release 0.6.x? Examples, i.e. from recently deployed contracts, are very welcome.


texts: How to properly create a raw transaction and sign it using web3 in browser

texts:
I want to create and sign a transaction in browser using web3. In order to create a raw transaction, I think I have to do something like this (hopefully you can fill the gaps of my knowledge)

var pk = '0x6ba33b3f7997c2bf63d82f3baa1a8069014a59fa1f554af3266aa85afee9d0a9';

pk = new Buffer(pk,'hex');

var address = '0xFb4d271F3056aAF8Bcf8aeB00b5cb4B6C02c7368';

var myContractsAddress = '0x0cb4edc28d17c43a75797bf5effc141fd5da8715';

var rawTx = {

nonce: web3.toHex(web3.eth.getTransactionCount(acct1)),

to: myContractsAddress,

gasPrice: web3.toHex(20000000000),

gasLimit: web3.toHex(200000),

value: ***Here I am not sure, am I supposed to encode my list of variables? and do I encode everything to hex, or just integers? And how would that list look like?***

data: *This field is irrelevant for now, and just for documentationpurpose, right?*
}

This should give me my raw transaction (the part about the datafield I unfortunately don't know and would love to get help with!

Lets say my raw transaction is valid and correct at this point, I would have to sign it with the private key now. The solution I've seen used a node.js library called ethereumjs-tx. Is there a solution with web3 only, or do I have to port this library somehow into my browser?


texts: How to Calculate How Long an Address Has Held A Token? (for paying interest/rewards)

texts:
I'm writing a smart contract function that rewards users some rate of interest/reward for holding my stablecoin over owning competitors (Dai, Tether, etc). What is the most efficient manner to calculate this in a collect_interest function? I've studied how the Dai Savings Rate (DSR) and compound.finance work, and I think my implementation would need to be slightly different because users don't deposit the stablecoin into a contract like DSR or compound. They simply earn interest/rewards for owning the stablecoin in their address. The amount of stablecoin they own in their address can vary across time so their reward can vary as a result, and the function would have to check which windows of time the user has already collected interest/rewards so they don't collect interest more than once for each period.

Is this too complicated or too inefficient/costly? Should I just replicate compound/DSR and have holders of my stablecoin deposit it into an interest_rate smart contract and receive a 1:1 interest_rate_ERC20 token like compound? Or is there a simple way to do this that I'm not seeing? Thanks in advance, even just pointing me to an example link would help.


texts: Is it possible to view the bids on Ethereum Name Service (ENS)? For example, via https://etherscan.io, or https://myetherwallet.com


texts: How to make an ETH transfer from a contract that appears as an ETH transaction on the destination address?

texts:
I'm learning Solidity, and I've created a very basic contract that sends Ether from the contract to another address.

My contract works, and ETH is being transfered (I'm on Rinkeby). ETH is subtracted from the contract wallet and appears in the dest address. I'm also logging the the transaction with an Event.

But, there is no record of the tx on the destination address. Is this the expected outcome? Is it possible to transfer ETH from a contract to an address that appears as an ETH transaction on the destination address?

For reference, my contract code:

pragma solidity ^0.4.11;

contract SimpleSend {

uint public value;
address public dest;

event Init(address _dest, string _logos);
event LogWithdrawal(address _from, uint _amount);

function SimpleSend(address _dest) public {
    dest = _dest;
    emit Init(_dest);
}

function() payable public {
    value = msg.value;
    emit LogWithdrawal(msg.sender, msg.value);
    dest.transfer(value);
}
}


texts:
I'm getting an error using web3.eth.personal.sign, with it complaining that the call "Expected 0 arguments, but got 3". I call it in an Angular/Typescript/javascript environment:

this.bottleSig=this.web3.eth.personal.sign(this.bottleDataToSign, this.addressProd, this.passwordProd);

I'm using a recent version of the npm web3 package: 1.0.0-beta.33. I'm following the documentation at http://web3js.readthedocs.io/en/1.0/web3-eth-personal.html. I poked around under .../node_modules and looked at various web3* directories, but nothing obvious looked wrong, at least to me. Under node_modules/web3-eth-personal/src/index.js, it looks like it should be expecting 3 args:

new Method({
        name: 'sign',
        call: 'personal_sign',
        params: 3,
        inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null]
    }),

Any searching returns very few results, which don't seem to be applicable here.
Any thoughts on what's wrong? How to fix/workaround? Since beta, just need to wait till "fixed"? Thanks.

Update:

Also, in node_modules/web3/types.d.ts, I see:

export declare class Eth
. . .
personal: Personal

export declare class Personal
. . .
  sign()

Is this where the expectation of 0 arguments is gotten from?

Update2:

This link seems to offer some solutions, but a little too deep into directives and controllers for me!

http://danlec.com/st4k#questions/46692046


texts: ALERT: Transaction Error. Exception thrown in contract code. Metamask while interacting with contract

texts:
When I try to interact with my contract (.vue, Web3) via Metamask browser extension, I get the warning "ALERT: Transaction Error. Exception thrown in contract code." when I attempt to buy. The code works, and the site is fine, it's just that when I attempt to transact, I get the error, and the transaction doesn't go through.
Codes: Migrations.sol,
AdSpace.sol,
App.vue,Buy.vue,
truffle.js.
AdSpace.json is 11385 lines long, please let me know if needed.
I tried debugging with Remix, but it only highlighted that certain parts of the code were deprecated, nothing else. I was also able to successfully deploy the contract to Rinkeby testnet via Remix (for the 2nd time, I first deployed via command line).

This is what the contract looks like (not my picture, but this how the warning is shown). I have currently only deployed to Rinkeby and used it for all testing also. What could be causing this error?
Thank you.


texts: Meteor web3 sendTransaction - error cannot create property 'from

texts:
Hello ethereum experts,

I got the following error in the Chrome's Javascript Console:
ethereum_web3.js?hash=ee8d37819d18de934b202361e374522a33bbd060:3783 Uncaught TypeError: Cannot create property 'from' on string..

I'm on an MacOS(10.12.6) and using using Meteor (1.5) + Metamask. I started geth(1.6.7-stable) with the following commandline:

geth --datadir "net_a" --networkid 1234 --rpc --rpcport "8545" --rpccorsdomain "*" --rpcapi "eth,net,web3,personal" console 2>console.log

And the followings are my attempt to send a transaction:

// Transaction object
var tnxObj = '{from: "'+fromAddr+'", to: "'+toAddr+'", value: "' + amount + '"}';
web3.personal.unlockAccount(fromAddr, "pwd123", function(err, result) {
  if (err != null) {
    console.error("Error while unlocking account: "+err);
  }
  else{
    console.log("Account unlocked!");
    web3.eth.sendTransaction({tnxObj} , function(err, result) {
      if (err != null) {
        console.error("Error while sending transaction: "+err);
      }
      else{
        console.log("Transaction Sent!");
      }
    });
  }
});

Any idea what I did wrong?


texts:
I sent almost 3 ETH from my Bitfinex account to a wallet on Mist. I had just downloaded Mist and was not familiar with the Addresses.... I accidentally sent this ETH to my Mist wallet on the Rinkeby Test net. Is there any way to get this back? It has not appeared in my Testnet wallet balance. Please laugh and advise.

Thanks!


texts:
I've just recently started developing in solidity and was wondering if I was using the ERC20 standard correctly. When I attempt to test the contract on remix i get "Error: gas required exceeds allowance or always failing transaction" but on truffle, my tests seem to pass. Any thoughts?

Note: I dont actually have any contract address filled in when referring to the token or lottery contract I just used filler variable names.

pragma solidity ^0.4.17;

contract ERC20Interface {
    function totalSupply() public constant returns (uint);
    function balanceOf(address tokenOwner) public constant returns (uint balance);
    function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);

    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

contract Lottery {
    address public manager;
    address[] public players;
    // the address of the token that is used in the lottery
    address tokenAddress;

    function Lottery() public {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);

        players.push(msg.sender);
    }

    function enter() external payable {
        uint amount = msg.value;
        ERC20Interface tokenContract = ERC20Interface(tokenAddress);
        require(tokenContract.transferFrom(msg.sender, this, amount));
        //Add person to the contract if they send tokens
        players.push(msg.sender);
    }

    function random() private view returns (uint) {
        return uint(keccak256(block.difficulty, now, players));
    }

    function pickWinner() public restricted {
        ERC20Interface tokenContract = ERC20Interface(tokenAddress);
        // gets token balance of the lottery contract
        uint contractBalance = tokenContract.balanceOf(address(this));
        uint index = random() % players.length;
        //gets psuedo random number and sends to the player at that index
        tokenContract.transfer( players[index], contractBalance / 2 );
        // sends the remaining balance to a treasury
        address treasury;
        tokenContract.transfer( treasury, contractBalance / 2 );
        //resets player list
        players = new address[](0);
    }

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    function getPlayers() public view returns (address[]) {
        return players;
    }
}


texts: How to import a plain private key into geth or Mist?

texts:
This is such a basic question, but I can not figure out how to import a plain, unencrypted private key into geth or mist?

I tried geth account import 7[......]bla but it seems this command is always looking for an unencrypted keyfile.

Any ideas?


texts: Etherum network topolgy in private and main nets

texts:
I was wondering, what do the peers the ethereum client connects to, do? Do they store the block chain, fragments of it or point to other nodes that store it?

From a topology perspective, how does the ethereum network look like?

Is it something along the lines of:

[my client node] ---> [bootstrap node] ---> [nodes that hold the block chain]

where the bootstrap node contains a list of peer nodes each containing parts of the block chain, the "main net"?


texts: What is the regex to validate an Ethereum transaction hash?

texts:
I am building an application which requires user to paste the transaction hash of a transaction. But i want a regex string i could pass to the pattern attribute of the input element that receives it to validate it.
What is the general regexp that validates ethereum transaction hash?


texts:
I've set up an Ethereum node on a spare Raspberry Pi 2 with a 64GB memory card. I used the excellent instructions found on github. The blockchain has synced. I have a few questions:

How can I verify that the network sees my node?
Do I need to configure any port forwarding?
Anything else that should be on my radar?


texts: Is there a way to call a constant function asynchronously?

texts:
I'm trying to invoke a constant function test from a webpage. I've injected web3 object through MetaMask.

contract A {
     function test(uint8 x) constant returns(uint8) {
        return x + 10;
    }
}

My JS code:

var contractA = web3.eth.contract(abiDefinition).at(address);
var retVal = contractA.test(10);

I get an error:

The MetaMask Web3 object does not support synchronous methods

Is there an async version of this api method?


texts: Deploying Contract Factory Structure in Remix

texts:
I am working on a Contract Factory Concept.  The model below describes the structure.   I have problems

contract ParentA
contract ChildAA is ParentA
contract ChildBB is ParentA

contract ParentB
contract ChildCC is ParentB
contract ChildDD is ParentB

contract FactoryXX {Creates Contracts of Type ChildAA and ChildBB, and maintains a Map of all the contracts generated as State Variables}
contract FactoryYY {Creates Contracts of Type ChildCC and ChildDD, and maintains a Map of all the contracts generated}

I had a couple of questions on the deployment of such a structure in Remix and test it out:

How to deploy the contracts in Remix so that I can access all the functions of both the Factory contracts.  Do I have to deploy each contract separately?  They are all connected.
Is there a concept of a "Main" - that can tie the structure together, so that I can deploy the Main contract and be able to call all functions of the Factory Contracts.  Will Delegate function call help here?


texts: Who is the msg.sender when calling function of ERC20 token contract inside a smart contract?

texts:
Here is a function in a smart contract to call transferFrom in ERC20 token contract.
pragma ^0.7.0

interface ERC20Token {
   function transfer(address recipient, uint256 amount) external returns (bool);
   function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
 }

contract MyContract {
  ...
  function depositEscrow(uint256 _value) payable external  returns (bool) {
        ...
        ERC20Token _fex = ERC20Token(contractFEX);  //<<==create instance of the ERC20 token contract with its address
        _fex.transferFrom(msg.sender, address(this), value);  //Who is msg.sender in transferFrom? is it the MyContract address?
        ...
        return true;
    }

}
When executing _fex.transferFrom(), is msg.sender the address of MyContract?


texts: How to link libraries in browser-solidity?

texts: How to link library in browser-solidity? While creating a contract using library, solidity compiler requires to link the contract with the library. But there is no options in the browser to provide it. Contract is not created as it has lib's placeholders in bytecode similar to  _______LibName_________


texts: What's the point of RLP over other encoding formats?

texts: What makes Ethereum need an encoding like RLP? What's so special about this format over others? How does it fit in specifically for Ethereum's needs?


texts:
I am trying to integrate MetaMask version 5.3.1 in my Dapp. I am unable to call web3 functions like getBalance with the given instance, also I am unable to post a transaction.

Is there any documentation on that?

Error:

ethereum.eth is undefined for calling web funcrtions like
getBalance etc
Transaction from address isn't valid for this account while sending a
tx to metamask

The code I am using:

let metamaskTx = async () => {
    console.log("is metamask" , ethereum.isMetaMask) // true
    let accounts = await ethereum.enable()
    console.log(ethereum.selectedAddress) // prints selected address
    console.log(ethereum.networkVersion) // prints network ID
    // ethereum.eth is undefined
    let balance = await ethereum.eth.getBalance(ethereum.selectedAddress)
    console.log(balance)

    let transactionParameters = {
      to: '0xe58db6b23575a93c185f756618f8e42745d7292b',
      value: '0x1'
    }
    // fails with RPC Error: Error: Transaction from address isn't valid for this account
    ethereum.sendAsync({
      method: 'eth_sendTransaction',
      params: [transactionParameters],
      from: ethereum.selectedAddress,
    }, function(err, res){
      console.log({err})
      console.log({res})
    })
  }


texts:
I'm running geth with

geth --rpc --rpccorsdomain "localhost"

and ethminer 1.1.4 in a separate terminal, and I've noticed that in the geth console I'm getting a lot of messages that simply just say "short write".  E.g.:

I0225 13:05:53.940248 rpc/server.go:347] short write

Couldn't find any documentation on this - anyone know if this is something to worry about?


texts:
Im trying to rewrite the all ethereum address creation and Tx creation in PHP and Im almost there. I have implemented a sha3 but now Im confused  on if its giving me the correct output because it seems ethereum sha3 implemenations lack consistency when dealing with prefixed hex characters Which of the following scenarios has the correct sha3 of this RPL hash.
In my php I have generated this RPL hash (its a hex output)
PS Iknow the difference between Ethereum sha3 (Keccak) and standard sha3
     ec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000080038080

Now using Parity node and web3js I create a sha3().

Scenario 1

web3.utils.sha3('ec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000080038080')

or

web3.utils.sha3('ec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000080038080',{encoding:'hex'})

  '0x9a8419514d3c7382a6dafc67adf18ac13b818687e9a074a0cee123e0f9a483d8'

Scenario 2

web3.utils.sha3('0xec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000080038080')

  '0xf1d622e8725ef0dd84e1e65239a0ecac4428b05a2ee0c219739e6e85eb57a8b6'

scenario 3

Using etheruemjs

var util = require('ethereumjs-util');
var hashed = util.sha3('0xec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000000038080')

  '0x0e79fdc47ef979edbbed33d347f42da74849149139db9d5a58a4038ae6bdc99c'

scenario 4

(Using etheruemjs)

var util = require('ethereumjs-util');
var hashed = util.sha3('ec0185055f9408bc82520c94145e99f7bc840f3ea42d9a64221f041f9955dca2880429d069189e000080038080')

  '0x9a8419514d3c7382a6dafc67adf18ac13b818687e9a074a0cee123e0f9a483d8'


texts: Can I define global variables in Library contract?

texts:
I want to use some variables in multiple functions in my library contract. Is there any way to do that? I got following error code for my library code.

library myArithmetic {
    bytes1[10] mData;

    function doSomeMath(bytes1[10] _input) public returns (bytes1[10]) {
        for(uint8 i=0 ; i<10 ; i++){
            mData[i] = _input[i];
        }
        //do some my math..here..
    }
}

I have error, like  TypeError: Library cannot have non-constant state variables
I do not want to make each of my functions with several parameter input and return, and to another functions..so on.
Is it possible to do that??

I know in the normal contract, the mData will be storage variables. But library does not allow to have state variables. So I cannot define such this way?


texts:
I have the two following contracts: tryContract and testData. The testData contract aims at fetching data from the tryContract contract utilizing its get_attributes function. Before doing any fetching, assume I fill in the map in the tryContract contract using the following inputs:

["0x0","0x1","0x2","0x3","0x4","0x5","0x6","0x7","0x8","0x9"]

pragma solidity ^0.4.21;
contract tryContract {
    mapping (address=>bytes32[10]) Map;

    function fill_map(bytes32[10] _attributes) public  {
            Map[msg.sender] = _attributes;
    }

    function get_attributes(address _id) view public returns (bytes32[10]){
      return Map[_id];
    }
}

contract testData {
    address Address;
    //function takes address of user as input
    function get_address (address _Address) constant{
        Address = _Address;
    }

    bytes32[10] Data;
    //function takes the address of previous contract as input
    function fetch(address _try_Adress) public view returns (bytes32[10]) {
        tryContract r = tryContract(_try_Adress);
        Data = r.get_attributes(Address);
        return (Data);
    }
}

After running the code and trying to fetch the data stored, the output I receive is incorrect. The output is:

["0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0"]

Why does it not recognize the data that had been previously stored in the map?


texts: How to store the user activity in smart contract or can I use smart contract to track all user activity on my site?

texts:
New to blockchain and smart contracts. Been doing research and I am having a CRUD application in SQL Server.

I want to use ethereum private blockchain to record all the user activity. Can I use for that purpose?


texts: Metamas - Infura problem. Cannot read property 'currentProvider' of undefined

texts:
I got a problem. I  am using code below to connect to the eth from node.js app. Everything works perfect as long as I have installed MetaMask in my browser. I can be logged in, logged out, all good when I fetch the data. Problems comes when I uninstall MetaMask. It writes, that currentProvider is undefined.
Is there a workaroud? What am I doing wrong?

System: Windows ''
Browsers: Brave, Chrome, Opera (havent tried others)
Node version: 8.12.
web3 version:  1.0.0-beta.46

import Web3 from 'web3';

var web3;

if (typeof window !== 'undefined' && window.web3 !== 'undefined') {
    web3 = new Web3(window.web3.currentProvider);
} else {
    const provider = new   Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/...' );
    web3 = new Web3(provider);
}
export default web3;


texts: Transaction using Metamask works. Fails with web3.py

texts:
I have two transaction, the first from MetaMask (everything is fine)

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

the second using web3.py (it seems to be identical but fails)

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

Here is my part of the code: (I hope it is clear what is going on - it is copied from a class)

# same as in the working one
abidata = '0x338b5dea000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f49800000000000000000000000000000000000000000000000000002d79883d2000'
trans = {
                        'to': self.address,
                        'from': self.ethapi.address,
                        'data': abidata,
                        'value': 0,
                        'chainId': 1}
# transaction gas data [pseudocode]
trans_new = trans.copy()
nonce = w3.eth.getTransactionCount(self.address)
gas_price = self.get_gas_price()
gas_price_wei = self.w3.toWei(gas_price,"Gwei")
trans_new["gas"] = 250000
trans_new["nonce"] = nonce
trans_new["gasPrice"] = gas_price_wei
signed_transaction = account.signTransaction(trans)
w3.eth.sendRawTransaction(signed_transaction.rawTransaction)

Thanks for any hint!


texts: Updating Smart Contract in Quorum with no change to the smart contract address

texts:
Understand that a smart contract address is deterministically computed from the address of its creator and how many transactions the creator has sent and thus every new smart contract deployment will generate a new address -- this makes a great deal of sense for public ethereum.

In Quorum, if I need to make an update to a smart contract (e.g., add/modify a new trading rule/logic) which has already been deployed, is there some way to ensure that the DApps connecting to the old smart address can swing over to the new smart contract seamlessly? i.e., no downtime needed to rewire the DApp to the new smart contract address.

Say, if downtime is not permitted (critical production system), transactions will continue to be sent to the old smart contract address, is there some way to migrate all the delta transactions sent during this period?

Nathan Aw (Singapore)


texts: Meaning of 'using SafeMath for uint256;'

texts:
Hi I just started to study solidity. Can you tell me what is using SafeMath for uint256;?

https://github.com/decentraland/mana/blob/master/contracts/ContinuousSale.sol#L10


texts: What is the difference between a transaction and a call? In some interfaces, I can interact with contracts via calls or via transactions. What is the difference between the two, and can contracts also do transactions and calls?


texts: What's the formula to calculate the mining profitability for ETC?

texts:
I know there are calculators for mining profit, but I need to include the same thing in an app I'm building, what formula do they use for Ethereum Classic?
Also, can I use the same formula for other cryptocurrencies or is it different every time?
Is there some website/guide/etc. that I can use to learn more about this?


texts:
I'm using Ether.js for my react native app to create mnemonic.
i want use Wallet.fromMnemonic(code, path) to get key pairs but when i send bitcoin Derivation Path i get and ethereum private key which is started with 0x.Is there any way to use ether.js to get other coin key pairs?


texts: Will OmiseGO (OMG) become redundant when Ethereum migrates to Proof of Stake?

texts: When Ethereum migrates to "Proof of Stake" to validate the transactions. Will OmiseGO (OMG) lose its value ? as scalability issues in Ethereum would be resolved after the migration and I am trying to understand what purpose would OMG coin serve ?


texts:
In current geth, how long (in terms of blocks) will a state tree node put into the death row before being pruned? Does this vary among different sync mode? And can we configure it?

Besides state trees are pruned, will blocks/ transactions/ transaction receipts stored in geth node be 'pruned' after certain period of time? Or do they persist unless i re-sync the client?

Edited on 2 Nov 2017: For the 2nd question, this post answered that only state trees are pruned. Blocks or any other data remain since a joining node needs these data to sync.

Edited on 13 Nov 2017: For the 1st question, seems Vitalik's state trie pruning was not implemented. (Ref: this PR). So that's no such death row (mentioned by Vitalik) config in geth. And EIP-161 seems to be the only state trie pruning technique available in geth now. So in full sync mode, no past states of existent accounts are pruned and all state tries from genesis block to current block are kept. And in fast sync mode, only state tries of recent blocks with dead accounts pruned are stored. Am I correct?


texts: Is it possible to call payable functions of smart contract using web3j’s smart contract wrappers?

texts:
How do we call payable functions of smart contract using web3j?

UPDATE:

I'm going to change generated smart contract wrapper class manually. Now I have:

    public Future<TransactionReceipt> uploadSignedString(Uint256 verificationId,
                                                     Utf8String signedString) {
    Function function = new Function("uploadSignedString",
            Arrays.<Type>asList(
                    verificationId,
                    signedString
            ),
            Collections.<TypeReference<?>>emptyList());

    return executeTransactionAsync(function);
}

and I'm going to add manually:

public TransactionReceipt uploadSignedStringPayable(Uint256 verificationId,
                                                    Utf8String signedString,
                                                    BigInteger weiValue)
        throws InterruptedException, TransactionTimeoutException, IOException {
    Function function = new Function(
            "uploadSignedString",
            Arrays.<Type>asList(
                    verificationId,
                    signedString
            ),
            Collections.<TypeReference<?>>emptyList());

    return executeTransaction(FunctionEncoder.encode(function), weiValue);
}

and as I see it can be done only as a sync call.


texts:
I'm trying to get the ether balance for any ethereum address. I've set up a node with the Ethereum daemon, but as far as I can tell, using eth_getBalance you can only get the balance of your own Accounts, and you can't query against an arbitrary address in the blockchain.

Is there a way to do this using the JSON RPC API? If not, how do block explorers provide this information?

Thank you!


texts:
I want to be able to transfer files from one Ethereum wallet to another using Mist. Is it possible to this?

The files I am planning to transfer are small files. They would be less than 5mb.

If yes, how is it possible?


texts: Installing Web3 stuck on fetchMetadata: sill resolveWithNewModule http-https@1.0

texts: I am trying to install web3 for ethereum but it keeps sticking on this fetchMetadata


texts: ENS on Rinkeby - Network does not support ENS?

texts:
I was able to register the ENS domain on Rinkeby, as the network supports ENS.

My TX: https://rinkeby.etherscan.io/tx/0xd42b64ab03387d7ca405e7ba7b85ce893444a141e7a7de174f0361e2c4231674

My subdomain: testing.estoniadao.eth

Does it support or does it not?

Domain is registered: https://app.ens.domains/name/estoniadao.eth

Cannot lookup on Etherscan, cannot find any other blockchain explorer supporting Rinkeby.


texts: Easiest way to get maximum transaction stack depth level

texts:
When a contract causes an addresses code on the EVM, a stack depth counter is kept. I need this stack information as I am producing a EVM execution visualiser.
This stack depth changes when a function is called.

I am currently getting that information by running debug.traceTransaction in my local geth instance and parsing the returned JSON. However, I would like to know this information BEFORE I get the returned trace JSON.

Does anyone know an easier way (an API)?

Thanks


texts: When is a transaction signature checked in a contract?

texts:
In the Solidity tutorial and examples here, I don't see any signature checking. In particular, in the contracts provided there, they don't check whether the sender of a message is actually the person who claims to be. So, my question is:

Question: In contracts written in Solidity,  do we usually check the signature (of the message sender)?  if yes, when?


texts: How do I execute this Timelock contract on Remix Ethereum?

texts: i am using a timelock smart contract but im not sure how to input the proper value to use this function on remix. what exactly do i put in data byte field? how do i get that data from the other contract that i want to execute?


texts: Does the 10,000 refund apply to booleans too?

texts:
I understand from this thread that you're refunded up to 10,000 gas when setting a value to 0.

Does this also apply to boolean values? That is, going from true to false?


texts: Is the value of a mined 5eth block significantly higher than 5eth on its own?

texts:
If I buy 5eth from a site like coinbase, I own 5eth and can spend it however. However, if I mine 5eth, I am entitled to the gas from transactions originating from the block.

Does this then mean that the value of mining a block (which is currently 5eth) is worth significantly more than the plain 5eth (assuming people continue to use eth and that I spend that 5eth)?


texts: ETH same transaction different amount of gas used

texts:
The two transactions:
a) https://etherscan.io/tx/0x9227f7b00bf2c98a7e16eb5ab90c04df5b49698297ee7f52c765d5218af395ad
b) https://etherscan.io/tx/0x1af76244391e06c375e8511f4140191fb874362b238aa9b6fdacc072e35cd778
are exactly the same but as you can see TX (a) failed as it used up all its available gas. The limit was set to 53,356. The second TX (b) is exactly the same but gas limit was set to 160,000 and the transaction succeeded. Although it used only 38,368 gas which is less than the limit of TX (a). But before I get answers like "some instructions take a different amount of gas depending on XYZ" I checked the execution of the contracts:
a) https://etherscan.io/vmtrace?txhash=0x9227f7b00bf2c98a7e16eb5ab90c04df5b49698297ee7f52c765d5218af395ad
b) https://etherscan.io/vmtrace?txhash=0x1af76244391e06c375e8511f4140191fb874362b238aa9b6fdacc072e35cd778
They seem to be doing the exact same thing with the exact same amounts of gas used. So why did the first transaction fail? And why does is say there's only 31700 gas to start with on TX (a)?


texts: Conceptualizing smart contract variables

texts:
I'm having trouble figuring out how variables are stored on the block chain. How can a smart contract be immutable and have global variables that can change?

Just say I a simple contract like below...

contract SimpleStorage {
  uint storedData;

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

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

I understand this code will be broken down into byte code and stored on the blockchain. What I don't understand is where the storedData variable will be saved when I set a new value on it. Wouldn't the bytecode on that block need to be updated once I update the value?


texts: Solidity: which method should I use to call a function from an external Contract?

texts:
When using solidity, I have a doubt when I need to call a function which was created in a different contract. I know 2 ways of doing it, and I don't understand what is more recommendable and why. These are the ways I know:
Method 1:
contract A {
  function foo() external {
    return true;
  }
}

contract B is A {
  foo();
}

Method 2:
contract A {
  function foo() external {
    return true;
  }
}

contract B {
  function callFoo() external {
    A a = A(addressA);
    return a.foo();
  }
}

Could anyone tell me the differences, and when it is more convenient to use either Method 1 or Method 2?
Thank you!!


texts: Uncle blocks got generated during the mining process with only one node[one miner]?

texts:
In order to increase the speed to mining, I edit some code in consensus.go to reduce the speed of increasing the difficulty of mining. Somehow, when I have my speed of 20 per block, I found that the transaction will be stuck in pending status sometimes and it will never be mined by the miner. In addition, based on the mining info, the block with the corresponding transaction seems to become the uncle block.

Therefore, does anybody know what is going on here and what is the problem?

And also, I found the miner always mine two blocks at the same time.
My guess is that 2 blocks are mined at the same time and since mining a transaction will take a bit of time, so the block with the pending transaction will be considered as the uncle block because the new block is appended to the chain quicker.


texts: Is it possible to save data somewhere other than in the node when using web3.js?

texts:
Is it possible to use the web3.js apis with geth and store the sensitive data elsewhere and specifically not save any data on the node?

I know I can save the sensitive data by looking at the docs, however I'm unsure if I can prevent the node from storing any data in it's database. I'm fine with it being in memory for the purpose of executing the request I made.


texts:
I have tried for await ipfs.files.add(this.state.buffer)
I have tried ipfs.add(this.state.buffer, (error,result)=>{console.log('ipfsresult', result)
I'm new to all this. Any help will be appreciable.


texts: Call() function returns "Error: Returned values aren't valid, did it run Out of Gas?"

texts:
I am connecting to Binance Smart Chain mainnet via rpc. The error message I get is following:
(node:17667) UnhandledPromiseRejectionWarning: Error: Returned values aren't valid, did it run Out of Gas?
You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
    at ABICoder.decodeParameters (/home/username/basc/node_modules/web3-eth-abi/lib/index.js:286:15)
    at Contract._decodeMethodReturn (/home/username/basc/node_modules/web3-eth-contract/lib/index.js:470:22)
    at Method.outputFormatter (/home/username/basc/node_modules/web3-eth-contract/lib/index.js:760:42)
    at Method.formatOutput (/home/username/basc/node_modules/web3-core-method/lib/index.js:147:54)
    at sendTxCallback (/home/username/basc/node_modules/web3-core-method/lib/index.js:523:33)
    at /home/username/basc/node_modules/web3-core-requestmanager/lib/index.js:293:9
    at XMLHttpRequest.request.onreadystatechange (/home/username/basc/node_modules/web3-providers-http/lib/index.js:98:13
)
    at XMLHttpRequestEventTarget.dispatchEvent (/home/username/basc/node_modules/xhr2-cookies/dist/xml-http-request-event
-target.js:34:22)

These are versions of modules:
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "web3": "^1.3.0"
  }

I am calling a getAmountsIn() in this snippet and expecting "amount" to be returned.
//Check price of a pair
async function checkPair() {
        const WETH = await factoryContract.methods.WETH().call()
        const amount = web3.utils.fromWei('1000000000000000000', 'Ether')
        const getAmountsIn = await factoryContract.methods.getAmountsIn(amount, [WETH, "0xbf5140a22578168fd562dccf235e5d43a02ce9b1"]).call()
        console.log(getAmountsIn)
}

I am accessing this contract (see below) and its ABI in a standard way. I brought the ABI directly from BSCscan and it seems to be working accurately. In fact calling this getAmountsIn on WBNB/BUSD pair went correctly without an error. Other pairs do not work.  https://bscscan.com/address/0x5334defbffdd7ec8705878db226cc4a0b498cd12#code
I tried lots of other known solution but none of them work. Essentially, we can be sure it is not 'out of gas' error, it is rather related to ABI decoding or encoding. I will appreciate your help.


texts: Waiting for transaction to be mined - Rinkeby

texts:
Trying to send a contract to Rinkeby. I get waiting for transaction to be mined indefinitely.

Any ideas why it's not mining? Seems to be fine on rinkeby.io.

Injection Web3 from Remix IDE via Metamask.


texts: on deploy MultiSigWalletWithDailyLimit: Error VM Exception while processing transaction: revert

texts:
I'm trying out a very simple js script through truffle to create the Gnosis multisig wallet on a local testrpc net. However it always fails.

JS deploy file:

const MultiSigWalletWithDailyLimit = artifacts.require("./MultiSigWalletWithDailyLimit.sol")
module.exports = async function (callback) {
  let wallet
  try {
    wallet = await MultiSigWalletWithDailyLimit.new([multisigWalletAddress1, multisigWalletAddress2], 2, multisigWalletDailyLimit)
    console.log(`MultisigWallet: ${wallet.address}`)
  } catch (error) {
    console.log('error → ', error)
  }
}

Command:

truffle exec exec/KickStarter/deploy.js --network testrpc

Error:

error →  Error: VM Exception while processing transaction: revert
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43303:16)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:331156:36
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:314196:9
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:315621:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70159:18)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70449:12)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70604:12)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70564:24)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1086:12)


texts: can erc20 token transaction work on Fast Sync-ed node ? OR it need Full node to transact any token?

texts:
I need help regarding couple doubts.

Which sync method is good for me. My client is asking me to make an Exchange website. Also ERC20 tokens will get transacted in this exchange.

Do I need a full node? Or Fast sync is Okay for ERC 20 tokens. I don't know exactly.

For this questions I need to know WHAT a Fast Sync node CAN NOT do what a Full node can do?

Also which one I should sync? GO/Geth or CPP node ?
Do they vary in performance or any other parameter ?

Any new suggestions are welcome guys.


texts: Best way to perform a Token conversion formula

texts:
So I am having difficulty with multiplying in Wei.

=======================================================================
Here is the short version:

I want to multiply 7000 ether by 1.25 to get 8750 ether as the expected result.

=======================================================================

Here is the long confusion version:

I have a Smart Contract that pulls the USD value of ETH then performs a conversion of the USD value at 75 cents on the dollar an issues the tokens appropriately.

My issue is multiplying in Wei.

I would have loved to do all the calculations in Wei but I need to have a USD conversion as part of the formula.

I do want to continue using SafeMath in the calculations.

Say I have 7 ETH sent to the contract
The ETH price is 1,000 USD at the time
Which makes the USD value at 7,000
The exchange rate is 0.001 USD to ETH

The tokens are issued at .75 to 1 dollar so I multiply by 1.25 to get the 8,750 tokens as the final number in regular math

I have all of it except multiplying by 1.25

I assumed I would multiply by 1250000000000000000 Wei for 1.25 but my final number it way to large.

Whats the right way to perform that math in solidity?

Here is my code:

pragma solidity ^0.4.18;

import "./SafeMath.sol";
import "./Ownable.sol";
import "./usingOraclize.sol";

contract Test is Ownable, usingOraclize {

  using SafeMath for uint256;

  uint public ETHUSDPriceUINT = 1000000000000000000; // this is a place holder for the Oraclize API call back variable

  function Test(address _tokenAddress, address _multiSigAddress) {

  }

  function buyTokens(string _ETHprice) payable returns (uint) {
      result = _ETHprice; // provide the current price of ETH in USD
      uint ETHContributionInWei = msg.value;
      ETHUSDPriceUINT = parseInt(result, 2); // let's use two decimal points
      uint exchangeRate = ETHUSDPriceUINT.div(ETHUSDPriceUINT);
      uint USD_Value = ETHContributionInWei.mul(ETHUSDPriceUINT);
      uint tokenFactor = 1250000000000000000 wei;
      uint numTokensIssued = USD_Value.mul(tokenFactor);

      return numTokensIssued;

  }

  function () payable {

  }

}


texts: Uncaught Error: CONNECTION ERROR: Couldn't connect to node http://localhost:8545

texts:
I am running ganache app locally in windows 10 and trying to connect with node app on localhost:8080 but getting below error

Please help me!


texts: I am getting the following wrror while i tried to do node  and also truffle test

texts:
Error: Cannot find module 'web3'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (F:\tuffle\toke.test.js:3:14)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at C:\Users\user\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:250:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (C:\Users\user\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:247:14)
    at Mocha.run (C:\Users\user\AppData\Roaming\npm\node_modules\truffle\node_modules\mocha\lib\mocha.js:576:10)
    at resolve (C:\Users\user\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\test.js:116:1)
    at new Promise (<anonymous>)
    at Object.run (C:\Users\user\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-core\lib\test.js:115:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Truffle v5.0.33 (core: 5.0.33)
Node v10.15.0


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


texts:
I'm creating a tool to track ERC20 token movements. My assumption is that tokens moves or via transfer or transferFrom function. The first one is the first spreading of the token, the other one when the token is transferred from an owner to another.
Is this assumption correct?
Apparently with a few experiment I did I can see just the transfer call...


texts: encodeABI() throws Uncaught (in promise) Error

texts:
I am trying to use encodeABI() on one of my contract methods like this:

signTx = async () => {
   ...
   const response = await contract.methods.recoverAddr(fixed_msg_sha,
   v_decimal, r, s).encodeABI()
   ...
 }

Here is the contract implementation of the method:

  function recoverAddr(bytes32 msgHash, uint8 v, bytes32 r, bytes32 s) public returns (address) {
    address signer = ecrecover(msgHash, v, r, s);
    emit LogMyHash(msgHash);
    emit LogMyAddress(signer);
    return signer;
}

But what I get is this error:

However, when I try to use call() or send() on my contract instance, it works just fine. What am I missing here? Any help is much appreciated!


texts: How does this function potentially violates the Checks-Effects-Interaction pattern?

texts:
I am developing a smart contract that integrates with the DAI stable coin. In the function below, you can see that I have followed the check effects interaction pattern, so how come I still get a prompt from the Remix compiler that I am potentially violating the check effects interactions pattern?

function depositParty (uint amount) public payable {
    require (daitoken.balanceOf(msg.sender) >= amount);
    accountBalance [msg.sender] += amount;
    daitoken.transferFrom(msg.sender, address(this), amount);


texts: Get the public address & key associated with one of the Ganache accounts using Web3.js?

texts: How do I get the public address & key (not address or account) for one of the accounts that Ganache displays on startup using Web3.js? I need it for a unit test I'm creating that tests transaction signing on the Ganache network, but without using Metamask. When Ganache starts up I see 10 accounts and 10 private keys along with the Mnemonic words, but no public addresses.  I am already retrieving the accounts list from Ganache using web3.eth.getAccounts(), but I don't know how to get the public address & key associated with a particular account.


texts: Contract's functions: Calls vs Transactions

texts:
I have a doubt about the behavior when you call a contract's function.

I know if you call a function by sending a transaction that code will be executed in every single node of the chain. But what about calling constant functions? In that case, is the code executed in all the nodes also or just in the caller node?


texts: Can Nethermind client run a Binance/BSC node?

texts:
Coming from a .NET background, I'm interested in running a BSC node using Nethermind. is it possible?  If so, how would you configure it?
Thanks!


texts: walletlink and/or walletconnect on mobile browser

texts:
I want to use DeFi apps over my mobile or mobile browser. Is there a way to connect to my wallet (Metmask, etc.) to the DeFi apps on my mobile or mobile browser?
I don't want to use the DeFi apps on my desktop only.


texts: A smart contract's storage problem , further ERC ？

texts:
Er .. I have a question about smart contract , a single smart contract's storage capacity

Follow the answer is this question：

Is there a (theoretical) limit for amount of data that a contract can store?

Can a contract's internal storage keep increasing forever?

In conclusion , A single smart contract only can storage 1.46GB

If , the limit is 1.46G：

My question is , will a smart contract storage be full of data , then can't work？

so , how ERC token storages large number of users and make function still work？

Is 1.46GB really enough for storaging many users and doing other operation？

If , a single smart contract has no limit ：

there is no limit problem , but gas is problem for operation.

If I actually do precise operation (like: query) to my data , I can keep my data growing whatever , and my function won't happend out of service situation.

Also , Is this a reason that why ERC token can be afford large number of users？ But how did they make it (not exceed gas)？

I'm silly on base problem on smart contract , If any can tell or tag resource(associated knowledge) , really appreciate..!


texts: if I have a contract which I use to store patient weight. I want to display last 5 weights of that patient. how can I access previous value on weight?


texts:
i'm currently learning solidity and was toying around with the now keyword. This function is supposed to mint new tokens at an inflation rate of 0.05% per year. I'm just not sure if the now keyword is reliable since, from my understanding, it is based on information from miners which could be faulty. Any thoughts? Does this code work and is it reliable?

    uint256 public deploymentTime = now;
    uint256 public year = 0;
    uint256 public supply = 90000000;

function checkInflation() returns (bool success)
{
    if(year >= 5) {
        return false;
    }
    else if (now >= deploymentTime + 31557600) { //31557600 seconds per year
        uint256 supplyIncrease = (supply*5) / 100;
        mintToken(0x8E73AEF2448068d4e31F86Aa08279465339fF601, supplyIncrease);
        year+=1; // increase the current year count
        supply += supplyIncrease; // increase supply count
        deploymentTime += 31557600; // increase the time since deployment
        return true;
    }
    else {
        return false;
    }
}