texts: connecting to Metamask using React.js and Next.js without having to refresh the page each time

texts:
StackShare question
Hello, I am having a problem with connecting to Metamask dynamically.
I created a voting website using React.js and Next.js, and was using UseEffect() to connect to Metamask.
Currently, when I navigate to a page with its link or make any changes to a one, I fail to connect to my smart contract, although I can connect when I refresh manually. I believe that this is due to Next.js preloading data.
For instance, this is what I see when navigating to index.js :

However, everything usually works after I refresh the page

Here is a basic implementation of my index.js
  useEffect(() => {// get web3
    async function initWeb3() {
      const web3Instance = await getWeb3();
      setWeb3(web3Instance)
    }
    initWeb3();
  },[]);

  useEffect(() => {// get Factory contract
    async function setup() {
      if(web3 == "") {
        console.log('unable to get factory')
        return;
      }
      try {
        // Get the contract instance.
        const networkId = await web3.eth.net.getId();
        const deployedNetwork = VoteFactoryContract.networks[networkId];
        const instance = new web3.eth.Contract(
          VoteFactoryContract.abi,
          deployedNetwork && deployedNetwork.address,
        );
        setContract(instance);// Set web3, accounts, and contract to the state, and then proceed with an
      } catch (error) {
        // Catch any errors for any of the above operations.
        alert(
          `Failed to load web3, accounts, or contract. Check console for details.`,
);
        console.error(error);
      }
    }
      setup();
  },[web3]);

  useEffect(()=> {//display available votes addresses
    var displayVotes = async () => {
      if(contract == ''){
        return;
      }
      const response = await contract.methods.getDeployedVotes().call();
      // Update state with the result.
      setVotesAddresses(response);
    };
    displayVotes();
  },[contract]);

getWeb3() looks like this:
import Web3 from "web3";

const getWeb3 = () =>
  new Promise((resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener("load", async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.eth_requestAccounts;
          // Acccounts now exposed
          resolve(web3);
        } catch (error) {
          reject(error);
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log("Injected web3 detected.");
        resolve(web3);
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider(
          "http://127.0.0.1:8545"
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      }
    });
  });

export default getWeb3;

Finally, my contract code is as follows:
pragma solidity ^0.7.4;
//"SPDX-License-Identifier: UNLICENSED"

import "./Vote.sol";

contract VoteFactory{
    address[] public deployedVotes;

    function createVote(uint typeOf) public{
        address newVote = address(new Vote(msg.sender, typeOf));
        deployedVotes.push(newVote);
    }

    function getDeployedVotes() public view returns (address[] memory) {
        return deployedVotes;
    }

}

I have spent endless hours trying to debug this, and although I feel like I know what the error is, I cannot find a solution.


texts: How to return a exact value pushed before in my contract?

texts:
How do you return the value pushed before with only one function? I read some information about events, so I think it may be a solution, but it doesn't return the exact value pushed before. There is my new source below which added events:

pragma solidity ^0.4.0;
////////////////////////////////////////////////////////////
// This is an example contract hacked together at a meetup.
// It is by far not complete and only used to show some
// features of Solidity.
////////////////////////////////////////////////////////////
contract queue
{
    struct Queue {
        uint256[] data;
        uint256 front;
        uint256 back;
    }
    /// @dev the number of elements stored in the queue.
    function length(Queue storage q) constant internal returns (uint256) {
        return q.back - q.front;
    }
    /// @dev the number of elements this queue can hold
    function capacity(Queue storage q) constant internal returns (uint256) {
        return q.data.length - 1;
    }
    /// @dev push a new element to the back of the queue
    function push(Queue storage q, uint256 data) internal
    {
        if ((q.back + 1) % q.data.length == q.front)
            return; // throw;
        q.data[q.back] = data;
        q.back = (q.back + 1) % q.data.length;
    }

    /// @dev remove and return the element at the front of the queue
    function pop(Queue storage q) internal returns (uint256 r)
    {
        if (q.back == q.front)
            return; // throw;
        r = q.data[q.front];
        delete q.data[q.front];
        q.front = (q.front + 1) % q.data.length;
        return r;
    }
    Queue requests;
    event PopEvent(bool ok); //my event designed by me here.
    function queue() {
        requests.data.length = 200;
    }
    function addRequest(uint256 d) {
        push(requests, d);
    }
    function popRequest()  returns (uint256) {
        PopEvent(true);
        return pop(requests);
    }
    function queueLength()  constant returns (uint256) {
        return length(requests);
    }
    function hello() constant returns(string s){
        return 'hello world!';
    }
}

I just want the popRequest function to return the exact value pushed before.


texts: How to verify if an address is an instance of the desired smart contract?

texts:
Given an address (in server-side javascript), is there a way to check that the address is an instance of a specific smart contract?

I've tried using

web3.eth.getCode(addr)

for a recently deployed contract, but this gives me slightly different bytecode (ie same prefix and postfix with some similar stuff in between) than what was used to deploy it. Am I missing something, or is there another way to do this?


texts: Connecting a geth node over LAN to a public geth node on my network

texts:
I need to run 2 geth nodes on separate computers on my network (ethereum Mainnet). I understand that I could connect them both to public peers the regular way over the internet simply by changing the port of one of my nodes (correct me if I'm wrong here).
However, I would like to save some internet bandwidth by connecting one node through the internet (the regular way) and the other only over LAN to that first node.

How would I do that?
How much additional latency should I expect on the LAN node?

Thanks a lot in advance!


texts: method like fallback function for ERC20 tokens?

texts:
I want to write a contract that uses USDT (Tether) for payment.
How can I use the ERC20 token as an ERC777 token, for example:

Use a fallback function that executes when we receive USDT token.
Or use some data while sendeing token to be processed by the receiver contract.

Is there any way like using Tether contract address in our new contract and extending its capablities?
I also saw this question, but this is about developing a new token, not an existing one.


texts: Is there any c++ library for signing transactions?

texts:
I am working on light wallet in c++, and I am looking for a c++ library for signing transactions. I mean something where i will pass transaction and private key and it will return signed transaction so I can send it to infura.
Does any exists?


texts: What exactly happens when you send ETH to The DAO Contract and why does it require so much gas?

texts: I understand that transactions to contracts require more gas than normal transactions. But what exactly is happening that requires more gas?


texts: When my app disconnects from remote Geth does it mean it lose whole sync information?

texts:
My app interacts with remote Geth node through SSH. The first sended command was geth --cache=1024 When the node was sending back some sync logging information, the connection has been lost. Then I make a new session and send geth attach and think the node is running still. However it returns error:

  Unable to attach to remote geth: dial unix
  /home/.../.ethereum/geth.ipc: connect: no such file or directory

Is it true geth deletes any sync files when it lose the current connection? And if it's false even, what happens when the Geth node terminates its running (for e.g. because of crash)?


texts:
A msg.sender can create multiple Struct Item . What would be best way to store the Item ?

Currently I'm using

struct Item {
    uint256 amt;
    bool isActive;
    address owner;
}
Item[] public items;
function createItem(uint amt) returns(uint a){
   items.push(Item({
      ...
   }))
   return (items.length);
}

But createItem returns a tx hash as it's not mined yet.

Calling a items.length after mining completes won't guarantee me the id.

I also tried adding it in mapping but mapping don't accept Struct Arrays

Item[] public itemStack;
mapping(address => itemStack) public items; //TypeError: Name has to refer to a struct, enum or contract.
...
items[msg.sender].push(...)


texts:
I connecting to my GethNode of Private Block chain setup with Ubuntu. But whenever i exit from terminal my GethConnection also get terminated and mining also stops.
How to keep alive the Geth Connection and Mining after disconnecting from the terminal.

Thanks
AKM


texts:
Following is a very simple contract which implements deposit and withdraw functions. I have defined two events :

deposited(address from, string msg)
withDrawn(address from, string msg)

The contract is as follows:

pragma solidity ^0.4.4;
contract Bank{
uint balance;
address owner;

event deposited(address from, string msg);
event withDrawn(address from, string msg);

function deposit(uint amount){
    balance = balance + amount;
    deposited(msg.sender, "Amount has been deposited successfully");
}

function withDraw(uint amount){
    if(amount >= balance){
        throw;
    }
    else{
        balance = balance - amount;
        withDrawn(msg.sender, "Amount has been withdrawn successfully");
    }
}

function getBalance()constant returns (uint){
    return balance;
}

}

Now, when i run this contract from command prompt using its compiled code, the events are not shown. How should i output them in nodeJS.


texts: Are there any cryptocurrencies built by modifying ethereum code, like there are many alt-coins based on bitcoin code?

texts: Is it legal to build a separate blockchain with our own coins/tokens and miner-code to mine those coins/tokens (not a private one) based on ethereum open-source code ?


texts:
I just used Meta-Mask and funded the program with BUSD from my Binance account in order to test a deposition on curve.fi. Moreover, a small amount of ETH was transferred to Meta-Mask in order to cover the gas prize. Afterwards, I transferred the stable coins (BUSD) via Meta-Mask to curve.fi, but although etherscan says that transaction was successful, money never reached the curve platform. I would like to understand what happened and why my curve.fi deposit is still empty?
Here is the link to the transaction on etherscan:
https://etherscan.io/tx/0x9605cf73399130b02939949de402a98e52732ffb17bda2e32ab53f4ba3b5f6f5
Cheers,
RN


texts: Force two users to send the same amount of ether when starting a game

texts:
In my smart contract, I want the two participants to send the same amount of ether so they can start a game of rock, paper, scissors. How can I modify the sendEnoughCash() function do that?

This is the contract:

function register (string choice) payable notRegisteredyet()  sentEnoughCash(5 wei) {

        if(player1 == 0)
        player1=msg.sender;
        else if (player2 == 0)
        player2=msg.sender;
        if (msg.sender == player1)
            player1Choice = choice;
        else if (msg.sender == player2)
            player2Choice = choice;

    }

    function rpsgame()
    {   // constructor
        scenarioMatrix["rock"]["rock"] = 0;
        scenarioMatrix["rock"]["paper"] = 2;
        scenarioMatrix["rock"]["scissors"] = 1;
        scenarioMatrix["paper"]["rock"] = 1;
        scenarioMatrix["paper"]["paper"] = 0;
        scenarioMatrix["paper"]["scissors"] = 2;
        scenarioMatrix["scissors"]["rock"] = 2;
        scenarioMatrix["scissors"]["paper"] = 1;
        scenarioMatrix["scissors"]["scissors"] = 0;
    }

    modifier notRegisteredyet() {

        if (msg.sender == player1 || msg.sender == player2)
         revert();
         else
          _;

    }

     modifier sentEnoughCash(uint amount) {
        if (msg.value < amount)
         revert();
         else
         _;
    }

     function play() returns (int w ){

            if (bytes(player1Choice).length != 0 && bytes(player2Choice).length != 0){

            int winner = scenarioMatrix[player1Choice][player2Choice];
            if (winner == 1)
                player1.transfer(this.balance);
            else if (winner == 2)
                player2.transfer(this.balance);

            else
            {
                player1.transfer(this.balance/2);
                player2.transfer(this.balance);
            }
            // to reset game
           player1Choice = "";
            player2Choice = "";
            player1 = 0;
           player2 = 0;
            return winner;
        }
        else
            return -1;
    }
}


