texts: How to show 18 decimals token balance in readable format?

texts:
I have number which has 18 decimal points.
I want to get the digits before the decimal points in a variable and the digits after the decimals in another variable.

Let's say the original variable value is 100,

I want to show that like this 100.000000000000000000 but now I am getting 100000000000000000000 (without decimal point)

I am trying to print the digits before the decimal points in a HTML element and the rest in another HTML

var original = data['result'];
$(".original").html(original]);

This prints 100000000000000000000 in the element original and that's fine.

Now I want to  print the digits before the decimal points in a HTML element 'beforeDecimal' and point then the rest

So my mark up is:

 .

var beforeDecimal = data['result']; // how do I have to change this ?
$(".beforeDecimal").html(beforeDecimal]);

var afterDecimal = data['result']; // how do I have to change this ?
$(".afterDecimal").html(afterDecimal]);

if I use var beforeDecimal = parseFloat(data['result']).toFixed(4); is shows 100.00000000000e+21 but I want 100 . 000000000000000000

How can I do this?


texts: One of the requirements of building our company's DApp is to maintain a separate, custom Merkle Patricia Tree that contain's data from our company's platform only. The Tree needs all CRUD operations for each ethereum accounts, and must be saved across the ethereum network. So basically I need a State trie equivalent of Ethereum but only with our custom data. Can anyone give me hints on how to do this or reference to where I can start?


texts:
I want to create my own coin but I want to experiment first. I'm trying to deploy in the Eth wallet. All the websites to get Ropsten eth are down.How can I try making a coin without spending any money? Or do I need to? Is there a better way to deploy? I understand the code for the most part but I'd like to know how to run it and try things.

Ropsten address
0x56212F540b4a1057cEBD6d10EE66D56a527CfCA2


texts: Fallback function does not work solidity

texts:
Solidity version is 0.5.1
the buyTokens function works fine when i call it directly from myetherwallet or remix, but it does not work when i send some ether to address. I think it doesn't even call the fallback function.
the buyTokens function is an public payable function
function () external payable {
        buyTokens(msg.sender);
    }


texts: Questions about the Yellowpaper notations

texts:
Got some questions on notations (Page 4)-

What does function/tuple L represent? Also, what are its subscripted subparts? (Equations - 6, 7, 9)

What does  mean? (Equation - 9)

What do these symbols mean - ,  and  ? (Equations - 11, 12)

The names of the symbols would be a help too. Thanks a Lot for your time and efforts.


texts: What parameter type should I use for contract methods that specify floating point amounts?

texts:
In my dApp the user sets the entry fee for the game they are creating. The entry fee for games will usually be between $5 USD and $50 USD. What unit should I use for the contract method that accepts payment for the game (i.e. - the type to preface the relevant method parameter with)? Should I use: wei, gwei, eth, etc.?

Also, what Solidity type should I use internally in my contract that does a fair number of numeric calculations when it comes time to pay the players? I assume a fixed point type like uint* is not a good fit? I'm asking this question both for storage and memory variables.

I assume for percentages I can just use uint and divide by 100 internally?  But I'm asking the above questions for parameters that will be receiving floating point numbers generally.


texts: Paying gas from different Address and sending from different

texts:
I am use Web3J 4.5.7 with Java 1.8
I am integrating ERC20 tokens for an exchange. We have a scenario.
A user doesn't have any ETH in his address, but has ERC20 token, let's say USDT. Now the user wants to withdraw his USDT to some other wallet. But as he doesn't have any ETH in his wallet to cover the gas fees, transaction results in error.
I am trying to figure out a way to resolve this.
Is there any way, where we can assign one exchange Wallet which pays all the gas for all the transfer events ? If yes, can someone point to correct docs or maybe a small code snipped on how to achieve it.
Thanks.


texts: How to invoke functions or get data in/of a contract from another contract?

texts:
I have a contract that creates instances of a contract and now I have to get the data of the newly created contract. Is there a way to do that?

This is my contract that creates new contracts:

pragma solidity ^0.4.8;

contract myFirstContract
{
    address[] public childContracts;
    uint public idd;
    string public name1;

    function newContracts(uint _id,string _name) public returns(address _newContract)
    {
        uint id=_id;
        string memory name=_name;
        anotherContract a = new anotherContract(id,name);
        childContracts.push(a);
        return a;
    }

    function getContractData(uint _address) public
    {

    }
}

contract anotherContract
{
    string public name;
    uint  public id;
    constructor(uint _id,string _name) public
    {
        name=_name;
        id=_id;
    }
}

Now, let's say that there is a new anotherContract getting created and I have the address of this contract then how do I get the data in this new contract.


texts: js commands which used to work in node console not working when accessed from webpage

texts:
I am unable to contact the local testrpc server that I set up when I am executing the javascript file through a webpage. Everything works fine when the js file is executed from the node console

My html code:

<html>
    <head>
        <script type="text/javascript" src="./malware.js"></script>
    </head>
    <body>
    </body>
</html>

malware.js file

//create web3 object
const Web3 = require('web3');
const fs = require('fs');
//alert("testing");

var web3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));
var code = fs.readFileSync('malware.sol').toString();

//deploy a smart contract instance from a node using code information generated during compilation
var malwareContract = web3.eth.contract(contract.info.abiDefinition);
var deployedContract = malwareContract.new({data: contract.code, from: web3.eth.accounts[0], gas: 4700000});

//save the smart contract instance to access it later
var contractInstance = malwareContract.at(/*here the value obtained from contractInstance.address in the node console is used*/);

//here I am using an alert to check contractInstance.address
alert(contractInstance.address);

No part of the javascript code is running when it is accessed through the webpage.When I uncomment the first alert, nothing happens. However when I am running the same code in node console everything is printing as expected.

On further research, I found that require functions can't be directly called
from a webpage. What is the alternative for using web3 libraries


texts:
I've got a contract which creates another contracts and stores them in a list. How can I check that contract with specific index already exists?

import "./User.sol";

contract Main is Ownable {

    User[] private _users;

    function createUser(uint256 _id) onlyOwner external {
        // How can I check if User in list of _users??
        // I tried different approaches but it gives compilation or VM Exception while processing transaction: invalid opcode errors

        // require(address(_users[_id]) == address(0), "User already exists.");
        User user = new User(_id);

        emit UserCreated(user, _users.length);

        _users.push(user);
    }
}


texts: Create a child contract from a parent contract and forward the sender amount to it?

texts:
I want to spawn a child contract from a parent/owner contract. I would like the caller of the creating function on the parent contract to pay for gas and fee and also pass on the sent value (payable amount) to the child contract on creation.

pragma solidity ^0.4.25;

contract Child {
   string public a;
   constructor (string arg) public payable {
       a = arg;
   }
}

contract Factory {
    constructor () public {}
    function createChild(string arg) public payable {
        address issueContract = (new Child).value(msg.value)(arg);
    }
}

Any idea why the transaction to Factory.createchild keeps failing when the value/payable amount passed is greater than 0 WEI? (it does only work when not value is passed at all ... )

Thanks a lot!


texts: Is the LogsBloom in the block header the same as the Bloom filter in the Transaction Receipts Trie?

texts:
Reading the yellow paper, I'm attempting to understand the difference between the Hb and Rb values - they appear to be the same thing, unless I've missed something.

Is the LogsBloom in the block header, Hb , the same as the Bloom filter in the Transaction Receipts Trie, Rb?

If they are the same thing - why is it stored twice?

If they are different, please explain how they are different.


texts:
Is it possible to run the Mist browser with an external ETH client like INFURA?
Yes, I understand this may not be the decentralized paradise we want to get to, but I'd just be happy to run a browser for now w/o having to download the entire blockchain. I understand I'll have to trust INFURA and I'm willing to do that for now.


texts:
I am not able to fully understand the flow of gnosis safe contracts - its master copy, proxies and all. Can somebody help me understand the gnosis safe from developer's pov.
I am working on a multisignature contract where there are several roles (Say role A and role B) where users of a particular role can sign transactions meant for them only and cannot cross the line ie. role A users cannot sign transaction meant for role B users.
Since this inherently is a multisignature contract I thought Gnosis Multisig/Safe Contract is the better place to look into but I am  not able to find out the starting point.


texts: What is the best way to tranfer ERC20 token from a contract?

texts:
I have a smart contract called "PlayerContract" and a smart contract which implements ERC20 called "MyToken".

in PlayerContract I have a method that accepts an uint256 (represent an amount of MyToken) from users and when we reach a known condition one user win the sum of tokens.

example :

function play (uint256 tokens) public {

   // store values for each participant.

  if (condition) {
   //transfer token to winers from loosers
  }
}

My question is how can "PlayerContract" transfer token from one to onther and what is the best way to do that?


texts: How to initiate a transaction with address and privateKey using web3js

texts:
I have a list of ethereum addresses and private keys, I need to write an automation script which checks for the balance in each address and transfer the balance funds to another ethereum address.
My question is how I perform the fund transfer with address and privateKey using web3js

Thanks in Advance


texts: How to fix Web3 syntax error ("Unexpected token {")?

texts:
On line 33717 of Web3's app.js file (in the /build folder of a truffle project) there's the following line:

})[0] || {};

However, somehow this turns into the following when app.js runs when my app is first loaded:

})[0] ||Â {};

This causes a syntax error. This is a known bug: https://github.com/ethereum/web3.js/issues/555 (apparently some kind of encoding issue)

How could this be fixed in the simplest way possible? I've tried (naively) copying and pasting the line into notepad and back into app.js but it does nothing.


texts: Truffle console error "Error: Returned error: VM Exception while processing transaction: revert"

texts:
I compiled and migrated my solidity codes of erc20 token to development networks on truffle, and use it on truffle console.

truffle(development)> let instance = await XToken.deployed()
truffle(development)> let accountsArray = await web3.eth.getAccounts()
truffle(development)> instance.sendTxAndMessage(accountsArray[1], accountsArray[2], 60, "Hi!")

Then, I got error below:

Error: Returned error: VM Exception while processing transaction: revert
at XMLHttpRequest._onHttpResponseEnd (/Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request.js:318:1)
at XMLHttpRequest._setReadyState (/Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request.js:208:1)
at XMLHttpRequestEventTarget.dispatchEvent (/Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/xhr2-cookies/dist/xml-http-request-event-target.js:34:1)
at XMLHttpRequest.request.onreadystatechange (/Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/web3/~/web3-providers-http/src/index.js:96:1)
at /Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:112:1
at /Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/web3-eth/~/web3-core-requestmanager/src/index.js:140:1
at Object.ErrorResponse (/Users/user/.nodebrew/node/v10.9.0/lib/node_modules/truffle/build/webpack:/~/web3-eth/~/web3-core-helpers/src/errors.js:29:1)