texts:
How can organizations with existing messaging infrastructures integrate with Ethereum?

For example, an organization with a large investment in Solace Messaging asked us how to integrate Ethereum into their existing event-based infrastructure.

Can the Framework based on the Whisper Protocol in Ethereum be replaced with a centralized event based platform?

Can the Framework based on the Whisper Protocol in Ethereum be configured to use the Solace Platform or other messaging platforms like ActiveMQ that support AMQP 1.0?


texts:
I understood that print is not possible on Solidity, is recommended to use event and events can be read by using .watch. In order for an event to appear it has to be mined first.

What if I have a function in Solidity the goal is to search through an array and print out all elements that meet certain criteria. This constant function is to be executed locally, not via mining, is it possible?


texts:
Caller -> Contract B -> Contract A

Contract A has a msg.sender variable.

I want to use the Caller as Msg.Sender for Contract A through Contract B.

How is this done?


texts: Create a members address array in a struct

texts:
I have the following struct:

struct Group {
    string name;
    address[] members;
}

and the following array:

Group[] public groups;

I don't need values, I only want to add one address after the next to check easier if a user is in a group or not (without creating another array and pointing that array to the struct).

Now I know, that for example groups[0].members[0] could be msg.sender.

Is there a way to create like only one way arrays, for example, that it is members[msg.sender] instead of members[0,1,273,37382...]?


texts: Why not possible limiting gas but forwarding ether in creating this contract from Solidity documentation

texts:
In the Solidity docs Creating contracts via new there is an example:

contract D {
    uint x;
    function D(uint a) public payable {
        x = a;
    }
}

and it states in the accompanying text:

  As seen in the example, it is possible to forward Ether while creating an instance of D using the .value() option, but it is not possible to limit the amount of gas.

Why not?


texts: Where is the binary file that lets me change from Homestead to Classic in Parity? Does changing the "config.full.toml" do the trick?

texts:
I am trying to run an ethereum classic node on parity so that I can sell my classic. I see the doc that says: https://github.com/ethcore/parity/wiki/Ethereum-Classic

The only problem is after I "git clone https://github.com/ethcore/parity", I have no Idea which folder is considered the binary.

In Home->parity->parity->cli, I found config.full.toml, which when I open has: chain = "Homestead".

I changed that to: chain = "classic"

1)I am not sure if that worked, I am downloading now, but in the terminal, in the beginning, it says "Configured for Frontier/Homestead". How can I determine if I am downloading classic early on in the chain download process?

2) Which folder contains the actual binary file and what is its name?


texts:
In my previous post I got answer but still I need some clarifications
let say when deploying contract with node js we have this line

 try {
    web3.personal.unlockAccount(web3.eth.coinbase, password);
} catch(e) {
    console.log(e);
    return;
}

which is unlocking account to make transaction for contract creation .

What if account is created with this way

web3.eth.accounts.create([entropy]);

And I have private key encyrpted somewhere on the system how I shall use it to unlock (or jsut use account) account let say after a week from it's creation ?

Also can u give details on what does entropy do
?

Is it like password in case of personal account ?

Thanks and sorry if questions are similar , there are not much resources to get more detailed info


texts: If Metamask Gas calculations are nearly perfect why do we still get out of Gas error?

texts:
Pardon me if this question seems a bit naive.
I have written a smart contract (for proof of existence) and simulating it in Ganache. Inside it I have logic to store data in a mapping created between index and a struct as below:

/// mapping of document and index
mapping (uint => Proof) idToProof;

// Struct
struct Proof {
    uint16   id;
    uint     proofdate;
    address  creator;
    string   title;
    string   proofhash;
    string   ipfshash;

}

My contract runs into out of gas exception when the line of code related to store data in the mapping is executed (highlighted below):

 function _saveTheProof(uint _proofTimeStamp) private {
     Proof memory newProof = Proof(proofId, proofTimeStamp, proofCreator, proofTitle, proofHash, proofIpfsHash);
     idToProof[proofId] = newProof; // <-- this line
     newProofCreated(proofId, proofCreator, proofTitle, proofHash, proofIpfsHash, proofRemarks, proofTags, _proofTimeStamp);
}

When I remove this code my dapp works perfectly fine.
I am really puzzled what is the issue here, why does Gas computed by Metamask is insufficient for the execution of this logic.
If Gas needs computed by Metamask are nearly correct then why do we end up having Out of Gas error.

Please help correct my concepts here or if my code is to be blamed here.


texts:
With Truffle 3.0 when I call one of my contract's function, in console I have this error:

  Uncaught (in promise) Error: invalid address

I found  this workaround, and in my code I try this with no success.

this.web3Provided.eth.defaultAccount=this.web3Provided.eth.coinbase;

In truffle doc they sat I can set a from address in my config, but also this not work. from: '0x8c384d9f226ea92c99f7aa83340714a6f82a3161'

I also try with this after I have imported all truffle.config file:

TruffleConfig.networks[NODE_ENV].from = this.web3Provided.eth.coinbase;

Please help me.


texts: How to generate a new Ethereum address and private key from a command line?

texts:
How one can securely generate a new raw private key from a UNIX command line?

This private key can be then imported to wallet apps or web3.js.


texts: Contract method works on local but not on testnet

texts:
The following method, which works perfectly fine on my local ganache.
function someMethod() external view
    returns (
        bool someValue,
        uint256 lastIndex,
        uint256 totalTokens
    ) {
    address owner = msg.sender;
    uint256 tokensForOwner = ERC721.balanceOf(owner);

    for (uint256 i = 0; i < tokensForOwner; i++) {
        uint256 tokenId = tokenOfOwnerByIndex(owner, i);
        if (someValue[tokenId] > 0) {
            return (true, i, tokensForOwner);
        }
    }

    return (true, tokensForOwner);
  }

However when deployed to the Kovan testnet I get the following error
data: "Reverted 0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002a4552433732313a2062616c616e636520717565727920666f7220746865207a65726f206164647265737300000000000000000000000000000000000000000000"
message: "VM execution error."

I did some checking by deploying multiple versions it seems the line at fault is
        uint256 tokensForOwner = ERC721.balanceOf(owner);

For which I tried ERC721.balanceOf(owner); and balanceOf(owner);.
Would anyone have any idea on why this happens and what is the solution?


texts: Error converting wei using promises in NodeJS

texts:
I am running this code on NodeJS application:

  let destinationBalanceWei = web3.eth.getBalance(process.env.DESTINATION_WALLET_ADDRESS).then(result => result.toString())
  let destinationBalance = web3.utils.fromWei(destinationBalanceWei, 'ether')

but I get following error in the console:

(node:79279) UnhandledPromiseRejectionWarning: Error: Please pass numbers as strings or BigNumber objects to avoid precision errors.
    at Object.fromWei (/Users/sahelanthropus/progetti/nodejs/node_modules/web3-utils/dist/web3-utils.cjs.js:440:11)
    at proveTransaction (/Users/sahelanthropus/progetti/nodejs/routes/index.js:49:39)
    at /Users/sahelanthropus/progetti/nodejs/routes/index.js:105:7
    at IncomingForm.<anonymous> (/Users/sahelanthropus/progetti/nodejs/node_modules/formidable/lib/incoming_form.js:107:9)
    at IncomingForm.emit (events.js:197:13)
    at IncomingForm._maybeEnd (/Users/sahelanthropus/progetti/nodejs/node_modules/formidable/lib/incoming_form.js:557:8)
    at /Users/sahelanthropus/progetti/nodejs/node_modules/formidable/lib/incoming_form.js:238:12
    at WriteStream.<anonymous> (/Users/sahelanthropus/progetti/nodejs/node_modules/formidable/lib/file.js:79:5)
    at Object.onceWrapper (events.js:285:13)
    at WriteStream.emit (events.js:197:13)
    at finishMaybe (_stream_writable.js:646:14)
    at stream._final (_stream_writable.js:624:5)
    at WriteStream._final (internal/fs/streams.js:270:3)
    at callFinal (_stream_writable.js:617:10)
    at processTicksAndRejections (internal/process/next_tick.js:76:17)
(node:79279) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:79279) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What I can do to solve it?


texts: Communicating between a Sidechain and a Mainchain

texts:
Side chains (see linked question ) can be seen as a blockchain attached to a "parent" blockchain using a "two way" peg.  Smart contract addresses are generated deterministically(HD wallet style), but the wallet style addressing is for smart contracts.

Unlike smart contract addressing, when the Parent blockchain addresses the
side chain(or vice versa) are there addressing issues like making deterministic wallet style addresses for the chains(a main chain could make a wallet style address for a sidechain), or communicating between the two blockchains(Parent and Sidechain), or is done using network addressing via sockets(and so on..)?


texts: Javascript client generates transaction that is not found on etherchain

texts:
I'm having a tough time. I am trying to do a simple sendTransaction from the javascript console. I get a transaction id but it is invalid (or not found) on etherchain.org. I've already tried re-installing the console and reloading the database. Any help would be SOOO appreciated. Thanks!

This is an example of the command i'm using:

eth.sendTransaction({from: eth.coinbase, to: '0xa8ade7feab1ece71446bed25fa0cf6745c19c3d5', value: web3.toWei(1, "ether")})


texts: Unable to send large transactions on ethereum private chain

texts:
I have a small contract

pragma solidity ^0.4.17;

contract A10test{
 mapping(uint=>string) public data;
 uint public revisionNo=0;

 function setdata(string _data) public {
     data[revisionNo] = _data;
     revisionNo =revisionNo+1;
 }
}

I'm trying to save a file of 3MB in data using setdata.
I have edited the go-ethereum/core/tx_pool.go ==> tx.Size() > 10000000*1024 to accommodate large transactions.

I'm able to do 2-3 transactions of 3MB, when I start a new chain and then I receive an error

  "error invalid json rpc response:"""

and my transactions do not reach geth.
Small transactions <100kb still works fine.

I'm using Truffle,web3 and truffle-hdwallet-provider to send transactions

Plz help

solution if some one is reading it now
Changing geth version from 1.8.20 to 1.8.02 solves the problem


texts: Can ethereum really make a safe decentralized exchange?

texts: I see there are a few ethereum decentralized exchanges out there.  Are they really safe?  Is there one currently in existing? Will this save me from getting MTgoxed in the future?


texts: Logging eth.syncing.currentBlock and highestBlock

texts:
I'd to like currentBlock and highestBlock from geth using geth attach --exec to run this script for pickup by Telegraf:

blocks.sh

/usr/bin/geth --datadir /home/ethereum/.ethereum --jspath /home/ethereum --exec 'loadScript("blocks.js")' attach | head -n -1