So, does someone know how to handle this error?

Here is my solidiy code and truffle-config.js

XToken.sol

pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol;

contract XToken is ERC20, Ownable {
    using SafeMath for uint8;
    using SafeMath for uint256;

    string public constant name = "XToken";
    string public constant symbol = "XTN";
    uint256 public constant decimals = 8;
    uint256 public _totalSupply = 5000000;

    mapping(address => uint) balances;
    mapping(address => string) public  receivedMessage;
    mapping(address => string) public  sentMessage;

    constructor (uint256 _initialSupply) public {
        balances[msg.sender] = _initialSupply;
    }

    function airdrop(address _to, uint256 _value) public onlyOwner returns (bool) {
        transfer(_to, _value);
        return true;
    }

    function sendTxAndMessage(address _from, address _to, uint256 _value, string memory _calldata) public returns (bool) {
        transferFrom(_from, _to, _value);
        sentMessage[_from] = _calldata;
        receivedMessage[_to] = _calldata;
        return true;
    }

    function fetchReceivedMessage(address _to) public view returns (string memory) {
        return receivedMessage[_to];
    }

    function fetchSentMessage(address _from) public view returns (string memory) {
        return sentMessage[_from];
    }

}

truffle-config.js

const HDWalletProvider = require('truffle-hdwallet-provider');

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",     // Localhost (default: none)
      port: 7545,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
    },
  },
}

And also, my environment is:
Truffle v5.0.5 (core: 5.0.5)
Solidity v0.5.0 (solc-js)
Node v10.9.0

Thanks in advance!


texts: Can i call transfer function in other contract?

texts:
can i call ERC20 token's transfer function in other contract?
like transfer AToken from using BContract's function can I?


texts:
What is the Ethereum Virtual Machine?

How does it contrast to the Ethereum World Computer?

The description of the EVM tag says:

  EVM is the Ethereum Virtual Machine, the protected, distributed "sandbox area" (virtual machine) where contract execution occurs, replicated on every node in the network

Am I correctly inferring that code execution is repeated on all nodes?
 If so, why is only the miner compensated with gas?


texts:
Can anyone tell me what's going wrong? My contract function is working fine for some accounts, then not for other's. It completely random also, sometimes it's one account sometimes it's another.

Using web3 integration with react from truffle-react-box, any help or explanation is appreciated. It's obviously something to do with signing the transaction that I know, but how can I avoid it is what I'm asking.

After this error is faced once with that account any further tx's from that account are reverted.

MetaMask - RPC Error: Error: MetaMask Tx Signature: Unknown problem: {"from":"0x5aeda56215b167893e80b4fe645ba6d5bab767de","to":"0xf25186b5081ff5ce73482ad761db0eb0d25abfbf","value":"0x22b1c8c1227a0000","data":"0xb587448f0000000000000000000000000000000000000000000000000004592a454899b200000000000000000000000000000000000000000000000022b1c8c1227a00000000000000000000000000000000000000000000000000000000886c98b760004458000000000000000000000000000000000000000000000000000000000000","gas":"0x575184","gasPrice":"0x77359400","nonce":"0x2"} {code: -32603, message: "Error: MetaMask Tx Signature: Unknown problem: {"f…"0x575184","gasPrice":"0x77359400","nonce":"0x2"}"}


texts: Gas estimation failed when using web3 provider testrpc

texts:
Gas estimation failed error while invoking a simple function

pragma solidity ^0.5.9;

contract sample{
    uint number;
    function setNumber(uint _number) public{
        number = _number;
    }
    function getNumber() view public returns(uint){
        return number;
    }
}

It's deployed successfully on localhost:8545. But while checking the function from remix it gave me error.

  Gas estimation errored with the following message (see below). The
  transaction execution will likely fail. Do you want to force sending?
  VM Exception while processing transaction: invalid opcode

while working fine on javascript VM.


texts: Parity Signer qr code not working, stuck on "Parity Signer: Pending"

texts:
I'm having issues with with Parity when trying to do any type of transfer-I get stuck on the "parity signer: pending" screen. The prompt I get is "Please scan the transaction QR on your external device"  But when I scan, the qr code isn't recognized.

I have in the past successfully done transfers, though not sure if with the qr code signer however-it was a few months ago. My external device (phone) was lost, so not sure if this is part of the issue, as I'm using a new phone.

I'm running windows 10, google chrome, Parity v. 1.7, installed from Parity.io website.
I feel I must be missing something quite obvious...
Any help would be deeply appreciated, Thanks!


texts: Recovery an EtherWallet with seed ( WIF form )

texts:
Recovery an EtherWallet with seed. I had  an Etherwallet 5 years ago. My private key 35 caracters/alpha numerics : "3P7.........cW"  it ooks like WIF form. I have password, ID but i cannot remenber from where I created my wallet.
I try with MEW but it doesn't go.
Please do you have ideas to find my wallet again.
Thanks


texts:
I am sending 1 eth from one account to another account. But I am unable to understand why the required balance is too big. I am receiving following error message:

Error: Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 1096934302059488651232480448211091758313913168 and got: 9999999999999999999999999999999999.

I am using following script to send transaction:

const Web3 = require("web3"); //version "^0.20"
const Tx = require('ethereumjs-tx') //version "^1.3.4"
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

function sendBalance(address, amountInEth){
    var addressFrom= "0x00B2386D9...............7DE370BF5B1d4893";
    var privateKey = new Buffer('d549079....................2ae7de5', 'hex')

    const gasPriceHex = web3.toHex(10);

    var nonceval = web3.eth.getTransactionCount(addressFrom);

    var fTx = {
        nonce: nonceval,
        gasPrice: gasPriceHex,
        gasLimit: web3.toHex(210000),
        from: addressFrom,
        to: address,
        value: web3.toWei(amountInEth, 'ether')
    };

    var txx = new Tx(fTx);
    txx.sign(privateKey);

    var sTx =txx.serialize();
    console.log("Current Balance:",web3.eth.getBalance(addressFrom).toString());
    console.log("Transaction:",fTx)
    web3.eth.sendRawTransaction('0x' + sTx.toString('hex'), (err, hash) => {
        if (err) { console.log(err); return; }

        // Log the tx, you can explore status manually with eth.getTransaction()
        console.log('Tx Hash: ' + hash);
    });
}

// usage
sendBalance("0x004ec........................9513386F32E",1)

The output and error I receive with this script is as follows:

Current Balance: 9.999999999999999999999999999999999e+33
Transaction: { nonce: 0,
  gasPrice: '0xa',
  gasLimit: '0x33450',
  from: '0x00B2386........................B1d4893',
  to: '0x004ec07..........................386F32E',
  value: '1000000000000000000' }
Error: Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 1096934302059488651232480448211091758313913168 and got: 9999999999999999999999999999999999.

Note: Address and private keys have been modified to include minimal and relevant content.


texts: Web3JS throws InvalidResponse without Ganache core ever receiving a request?

texts:
Versions:

Ubuntu 18.04 LTS
Node.JS: 8.3.0
WebJS:
web3: ^1.0.0-beta.37
web3-utils: ^1.0.0-beta.36
npm: 5.6.0
Truffle version 5.x (latest)

I have traced through the HttpProvider code in the Web3 package and what I see is quite strange.  The provider's onreadystatechange gets a DONE/4 event even though Ganache does not receive a request.

To test this, I initiate a sendSignedTransaction() call from my Node.JS app with a breakpoint set right on the actual low-level send() method the provider uses to contact Ganache with the actual RPC request.  When the breakpoint is hit, I shut down Metamask to stop any other entity from making requests to Ganache.  I switch to another instance of my development IDE that has the ganache-cli repo loaded.  This repo has ganache-core resident as one of its packages.  I set breakpoints on the Ganache core server's on-data and on-end event handlers for the request object to make sure I trap any RPC request activity during the test.

With everything in place for a clean test, I resume execution of my Node.JS app and discover that the Web3JS code for the HttpProvider that made the request already processing a result  and as you can see in the screenshot below, the result variable is an empty string:

This results in that code throwing an InvalidResponse  error.  I have run this test several times and I always see the exact same behavior.  That is, the exact same sequence of code paths taken.  What could cause the Web3 provider's XMLHttpRequest to believe it already has received a response from Ganache when at least from Ganache's point of view, WebJS never even sent the request?

The last time I saw anomalies like this one was when I learned the hard way that you have to BigNumber everything related to gas values.  Assuming I haven't done something wrong and that's always strong possibility, it really feels like some other code in Web3JS is causing the event emitter code to misfire or suffer perhaps some data structure corruption.  I say this because except for the one particular smart contract method that results in this error when I call it,  all the other method calls work perfectly and there's quite a few of those.   I believe there's something about the arguments I am passing with this specific smart contract method and the way Web3JS is trying to parse the arguments against, or match them up to the Solidity ABI is resulting in an unexpected error.

Any tips you can give for debugging this would be appreciated.  Otherwise I have a long debug hunt in front of me.

Solidity method being called:

    function finalizeGame(
            address payable _paymentAndEscrowWarehouseAddr,
            uint256 _clientReferenceTimestamp,
            uint256 _gameId
        )

Node.JS code calling that method:

    return ebbDetails.contractInstanceObj.methods.finalizeGame(
    paymentsAndEscrowContractAddr,
    dataBag.paymentStartTimestamp,
    dataBag.idInSmartContract);


texts: PCIe Risers not working on x1 but works on x16

texts:
I have some problem with my USB PCIe Risers for my Ethereum Mining Rig. I have 6 of them, 1 out of six is working perfectly fine when I plug the riser into x1 or x16 slot. However my other 5 risers work only when plugged into x16 slot, they do not work in x1 slot. I tried changing between pimpOS, Ubuntu and windows 10, no difference was made. I even tried using different GPUs too but to no avail. Below is my hardware list.

MB -> Gigabyte H110-D3A
CPU -> Intel Pentium G4400
RAM -> 4GB Crucial
SSD -> 120GB Sandisk
GPU1 -> Zotac GTX 1070 mini (8GB)
GPU2 -> Zotac GTX 1060 Amp (6GB)
GPU3 -> MSI Radeon RX 570 (4GB)


texts:
I am having a mapping like
 struct Invoice {
    uint256 unitPrice;
    uint256 totalCost;
    uint256 discount;
    uint256 CostAfterDiscount;
    bool isConfirmedByBuyer;
}
mapping(bytes32 => Invoice) public invoices;

I am calling it like
await instance.methods.invoices(orderId).call()

where orderId = bytes32.
It works on Remix but it doesn't work on geth. When I call the function it says

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.
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 (node_modules/web3-eth-abi/src/index.js:239:15)
at Contract._decodeMethodReturn (node_modules/web3-eth-contract/src/index.js:557:22)
at Method.outputFormatter (node_modules/web3-eth-contract/src/index.js:910:46)
at Method.formatOutput (node_modules/web3-core-method/src/index.js:167:54)
at sendTxCallback (node_modules/web3-core-method/src/index.js:596:33)
at /Users/asifbhat/Accepire-BT/contracts.accepireBT/node_modules/web3-core-requestmanager/src/index.js:147:9
at XMLHttpRequest.request.onreadystatechange (node_modules/web3-providers-http/src/index.js:110:13)
at XMLHttpRequestEventTarget.dispatchEvent (node_modules/xhr2-cookies/xml-http-request-event-target.ts:44:13)
at XMLHttpRequest._setReadyState (node_modules/xhr2-cookies/xml-http-request.ts:219:8)
at XMLHttpRequest._onHttpResponseEnd (node_modules/xhr2-cookies/xml-http-request.ts:345:8)
at IncomingMessage. (node_modules/xhr2-cookies/xml-http-request.ts:311:39)
at endReadableNT (_stream_readable.js:1187:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)


texts: How to exchange ETH to DAI with web3 and node.js

texts:
I looking for solution how to convert eth to dai with web3 api. something like
https://kyber.network/swap/eth_knc
(I can send eth to specyfic contract adress and I receive back DAI to the same address from I send eth.)

DAI contract address https://etherscan.io/address/0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359
Sorry for my english.


texts: Solidity - Is it possible to sort an Array of Structs? - UnimplementedFeatureError

texts:
I'm getting the following error trying to sort an array of Structs.

  UnimplementedFeatureError: Copying of type struct
  SortStruct.TestStruct memory[] memory to storage not yet supported.

Contract:

pragma solidity ^0.5;

contract SortStruct {

    struct TestStruct {
        address user;
        uint256 value;
    }
    TestStruct[] public testStructArray;
    TestStruct[] public sortedArray;

    function add(uint256 _value) public {

        TestStruct memory test;

        test.value = _value;
        testStructArray.push(test);

    }

    function sort() public {
        sortedArray = sort(testStructArray);
    }

    //
    // sort
    //
    function sort(TestStruct[] memory  data) internal returns (TestStruct[] memory) {
       quickSort(data, int(0), int(data.length - 1));
       return data;
    }

    function quickSort(TestStruct[] memory arr, int left, int right) internal {
        int i = left;
        int j = right;
        if(i==j) return;
        uint pivot = arr[uint(left + (right - left) / 2)].value;
        while (i <= j) {
            while (arr[uint(i)].value < pivot) i++;
            while (pivot < arr[uint(j)].value) j--;
            if (i <= j) {

                // swap
                TestStruct memory tempSortCandidate;
                tempSortCandidate = arr[uint(i)];
                arr[uint(i)] = arr[uint(j)];
                arr[uint(j)] = tempSortCandidate;

                i++;
                j--;
            }
        }
        if (left < j)
            quickSort(arr, left, j);
        if (i < right)
            quickSort(arr, i, right);
    }

}


texts: Operator == not compatible with type unit256 and address // TypeError: Invalid type for argument in function call

texts:
I got 2 problem when i follow instruction. Here my contract file:

pragma solidity ^0.5.0;

import "./DappToken.sol";

contract DappTokenSale {
    address admin;
    DappToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor (DappToken _tokenContract, uint256 _tokenPrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;
    }

    function multiply (uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x);
    }

    function buyTokens (uint256 _numberOfTokens) public payable {
        require (msg.value == multiply(_numberOfTokens, tokenPrice));
        require (tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        require (tokenContract.transfer(msg.sender, _numberOfTokens));

        tokensSold += _numberOfTokens;
        emit Sell(msg.sender, _numberOfTokens);
    }

    function endSale () public {
        require (msg.value == admin);
        require (tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));
        selfdestruct(admin);
    }
}

and the cmd said:

How to fix this ??


texts:
I am sending a transaction through this code:

            txhash = careercertificate
                .createCertificate(id, fecha, nombre, rutalumno, instituto, rutinstituto, titulo, totalhash, fechatitulacion, registronumber, codigoV)
                .send().getTransactionHash();

And I return this exception, my application has it on a tomcat server but the tomcat does not receive it for timeout exception, how could txhash return to the tomcat?

org.web3j.protocol.exceptions.TransactionException: Transaction receipt was not generated after 600 seconds for transaction:0x625261.....


texts: What is meant by 'consensus breaking changes'?

texts:
Reading this Blockstack paper : https://blockstack.org/blockstack.pdf it states :

With Blockstack,
we extend the single state machine model of
blockchains to allow for arbitrary state machines without
requiring consensus breaking changes in the underlying
blockchain.

What is meant by 'consensus breaking changes' ? Is it related to once 51% consensus has been achieved that something can break ?


texts: Is it possible to create a smart contract from a multi sig smart contract wallet?

texts: Is it possible to create a smart contract, for example a ERC-20 from a multi signature smart contract wallet?


texts: What happens if it's no longer profitable to mine?

texts:
If enough people sell ether and drive the price down, is it possible that it would no longer be profitable for the vast majority of people to continue mining?

If so, it seems like it would be a snowballing effect on the network. E.g. people sell -> price goes down -> profit falls for miners -> miners stop working -> network halts.

Just trying to understand the worst case scenario.


texts: Is it legal to include arbitrary bytes at the end of the DATA section executing a contract method?

texts:
Feel free to refer directly to the yellow paper or other similar baseline documents - I've been reading those documents looking for an answer to my question.  I wish there were a "language-lawyer" tag similar to the one on stackoverflow, because I'll only accept an answer that proves conclusively that the answer is "yes", "no", or "unspecified" - I won't accept an answer appealing to your gut feeling.

Solidity contracts appear to operate at a significantly higher level of abstraction than the EVM itself.

For instance, to determine which contract method a transaction executes, the ethereum wiki states:

  The first four bytes of the call data for a function call specifies the function to be called.

Going back to the yellow paper to figure out what happens during a message call:

  The account’s associated code (identified as the fragment whose Keccak hash is σ[c]_c) is executed according to the execution model.

Now, the associated code is simply the output of the contract creation code.  The yellow paper also states:

  ...the resultant byte sequence from the execution of the
  initialisation code,  specifies the final body code for the
  newly-created account

So in the yellow paper there is no mention of contracts even having methods, much less of the first 4 bytes of the transaction data specifying which one is to be called.  I gather, therefore, that it is Solidity (or another layer above the EVM itself) that outputs contract EVM bytecode that branches based on the first 4 bytes, and this is not a feature of the EVM.

Therefore, this question is probably more related to Solidity than contract execution, and may even have a different answer case-by-case for different smart contracts that are implemented.

That being said, the question is this:

Take a look at this transaction.  I created a well-formed call to a smart contract, sending 1 token to an address, however onto the transaction data I concatenated the hex data 0xdeadbeef.  I would like to use this as a way to attach application-specific memos.

Given that this works today, is there any reason why it wouldn't work in the future?


texts: My is metamask returning RPC Error: Error: [ethjs-rpc] rpc error with payload, metamask shows failed [object, object]

texts:
My metamask shows ALERT: Transaction Error. Exception thrown in contract code. When I am about to transfer using truffle, open zeppelin and ganache on localhost:7545

after confirming the transaction it shows

inpage.js:1 MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload {"id":6736485951990,"jsonrpc":"2.0","params":["0xf86f048504a817c800836170d494ef9b511c0ddaea1f38ed82becb523a414dc6d7cc8806f05b59d3b2000080822d46a0fa7b64f06fe5520527e3ea35a445d3c461ca97ac25d73062caa9d64025fde7aaa02a5127f46ea982b6b71fd88ebe2a22679b45de0ebaef32137a65171f562caa03"],"method":"eth_sendRawTransaction"} [object Object] {code: -32603, message: "Error: [ethjs-rpc] rpc error with payload {"id":67…method":"eth_sendRawTransaction"} [object Object]", stack: "Error: Error: [ethjs-rpc] rpc error with payload {…method":"eth_sendRawTransaction"} [object Object]"}

My Crowdsale code

pragma solidity ^0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol";

contract MyCrowdsale is Crowdsale, TimedCrowdsale, CappedCrowdsale, AllowanceCrowdsale {
    constructor (
        uint256 _rate,
        address payable _wallet,
        ERC20 _token,
        uint256 _openingTime,
        uint256 _closingTime,
        uint256 _cap,
        address _tokenAdd
    )
    Crowdsale(_rate, _wallet, _token)
    TimedCrowdsale(_openingTime, _closingTime)
    CappedCrowdsale(_cap)
    AllowanceCrowdsale(_wallet)

    public
    {
    }
}

deploy_contract.js

module.exports = async function (deployer, network, accounts) {
    await deployer.deploy(A1Token, "A1Token", "A1T", 2,5000000);
    //deployer.deploy(AddNumbers);
    const deployedToken = await A1Token.deployed();
    console.log(deployedToken.address)
    const rate = 1000;
    const wallet = accounts[0];
    const timeNow = Math.floor(Date.now() / 1000);
    const openingTime = timeNow + duration.seconds(30);
    const closingTime = timeNow + duration.years(1);
    const cap = web3.utils.toWei("100");
    console.log(cap)
    await deployer.deploy(MyCrowdsale,
         rate, wallet, deployedToken.address, openingTime, closingTime, cap, wallet
         );
    const deployedCrowdsale = await MyCrowdsale.deployed();
    //await deployedToken.transfer(deployedCrowdsale.address, await deployedToken.totalSupply());
    deployedToken.approve(deployedCrowdsale.address, 20000);
    console.log(deployedCrowdsale.address);
}

And this is linked to a ERC20 token with an initial supply.

I have tried reinstalling metamask and clearing cache, i have enabled ethereum.enable();, tried using truffle develop account, ganache CLI and GUI, changing gas limit and gas. How do i fix this?


texts: Input data into remix through javascript

texts:
I am trying to update and call data to remix using node js. I have the temperature captured in my js code and I am trying to call it using the updateWeather function.

Node.js code

let request = require('request');
let url = 'https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20%3D%202487889&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'

request(url, function (err, response, body) {
  if(err){
    console.log('error:', error);
  } else {
    let weather = JSON.parse(body)
    let temperature = weather.query.results.channel.item.condition.temp.toString();
    let message = `It's ${temperature} in Hawaii!`;
    console.log(message);
  }
});

Web3 = require('web3')
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }

    web3.eth.defaultAccount = web3.eth.accounts[0];

const contract = web3.eth.contract(ABI).at('ADDRESS');

const account = () => {
  return new Promise((resolve, reject) => {
    web3.eth.getAccounts((err, accounts) => {
      if (err === null) {
        resolve(accounts[0]);
      } else {
        reject(err);
      }
    });
  });
};