blocks.js

if (eth.syncing) {
    console.log("blocks,network=" + admin.nodeInfo.protocols.eth.network + " current=" + eth.syncing.currentBlock + ",highest=" + eth.syncing.highestBlock);
}

console.log("peers count=" + net.peerCount);

And the output (in Influx line protocol format) looks like:

blocks,network=1 current=2194411,highest=5119467
peers count=5

However, they're only available when eth.syncing is not false, which, after a full sync is not very often. Is there somewhere else to get those values that's always available?


texts: How does one setup a private network with ethereum docker images?

texts:
I'm confused about how to get/access geth that is inside the container.

So far I have:

docker pull ethereum/client-go

it seems though that this image is designed to work on the public network. do i have to make my own dockerfile?

What do I need to include in that dockerfile and how do I access geth?

Should geth be installed on the 'host' os/where the image/containers are or can it be solely in the docker container?


texts: Minimize mining times for private blockchain

texts:
a title is pretty straightforward. I need to set up miners on a private blockchain to mine blocks as fast as possible.

I have compiled a go-ethereum client with a constant value of difficulty but seems that mining complexity still grows. What directions should I look into to achieve the goal? Thanks


texts: Contract working on Javascript VM and not Web3 Provider, why?

texts:
Here is the code:

Calling contract:

pragma solidity ^0.4.24;

contract Caller {

    address public called_address;

    constructor() public payable {

    }

    function set_address(address _addy) public {
        called_address = address(_addy);
    }
    function () public payable{
        Called c = Called(called_address);
        if (c.get() > 10 ){
            revert("Too much sauce");
        }
        c.set();
    }

}

interface Called{

    function set() external;
    function get() external view returns (uint);
}

Called Contract:

pragma solidity ^0.4.24;

contract Called{

    uint public number;

    function myuint() public view returns(uint _number) {
        _number = number;
    }

    function set() public {
        number++;
    }

    function get() public view returns (uint){
        return number;
    }
}

When I call the fallback function I get an error. This only happens when using Web3 provider, but works well in JavaScript VM. Saw this question too Can't call another contract constant function in Remix in Web3 provider mode, but it works in Javascript VM

Is it a bug in Remix? Does my code have an error? Why do I get different results with the different environments?


texts:
I'm running a geth node on the testnet and trying to run web3.js method from my node server code.

Here's my code

var Web3 = require("web3");
var web3 = new Web3(new Web3.providers.HttpProvider('http://0.0.0.0:8545'));
console.log(web3.net.peerCount);

However, I'm getting net_peerCount method not implemented error.

Infact, I'm getting a similar method not implemented error when I try to access any net or eth methods.

Any help appreciated!


texts: Does Geth store trace data for later calls (after full-sync with pruning + reexec)?

texts:
The wisdom is that having a full node is enough to reconstruct all past information the archive nodes keeps readily constructured, hence available faster.

I was reading the Geth IceBerg 1.8 release notes and saw the notes about state pruning and checked the notest at https://github.com/ethereum/go-ethereum/wiki/Tracing:-Introduction.

There's a section about accessing state, which notes

  Pruning

  Geth by default does in-memory pruning of state, discarding state entries that it deems is no longer necessary to maintain. This is configured via the --gcmode option. Often, people run into the error that state is not available.

  Say you want to do a trace on block B. Now there are a couple of cases:

1. You have done a fast-sync, pivot block P where P <= B.
2. You have done a fast-sync, pivot block P where P > B.
3. You have done a full-sync, with pruning
4. You have done a full-sync, without pruning (--gcmode=archive)

  Here's what happens in each respective case:

1. Geth will regenerate the desired state by replaying blocks from the closest point in time before B where it has full state. This defaults to 128 blocks max, but you can specify more in the actual call ... "reexec":1000 .. } to the tracer.
2. Sorry, can't be done without replaying from genesis.
3. Same as 1)
4. Does not need to replay anything, can immediately load up the state and serve the request.

Questions:

If one needs to examine trace closer to genesis, should, or is it useful, to set "reexec": nnnn parameter accordingly as very high or can Geth replay equally well with the default of 128?
Does Geth store the information it has used during previous tracing calls?

The larger consideration behind this is that what options are there if I'd like to use Geth to sync, but instead of storing the full archive node state in a filesystem (local, or mounted) I could ingest the data, as queried to avoid parsing the actual block data, to some other storage and then keep updating this other storage using Geth as new blocks come available.

This could prompt an extra question:

Is it possible to collect all the trace data during Geth syncing and storing  as it goes such a way that it looks like (or can be constructed to look like) the RPC calls? I may have overlooked such an option.


texts: Link library to contract without migrations

texts:
To link library in migrations I use:

await deployer.deploy(MyTokenL)
await deployer.link(MyTokenL, MyToken)

We want to use migrations as infrastructure deployment and then have a deployment factory nodejs for tokens that use the infrastructure. I read that migrations are not ideal for this factory approach because migrations are not intended to deploy the same token multiple times.

So I have the deployed MyTokenL and want to link it to a new contract deployed without migrations via:

//how link existing library, there is no deployer available???
const newlyDeployedToken = await MyToken.new()


texts: Estimation of blocks time generation programmatically

texts: What is the correct way to estimate blocks time generation for chain with Web3?


texts: error: { code: -32000, message: 'invalid sender' }

texts:
I'm trying to deploy my Smart Contract onto the Rinkeby test network. Everything is working fine, my rinkeby account is also having enough ethers. And also using HDWalletProvider, I am able to access my rinkeby account as it's getting logged out on the terminal too but still I am getting this error don't know why
My abi and bytecode are also working fine as previously I deployed the same contract on my ganache local network. Only when deploying it on rinkeby, I'm facing this issue.
Also if I don't use try and catch, some really really huge chunk of characters keep printing on my terminal. I have no clue what's the real problem here.


texts: Where does the line blur between a task and a script in Hardhat?

texts:
This is a question about Hardhat, the task runner that facilitates building on Ethereum.
From Writing scripts with Hardhat:

You can write your custom scripts that can use all of Hardhat's functionality. A classic use case is writing a deployment script for your smart contracts.

From Creating a task:

A task is a JavaScript async function with some associated metadata. This metadata is used by Hardhat to automate some things for you. Arguments parsing, validation, and help messages are taken care of.

What is the difference between the two and when should go with one over another?


texts: Must token contract transfer all tokens to crowdsale contract before it can sell them?

texts:
I notice that on the standard tests for crowdsale contracts in Openzeppelin, they transfer the tokens from the Token contract to the Crowdsale Contract:

context('once deployed', async function () {
      beforeEach(async function () {
        this.tokensale = await TokenSale.new(rate, wallet, this.token.address);
        await this.token.transfer(this.tokensale.address, tokenSupply);
      });

However other examples do not do this. So I wonder why this is necessary, if internally the CrowdSale contract uses the token contract to send the tokens:

function _deliverTokens(
        address beneficiary,
        uint256 tokenAmount
    )
    internal
    {
        _token.safeTransfer(beneficiary, tokenAmount);
    }

In the function above _token is the IERC20 interface of the Token contract. Can some one explain this a bit better than this page?


texts: Geth mining stuck: Commit new mining work on Ubuntu instance

texts:
I have an Ubuntu instance running on aws ec2. I'm currently using Ubuntu server ec2 instance with the configuration as: 1 vCPU, 2.5 GHz, Intel Xeon Family, 1 GiB memory.
I'm running my Geth on this using command

geth --datadir ./Doc-Nodes --networkid 4780 --port 30306 --rpc --rpcapi "db,personal,eth,net,web3,debug,admin" --rpccorsdomain="*" --rpcaddr="0.0.0.0" --rpcport 8545 --allow-insecure-unlock console

The issue arises in the case of mining. Whenever I'm trying to mine the blocks on this instance using miner.start() ,  it gets stuck at for a long time.

  Commit new mining work

While the same is working when I'm running the Geth locally on my machine.

What's the issue behind this? Do I need to increase the Ubuntu configurations?

Thanks.


texts: Can I create a (for-profit) cooperative in Ethereum?

texts: I am interested in cooperatives in the physical world, and learning about DAO provides interesting possibilities for the Cooperative world. So far I have see no attempt to create a cooperative in Ethereum. I don't even know if its possible. But judging by descriptions of the DAO (and the fact that you can create a non-business democratic organisation), I imagine it might be possible to set up a cooperative in Ethereum. Is this the case?


texts: Can not verify contract on etherscan.io "Error! Unable to generate Contract ByteCode and ABI"

texts:
I'm trying to verify my deployed contract on etherscan.io

However I get the following error:

"rror! Unable to generate Contract ByteCode and ABI"

I'm not putting in an ABI because my constructor doesn't have any values or arguments.

What am I doing wrong?

Below is my contract code:

pragma solidity ^0.4.0;

// deploying contract on account 0x80A3bA6F52D63aFF73cA582343C2F67046DcEC6f
contract PayCheck {
    //List all the empolyees ethereum payment addresses in an array.
    address[] employees = [0x9391ea51c338410B6603e38dD14C00a1b218C8d5, 0x9391ea51c338410B6603e38dD14C00a1b218C8d5 ];

    //Set a variable that trackes the total recieved to the contract, starting with 0.
    uint totalReceived = 0;

    //Create a dictionary that tracks how much as been withdrawn to each ethereum address.
    mapping (address => uint) withdrawnAmounts;

    //This function updates the total amount that's been sent to the contract
    function PayCheck() payable {
        updateTotal();
    }
    function () payable {
        updateTotal();
    }
    // This is an internal function that updates the total amount that's been sent to the contract.
    function updateTotal() internal {
        totalReceived += msg.value;
    }

    //Here is a modifier that ensures only people in the empolyees list that execute the withdraw function.
    modifier canWidthdraw() {
        bool contains = false;

    //A simple for loop that check if they are in the empolyee list before it's aloud to execute the function this modifier is assigned to.
        for(uint i = 0; i < employees.length; i++) {
            if(employees[i] == msg.sender) {
                contains = true;
            }
        }
        require(contains);
        _;
    }

    // Function that calculates what the user can withdraw and to where.
    function withdraw() canWidthdraw {
        uint amountAllocated = totalReceived/employees.length;
        uint amountWithdrawn = withdrawnAmounts[msg.sender];
        uint amount = amountAllocated - amountWithdrawn;
        withdrawnAmounts[msg.sender] = amountWithdrawn + amount;
        if (amount > 0) {
            msg.sender.transfer(amount);
        }
    }

}


texts: "TxRejectedError" Using Ganache with Web3

texts:
I am having trouble sending my transaction Using Ganache. I am showing the logic that creates and sends the transaction and it says it cant be found or it is rejected don;t really know what the error message means. Couldn't find a fix about it might be a problem on Ganache side.
@app.route("/TransactionForm",methods=['GET','POST'])
@login_required
def Transaction():
    form = TransactionForms()
    if form.validate_on_submit():
        if User.query.filter_by(username=form.sendTo.data).first() is not None:
            user = User.query.filter_by(username=form.sendTo.data).first()
            emailTo = user.email
            usernameTo = user.username
            publicKeyTo = user.public_key
            passphrase = PassPhrase('english', user.password)
            trans = CreateTransaction(GLink,current_user.public_key, publicKeyTo,1,21000, 20)
            print(GLink.geth.personal.listAccounts())
            SendTransaction(GLink,trans)
            flash('Money Sent', 'success')
            return redirect(url_for('account'))
        elif User.query.filter_by(email=form.sendTo.data).first() is not None:
            user = User.query.filter_by(email=form.sendTo.data).first()
            emailTo = user.email
            usernameTo = user.username
            publicKeyTo = user.public_key
            passphrase = PassPhrase('english', user.password)
            trans = CreateTransaction(GLink,current_user.public_key,publicKeyTo,1, 21000, 20)
            print(GLink.geth.personal.listAccounts())
            SendTransaction(GLink,trans)
            flash('Money Sent', 'success')
            return redirect(url_for('account'))
        else:
             flash('Account Does Not Exist', 'danger')
    return render_template('TransactionForm.html', title='TransactionForm', form=form)

def CreateTransaction(web3, account, to, value, gas, gasprice):
    nonce = savedW.eth.getTransactionCount(account)
    transaction = {
        'nonce' : nonce,
        'to' : to,
        'value' : web3.toWei(value,'ether'),
        'gas' : gas,
        'gasPrice' : web3.toWei(gasprice,'gwei'),
        'ChainID' : str(5777)
        }
    return transaction

def CreateTransaction2(web3,toA, value):
    transaction = {
        'to' : toA,
        'value' : web3.toWei(value,'ether'),
        }
    return transaction

def SendTransaction(web3,transaction):
    web3.eth.sendTransaction(transaction)


texts: How to extract token transfer data from Transaction? (Web3j)

texts:
I'm new to ethereum and I would like to confirm a few things about Transaction.

I've transferred tokens and I would like to extract method, address transferred to and amount from Transaction(org.web3j.protocol.core.methods.response). I've extracted Transaction with web3j

{
  "hash": "0xfa9007eae34dfac8813a2f49d2514ceec881ebc5c33a8e7ad3dd229861e32e52",
  "nonce": 1449,
  "blockHash": "0xb2376edfeea3800afc7678ea00e761e3766ae0d9cefc17adbf7148bce3f4e459",
  "blockNumber": 1734050,
  "transactionIndex": 0,
  "from": "0x0124ceea90258dc124b698f3c88fee8eec0c3d10",
  "to": "0xecbe04bbe35b70c91ba62ec229de49eea97e4a0d",
  "value": 0,
  "gasPrice": 100000000000,
  "gas": 6000000,
  "input": "0x40c10f19000000000000000000000000a4d0fb50a216d005d0510743686bfca140856f4500000000000000000000000000000000000000000000003635c9adc5dea00000",
  "creates": null,
  "publicKey": null,
  "raw": null,
  "r": "0xe03ac6d55cd81f8ba0d0575a9455db86169e0b6d6dbbc255058dd67441913ff1",
  "s": "0x24a2f26c05f80f1b0ba97eddc2f4c82424155db5f5659db834353cc8d0170581",
  "v": 44,
  "gasRaw": "0x5b8d80",
  "nonceRaw": "0x5a9",
  "valueRaw": "0x0",
  "gasPriceRaw": "0x174876e800",
  "blockNumberRaw": "0x1a75a2",
  "transactionIndexRaw": "0x0"
}

It looks like all the necessary data is in field input(methodId, to, amount). Check input data in transaction

So I would like to confirm following things:

1) Is Checking methodId 0x40c10f19 enough to confirm that method mint was called?

2) Is there a good way to parse input field (like library e.t.c), it doesn't really looks great to parse it manually.