const updateWeather = ({temperature }) => {
  return new Promise((resolve, reject) => {
    account().then(account => {
      contract.updateWeather(temperature,{ from: account }, (err, res) => {
          if (err === null) {
            resolve(res);
          } else {
            reject(err);
          }
        }
      );
    }).catch(error => reject(error));
  });
};

const weatherUpdate = (callback) => {
  contract.WeatherUpdate((error, result) => callback(error, result));
};

Remix Code

pragma solidity 0.4.24;

contract WeatherOracle {

  event WeatherUpdate (
    string temperature
  );

  function updateWeather (string temperature) public {
      emit WeatherUpdate (
      temperature
      );
  }
}


texts:
I want to interact with my contracts through truffle console. I am using test rpc and web3.

Basically for a standard token contract:

contract Token{
       function Token() payable{...}
       function _transfer(...) internal {...}
       function transfer (..) payable{..}
}

i use those command lines in the truffle console:

var contract=null;

Token.new({ from: web3.eth.accounts[0], value: web3.toWei(100, "ether") }).then(function(_contract) { contract = _contract; });

contract.transfer('address of another testrpc accounts', 10, { from: web3.eth.accounts[0], value: web3.toWei(100, "ether") })

Then i got a "Cannot read property 'match' or undefined truffle console" error.

I am lost now because the getters of my contract are actually working.. (ex: token.get_balance.call(..)  )

Any idea? Does the syntax of truffle console has changed recently?

Thks.


texts: Ethereum full stack application development

texts:
I am novice solidity developer and I am trying to develop a voting application on ethereum

Requirements of application are -

1) There should be candidate and voter registration form

2) Voter should be able to login using some authentication mechanism like username , password

3) Each voter should be able to vote only once

4) Result of voting should be visible to everyone

Things that I have tried -

I have developed a smart contract for voting in candidate and voter are of struct type in which respective attributes of candidate and voter are stored.

Data of candidates and voters is stored in array of structures. Functions are written in smart contract to vote , to get count of no. of voters and candidates, to insert a voter and candidate etc.

Issues I am facing -

1) How shall I authenticate voter and candidate ?

2) Shall I create new account using personal.newAccount() command for every candidate and voter ?

3) Can one account have multiple addresses ? so that I can create multiple addresses for different voter and candidate ?

4) According to answer of this question message.sender() shall be used for authenticating user. I am not able to understand that how every user will have different addresses ? Is it address of account that we can create using personal.newAccount() command ?

5) As ethereum is permission less block chain ,how to implement/simulate authentication and authorisation with  the help of which one can control who can participate in a private block chain network?


texts: TypeError: Invalid type for argument in function call. Invalid implicit conversion from contract to address requested

texts:
I am unable to use the 'this' Keyword in below code.

    function buyTokens(uint256 _numberOfTokens) public payable {
    require(msg.value == multiply(_numberOfTokens, tokenPrice));
    require(tokenContract.balanceOf(this) >= _numberOfTokens);(issue is here)
    require(tokenContract.transfer(msg.sender, _numberOfTokens));

giving below error.

TypeError: Invalid type for argument in function call. Invalid
  implicit conversion from contract DappTokenSale to address requested.
    require(tokenContract.balanceOf(this) >= _numberOfTokens);


texts: How can i deploy contract with > 4.7 Mgas required on Ropsten?

texts:
I was able to deploy contract that requires more gas than default Ropsten block gas limit:
https://ropsten.etherscan.io/tx/0x7c40cd2c539c03d110da8988641518ff6ff907a284f5074ed3d8517eb80b51f9 (5594037 > 4.7M)

For some reason i can't do the same again with:

  $geth --verbosity "4" -rpc --nousb --ipcdisable --rpcaddr "127.0.0.1" --rpccorsdomain "" --rpcvhosts "" --syncmode "fast" --rpcapi="db,personal,eth,net,web3,admin" --cache=2048 --testnet --mine --targetgaslimit 7000000

Does --targetgaslimit work for Ropsten (not private network)? How can i deploy it without splitting/using libraries/etc?

Currently i'm getting Remix deploy error (connected to Web3 provider):

  creation of Contract errored: exceeds block gas limit

PS. I did it few times so i'm absolutely sure it's doable. But i can't understand what affects this and how can i deploy it intentionally.


texts:
I'm newbie of solidity develop flatform, when I do a example from solidity document at Remix IDE, I have a error with my event and I don't know how to fix it, here my code:

contract Coin {
    address public minter;

    mapping (address => uint) public banlances

    event Sent (address from, address to , uint amount);

    constructor() public {
        minter = msg.sender;
    }
    function mint(address recevier, uint amount) public {
        require(msg.sender == minter)
        require(amount < 1e60);
        banlances[recevier] += amount;
    }

}


texts: Can't open Ledger nano s at MyEtherWallet

texts:
I just got Ledger Nano S but can't figure out how to use it at MyEtherWallet.
My problem happens at number 3)

1)going to 'Send Ether & Tokens' page.
2)choosing 'Ledger Wallet'.
3)Clicking 'Connect to Ledger Wallet', but nothing happens.

I have latest firmware installed(1.3.1), and browser support enabled in Ethereum App.
It works with Ledger Wallet Ethereum(chrome), but can't figure out what's wrong with MyEtherWallet, and why it's not working.
Is it something wrong with my settings, or broken hardware?

I really appreciate your help. Thanks in advance!


texts: Is timestamp manipulation still possible? And if yes, can users spot that and did that happen?

texts: I have readed an ethereum post from 2015 where it states that miners can manipulate the block timestamp up to 900 seconds. Can they in 2021 still do it and, if yes, can users see this and did this happen in the past? Would i.e. Etherscan show the manipulated timestamp too?


texts: Resyncing and deleting chaindata directory

texts:
I'm about to do a resync of the blockchain but as I was deleting my chaindata directory from:

~/Library/Ethereum/chaindata

I noticed there was also another chaindata directory located here:

~/Library/Ethereum/geth/chaindata

This seems a bit confusing to me. Am I supposed to delete both? What is the difference between the two? I'm not sure if the chaindata directory existed before I updated geth to 1.5.9 today. I'm using Mist if that helps.


texts: Forked Mainnet `INSUFFICIENT_OUTPUT_AMOUNT` on a transaction

texts:
I am currently using ganache and forked mainnet to test if a transaction in advance will fail or not. I get error INSUFFICIENT_INPUT_AMOUNT on ganache while the tx success on mainnet and observed that this occur if the sender eth balance is  less than their input also if they use different token as input. How do I make it relative to the input value to avoid the error?
The snippet:
const localTx =
    {
      from: tx.from,
      to: tx.to,
      value: tx.value,
      gasPrice: tx.gasPrice,
      gasLimit: tx.gas,
      input: tx.input,
    };

    await localWeb3.eth.sendTransaction(localTx)
    .on('error', (err) => { console.log(err) })


texts: Migration internal storage to a new smart contract

texts: What is currently the best way to migrate data from one contract for example the mapping to a new one?


texts: Why are some EIPs specified in "params" and others in "engine"-->"params

texts:
I see that in the main net Parity chain spec file (https://github.com/paritytech/parity/blob/master/ethcore/res/ethereum/foundation.json) some eipTransitions are specified in the engine-->Ethash-->params section and other are specified in the params section.

Why is this?  Does it matter?


texts: Yesterday, everything was fine (Mist 0.8.9), today when I started it, all my tokens were gone and there was no transaction history. It told me that there was a new version (0.8.10), which I downloaded and installed. After doing that, everything was gone, wallet, blockchain etc etc, it's like I have to start over from scratch. I tried the old shortcuts and the old application (mist.exe), but it's all gone. What did I do wrong and why isn't there just a simple way to update from within the application? How do I recover my wallet and everything I downloaded? What files does it delete during the installation? Thanks,


texts: address.transfer(uint amount) TRON blockchain

texts:
msg.sender.transfer(amount)
// 1) Is it true, that when I execute this code inside the function, it sends the amount to that contract?
// 2) Is there any function, which does the opposite(from contract to msg.sender)? Thank you


texts:
from https://blog.ethereum.org/2014/07/11/toward-a-12-second-block-time/
At a block time of 600 seconds, as in Bitcoin, this is not an issue; 12 seconds is a very
small amount of time, and Decker and Wattenhofer estimate the total stale rate as being
around 1.7%. Hence, an attacker does not actually need 50.001% of the network in order
to launch a 51% attack; if the attacker is a single node, they would only need
0.983 / 1 + 0.983 = 49.5%. We can estimate this via a mathematical formula: if transit
time is 12 seconds, then after a block is produced the network will be producing stales
for 12 seconds before the block propagates, so we can assume an average of 12 / 600 = 0.02
stales per valid block or a stale rate of 1.97%. At 60 seconds per block, however,
we get 12 / 60 = 0.2 stales per valid block or a stale rate of 16.67%. At 12 seconds
 per block, we get 12 / 12 = 1 stale per valid block, or a stale rate of 50%. Thus,
we can see the network get substantially weaker against attacks.

I couldnt understand the concept of stale blocks..
so if the transit time is 12 seconds (a block reaches to every node in the network) and the block time is 600 seconds ( New block will only be appended in 600 seconds) how come the rate of stale block is 12/600 = 0.02, because the block will only be made in 600 seconds and then it will take another 12 second to reach every node.


texts: How to deploy multiple compiled solidity with web3?

texts:
So I have this codes

  const MultiSigWalletFactory = fs.readFileSync(path.resolve(__dirname, "MultiSigWalletFactory.sol"), "utf8");
  const Factory = fs.readFileSync(path.resolve(__dirname, "Factory.sol"), "utf8");
  const MultiSigWallet = fs.readFileSync(path.resolve(__dirname, "MultiSigWallet.sol"), "utf8");
  const input = {
    language: "Solidity",
    sources: {
      "Factory.sol": Factory,
      "MultiSigWallet.sol": MultiSigWallet,
      "MultiSigWalletFactory.sol": MultiSigWalletFactory,
    },
    settings: {
      outputSelection: {
        '*': {
          '*': ['*'],
        },
      },
    },
  };
  const output = solc.compile(input);

it will output bytecode and ABI for each file.

How can I deploy this to the blockchain using web3?


texts: Keeping a finite set of addresses (Solidity)

texts:
struct Data {
  ...
}

contract Court {
  mapping(address => Data) subcourts;
}

I want to keep track of a small finite set (which can be added or removed) of all keys of this mapping.

What is the better way?

make an array of addresses as a new field of Court;
add a new address field to Data to make a linked list;
add two new address fields to Data to make a doubly linked list.


texts: secp256k1 library does not create correct public key

texts:
I am trying to get public key from private key using secp256k1 library. https://github.com/bitcoin-core/secp256k1

I set same private key(sk) in here. https://github.com/ethereumbook/ethereumbook/blob/develop/04keys-addresses.asciidoc#ethereum-addresses

unsigned char *sk = "f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315";
secp256k1_ec_pubkey_create(secp256k1_ctx, &pk, sk);
secp256k1_ec_pubkey_serialize(secp256k1_ctx, output, &outputlen, &pk, SECP256K1_EC_UNCOMPRESSED);

But serialized public key (output) which I got is

04a82b7752a73ab1de51ae4f614e7e9908fb891c1cdeeab96c0e7c237d3e3a0369daf8eab4e3864668575c5d10fc000a6897b10102c14671140c1cdf9765fd46b0

Not same public key in ethereum book. Am I writing wrong code to get correct public key ?


texts: how can i find the contract name from the address using the etherscan API?

texts: I have the address but I want to know the name of contract. Is there any way to get that from the etherscan API?


texts: how to read a variable from an already deployed smartcontract without a predeclared getter function?

texts:
i want to read a variable from an existing contract to my own contract using smart contracts. (not js)
i know there are methods to import smart contracts:

import './OtherContract.sol'
contract cont is OtherContract {}

but I'm thinking of there is any method that we can put a contract's address and call/read that contract's functions/variables from another contract?
for example (something like):

import address(0x...)
contract cont = address(0x...)


texts: Is there an easy GUI way to get the namehash of an ENS subdomain name? I know how to get the needed namehashes from Geth console using the ensutils script, or writing javascript that uses web3 & eth-ens-namehash. But is there a way for people to get the namehash without using command line, simply via browser. I see that MEW will produce the label & namehash for domains, but there is no way to search subdomains. Does Solidity have a namehash function? Or would I have to write my own, recursively calling the sha3 (or is it keccak-256)?? It was one solution so that users could just interact with the contract via MEW to get namehashes. Any other ways to get the namehash without using command line??


texts:
I am fairly new to smart contract development and am still trying to figure out the whole sending ETH/tokens to a contract thing. In an article I saw the following example of a contract's terminate method which would refund all tokens in the contract to the owner:

function terminate(IERC20Basic[] tokens) external onlyOwner {
        // Transfer tokens to owner
        for(uint i = 0; i < tokens.length; i++) {
            uint256 balance = tokens[i].balanceOf(this);
            tokens[i].transfer(owner, balance);
        }
        // Transfer Ether to owner and terminate contract
        selfdestruct(owner);
    }

What I don't understand is - when the owner calls terminate what should they pass as tokens parameter? I would love to see a concrete example, it would help me wrap my head around it


texts: How to run slasher slashing detectors in Ethereum 2.0?

texts:
"A validator client will likely store tens or hundreds of MB of historical votes to prevent slashings." (Source)
Do beacon nodes or validator clients automatically run slashing detectors?
If not, what are the instructions for running slashers (slashing detectors)?  Hardware requirements would also be helpful.


texts: What portions of the block are validated in Geth's --fast and Parity's --warp mode?

texts:
When I am syncing an Ethereum node using Geth's --fast mode and Parity's --warp mode, what portions of the block are being validated as they are being downloaded?

I understand that --fast and --warp are both pruning modes. I understand that in both modes, you do not take a snapshot of the state until you are very close to the latest/best block.

I am curious about the following:

Is only the proof of work of each block header checked in order to be considered valid? I understand that the transactions are downloaded as well, but are the transactions validated as well?
Are the transactions validated locally by verifying that the merkle root of these transactions is equivalent to the hash of the transaction root?

My goal is to understand pruned nodes enough to write a blog post about it that dispels myths concerning pruned nodes.


texts: Contract code not executing from web3, works from Mist

texts:
I seem to be having a problem w/ contract code not executing when called from web3 (works when called from mist). The Eth goes to the contract, so I know it is making the call at least. I am calling the contract as such:

```

    var fromAddr = sender;
    if(typeof fromAddr == "undefined" || !fromAddr )
        return false;

    var contractAddr = this.addr;
    var abi = this.abi;
    var contract = web3.eth.contract(abi).at(contractAddr);

    ...(some vars)...

    args.push({from: fromAddr, value: parseInt(value), gasPrice: gasPrice, gas: gas});
    var callback = function(err, txhash) {
        console.log('error: ' + err);
        console.log('txhash: ' + txhash);
    }
    args.push(callback);

    web3.personal.unlockAccount(fromAddr, pw);

    contract[functionName].apply(this,args);

```

and as mentioned, it works from Mist but not web3. I have some public counters that increment correctly when using the former. Any ideas on this? I had a modifier on the solidity contract but removed it an no difference. I have also tried calling the contract like:

contract[functionName](args[0],args[1],..., { gas: ... } );

with no difference. I am running an RPC node on an AWS Linux instance.

I am running geth as such:

geth --testnet --rpc --rpcaddr="0.0.0.0" --rpccorsdomain="*" --rpcapi="db,eth,net,web3,personal,web3"

EDIT: Here is a working and non-working vmtrace

working: http://testnet.etherscan.io/vmtrace?txhash=0xfb022ae9cbf0b39f9ee1890e794226ab02737bc0ccd9ae95d87a646ecbc91744

non-working (consistently stops at step 65): http://testnet.etherscan.io/vmtrace?txhash=0x0c8447d26c90189d4fcb6cfac3a2143d7132db9b6b6b55854401b4a9be99cb28


texts: Not able to add instance to array after adding in mapping in one function

texts:
function addCropDetails   //only farmer can call
(
uint _cropType,
//string memory _cropName,
uint _quantity,
string memory _location
)
public
{
require ( owner != msg.sender , "owner cant add crop details" );
//u r not registered yet
require (farmers[msg.sender].isRegistered == true, "You are not registered yet or you are not farmer");
require ( allPricesSet==true , "gov isnt initialized prices yet" );
require ( setProfitPercent == true , "gov isnt initialized profit rates yet" );
require ( _cropType < arraySize && _cropType >= 0 , "invalid crop type");
    uint cropPr = cropTypes[_cropType]; //fetched cropPrice by cropType (by gov)

    cropCounter++;
    Crop memory crop ;
    crop.cropId=cropCounter;
    //adding crop type to cropType
    crop.cropType = _cropType;
    crop.farmer_quantity=_quantity;
    crop.location=_location;
    crop.farmerAddrs = payable(msg.sender);
    crop.cropPrice = cropPr;
    crop.isAdded=true;
    crops[cropCounter] = crop;      //here i passed instance to mapping

//in below lines i tried to add instance to array in many ways but not even one is working
//function is working only after commenting this.
    //fCropArray[cropCounter] = crops[cropCounter];
    //fCropArray[cropCounter]=crop;
    //addCropToArray(crops[cropCounter]);

    emit cropAdded();
}


texts: If you accidently set a very HIGH gas limit to purchase a smart contract for ETH can it be changed?

texts: Ex. Gas limit was accidentally set to 5,000,000 & now when Trying to customize it keeps auto-populating to that causing me an INSANE gas fee of over $400.  I don't want to cancel because I don't want to be charged but it has been pending for 4 days & nothing I have done has worked.  Does anyone have any experience or advice on this?  TIA


texts:
This is a noob question - apologies.

Suppose I have a smart contract that allows people to register something with an ID.  For example, my public address is o4f... and I want to register the ID 012345 to my public address.

Later on I make a transaction where someone buys that ID from me, so now the ID 012345 belongs to a different public address, say 05f....

My question is: can I treat Ethereum like a database and ask the blockchain to give me all transactions that involved the ID 012345?  What would that look like?


texts:
I have a contract inheritance in my design and i want to call via web3 a method from the base contract. the oriblem is that i can't know how to do that :

if i do like this :

   contract B {
        uint Bstate;
        function methodX (){
        Bstate =1;
        }
    }

then

import "B.sol"; // because B is in an other file
contract A is B {

}

do i need to manually deploy contract B after deploying contract A and use its abi to call methodX or i can call it directly from the abi of contract A?


texts: Can I receive to myetherwallet.com with this code any ETH?

texts:
Can I actually receive ETH to my MyEtherWAllet.com account
with this token contract source?

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

Or do I have set token-name and symbol and other things?

If I have to set symbol, token-name and so on, where to edit this contract code, please?


texts: Library to get a graphic representation of the blockchain

texts:
I'm trying to find a library to make a graphic representation of the blockchain. Something similar to Gource but instead with git versions, with ethereum

Any idea if something like that exists?


texts: serializing byte array for transaction data

texts:
I've upgraded from python 2 to python 3 and some code that used to work is now broken.  I can't seem to fix it.  Any suggestions?

Worked in python 2

# Convert hex string to byte array
hex_string = "0x00012345...."
data_bytearray = bytearray.fromhex(hex_string.replace("0x", ""))

# Then I pass data_bytearray into transactions.Transaction and it works.
try:
    return {'error': False, 'sign': rlp.encode(transactions.Transaction(nonce, gasPrice_int, gas_int, to, value, data_bytearray).sign(privkey)).encode('hex')}
except Exception as msg:
    return {'error': True, 'message': msg}

Same code doesn't work in python 3 and note the byte array data type has changed to

<class 'bytearray'>   # python 3 produces this from bytearray.fromhex
<type 'bytearray'>    # python 2 produces this from bytearray.fromhex

I get the following error:

{'error': True, 'message': ObjectSerializationError('Serialization failed because of field data ("Object is not a serializable (<class \'bytearray\'>)")',)}

I tried serializing the output using pickle, but got another error:

import pickle
data_bytearray = pickle.dumps(data_bytearray)

{'error': True, 'message': AttributeError("'bytes' object has no attribute 'encode'",)}

What am I doing wrong here?

Solution:

try:
    data_hex_with0xRemoved = data_hex.replace("0x", "")
    # If I use bytearray.fromhex, it results in {'error': True, 'message': ObjectSerializationError('Serialization failed because of field data ("Object is not a serializable (<class \'bytearray\'>)")',)}
    # data = bytearray.fromhex('deadbeef')
    # So instead I use bytes.fromhex
    data = bytes.fromhex(data_hex_with0xRemoved)
    unsigned_transaction = transactions.Transaction(nonce, gasPrice_int, gas_int, to, value, data)
    raw_transaction_bytes = rlp.encode(unsigned_transaction.sign(privkey))
    raw_transaction_hex = Web3.toHex(raw_transaction_bytes)
    raw_transaction_hex_0xRemoved = raw_transaction_hex.replace("0x", "")
    return {'error': False, 'sign': raw_transaction_hex_0xRemoved}
except Exception as msg:
    return {'error': True, 'message': msg}


texts: why out of gas when gasLimit is not reached

texts:
https://etherscan.io/tx/0x43f39829b3a48c4146808b12489e01bdb5dfa32d5b49514298339a719e538c09

this tx failed, and the msg shows the cause is: out of gas, but Gas Limit is 520000, while only 86056 Gas Used By Txn.

why would this happen?

ps. source code of the erc20 token we are trying to swap is at https://etherscan.io/address/0x4ceda7906a5ed2179785cd3a40a69ee8bc99c466#code


texts: Is it possible to query blockchain using wallet extra-infos?

texts: I read here how to add extra fields to a wallet address, is it possible to query the ethereum blockchain and find all wallets with the same extra-filed? For example: all wallets with the same user name?


texts: Smartpools' sha3_512, is there a stand alone implementation?

texts: Smart pool has implemented sha3_512 (contract), tough it looks like it is combined with EthHash. Is there a stand alone library just for the sha3_512 function?


texts:
I'm trying to connect ethers.js to a geth light client. A connection seems to form, but with no indication that I'm able to receive the right data.
Here's the geth command I'm using:
geth --rpc --rpcport 8555 --rpccorsdomain "*" --syncmode "light"

And here's the ethers.js code I'm using (in an Observable notebook).
ethers = require("ethers")
provider = new ethers.providers.JsonRpcProvider("HTTP://127.0.0.1:8555")
provider.getBlockNumber() // this block number comes out at 0 which doesn't sound right at all


texts:
I got stuck with the error:

  ERROR: NetworkId mismatch: 3 (!= 1100)

Running geth node with parameters:

geth --rpccorsdomain "*" --ipcapi "admin,eth,miner" --rpcapi "eth,web3" --networkid 1100 --maxpeers 5 --etherbase "xxxxx(hidden)" --verbosity 3 --minerthreads 1 console

And then run swarm with:

$GOPATH/bin/swarm --bzzaccount 41bad198c4504045f3dfa54902e08384e9162b04 --datadir /home/ubuntu/.ethereum --ethapi /home/ubuntu/.ethereum/geth.ipc --verbosity 3 --maxpeers 5 --bzznetworkid 1100

After all I'm getting the logs:

  I0206 12:20:28.403510 errs/errors.go:86] [BZZ] ERROR: NetworkId mismatch: 3 (!= 1100)