3) Is there some official description that describes what input field generally contains? (I found nothing here)

4) Could the format of input field change for the same contract's successful transaction? By this I mean if I parse input field myself could there be any problems with in like order of fields have changed or a new parameter would be added to field thus leading my parameter to work in improper way?

Thanks,


texts:
We already know that ERC-1155 is a combination of ERC-20 and ERC-721. Now, a new standard has arrived called EthItem saying that it is the combination of ERC-20, ERC-721, ERC-1155. So what is the difference between ERC-1155 and EthItem?
As far as I have analyzed, I guess that "ERC-1155 allows us to mint both ERC-20 and ERC-721 in a single contract, whereas EthItem allows us to convert Native items to Wrapped items and vice versa. Say for eg. a non-fungible ERC-721 or ERC-1155 token can be wrapped into fungible ERC-20 token". But is this correct? Can somebody please explain more clearly about EthItem? And what are those native and wrapped item?


texts: Verifying Bicoin signed message in Ethereum smart contract

texts:
I'd like to explore the option to verify the messages that have been signed in Bitcoin wallets in Ethereum smart contracts.

Ethereum smart contract is given a list of Bitcoin addresses
Ethereum smart contract can verify if the incoming function call msg, v, r, s matches any of previously given Bitcoin addresses

Now, the question is that the built-in ecrecover() only gives a resulting Ethereum address and I do not know how could I proceed from here.

Can built-in ecrecover() deal with Bitcoin addresses
Does there exist a way to mapBitcoin address to Ethereum address 1:1
Can built-in ecrecover() give full public key output?
If built-in ecrecover() does not work, can I write my own recover that outputs a Bitcoin address and spends reasonable gas?
Can I somehow preprocess Bitcoin addresses (or public keys) to Ethereum ecrecover() compatible format?

... which all kind of are related to one question

Do I need full Bitcoin public key as a starting point or is Bitcoin address enough?


texts: Compiling solidity code with geth+testrpc - Error: Invalid JSON RPC response

texts:
I'm attempting to compile the following contract using geth console attached to a testrpc instance:

contract UnitCounter {
    mapping (address => uint256) public UnitsFrom;
    uint256 public TotalUnits;

    function submitUnits(uint256 Units) {
        UnitsFrom[msg.sender] = Units;
        TotalUnits += Units;
    }
}

After running testrpc and connecting:

testrpc -a 1000

I attached a geth cosole

geth attach rpc:http://localhost:8545

and did the following:

> eth.getCompilers()
["solidity"]
> co=eth.compile.solidity("contract UnitCounter {mapping (address => uint256) public UnitsFrom;uint256 public TotalUnits;function SubmitUnits(uint256 Units) {UnitsFrom[msg.sender] = Units;TotalUnits += Units;}}")

Which gives this error:

Error: Invalid JSON RPC response: {"error":{"code":-32603,"json: cannot unmarshal array into Go value of type string":"json: cannot unmarshal array into Go value of type string"},"id":11,"version":"2.0"}
    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at <anonymous>:1:4

What does this error mean?
What steps should I take to debug?


texts: Puzzle- how to implement simple savings pool (via cDai) without iterating over unbounded loops?

texts:
Consider this example of a very simple savings contract, where users send Dai, which the contract converts to cDai. At any time users are free to withdraw their share of the accrued interest. I cannot figure out how to do this without iterating over an unbounded loop.

Consider:

User A sends 100 Dai to the contract, which converts the Dai to cDai. One week later, user B sends 100 Dai to the contract, which again is converted to cDai. Another week passes, and user A wishes to withdraw his accrued interest.

Assume current value of the cDai is 203 Dai. 200 Dai principal, 3 Dai interest.

User A has locked up his Dai for twice as long (two weeks) as user B (one week), therefore he is owed twice as much interest- i.e. of the 3 Dai interest he should get 2.

Interest allocated to user A is calculated this way:

Total interest (3) * number of weeks user A has held it (2) / number of weeks all users have held it (3)

Here's my question. How to do the above, without iterating over an unbounded loop, which is extremely bad practice in ethereum? How do you figure out that total number of weeks all users have held it is 3, without looping over every individual user, and taking the difference between deposit time and current time?

Is there some other way to arrive at the answer of user A is owed 2 Dai interest?


texts: How to setup testing environment for smart contract in solidity

texts:
I am following https://truffleframework.com/docs/getting_started/solidity-tests to set up a test in solidity for smart contract. Here is my test.sol

pragma solidity ^0.4.17;

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

const Auction_sol = artifacts.require("./Auction.sol");

contract TestAuction {

}

But I am constantly have the error below about missing artifacts:

Error: Could not find artifacts for ./test.sol from any sources
    at Resolver.require (C:\Users\AppData\Roaming\npm\node_modules\truffle\build\webpack:\.-resolver\index.js:37:1)
    at TestResolver.require (C:\Users\AppData\Roaming\npm\node_modules\truffle\build\webpack:\.-core\lib\testing\testresolver.js:17:1)
    at C:\Users\AppData\Roaming\npm\node_modules\truffle\build\webpack:\.-core\lib\test.js:109:1
    at Array.map (<anonymous>)
    at C:\Users\AppData\Roaming\npm\node_modules\truffle\build\webpack:\.-core\lib\test.js:107:1

What I am missing here? It seems to be simple task but somehow the online post did not work for me.

Here is the 2_deploy_contracts.js

var Auction = artifacts.require("Auction");
const Auction_sol = artifacts.require('Auction.sol');  //this line seems no use

module.exports = function(deployer) {
  deployer.deploy(Auction);
},

Here is the portion of smart contract:

pragma solidity ^0.4.17;
contract Auction {

    // Data
    //Structure to hold details of the item
    struct Item {
        uint itemId; // id of the item
        uint[] itemTokens;  //tokens bid in favor of the item

    }

   //Structure to hold the details of a persons
    struct Person {
        uint remainingTokens; // tokens remaining with bidder
        uint personId; // it serves as tokenId as well
        address addr;//address of the bidder
    }

    mapping(address => Person) tokenDetails; //address to person
    Person [4] bidders;//Array containing 4 person objects

    Item [3] public items;//Array containing 3 item objects
    address[3] public winners;//Array for address of winners
    address public beneficiary;//owner of the smart contract

    uint bidderCount=0;//counter

    //functions

    function Auction() public payable{    //constructor
  ......................


texts: Difference between account, wallet and deployed addresses: Remix IDE & Code

texts:
When I am executing the program on the remix IDE (got from internet), it asks me the address, _wallet, which I am passing in the constructor. Remix IDE shows me 3 addresses: Account, Deploy _wallet and Deployed Contracts. In the code, I am using the only the wallet address retrieved from wallet. What the statement

wallet.transfer(msg.value)

would do? Will it transfer Ether to the Account address. What is the difference between the 3 address and their usage.

pragma solidity 0.5.4;
  contract MyContractEtherEvents {
    mapping(address => uint256) public balances;
    address payable wallet;
    event Purchase(
        address indexed _buyer,
        uint256 _amount
    );

    constructor(address payable _wallet) public {
        wallet = _wallet;
    }

    function() external payable {
        buyToken();
    }

    function buyToken() public payable {
        balances[msg.sender] += 1;
        wallet.transfer(msg.value);
        emit Purchase(msg.sender, 1);
    }
}

Somebody please guide me.

Zulfi.


texts: How to add Uniswap liquidity fees for each transaction?

texts:
I know how to implement a tax/fee on each transaction.
What I'd like to know is where to send the tokens? Is the liquidity pool simply an address I can redirect the taxes to? Do I have to use some Uniswap library?
Thanks!


texts:
Inside Remix I'm using one address (addr1) to deploy the contract, and another (addr2) to call a function within the contract. The function is a simple transfer function. I'm transferring 1000000000000000000 Wei (1 ether) from addr2 to addr1. However it's unable to transfer and my output keeps returning false. What is wrong here?

Also I'm using SafeMath library for the sub, it's the same thing as subtract.

function transferToOwner() payable returns (bool) {
    owner.transfer(msg.value.sub(1000000000000000000));
    return true;
}


texts: Create New Contract from within another contract of the same type in Solidity

texts:
How can I create multiple contracts of Contract X using the new key word. I am getting an error that says cannot create instance of the same contract type. Is there a way around it ...

I would like to create a chain of contracts of the same type that point to each other.


texts: Solved: How to change Solidity linter [solc] compiler version in Visual Studio Code?

texts:
Hi may I know how to change my Solidity linter compiler version in Visual Studio Code(vscode)? OR Visual studio code how to specify solidity compiler version?

The only Solidity related extensions I have installed are solidity 0.0.38 by Juan Blanco, and Solidity Extended 3.0.2 by beaugunderson.

I have applied the User Settings in VS Code as the following but still get error:

{"files.autoSave": "afterDelay",
  "files.autoSaveDelay": 1000,
  "editor.minimap.enabled": false,
  "editor.tabSize": 2,
  "editor.detectIndentation": false,
  "editor.wordWrap": "on",
  "files.associations": {
    "*.sol": "solidity"
  },
  "workbench.iconTheme": "material-icon-theme",
  "material-icon-theme.showUpdateMessage": false,

  "solidity.compileUsingRemoteVersion" : "latest",
  "solidity.linter":"solium",
  "solidity.packageDefaultDependenciesContractsDirectory": "contracts",
  "solidity.packageDefaultDependenciesDirectory": "node_modules",
  "solidity.soliumRules": {
    "imports-on-top": 0,
    "variable-declarations": 0,
    "no-inline-assembly": 5,
    "indentation": ["error",2],
    "quotes": ["error","double"]
  },
  "solidity.validationDelay": 1000,

  if in Windows system:
  "terminal.integrated.shell.windows":"C:\\WINDOWS\\System32\\cmd.exe",
  "window.zoomLevel":1

Now I've also install Solidity globally in my Linux: $ sudo npm install -g solc
Then I've got this from the terminal:
/home/userXYZ/.npm-global/bin/solcjs -> /home/userXYZ/.npm-global/lib/node_modules/solc/solcjs
+ solc@0.4.22

Then changed User Setting: "solidity.compileUsingRemoteVersion" : "latest"

Then re-started VS Code, still I am getting this error...
Please help. Thank you


texts: Calling payable function inside the function

texts:
function trxToTokenOutput(uint256 tokens_bought, uint256 max_trx, uint256 deadline, address payable buyer, address recipient) private nonReentrant returns (uint256) {
    require(deadline >= block.timestamp && tokens_bought > 0 && max_trx > 0);
    uint256 token_reserve = token.balanceOf(address(this));
    uint256 trx_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_trx), token_reserve);
    // Throws if trx_sold > max_trx
    uint256 trx_refund = max_trx.sub(trx_sold);
    if (trx_refund > 0) {
      buyer.transfer(trx_refund);
    }
    require(address(token).safeTransfer(recipient,tokens_bought));
    emit TokenPurchase(buyer, trx_sold, tokens_bought);
    emit Snapshot(buyer,address(this).balance,token.balanceOf(address(this)));
    return trx_sold;
  }

function trxToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) public payable returns(uint256) {
    return trxToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender);
  }

function _sellTrxForFixedToken(uint _tokens_bought, uint _deadline) private returns (uint) {
        return exchangeToken.trxToTokenSwapOutput(_tokens_bought, _deadline);
    }

Here, the trxToTokenSwapOutput() function is payable, so the msg.value parameter is not included in function signature.
I was wondering if I need to to make some explicit actions with msg.value (with making the higher order function payable of course) or the code will do it for itself.
Thanks.


texts: Truffle - Transfer leads to "Error: VM Exception while processing transaction: revert"

texts:
For reference, I am using Solidity to develop a smart contract for my company. I created a smart contract and attempted to use Truffle and Ganache to unit test it. However, I'm having a bit of an issue with my smart contract returning Error: VM Exception while processing transaction: revert when I try to unit test it with Truffle. After testing my code a lot, I have managed to cut down the smart contract to the following code, which still produces the error.

pragma solidity ^0.4.22;

contract Purchase {

 address public buyer;
 address public seller;
 address public companyEscrow;
 uint private moneyInEscrow = 0;

 modifier onlyCompanyEscrow {
    require(
        msg.sender == companyEscrow,
        "Only the escrow account of the company can call this function."
    );
    _;
 }

 modifier onlyBuyer {
    require(
        msg.sender == buyer,
        "Only the buyer can call this function."
    );
    _;
 }

 constructor (address addressSeller, address addressCompanyEscrow) public payable {
    buyer = msg.sender;
    seller = addressSeller;
    companyEscrow = addressCompanyEscrow;
 }

 function sendFundsToCompany ()
      public
      payable
      onlyBuyer
      returns (bool completed)
  {
      moneyInEscrow = msg.value;
      companyEscrow.transfer(moneyInEscrow);
      return true;
  }

  function sendFundsToSeller ()
      public
      payable
      onlyCompanyEscrow
      returns (bool completed)
  {
      seller.transfer(moneyInEscrow);
      moneyInEscrow = 0;
      return true;
  }
}

The function sendFundsToCompany() is supposed to be executed first and then afterwards, the function sendFundsToSeller() is supposed to be executed. I cut down my unit testing to the following Truffle unit test, which still produces the error:

var Web3Beta = require('web3')
var web3beta = new Web3Beta()
var Purchase = artifacts.require('Purchase')

contract('Purchase', function ([buyer, seller, companyEscrow] {

  var purchase = await Purchase.new(seller, companyEscrow)

  it('Should send funds to seller', async function () {
    var sellerInitialBalance = web3.eth.getBalance(seller).toNumber()
    var companyEscrowInitialBalance = web3.eth.getBalance(companyEscrow).toNumber()

    await purchase.sendFundsToCompany({ value: web3beta.utils.toWei('3', 'ether'), gas: "6600000" })
    await purchase.sendFundsToSeller({ from: companyEscrow, gas: "6600000" })

    assert.isAbove(web3.eth.getBalance(seller).toNumber(), sellerInitialBalance)
    assert.isBelow(web3.eth.getBalance(companyEscrow).toNumber(), companyEscrowInitialBalance)
  })
})

I have combed through the Ethereum StackExchange, the Truffle help boards, and the Solidity documentation. However, the bug still eludes me. After looking through similar questions on the Ethereum StackExchange, I performed the following actions:

I made sure both functions have the 'payable' modifier.
I explicitly sent the functions a large gas limit.
I deleted the /builds folder and recompiled everything.
I ended the current deployment and started a new instance with 'truffle develop'.

Unfortunately, doing these things didn't resolve my problem. I'm at a bit of a loss as to what the problem is. I'm new to Solidity so it's probably something basic; however, I can't seem to figure out what it is.

For reference, my version of Truffle is 4.1.13 and my version of Ganache is 6.1.6 (ganache-core = 2.1.5). Also, I'm running 'truffle develop' and performing my unit tests in two separate command prompts - I run 'truffle develop' in one prompt and only after do I perform the unit tests in the other command prompt.

I would greatly appreciate any help or guidance you can provide me. Thank you in advance!


texts: zero-initialisation of storage values in constructor or gas optimization

texts: is it better to pay extra gas to initialise storage variables that are empty as zeroes in the constructor, or save the gas since the default is zero?


texts: Uniswap Router V2 Deployment AddLiquidity()

texts:
I'm getting an error on the addLiquidity() method of Uniswap's Router (UniswapV2Router02.sol) using my own deployed version of the contract on a testnet. I'm using Remix, and am receiving the message: "Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Internal JSON-RPC error. { "code": -32000, "message": "execution reverted" }"
For testing purposes, I've created two ERC20 tokens, let's call them TOK1, TOK2.
I minted myself 100 of TOK1 and 100 of TOK2
I called the approve function on both TOK1 and TOK2 contract with my wallet address
I compiled + deployed the Uniswap Factory (UniswapV2Factory) as well as the UniswapV2Router02
I set up the Router (init() method) by providing the Factory address that I deployed (above), and the address of TOK1 (also above).
I then try to call the addLiquidity(..) method with the following parameters:
tokenA = TOK1 address
tokenB = TOK2 address
amountADesired = 1 (in wei => 1000000000000000000)
amountBDesired = 1 (in wei => 1000000000000000000)
amountAMin = 0.1 (in wei => 100000000000000000)
amountBMin = 0.1 (in wei => 100000000000000000)
to: my wallet address
deadline: unix timestamp + 20 minutes

This results in the above gas estimation error message from Remix. I've tried changing the Gas limits as well as the Value field in the Deploy & Run Transactions window of Remix. Neither seems to have any effect.
Is there something that needs to be done first?


texts: Which type of Projects/Apps are suitable/best to be developed in blockchain/dapp technology?

texts: Which kind of Apps are best to be developed on the base of blockchain/dapp/web3 technology. Suggest me please as I am looking for an advice for an academic final year project.


texts: The sendSignedTransaction function does not activate the on('receipt') event at an appropriate time

texts:
console.log(transacting...);
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', receipt => {
    log(receipt);
    log(`https://ropsten.etherscan.io/tx/${receipt.transactionHash}`.cyan);
    console.log("transaction done");
    return receipt.transactionHash;
});

I am using "web3": "^1.0.0-beta.35". The provider (INFURA) is so configured:

const ropsten = `wss://ropsten.infura.io/ws/v3${process.env.INFURA_ACCESS_TOKEN}`;
const web3 = new Web3(new Web3.providers.WebsocketProvider(ropsten));

The transaction works. I can see on Ropsten Etherscan that actually is performed and accepted.

The problem is that the on('receipt') event is not captured in time. Indeed, to be more precise, only a couple of times (without ever changing the code) worked. Once even after 12 minutes the on has "woken up" and the code continued without problems.

Note that the transaction took no more than 12 minutes to register on blockchain. From the moment the transaction starts, in about a minute I can see it completely executed on Etherscan, but in my NodeJS application the on event comes after 12 minutes of delay or even a lot more and it's not good. What can I do?