Where could that error come from?


texts: Someone mentioned some settings to set when mining in ethos. I have all of them but how do I set the "power at 60%" in the config?


texts: How to reward distributed cloud computing on ethereum?

texts:
I refer to 5.Cloud computing in the Further Application section of the Ethereum whitepaper, and I wonder how this can be achieved in a decentralized way.

For example, if I have a task that I want to distribute to different nodes and wait for the results, without using an oracle to verify the results, an approach I can think of is to distribute the same task to multiple nodes and compare the collected results, and then take the majority of the answers as the correct answer and reward the nodes giving the correct answer.

If I have to code this logic in a smart contract, I will have to write a contract method for nodes to return the results, and specify the logic of verifying the results in the contract. My concern is, since the blockchain is open and transparent, when a node wants to return the result and waits for reward, the result returned will essentially by visible to all and other nodes can therefore "steal" the result and call the same method with that result without actually doing the computation task.

So how exactly can cloud computing be distributed, verified and rewarded in a decentralized manner when all results are open?

I have also looked into some other posts for ideas, such as
Using ethereum to fund distributed cloud computations? and Verifiable computing?. But it seems to me that the problem is really that there is no way to encrypt the results returned from running a computation task and thus prevent others from stealing it without actually doing the work.

Any advice or comment will be appreciated.


texts: Create a contract that can restrict the sale of the token in exchange

texts:
Possibility of  create a contract that can restrict the sale of the token in exchange.

Restrict by not selling all token only particular percentage of token.
To make use of the major token in platform.

Ex : if x Token is hold by the Certain investor. Should Restrict the investor from selling full token in Exchange.

Only certain percentage should be sold in the Exchange.

Should force the rest Token holder to use the token in Platform.


texts: Deploying Network; Using Different PC for different user

texts:
I am using MIX IDE in Windows.

I have created a new smart contract in Contract.sol, I have 4 Pages of html and there are 4 users.

Each html page is controlled by each user. The pages are also checking, while calling a function, whether it is send by prescribed user.

I want to Work this all pages simultaneously in different systems as different users . How can I do that. And Also I want to control as a new user from raspberry pi 2 b+?


texts: Parity sync time April 2018 - many days normal?

texts:
I am trying to set up an Ethereum node. I have tried with both geth and Parity and they both seem to be taking several days. I am on a high-end system with fiber internet, so I am wondering if this is to be expected.

My system specs are as follows:

CPU: Intel i7 6700K
GPU: GeForce GTX 1060 6GB
RAM: 16GB DDR4 SDRAM
HD: 128GB M.2 SSD
Internet: 950 Mb/s down, 120 Mb/s up, fiber

I am running Ubuntu 16.06 with Parity version v1.10.2-beta-f4ae813-20180423/x86_64-linux-gnu/rustc1.25.0. Clock is synced.

I launched Parity firstly with no args, waited a couple of days, then deleted ~/.local/share/io.parity.ethereum (around 70GB iirc) and tried again with:

parity --mode active --tracing off --pruning fast --db-compaction ssd --cache-size 1024

This time it's been running for about 4 days and by a quick back-of-envelope calculation it will take another few days still.

With geth, I would quickly sync just to the last 100 blocks (~70GB) after only a few hours - but it wouldn't catch up the last 100 blocks given another 24 hours. Is this normal?


texts: I have an application in which I have to put each user information on a different block to get the block unique address, do I have to deploy contract every time I will add new user information?


texts: Is it possible to artificially make the blockchain fork while multiple miners are mining?

texts:
I want to artificially make the blockchain fork, so that some blocks are invalidated. This is for testing purpose.

Does anyone have clues on how to do this?


texts: Reading require() error reason in web3.js client

texts:
Solidity version 0.4.22 introduced error reasons for require and revert (https://github.com/ethereum/solidity/releases/tag/v0.4.22).

I tried using them, but it looks like they only work when I'm using the javascript VM on remix. When calling a function using web3 the error is a good old "Error: VM Exception while processing transaction: revert" without any extra info.

Am I missing something?


texts:
I would like some affirmation that I'm mining correctly. Please take a look:

screenshot

I want to solo mine, to me it seems to be working? What does it mean by "solution found"? Did I find a block result?

I appreciate any input.


texts: Connecting my Golang Backend server with Metamask

texts:
I'm trying to build a Ticket-Office project in one of my courses at the University.

The project uses a backend server (which I'm writing in Golang) and it should be able to deploy and use smart contracts; to be able to create events (concerts and sports for example), tickets for these events, and the ability for the end user to 'purchase' them.

The ticket purchase should be based on smart contract transactions.
I already figured out how to connect to the Ropsten test network (where all my contracts will live).
My issue is, that I can't figure out how to connect users(those who potentially will want to buy a ticket) Metamask account to my service.
I can't find an example for that either.

Any suggestions?
Thanks ahead!


texts:
I'm currently running geth.
I have 4 nodes in my network and I'm willing to make them interact with each other.
On host-01, I've run:
geth --identity "Node1" --genesis /tmp/eth/genesis.json --rpc --rpcport \
    "8001" --rpccorsdomain "*" --datadir /tmp/eth/60/01/ --port "30301" \
    --nodiscover -ipcapi "admin,db,eth,debug,miner,net,shh,txpool,personal,web3" \
    -rpcapi "db,eth,net,web3" --autodag --networkid 4828 --nat \
    "any" console 2>> /tmp/eth/60/01.log

On host-02, I've copied the genesis.json file from host-01, and ran the same command, just changing the --identity argument.
Now I'm trying to make them talk to each other. I've obtained host-01 enode:
admin.nodeInfo.enode

this gave me a string like:
"enode://6380bf79e7900309ac71612835f...@[::]:30301?discport=0"

Then, on host-02, I've run in the console:
admin.addPeer("enode://6380bf79e7900309ac71612835f...@[::]:30301?discport=0")

The result is true, but when I run:
admin.peers

it shows me an empty list.
What am I missing?

Edit
Additional info:
The hosts do see each other in the network (tested via ping) and the ports are up (tested via telnet), although the connection only keeps open for approximately 1 sec. Not sure if this is the problem.


texts: Is there a way to get the *current* price of ETH in solidity function?

texts:
Is it possible to get the current price of ETH in USD in a buyTokens function of a deployed solidity smart contract?

For instance, every time GETH starts up is determines the price of ETH during initialization.

Or, is the real way to do it with pre-calculation on a site using web3 to interact with the smart contract once it determines the USD value?

Thank you in advance!


texts: Any erc20 token transfer simple code in ethers.js?

texts:
I tried a lot but the code to transfer erc20 token not working, always return error replacement fee too low
Unhandledpromiserejectionwarning etc
Any easy code to transfer erc20 token in ethers.js?


texts: Why is my geth node stuck on "Looking for peers"?

texts:
I created a private test network using Puppeth and two nodes using Geth:
geth account new --datadir node1
geth account new --datadir node2

geth init mynetwork.json --datadir node1
geth init mynetwork.json --datadir node2

geth --datadir node1 --mine --miner.threads 1
geth --datadir node2 --port 30304 --rpc --bootnodes "enode://<enode address from node1>@127.0.0.1:30303"

Both nodes start up normally (AFAI can tell), but they stay "Looking for peers". The only warnings shown are "Sanitizing cache to Go's GC limits", "The flag --rpc is deprecated and will be removed in the future, please use --http" and "Upgrade blockchain database version from= to=7".
I've run the exact same commands previously and was able to mine, but after stopping and restarting the nodes they just continually look for peers. The peercount jumps between 0 and 3, but typically it will show peercount=1.
I've tried deleting the network (~/.puppeth/mynetwork) (and the nodes) and creating a new one using the same steps, and sometimes it will work (i.e. the mining node will mine successfully (I've verified this using the MyCrypto desktop app)), but the last two times I've gone through the same steps I get the aforementioned result (Looking for peers).
I do have a firewall (the basic Mac OSX firewall), but it does not "Block all connections" and does "Automatically allow built-in software to receive incoming connections", if that's relevant, and I haven't changed the firewall settings since before when the nodes did mine.
At
geth not connecting to bootnodes on private test network
someone suggests syncing the nodes using sudo ntpdate -s time.nist.gov. I don't have ntpdate, so I tried systemsetup -setnetworktimeserver time.nist.gov, but that didn't seem to fix anything.
I'm stuck! Like I said, it has worked before (viz. yesterday) with the same setup. Thanks in advance.


texts: Running truffle migrate just opens my truffle.js file and does nothing

texts:
I am following this tutorial: http://truffleframework.com/tutorials/building-dapps-for-quorum-private-enterprise-blockchains.

I am trying to run truffle migrate on my project but it just opens my file in VSCode and nothing seems to happen. Any ideas what this problem is?


texts: Change name "Ethereum", "ETH" etc. of a private chain

texts:
I'm trying to run a private chain with geth and all works properly, but how can I change the name of "Ethereum" and "ETH" and choose a new name and a new TAG?

Thank you.


texts: When syncing, the current block is 6154852 and eth.blockNumber shows 0

texts:
I used geth to sync the blocks in mainnet, but the sync last for a long time.
eth.syncing shows the current block is 6154852, near the highest block.  But eth.blockNumber shows 0.  Why does this happen?  And will the sync finish?


texts:
As we know, it's possible to distinguish between two functions have same names. Different number of the functions arguments is a way for that. If the number of arguments is the same but the set of the arguments' types is different, will there still be a difference between the functions of the same name? If the number of arguments is the same and the set of the arguments' types is the same but the order of these types is different in the functions, does it make a difference between the functions of the same name?
The below solidity code has all states mentioned in the question. Two first functions return the expected values but two last functions return
Result { '0': '', '1': true }

that is unexpected.
Solidity code:
pragma solidity ^0.5.12;

contract A{

    function demo(string memory n, bool b) view public returns(string memory, bool){
        return (n, b);
    }

    function demo(address a, string memory n, bool b) view public returns(address, string memory, bool){
        return (a, n, b);
    }

    function demo(int a, int b) view public returns(int, int){
        return (a,b);
    }

    function demo(bool b, string memory n) view public returns( bool, string memory){
        return (b, n);
    }

}


texts:
I'm designing a proxy smart contract that will be filled with eth by users so that anyone has an incentive to perform transactions useful to the user. I won't go into the detail of "usefulness" here.

My contract is a proxy that calls a function XXX(data). So far I've got this:

contract Broker
{
    using SafeMathOZ for uint256;
    Target                      public target;
    mapping(address => uint256) public m_balance;
    mapping(address => uint256) public m_reward;

    constructor(address _target) public {
        target = Target(_target);
    }

    function () public payable {
        m_balance[msg.sender] = m_balance[msg.sender].add(msg.value);
    }

    function deposit() public payable {
        m_balance[msg.sender] = m_balance[msg.sender].add(msg.value);
    }

    function depositFor(address _account) public payable {
        m_balance[_account] = m_balance[_account].add(msg.value);
    }

    function withdraw(uint256 _amount) public {
        m_balance[msg.sender] = m_balance[msg.sender].sub(_amount);
        msg.sender.transfer(_amount);
    }

    function setReward(uint256 _reward) public {
        m_reward[msg.sender] = _reward;
    }

    function XXX(Data data) public returns (bytes32) {
        uint256 gasBefore = gasleft();
        bytes32 result = target.XXX(data);
        address payer = data.requester;
        uint256 price = tx.gasprice * (87000 + gasBefore - gasleft()) + m_reward[payer];
        m_balance[payer] = m_balance[payer].sub(price);
        msg.sender.transfer(price);
        return result;
    }
}

It works as expected and rewards the sender as I expect. What I am worried about is the possibility of a message sender to provide a very high gas price, thus draining the user balance and "giving" it to the miner :/

Any idea on how to solve this issue? Is there a better way then having the user specify a "maximum gas cost"?


texts: What filesystem should I use for geth and leveldb?

texts:
I used old LGA775 machine for running geth node. Its mobo has older sata 3gb/s (benchmark showed that ssd bottlenecked there) and only 4gb of DDR2, with windows installed. So syncing is a real pain process, for a week or more..

Now I accidentally have another better candidate, based on LGA1366 with 6gb/s sata  and 24gb of DDR3, and I am thinking of installing Debian. It will be installed on a separate drive, so whole SSD could be dedicaded for blockchain needs, with --datadir command. Even --keystore folder and binaries would sit on separate smaller ssd drive, alongside with Debian with ext4 filesystem.

But before performing that bold move, I have to decide filesystem for geth data directory, to make things work their best way right from the start. Possible candidates are:

FAT32 (easy to move along PCs with different OSes, or use as external HDD)
exFAT (dedicaded to flash-based storage, saves erase-cycles?)
Ext4 (native for linux, most stable and supported there)
ZFS (i heard that is used for enterprise storage, could be more manageable if i plan reconfigure HW, resize volumes, so on)

What to choose? Why? What tuning/parameters would you recommend? (since we all know that LevelDB stores enormous number of ~2100KB *.ldb files under chaindata directory)


texts: Deployed two dependent contracts: BigNumber Error: new BigNumber() not a base 16 number

texts:
Parent:

pragma solidity ^0.4.23;

import "./Config.sol";

contract ParentContract{

    ConfigContract _config;

    constructor(ConfigContract config) public{
        _config = ConfigContract(config);
    }

    function getNameFromOtherContract() public view returns(string) {
        return _config.getName();
    }
}

Config:

pragma solidity ^0.4.23;

contract ConfigContract{

    constructor() public{
    }

    function getName() external pure returns (string) {
        return "Amel";
    }
}

deploy script:

const Parent = artifacts.require("./ParentContract");
const Config = artifacts.require("./ConfigContract");

module.exports = function(deployer) {
    deployer.deploy(Config)
    .then(() => Config.deployed())
    .then(config => deployer.deploy(Parent, config.address));
};

Deployment is successful, but problem is that when I call:

  truffle(ourTestNet)> parent.getNameFromOtherContract()

I get:

BigNumber Error: new BigNumber() not a base 16 number:


texts:
I am trying to deploy my contracts with
const Migrations = artifacts.require("Migrations");
const Market = artifacts.require("Market");

module.exports = function (deployer, accounts) {

  deployer.deploy(Migrations, {from: accounts[0]});
  deployer.deploy(Market, {from: accounts[0]});
};

But, when I try to run the truffle migrate command, the editor gets its stack filled and I have to manually shut it down. I know that the problem is from the {from: accounts[0]} part, but I need to deploy them by this and this address only. What could you suggest?
Thanks.


texts: web3j command-line does not recognize flags

texts:
I am trying to run the command such as
web3j solidity generate -b SimpleBank/SimpleBank.bin -a SimpleBank/SimpleBank.abi -o ~/IdeaProjects/quiknode/src/main/java/ -p com.simplebank

Found here: https://blog.quiknode.io/web3j-ethereum-for-java-developers/
However, the web3j says :
Unknown opitions: -b, ...

Version is 1.4.1
Also, their docs of wrappers forward to a 404 page.
At this point, coding a wrapper by hand looks like the best option.
Edit: for the purpose of a code generating, I took the Java source-code for web3j/codegen and ran it against my own .abi and .bin files. However, since this post is about the command line interface, this is not the answer.


texts: Peers counts by bootnode and non-boot node are different

texts:
I just setup a 4 nodes Besu network 21.1.5 on a single Ubuntu 20.04 server. The peer count on boot node is 4. However it is 3 peers on all other non-boot node. Is it right that the peer counts from boot node and non-boot node are different?
The following is the log from boot node :
2021-05-24 12:50:33.065+08:00 | pool-8-thread-1 | DEBUG | BaseBftController | New chain head detected (block number=106392), currently mining on top of 106391.
2021-05-24 12:50:34.862+08:00 | EthScheduler-Timer-0 | DEBUG | FullSyncTargetManager | Caught up to best peer: 106391, Peers: 4
2021-05-24 12:50:34.862+08:00 | EthScheduler-Timer-0 | DEBUG | WaitForPeerTask | Waiting for new peer connection. 4 peers currently connected.
2021-05-24 12:50:35.000+08:00 | pool-8-thread-1 | DEBUG | IbftRound | Creating proposed block. round=ConsensusRoundIdentifier{Sequence=106393, Round=0}
2021-05-24 12:50:35.024+08:00 | pool-8-thread-1 | DEBUG | IbftRound | Received a prepare message. round=ConsensusRoundIdentifier{Sequence=106393, Round=0}

Here is non-boot node log:
3ef461d284abfecb72be4a2cdaa6a271) in 0.000s. Peers: 3
2021-05-24 12:40:17.057+08:00 | EthScheduler-Workers-2 | INFO | PersistBlockTask | Imported
#106
,084 / 0 tx / 0 om / 0 (0.0%) gas / (0x2b91d68407a7d67dee2209fd3ee6af967ac49870be363117019929f070f326a3) in 0.000s. Peers: 3
2021-05-24 12:40:17.058+08:00 | pool-8-thread-1 | INFO | IbftBesuControllerBuilder | Produced
#106
,084 / 0 tx / 0 pending / 0 (0.0%) gas / (0x2b91d68407a7d67dee2209fd3ee6af967ac49870be363117019929f070f326a3)
2021-05-24 12:40:19.059+08:00 | pool-8-thread-1 | INFO | IbftBesuControllerBuilder | Imported
#106
,085 / 0 tx / 0 pending / 0 (0.0%) gas / (0x2c99e49ea401105514369d507c87f22d91efa2b2e94fdfdd5f31e1780d484d3a)
2021-05-24 12:40:19.059+08:00 | EthScheduler-Workers-0 | INFO | PersistBlockTask | Imported
#106
,085 / 0 tx / 0 om / 0 (0.0%) gas / (0x2c99e49ea401105514369d507c87f22d91efa2b2e94fdfdd5f31e1780d484d3a) in 0.000s. Peers: 3


texts: Which is the best approach for upgradeable smart contracts proxy approach or eternal storage approach?


texts: Deleted ethash - ETH disappeared from Ethereum Wallet

texts:
I made a mistake and deleted ethash files from my Hard Drive and now my ETH, just 1.96 coins, has disappeared from my Ethereum Wallet. I can see the transaction details and the confirmations on the blockchain. How do I get it back into my Wallet?

Needless to say, I am an idiot.


texts: Is it possible to change the bytecode a factory is using to create child contracts?

texts:
Normally a factory includes the bytecode of any contract it creates. Now let's think about a scenario where there is an update of the child contract code necessary. I don't want to change existing childs, but I want to inject different bytecode into the factory, so from now on it produces the new variant of the child contracts.

Sample code:

contract Factory {
  // ...
  function newChild() returns (address) {
    Child c = new Child();
    return c;
  }
  // ...
}

contract Child_v1 {
  // ...
  public getVersion() constant returns (uint) {
    return 1;
  }
}

When compiling this the bytecode of Child_v1 will be embedded into the Factory contract. Now I want to change the factory so it produces childs of the type Child_v2:

contract Child_v2 {
  // ...
  public getVersion() constant returns (uint) {
    return 2;
  }
}

Is there a way to change the embedded bytecode of Child_v1 in Factory? E.g. I could compile Child_v2 offline and inject the new bytecode into the factory, something like this:

contract Factory {
  // ...
  function newChild() returns (address){
    Child c = new Child(); // should use bytecode as provided below
    return c;
  }
  function setChildCode(bytes[] bytecode) {
    // Some magic that updates the bytecode used in newChild() above
  }
}


texts: How could I update my enodeID using `geth`?

texts:
I have an Ethereum node on a Amazon AWS instance. When I clone my node, it will generate with the same enode-ID. When both machine try to connect to peers, they get race each other, so one of them able to connect to peers but other cannot.

[Q] How could I change my enodeID on using geth?

Solution for Parity node:

  Changing or removing the network key changes the enode address:

  ~/.local/share/io.parity.ethereum/network/key You could increment the
  value by one or generate a new one or remove it and parity will take
  care of that.

I don't know how to do this approach on geth.


texts: Event listener for changes to accounts list

texts: How is it possible to set an event listener for changes to web3.eth.accounts or web3.eth.getAccounts()?


texts: What precisely classifies an off-chain block as a fork?

texts:
I am looking for validation (or invalidation) of my assumption of what strictly counts as a fork in Ethereum.

If you start filters to multiple ETH nodes at the same time, you will very often see 2 or more blocks mined at the same height.

My understanding is that these off chain blocks will always be included as uncles in future blocks, with the following two cases counting as a fork:

1) a child is mined with an uncle as its parent (i.e. the classic type of fork you would see in BTC)

2) A reorg, e.g. a block that was regarded as main chain is swapped with an uncle block at the same height.

Can anyone tell me whether this is accurate, is it missing anything, and are there any errors in the above assumptions?


texts: Do we have any control over sharding in IPFS?

texts: Suppose I have a huge N-dimensional database and want to store it using IPFS, is there any way I can shard my dataset in such a way that I get N hashes each for single dimension using IPFS?


texts: Creating multiple accounts in metamask automatically

texts:
Say I could travel back in time, and wanted to take advantage of the uniswap airdrop.
Would it be possible to create multiple adresses on my metamask account through the web console of my pc, instead of manually adding them one by one? If so, how?


texts:
I want to call a function on an external contract from a Vyper contract.
I want to handle a potential revert of this call.
Python try...except is not implemented in Vyper. What should i do instead ?
Thanks


texts:
So i'm having some trouble with this.  Basically i'm trying to initiate a contract that sends MetaCoins to an address.  The other contract is supposed to subtract from the balance of MetaCoin to pay for the OtherCoin.  The balances of OtherCoin are accurate, but it's not firing m.sendCoin.

The owner of the OtherCoin contract should be receiving MetaCoin from the purchaser...

pragma solidity ^0.4.2;

import "./ConvertLib.sol";

// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!

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

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

    function MetaCoin() {
        balances[msg.sender] = 10000;
    }

    function sendCoin(address receiver, uint amount) returns(bool sufficient) {
        if (balances[msg.sender] < amount) return false;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Transfer(msg.sender, receiver, amount);
        return true;
    }

    function getBalanceInEth(address addr) returns(uint){
        return ConvertLib.convert(getBalance(addr),2);
    }

    function getBalance(address addr) returns(uint) {
        return balances[addr];
    }
}

contract otherCoin {
  mapping (address => uint) balances;
  address owner;

  function otherCoin() {
    owner = msg.sender;
    balances[owner] = 10000;
  }

  function purchaseCoin(address coinContractAddress, uint amount) returns(bool sufficient) {
    MetaCoin m = MetaCoin(coinContractAddress);
    if(m.getBalance(msg.sender) >= amount) {
      balances[msg.sender] += amount;
      balances[owner] -= amount;
      m.sendCoin(owner, amount);
      return true;
    }
    throw;
  }

  function getBalance(address addr) returns(uint) {
        return balances[addr];
    }
}

What am I missing here?


texts: Etherscan Verification when using a ContractFactory

texts:
If I have a contract (ContractFactory) that creates several instances of some other contract (SubContract), is there a way to verify all instances of SubContract?

pragma solidity ^0.4.19;

contract ContractFactory {
    address[] public deployed;

    function createSubContract() public {
        deployed.push(new SubContract());
    }
}
contract SubContract {
    uint public var1;
    uint public var2;

    function SubContract() public {
        var1 = 1;
        var2 = 10000;
    }
}


texts: testrpc, contract creating contract not mined?

texts:
I'm trying to develop a contract that creates a contract (factory/worker, faucet pattern). Think my issue may be with the tools I'm using:

testrpc (local blockchain)
Remix Browser Solidity (connected to testrpc)
MetaMask (for watching transactions, balances etc)
truffle (for deployment/migration)

When I deploy my contracts using truffle, I can see the transaction and contract address immediately in testrpc:

Transaction: 0x153a84e6478df590deb21a95cd9042dd5820e838ac14986fb47a8b13df34bd1b
Contract created: 0x7a5812ba512df41432ed408ed0a1b266aa8a27dc
Gas usage: 0x094d2a
Block Number: 0x49
Block Time: Tue Mar 21 2017 19:30:56 GMT+0000 (GMT)

However, when I get my Factory contract to create a contract I can only get the transaction - yet using Event's for logging I can see an address, but can't interact with it. Also testrpc reports the transaction but no contract address:

Transaction: 0x2984356f7ea77ac86f6dee92472736a682061fbeab7de335bc4a6aa7ed66462b
Gas usage: 0x0532a9
Block Number: 0x4c
Block Time: Tue Mar 21 2017 19:30:59 GMT+0000 (GMT)

It seems that testrpc isn't mining, I've tried adding the switch -b 1, but still same effect. Also I've tried the demo from embark, when I fire it up the framework deploys contracts successfully, as with truffle, but when I try their dapp transactions get created but never mined.

Factory contract

pragma solidity ^0.4.2;

import './Bar.sol';

contract Foo{

    function createBar(){

      Bar bar = new Bar();
    }
}

Worker / Child contract

pragma solidity ^0.4.2;

contract Bar{

}

The issue also persists with embark framework, where the frame work can create contracts but I can't. Seems like their not being mined?


texts: Decentralized exchange that lets you cash out Ether for fiat money?

texts:
Uniswap is a decentralized exchange that doesn't require KYC or ID
for trading between ETH and ERC-20 tokens (altcoins), while
Bisq is a decentralized exchange that doesn't require KYC or ID for
cashing out Bitcoin for fiat money.

Is there a similar exchange that doesn't require KYC or ID for cashing out Ethereum for fiat?


texts: What actually happens on the blockchain as a storage element is updated over time?

texts:
An "under the hood question" about actual contract storage elements.  If I add an element to a contract storage data time, for example, a list of zombies owned by different people in a game, what actually happens on the block chain?

Since the blockchain is immutable, I assume that the original map content is not touched, and that a new block is created on the public ledger that reflects the updated content of the zombie to owner map.

If that is correct, how does anyone querying my smart contract get (directed to/routed to/not sure how to say this) end up getting the results of the updated owner to zombies map instead of an older copy of that mapping from a block that is on the block chain?  In other words, how does the node software "know" to find the latest copy of the storage element and if so, what kind of search method does it use to do that?  (e.g. - if it is a linear search, wouldn't that mean if a smart contract records every transaction to the block chain that the search times would get extraordinarily long and if so, does this cost a lot of gas to execute?)

And going the other direction, is it still possible for me to query the content of previous/older images of the owner to zombie map printed earlier to the blockchain?  For example, let's say I want to create an audit history of changes to the owner to zombie map over time?

If there is a really good book, PDF, guide, etc. that goes into the details of how this works and what some of the strategic optimization nuances are with the mechanics of how smart contract storage elements are updated/searched-for over time, that would be appreciated.


texts:
How can I store a "database" in a smart contract and how would the cost be calculated, what is going to cost me gas ?

A practical exemple would be, I have an android app calling a smart contract with the ethereum-android-lib and adding data to it, i assume that this data can then be retrieve by another andoid client. What will be the cost of inputing this data in the smart contract ? Is it the amount of the new data that I am trying to input or the total cost of all the data that is in the smart contract ?

The contract pseudo I thought of would look like this:

contract patientRecord {
  address public owner;
  uint public numFiles;
  struct File {
    uint name;
    bytes32 illness;
  }
  mapping(uint => File) public files;

  // add a new file
  function files(bytes32 _message) {
    if (msg.value == 0 || complete || refunded) throw;
    files[numFiles] = Pledge(msg.value.name, msg.value.illness);
    numFiles++;
  }

  function retreive(uint id){
      //get back file of a pateint with ID
  }

  function retreive(uint id){
      //modify some value in a file
  }

}


texts: Log index change during chain reorganization

texts:
While working with log filters i've noticed interesting behavior of logs during chain reorganizations. Sometimes same event (log) can have different logIndex in transaction after chain reorganizations.

My question is: can logIndex change in the same block? For example: it happens that sometimes you can get duplicate events from listening eth_getFilterChanges, can it be that event you get as Duplicate (has same tx hash and blocknum) can have another logIndex than before?

Second question is: why do logIndex change at all?!


texts:
hey guys im trying to code a time based fee, where if you sell the token today you get a penalty of x amount , if you sell it tomorrow you get y...
Im quite new to solidity so idk
I know "now" stores the current time Unix value, is doing if else loop a good idea?
if now < time of tomorrow:
fee = ...
else now <....


texts: ZK-SNARKS with ZoKrates - problems with proving the hash preimage tutorial

texts:
Just noticed today that ZoKrates has finally support for SHA256! I wanted to see it in action, so I followed the tutorial at https://zokrates.github.io/sha256example.html with a slight modification of the form

def main(private field a, private field b, private field c, private field d, field h0Pub, field h1Pub) -> (field):
    h0, h1 = sha256packed(a, b, c, d)
    h0 == h0Pub
    h1 == h1Pub
    return 1

./zokrates compute-witness -a 0 0 0 5 263561599766550617289250058199814760685 65303172752238645975888084098459749904

Witness, proof, and solidity verification contract can be created. However, if I try to send the proof with public inputs to the verification contract (verifyTx function) the function returns false.

Contracts are deployed and called with truffle 4.1.3 and tested on ganache-cli 6.1.0

Any idea/hint?


texts: What unit are the Uniswap/PancakeSwap router functions expecting?

texts:
I'm looking at this transaction in BSCScan: https://bscscan.com/tx/0x09a19072b2374340de10dc6ac235fcd0ba229ff1eba41e155f5b0a60f9c2e2cd
When looking at Input Data for the method call, the caller indicated 11764337867528 for amountOutMin.  What unit is Pancake/Uniswap expecting this to be in?  The actual amount out was closer to 11,764.337867528.
I suspect it's GWEI.  Is that correct?  On a related note is Gas always given in WEI?