texts: Metamask RPC error -32603... {"error":"revert","program_counter":6758,"return":"0x"}

texts:
I have a dApp that leverages ERC721 contract which allows users to upload images onto IPFS and transfer them to each other.
User A can upload images fine and transfer them fine to User B. Once transferred User A can still upload new images -perfect! However, when User B then logins onto Metamask and try's to upload sketch's(string value of hash) I am hit with the error message below.
MetaMask - RPC Error: Error: [ethjs-query] while formatting outputs from RPC '{"value":{"code":-32603,"data":{"message":"VM Exception while processing transaction: revert","code":-32000,"data":{"0x33acf11f7fb6df195a58a8cd8e21a0f837f2710540f19122548f625ba5a5aef6":{"error":"revert","program_counter":6758,"return":"0x"},"stack":"c: VM Exception while processing transaction: revert\n    at Function.c.fromResults (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:4:194812)\n    at w.processBlock (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:42:53376)\n    at process._tickCallback (internal/process/next_tick.js:68:7)","name":"c"}}}}'
I have a truffle test which passes when a user uploads, transfers and then uploads again. Do I need a truffle test for a different account accessing and uploading sketch's to expose this problem? If so how do you change the accounts address accessing the contract in truffle test environment?
I begin the truffle test.js and expose the contract as follows:
const Sketch = artifacts.require('./Sketch.sol')

require('chai')
  .use(require('chai-as-promised'))
  .should()

contract('Sketch', (accounts) => {
    let contract

    before(async () => {
        contract = await Sketch.deployed()
    })

    describe('deployment', async () => {
        it('deploys successfully', async () => {
            const address = contract.address
            assert.notEqual(address, 0x0)
            assert.notEqual(address, '')
            assert.notEqual(address, null)
            assert.notEqual(address, undefined)
        })

Any help would be great


texts:
When I was trying to send multiple transactions, I received an error saying that "replacement transaction underpriced".

Searched around and it says that I was trying to replace an existing transaction, so I need to pay a higher price. But that was not my intention.

Searched further and it says that I need to increase the nonce or use a different nounce.

The question now is, can I use a random number? (just assume this random number will not repeat in the next one day)


texts: Ol' Timer Needs Help (Wallet Advice Please)

texts:
I recently returned to crypto and know very little of the hard fork and what it all means. I have a wallet that has not been opened in almost 6 months. It contains 7-800 ethers. I want to install a new windows based wallet on another machine. What is the best and safest method to achieve this.

Also, I read something about an Eth classic? what is this about? Do I receive those as well?

Thanks in advance and any help is greatly appreciated!

Scrap'


texts: I got funded from the rinkeby faucet but it didn't show up in my wallet. Does anyone have an idea why the sync with the rinkeby blockchain stopped with just 218 remaining?


texts: Multiplication and iteration in solidity

texts:
Iteration uses a lot of gas. I was thinking at different options I could minimise the costs. I must understand why one thing doesn't work:
Why can't I push into an array using multiplication rather than loops?

For example, this code works:

address[] contenders

for (int i; i<5;i++)
        contenders.push(msg.sender);

This code doesn't:

address[] contenders
uint numberToMultiply  /// let's say this variable is 5

contenders.push(msg.sender) * numberToMultiply

Basically in the last example I am expecting to push msg.sender in the array by the number of times stored in the variable.

Would it not be gas efficient? Furthermore, it doesn't work. Does anyone know the reason?


texts: How to access events via nodejs that were created in solidity

texts:
Following is my contract:

pragma solidity ^0.4.4;
contract Process{
address public owner;
uint balance;
uint amount;

function Process(){
    owner = msg.sender;
    balance = 1000;
}

 event DepositMade(string msg);
 event WithdrawalMade(string msg);

 function deposit(uint amot){
    balance = balance + amot;
    DepositMade("Deposit is done");
}

function getBalance()constant returns (uint){
    return balance;
}

function withdraw(uint amot)returns (bool){
    if(amot > balance){
        return false;
    }
    else{
        balance = balance - amot;
        WithdrawalMade("Withdrawal is done");
        return true;
    }
}

}

Now i am able to run this code using command prompt using its compiled code. When i deposit or withdraw amount, i only receive transaction hash, even though i have created events. I don't know the syntax of nodejs and web3js. I tried , but failed.How should i retrieve events using nodejs for above code?


texts: VM Exception: Contract from within a contract

texts:
I am following this example to experiment with contract from within a contract (using testrpc).

contract Product {
    bytes32 public Name;

    function Product (bytes32 _Name) {
        Name = _Name;
    }
}

contract ProductFactory {

    bytes32[] public productNames;
    address[] public productAddresses;

    function addProduct (bytes32 _productName) {
        address newProduct = new Product(_productName);
        productAddresses.push(newProduct);
    }

    function getName (uint i) {
    Product prod = Product(productAddresses[i]);

    productNames[i] = prod.Name();
  }
}

My filename is Product.sol and the deloy file in truffle is:

var Product = artifacts.require("./Product.sol");
var ProductFactory = artifacts.require('ProductFactory');

module.exports = function(deployer) {
  // deployer.deploy(supplyChain);
  deployer.deploy(Product);
  deployer.deploy(ProductFactory);
};

On deploy, ProductFactory and Product both work well, as demonstrated by creating a new product with addProduct. However, on doing a getName, error: VM Exception is returned.

truffle(development)> ProductFactory.deployed().then(function(instance){PF=ProductFactory.at(instance.address)})

truffle(development)> PF.addProduct('abcd')
{ tx: '0xe304f9194fb9b06ae5f0a3664f64255e74d88de099cce0cd38092030b5d48d7f',
  receipt:
   { transactionHash: '0xe304f9194fb9b06ae5f0a3664f64255e74d88de099cce0cd38092030b5d48d7f',
     transactionIndex: 0,
     blockHash: '0x09d3e5547b1d4cd9ef40d05b5b15561a45b9f62f55410d03c175886dd1c591eb',
     blockNumber: 122,
     gasUsed: 122275,
     cumulativeGasUsed: 122275,
     contractAddress: null,
     logs: [] },
  logs: [] }

truffle(development)> PF.getName(0)
Error: VM Exception while processing transaction: invalid opcode
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:37047:16)
...

EDIT1:
When I am trying the following,

truffle(development)> PF.productAddresses(0)
'0x4b01bd4691c306c59e8985bb6bd5bcc88abf1e81'
truffle(development)> Product.at('0x4b01bd4691c306c59e8985bb6bd5bcc88abf1e81').Name()
'0x6162686900000000000000000000000000000000000000000000000000000000'

understandably it works. PF.productAddresses(0) is an object as I gathered, and when I am using Product.at(PF.productAddresses(0)) it fails the same way as getName. However, on directly using the address string as just shown, it works. How to manage this issue?

EDIT1 over:

I am a newbie. If someone could let me know what might I am doing wrong. I think it is to do with async call, but I am not sure. I have tried multiple variations and on Remix as well, but it simply doesn't work.


texts:
When Ethereum changes to a PoW/PoS hybrid (Casper FFG), how will the staking process work? I heard that there might be smart-contracts and you need to send your coins to the contract to stake the coins but how will the contract be official? That's what I heard.

The question is: how will I be able to stake my coins when the change to hybrid scheme comes?

Casper FFG


texts:
I am using bootnode as a starting/meeting point for my private POA/clique network. When I start it since one of the latest versions it says:

fmt.Println("Note: you're using cmd/bootnode, a developer tool.")
fmt.Println("We recommend using a regular node as bootstrap node for production deployments.")

How can I prevent using a bootnode process and use a "boostrap node". I cannot find any details about that in the docs


texts:
It´s recommended to use the truffle framework for production?? Or just to develop purpose??

I mean can I connect my truffle to my private blockchain and execute the compile/migrate commands without hesitation. Or it´s better to do this without truffle??


texts: If the supply of Ether is finite, are there any mechanisms to deter hoarding?

texts:
The supply of bitcoin is capped at 21 million. The supply of Ether is similarly capped at ~90 million.

If we are to assume that Ethereum will become more popular as time progresses, and if we also assume - for the sake of argument - that the value of Ether will therefore also rise as demand increases, we might therefore think it likely that people mining in these early days might stockpile any Ether they mine to sell at a later date.

Regardless of whether this is happening (or will happen) or not, is there anything built into how Ethereum works to prevent such stockpiling from occurring?


texts: Details of transactions of ERC20 tokens with special fees

texts:
Some ERC20 tokens have special rules that affect transactions like:

burning certain % of every transaction,
taxing some % of every transaction and redistributing it back to all token holders or moving it to Uniswap pool.

However, if I use etherscan, these consequences of transactions are not shown.
For example, if a token has a special 10% burn rule in the contract and I use unisawp to exchange 100 tokens, etherscan will only show that 90 tokens have been moved to another account, but it will not show the details of what happened with those 10 remaining tokens. There is no record of that part of the transaction anywhere that I can find.
Also, if part of that special tax is redistributed to account holders, then those tokens will just appear in my account without record of how much and when.
Is there any way how one could get details of such transactions (like timestamps and amounts)?
In short, I would like to see the full transaction history that shows all tokens coming in my account and leaving it and if etherscan can't show me that, what do I need to do to get it?


texts: How does crowdsale contract with lots of tiers work?

texts: Hello :) I'm really interested in knowing how crowdsale contracts with tiers are made. ICOs these days have crowdsale for different tiers with different prices for each.. Like PreICO, Round 1, round 2, round 3 etc. I'm curious to know how that is achieved. Do they create and compile different crowdsale contracts for each tier or is there another way it's being done?


texts:
I read somewhere that the 'state' is only updated at the end of each block. I've also read that each block contains a specific sequence of transactions, and thus implicitly 'updates' the state within a block. This might be semantics, but I just want to be certain about how state variables are updated: will a transaction that alters the state do so before the next transaction, regardless of whether it is in the same block?
To be clear: assume a contract variable Book is 10 ETH, so that users can take bets against this 10 ETH. Each time a transaction bets an amount X, Book is decreased by X: Book = Book - X. Bets are restricted so that Book>=0 at all times: require(Book - X >= 0) at the top of the betting function.  If Bob bets 6 ETH, and Alice bets 6 ETH, this would obviously be counter to my requirement. However, if their transactions are in the same block, would the second transaction be rejected?


texts:
I am new to ethereum and deploying my first contract with simple method getting following error:

[2018-03-24 11:08:14.364] [ERROR] ipcProviderBackend - Send request failed { code: -32602,
  message: 'invalid argument 0: json: cannot unmarshal non-string into Go value of type common.Hash' }

Following is the contract method in solidity that i am calling:

function testContract(string title,string _description,
                           address _contractAddressOfAsset,
                           string _recordIdOfAsset,
                           uint _deadline,
                           uint _startingPrice,
                           uint _reservePrice,
                           uint _distributionCut,
                           address _distributionCutAddress) public returns (bool k) {

        test=title;
        return true;
    }

Here ,
test is the global variable of type string.

Note: I have deployed this contract in the private network and  this contract from the mist browser

Following are the version details of geth:

Geth
Version: 1.7.3-stable
Git Commit: 4bb3c89d44e372e6a9ab85a8be0c9345265c763a
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.9
Operating System: linux
GOPATH=
GOROOT=/usr/lib/go-1.9


texts: Truffle.js file is not created with truffle init command

texts: I have run the truffle init command successfully with creating the following directories and files such as contracts, migrations, test, and truffle-config.js but the one file is missing as truffle.js? Any solution


texts:
whether metamask can be used on cell phone browser? any plugin for cell phone? thanks
I try to use a wallet to send eth easily, but metamask can only work for desktop etc. for mobile, any metamask solution?


texts: How is the Ethereum Name Service Avatar records used?

texts:
What is the use or how is the avatar field in the ENS TEXT RECORD used?.
I am assuming that when the ENS address represents  a Token's contract address, the Image avatar pops up with token when it is searched for in exchanges or maybe added to wallets by first searching for the token using the ENS address like in the example below:

Is this assumption correct?


texts: My transaction has been pending for over 8h now

texts:
Wondering if someone could help me, I sent funds using mew and the first fund I sent, maybe I didn't put enough gas, now it's stuck in a limbo with two other payments that I made after first payment.

If you look at etherscan.io, you can see one transaction pending, but if you refresh the page, it will show another transaction pending... Changing the information every 5-10sec... If you look at the etherscan.io page, you will understand what I mean...

etherscan.io/address/0xdd1d9448fa077137488cf909c421a7f394991df9

Are my coins and account lost forever? Can someone help me pls?

Thank you...


texts: Automatically extracting functions names and parameters from ABI JSON file

texts:
I have done some work on captioned subject. For example, I can extract all getter functions (and some constructors as well) of all given smart contracts (in abi json file format). Then i can call (extracted) function of respective contract one by one after deploying (that) contracts on ganache.  Now i am facing problem that how to extract setter functions (which take some inputs of 1, 2, 3 or more arguments) name alongwith their parameter's type/name. So that i could caller such setter function with some valid random values.

function abiExpr()
{
for(i=0; i<sources.length; i++){ // here sources has my contracts in json files

  if(!getterFunctionsObject[i])
    getterFunctionsObject[i] = [] // making array to store getter function of each contract... I think , its not a good way ... but it working...

  if(!constrObject[i])
    constrObject[i] = [] // making array to store constructor of each contract

  if(!setterFunctionsObject[i])
  setterFunctionsObject[i] = [] //making array to store setter function of each contract

  if(!settersParameters[i])
  settersParameters[i] = []
  if(!settersParameters[i][i])
  settersParameters[i][i] = [] // HERE I AM STUCK, and confused how to achiev..... want to make array to store every parameter of each setter for each contract ... *

  for (let item of sources[i].abi) {

    if (item.type === "constructor") /// its OK for some constructor
    {
      constrObject[i].push(item.inputs)

    }

    if (item.type === "function") // its OK 100 %
    {
      if((item.inputs).length ==0 && item.stateMutability==='view')
     getterFunctionsObject[i].push(item.name)
    }

    if (item.type === "function") /// its not working .. HOW to achieve ...
    {
      if((item.inputs).length>0)
          {

            for(t=0 ; t<(item.inputs).length; t++)
            {
              if ((item.inputs[t].name).length>0)
              {
                setterFunctionsObject[i].push(item.name)
                settersParameters[i][t].push(item.inputs[t].name)
              }
            }
          }
    }
}
}
}

In order to summarize, how to store each parameter of each setter function of each contract. Is there any ABI APIs for my above mentioned tasks? If possible, also need some better coding approach, as i think above code is not good practice.

NOTE: For setter function, I means which take some parameters , and getter function means which just return some output.


texts:
How can I change the following to php format? what means the -d @...jaon, it means the parameter for this curl is json and post to the url?
cat call.json
{
    "private": "3ca40...",
    "gas_limit": 20000
}

curl -d @call.json -s https://api.blockcypher.com/v1/eth/main/contracts/0eb688e79698d645df015cf2e9db5a6fe16357f1/greet?token=YOURTOKEN


texts: How does PancakeSwap Lotery work? What is the Contract flow..?

texts:
I'm trying to figure out how the Lottery works... What is the flow..? How are Contracts connected?
If I look at the Contract they listed ob BscScan (0x3C3f2049cc17C136a604bE23cF7E42745edf3b91) and check transaction history back to about the end of april and before that, transactions kinda make sense to me. You would send cake to the contract and recive tickets (I'm not sure on how exactly...). Example: https://bscscan.com/tx/0xea770f1f15855ac45dde2b06471f3ee3c2ebc585aea0d332fab994098fe0d0c7. At list that's how I think it worked. But than something changed...
My end goal was to see if there is a way to see who the winners were and how the Cake was distributed...
I'm a noob in this space, so any help would be much appreciated, ty :)


texts: How do i test "it" methods with truffle?

texts:
I have this contract:
contract('MetaCoin', (accounts) => {
  it('should put 10000 MetaCoin in the first account', async () => {
    const metaCoinInstance = await MetaCoin.deployed();
    const balance = await metaCoinInstance.getBalance.call(accounts[0]);
    assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
  });

  it("thing test", async () => {
    const thing = await Thing.deployed();
    const res = await thing.specialThing.call(2, { from: accounts[0] });
    assert.equal(res, 200, "10000 wasn't in the first account");

  });

I'd like to specifically test thing test -- how do I do that with truffle?


texts: Is it viable to use a smart contract for string based authentication?

texts:
I am aware that security on the network is done at the private key level, but would love to know the security implications of having an additional password/string and time-based level of security on a smart contract.

A simple implementation of that would be something like this:

pragma solidity ^0.4.21;

contract PasswordTimeLock {
    uint timelock;
    bytes32 hashlock;
    address owner;
    string data = "hello world";

    function PasswordTimeLock(string _password) public {
        owner = msg.sender;
        hashlock = keccak256(owner, _password);
    }

    function unlock(string _password) public returns (bool) {
        require(keccak256(owner, _password) == hashlock);
        timelock = now + 20 seconds;
        return true;
    }

    function read() public view returns (string) {
        require(now < timelock);
        return data;
    }
}

Is there any exposure to the actual string passed to the unlock function or the constructor?


texts: Difference between bytecode and runtime bytecode

texts: In Remix, clicking on "details" for a contract reveals the "bytecode" and "runtime bytecode". What is the difference?


texts: How can I automatically send token in exchange for Ether

texts:
I want to send tokens in exchange for Ether.
And I want to send tokens in terms of 1 JPY / 1 token.
So I have to get ETH/JPY rate on smartcontract.
I tried to use oraclize to get its rate.
But because frequency of query execution is high (per 15 secounds) and gas cost is also high, I abandoned to use it.

below is a part of my contract code.

function() payable {
  if(msg.value <= 0) { throw; }
  if(!addressManage.profitContainerAddress.send(msg.value * 10 / 100)) { throw; }
  if(!addressManage.honshaAddress.send(msg.value * 10 / 100)) { throw; }
  ReceiveEther(msg.sender, profitContainerAddress, msg.value, name);

  transferFromOwner(msg.sender, msg.value / 1 ether * getPrice());
}

Please give me some advise.
Thank you.


texts: Stress test DApps on rinkeby test network

texts:
Is there any way of stress testing a dapp?
I developed dapp, now I want to see how much stress it can handle?
I can't test it on Main Ethereum Network. At least I can do it on Rinkeby test Network. Also, will there be any difference in processing time in the case of Main ethereum network and Rinkeby test Network


texts: Get past events of a contract without ABI using Web3?

texts:
I'm building a simple explorer and I would like to list events emitted by contracts. Since I can't know the ABI of each contract, is it possible to get past events from a contract using Web3?
If I knew the ABI, I would do something like this:

var myContract = new web3.eth.Contract(ABI, address);

myContract.getPastEvents('allEvents', {
    filter: {...},
    fromBlock: 0,
    toBlock: 'latest'
}, (error, events) => { console.log(events); })
.then((events) => {
    console.log(events) // same results as the optional callback above
});

But of course I can't instantiate a contract without its interface. I wonder how explorers such as Etherscan do this.


texts: Block reward from transaction regarding block's gas limit

texts:
maybe it's a silly question or remark, but given that the current block gas limit is about 8,000,000 and the average gasPrice is about '15Gwei' ( I roughly looked at the chart "Transaction Count by Gas Price" chart on ethgasstation.info and calculated the average ), then the total amount of dollars a miner can earn from that block is about:

$60 = (15Gwei * 8,000,000(gas limit) * pricePerGweiInDolars(~$0.0..1)).

Or you can also use the gas-price-estimator on that same website, just put 8,000,000 as gas used and slide the slider to the very right, for 20Gwei.
For me it's incredibly low compared to the reward he gains from mining the block ( it's currently 3 ETH, right?).
I am posting it beacuse I am almost sure I misunderstood something. Can someone clarify, or is the transaction reward indeed so low ?
Thanks.


texts: Where is the length of an array located in terms of memory layout?

texts:
For example, given the following cases:

uint[3] memory arr;
uint[] memory arr = new uint[](3);

Suppose I try to access arr from within an assembly block (using mload, for example).

Where (relatively to arr) is the value of arr.length located, and where are the entries located?

Thank you!


texts: Difference between @constant and @view on a smartcontract function

texts:
I am reading some vyper projects on github.
I have seen 2 attributes on the line before the function name: @constant and @view
According to documentation, this 2 attributes are saying the function may not change the state of the blockchain.
But what is the differences between this 2 attributes ?
Thanks


texts:
It kind of suck if every time we want to test our smart contract, we need to wait until our testnet blockchain is synced up.

How do you usually keep it up-to-date?


texts: smart contract transactions not committing to blockchain through nodejs web3

texts:
when i call any functionality of smart contract it returns me what its suppose to but doesnt reflect anyy changes when i query it. Its like the transaction never took place itself although it gave the right result from smart contract.Im using test-rpc. Have tested contract in truffle. and solidity browser. This is the simplified version of code that I've made.

var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

console.log("Talking with a geth server", web3.version.api);

function test(){

var sourceCode = fs.readFileSync('contracts/digitalToken.sol','utf8')

var compiled = solc.compile(sourceCode);

console.log(compiled.contracts[":digitalToken"]);

var abiArray = compiled.contracts[":digitalToken"].interface;

abiArray = JSON.parse(abiArray);

var MyContract = web3.eth.contract(abiArray);

var address = "0x1f81b5fa31d049b70556628cc01f22d362c41084";

var contractInstance = MyContract.at(address);

console.log(contractInstance);

var value=executeAddvid(contractInstance)

  console.log({message: "Success",value:value});

  console.log('after passing--');

  console.log({message: "Success",value:value});
var value1=readVidByUser(contractInstance);

console.log({message: "Success",value:value1});

  console.log('after passing--');

  console.log({message: "Success",value:value1});
}

function executeAddvid(contractInstance){

record = contractInstance;

return record.addVid.call('0x0000000000000000000000000000000000000124',5,"ronaldo","0xc9f5a0572d95d5dea1331edcc192dacef51ecbb7",1000000000000000000);

}

function readVidByUser(contractInstance){

record = contractInstance;

return record.readVidByUser.call('0x0000000000000000000000000000000000000124','0x1f81b5fa31d049b70556628cc01f22d362c41084');

}

test();


texts: Is it possible to emit event in view function (via event or logi)? Or is it possible to return value to javascript without(before) mining in a transaction function? My aim is to avoid wait due to mining with event logging.


texts:
Gas refunds are provided when clearing storage or calling SELFDESTRUCT on contracts.
The Yellow Paper mentions that refunds are "being capped up to a maximum of half...".  What exactly is this "half" and the other components that sum up to a refund?  Preferred answer will explain with a specific example (since the Yellow Paper has the definitions).
What are the limits? What attacks would have been possible if refunds were not limited?


texts: Is it possible to test for reentrancy within remix IDE? if so, could someone provide an example of how-to.


texts: How to import a smart contract on github in a truffle contract?

texts:
I am using a smart contract that imports and uses the Oraclize contract at https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol, if in the remix editor this can be done as follows:

import "http://github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";

However if I do this with a contract I want to compile with Truffle there is this error:

  Could not find
  http://github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol from any
  sources;

I have tried simply copying and pasting the entire Oraclize contract into my Truffle contract file, but this results in an "The contract code couldn't be stored, please check your gas amount" error regardless of how much gas I use (even the absolute maximum) - my guess is because the Oraclize contract is over 1000 lines of code long.

How should this be done?


texts: Documenting Smart Contracts and Dapps - community standards and tools

texts: Do you guys know of any kind of documentation standards that are widely used within the Ethereum community? Any kind of documentation tools will also be of great help. Thanks in advance.


texts: Enum Error while following along a tutorial

texts:
I was going through the tutorial from DappUniversity on Youtube when I stumbled across with my enum
pragma solidity ^0.6.0;

contract HotelRoom {
  address payable public owner; /*state variable, the payment is sent to this address*/

  enum Statuses { Vacant, Occupied };
  Statuses currentStatus;

  event Occupy(address _occupant, uint _value);

  constructor() public {
      owner = msg.sender; /*this is the address of the user who calls this function*/
       currentStatus = Statuses.Vacant;
  }

    modifier onlyWhileVacant {
        require(currentStatus == Statuses.Vacant, "Currently occupied.");
        _;
    }

    modifier costs (uint _amount) {
        require(msg.value >= _amount, "Not enough Ether provided.")
    }

    receive() external payable onlyWhileVacant costs(2 ether) {

        currentStatus = Statuses.Occupied;
        owner.transfer(msg.value);
      emit Occupy(msg.sender, msg.value);
    }

}

and the error yields this
browser/mycontract14.sol:6:37: ParserError: Function, variable, struct or modifier declaration expected enum Statuses { Vacant, Occupied };
                                                                ^

Like I said, this is not really my own code, I'm just following along a tutorial. And sorry if my format is messy, I'm new, but ambitious!


texts:
Working on this blog

Tried to initialize bootnode throws and error


texts: Does a contract message call require a signature from the sender?

texts:
Say for example you have this simple contract:

contract Example {
   function sayHello() constant returns (string msg) {
      return "hello";
}

And I make a message call:

exampleContract.sayHello.call();

Since it's a constant (read only) message call, according to the docs, a from address is optional.  Since a from is not required, does this mean anyone can call the function - no signature validation is performed?


texts: ETH sent to an address that was generated for contracts, how can I recover?

texts:
I have transferred money to an ethereum address that belongs to the smart contracts.
const priv = "0x" + crypto.randomBytes(32).toString("hex");
const pub = "0x" + util.generateAddress(util.toBuffer(priv), util.toBuffer(parseInt(req.params.nonce))).toString("hex");

This is how I generated the private key and public address. I have a track of the nonce but when I try to import this private key in trust wallet, I cannot see any funds there.
Crazy thing is that I found out now that the generateAddress expects the first parameter to be a smart contract address, whereas I provided a private key and it still accepted it. An error here would have saved me from losing 2000$.
Is there any way to recover this?
Thank you very much.


texts:
Let's suppose I have this struct:
struct Agent {
    uint idAgent;
    address direction;
    uint[] preferences;
}
Agent[] agents;

And there's a function:
/// @notice Registra a un nuevo agente a la subasta
/// @param _idAgent identificador del agente dentro de la subasta
/// @param _preferences preferencias del agente
function regAgent(uint[] _preferences) public{
    Agent memory newAgent = Agent(numAgents, msg.sender, _preferences);
    agents.push(newAgent);
    numAgents++;
}

When an agent tries to register twice, how can I check it? I want to check that the agent is already registered but I don't want to go through the agent array. Is that possible?


texts:
I have initialized my contract and need to balanceOf the current logged in address

const contract = new web3.eth.contract(abi).at(address);

  contract.balanceOf(function (error, balance) {
        $('account-balance').html = balance;
     });

but now i have troubles accessing the functions within the contract.

I get this error for trying to get "balanceOf"

inpage.js:1 Uncaught Error: Invalid number of arguments to Solidity function
    at Object.InvalidNumberOfSolidityArgs (inpage.js:1)
    at u.validateArgs (inpage.js:1)
    at u.toPayload (inpage.js:1)
    at u.call (inpage.js:1)
    at u.execute (inpage.js:1)
    at exchange.js:59


texts: Only one topics args for event logs visible in the transaction receipt, instead of three expected

texts:
I have a Smart Contrat where there is some events like bellow :

    MyContract {

   event CustomerDataSendingToSeller(address _seller, string _hasheCustomerData, uint256 _orderSeq);

     function SigneCustomerDataToSell(string _hasheCustomerData) public {

            require(seller != msg.sender);

            customer = msg.sender;

            DataExchangeSeq++;

            DataExchanges[DataExchangeSeq] = DataExchange(customer,_hasheCustomerData,0,0,DataExchangeSeq,0,Buyer(0,"0x",false,false),false);

            emit CustomerDataSendingToSeller(seller,_hasheCustomerData, DataExchangeSeq);

        }

}

Then I passed my the Smart Contract function as transaction after deployement, and I check the transaction receipt, I saw that there is only one args instead of my three args in the Smart Contract.

Here the output of the transaction receipt function :
w3.eth.getTransactionReceipt(tx_hash)

        AttributeDict({
        'transactionHash':HexBytes('0xee50268e0c525cdee61fa58b1459a74915d7ac25ca72ebdb06065c3bd03a8f73'),
        'transactionIndex': 0,
        'blockHash':HexBytes('0x2ddd79c415277e02dc51c649f3463085a8043b87bb7067e3da81062cf608357c'),
        'blockNumber': 97,
        'gasUsed': 93882,
        'cumulativeGasUsed': 93882,
        'contractAddress': None,
        'logs':
          [AttributeDict({
          'logIndex': 0,
          'transactionIndex': 0,         'transactionHash':0xee50268e0c525cdee61fa58b1459a74915d7ac25ca72ebdb06065c3bd03a8f73', 'blockHash':'0x2ddd79c415277e02dc51c649f3463085a8043b87bb7067e3da81062cf608357c', 'blockNumber': 97,
'address': '0xAAe858AE95DE4eA7acE44Bc58bBB27C331e6dc0d',     'data':'0x0000000000000000000000000db7fec9d38cb5a3e789228f93ac0b27cb25d24d00000000000000,
'topics': ['0xf9a97ac82c9d5863f1a327d99b2f678c53726ddea126435a5752717390af467b')], 'type': 'mined'})],
'status': 1,
'logsBloom':('0x0000000000004000000000000000000000000000000000000000000000000000000004')})

In the topics I should see my three hashed args, but only one is present and seems to be the hash of the event function itself, so why don't see the other ?

Thanks for help :)


texts: Why are local variables allocated to storage instead of memory?

texts:
Local variables (i.e. variables declared inside functions) are held in persistent storage by default instead of non-persistent memory (source).

The value of a local variable can not persist in between function invocations, so in my mind it makes more sense to have local variables stored in memory during the execution of a function call. Could someone explain the purpose of this decision?


texts:
I have used web3js by using it in the form of node(npm). But I don't know how to extract some data generated from nodes.

Does anyone know this web3js so the results can be changed to json form? Because I need this so that the data generated can be entered into the variable, so that I can then process the variable into the program.

Like let's say I use the web3-eth-accounts package as follows (use node with cmd) :

var Accounts = require('web3-eth-accounts')
var accounts = new Accounts('https://rinkeby.infura.io/')
accounts.create()

Example result from node :

Well, for the above does anyone know to be converted into json form?


texts: Is there any version of ethereumjs-testrpc for ethereum classic? How to launch geth --rpc in geth classic version on linux?

texts:
I was wondering if there is any version of that local test version but for ethereum classic.

Another question is, in order to use web3.py and geth in my VPS ubuntu terminal...how can I open a geth --rpc client or something for local test in terminal, because I am used to use geth in windows terminal...but I don´t know how to launch geth in linux terminal.


texts: Fallback function optimization: what better?

texts:
I have ERC20 contract with payable function.
1
function () external payable {
    uint256 amount = msg.value * unitsOneEthCanBuy / 1000000000000;
    balances[msg.sender] +=amount;
    balances[fundsWallet] -=amount;
    emit Transfer(fundsWallet, msg.sender, amount);
    fundsWallet.transfer(msg.value);
    }

2
function () external payable {

    create(msg.sender);

    }

function create(address _beneficiary) public payable {
    uint256 amount = msg.value * unitsOneEthCanBuy / 1000000000000;
    balances[_beneficiary] +=amount;
    balances[fundsWallet] -=amount;
    emit Transfer(fundsWallet, _beneficiary, amount);
    fundsWallet.transfer(msg.value);
    }

What better 1 or 2?


texts:
I run truffle test

and see my transaction in ganache:

 Transaction: 0x2e9aab59f190743cc740b6f4de9963354386fde246287fc383688f1e055e4451
  Gas usage: 137228
  Block Number: 92
  Block Time: Mon Jun 04 2018 11:12:12 GMT-0700 (PDT)

when I run truffle debug 0x2e9aab59f190743cc740b6f4de9963354386fde246287fc383688f1e055e4451

I get :

redux-saga error: uncaught at session.saga
at session.saga
 at recordInstance
 TypeError: Cannot read property 'context' of null

My versions are:

Truffle v4.1.11 (core: 4.1.11)
Solidity v0.4.24 (solc-js)

Any idea what I can do to get this working?
Thanks