texts: Calling function of one contract in another using truffle

texts:
I have one contract and in it's constructor I have initialized properties of balances

contract TestChainCoin is RefundableCrowdsale
{
    function TestChainCoin() RefundableCrowdsale() {
            balances[msg.sender] = 100;
        }
}

The balances is described in another contract and this contract have function balanceOf() to return balance.

contract StandardToken is Token {
    mapping (address => uint256) balances;

    function balanceOf(address _owner) constant returns (uint256) {
        return balances[_owner];
    }
  }

Now the problem arise here. I am trying to create test cases in Truffle using javascript and have following code. When I am trying to call balanceOf() then it hits but returns zero amount but I already initialized it to 100.

contract('TestChainCoin', function (accounts) {
  let owner = accounts[0];
      it("should TestChainCoin be deployed first", function() {
        return testChainCoin.deployed().then(function(instance) {
        testChainInstance=instance;
        });
      });

     it("should StandardToken be deployed first", function() {
        return standardToken.deployed().then(function(instance) {
            standTokenInstance=instance;
        });
      });

      it('should return balance of user', async () => {
      let userBal= await standTokenInstance.balanceOf.call(accounts[0]);
      console.log("the balance of user---"+userBal);
      assert(balanceFinal<= 100 && balanceFinal>0, 'balance should not be zero');
      });

So where I am doing wrong.


texts: How to insert multiple transactions into One Block in Ganache GUI

texts:
Is it possible to enable Ganache GUI to put multiple transactions into ONE block ?. The details about Why i need this thing, is given below;

I am going to test Transaction Order Dependence (TOD) contracts details are here, which need multiple transactions into one block (if i am not wrong). To achieve the real behavior of true miner, i have to test A race condition vulnerability in my contract. So, is it possible to launch TOD attack using Ganache ?


texts: What is the main difference between "light client" and "client" in sense of "functionality" and "capability"?

texts:
What is the main difference between "light client" and "client" in sense of "functionality and capability" ?

I mean, what can a client does that a light client cannot ? (ex. sending transactions? transaction confirmation? etc)


texts: Where can I find the source code for ETH 2.0?

texts:
Where can I find the source code for ethereum 2.0 and what programming language is it written in. Also, will this source code be rewritten into another language?
And can I also run it and test it?


texts:
This is the normal Data that I saw:
amount0In : 4000000000000000000
amount1In : 0
amount0Out : 0
amount1Out : 55176985192271150

But this one is different:
amount0In : 55242685893542
amount1In : 154962800000000000
amount0Out : 80496994724206125
amount1Out : 0

I don't understand this log. Normally there's only one value in amount0In or amount1In, so, I guess my question is:

What's the amount* field values for?
Can I use those values to determine the amount of a swap?

Source: https://etherscan.io/tx/0xcee96abc50e9adf8745f3fd642ee7be40dd0a6c50a72303fbd833c939bd5d5e1


texts: how Burn mechanism work, Who calls the burn method?

texts:
I am wondering on how does the burning mechanism work, as far as i know, that who ever called the contract msg.sender will be his ethereum address. But the twist is when i saw the burn function, it has the intended account that anyone can burn from:
function burn(address owner, uint256 value) public returns(bool){
        balances[owner] = balances[owner].sub(value);
        totalSupply = totalSupply.sub(value);
        emit Transfer(owner,address(0),value);
        return true;
    }

this is my edit, so that the caller is restricted to burn from his own address.
function burn(uint256 value) public returns(bool){
        balances[msg.sender] = balances[msg.sender].sub(value);
        totalSupply = totalSupply.sub(value);
        emit Transfer(msg.sender,address(0),value);
        return true;
    }

Any reflections on my edit? is everywhere has the access to them? And how would be possible that the first example will allow an unauthorized burning if it is public?


texts: How to limit contract compatibility to specific ERC20 token?

texts:
How would I go about making sure users of a DApp can only interact with the contract using a specific ERC20 token?

For example, say a user has Ethereum, Token 1, and Token 2 in their wallet. The DApp uses Token 2. How can I make it so if they send anything other than Token 2 to the DApp contract, they are refunded.


texts: In a private ethereum network, can I have 1 account running in multiple nodes? That is, that multiple nodes refer to the same account?


texts:
I have 2 contracts that deployed with truffle. Now I extended it and my contracts require some bootstrap actions like "set some address" or "set in contract1 address of contract2".

I will not change contracts to make it dependable or mention one contract inside another. I want just to call function contract1.setX(address_of_contract2) and contract2.setY(address_of_contract1).

How it could be done using truffle migration engine (not manually)?


texts:
I'm currently writing a thesis on a simulation of a peer to peer electricity market. The payments between the agents of the simulation would be settled through an Eth smart contract. I would like to run the simulation of the marketplace (supply/demand of agents, order book) in Python. I have zero experience coding smart contracts.

I was wondering if there was any way to invoke a smart contract using Python code. What I am envisioning is Python invoking a smart contract in an Ethereum test net which would keep track of how much Ethereum each agent has.

Thanks


texts:
I just request a token(Ropsten test net) from one of my "MetaMask" account(Account 1). But MetaMask showing me same token balance from each Account(I have 3 Accounts). Why this token added to each account?
Many Thanks..
i.e:-


texts: How do you reset an address variable in Solidity? You cannot assign it Null or 0 but I want to be able to "deassign" an address somehow. Any ideas?


texts: Providing Metamask hooks only using node hosted on server

texts:
I am currently looking into hosting an Ethereum node on my web server in order to allow my users to interact with my dApps without needing Metamask (although it could be used).  How could I have the client side Web3.js code interact with my server as the hook instead of whatever would normally be injected by Metamask.  If I were to include the web3.js code on my server and link it in the header, could I simply construct the Web3 object with my node as the provider and Metamask would no longer be necessary?

If Metamask is necessary for normal browsers no matter what, an explanation of why would be greatly appreciated.  If what I've stated could work, how could I use my server hosted node as a provider (what port would I use and could I use my normal domain) as well as what could I do to improve security.  My biggest worry is that if everything works as simply as I've suggested here, that someone could create a website of their own that connects to my node and everyone will start using my node for all of their websites.

My server is setup as a LAMP server and I use named virtual hosts in order to redirect/control traffic as I need it (could this be used to secure my node from others using it). I would prefer to stick with my current setup instead of switching to node.js but if it is absolutely necessary in order to get a site that works without Metamask, I would definitely look into it.


texts: Investing in private company's shares before they go public

texts:
I am very interested to invest in small start up companies that has upward potential to bringing it in the public stock exchanges.  Where can I find these start up listing that offering cheap shares to invest?
Thank you


texts: GasLimit check failed for header -1 when mining in private chain

texts:
On a machine with geth and geth --testnet running I would like to creat a private chain as well.

I have created a private chain with the following genesis.json

{
    "name": "hackathon",
    "engine": {
        "Ethash": {
            "params": {
                "gasLimitBoundDivisor": "0x0400",
                "minimumDifficulty": "0x400",
                "difficultyBoundDivisor": "0x0800",
                "durationLimit": "0x0a",
                "blockReward": "0x4563918244F40000",
                "registrar": "",
                "frontierCompatibilityModeLimit": "0x0"
            }
        }
    },
    "params": {
        "accountStartNonce": "0x0100000",
        "maximumExtraDataSize": "0x20",
        "minGasLimit": "0x1388",
        "networkID" : "0x3942"
    },
    "genesis": {
        "seal": {
            "ethereum": {
                "nonce": "0x0000000000003942",
                "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
            }
        },
        "difficulty": "0x400",
        "timestamp": "0x00",
        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "extraData": "0x0",
        "gasLimit": "0x4c4b40",
        "coinbase": "0x0000000000000000000000000000000000000000",
        "alloc": {}
    },
    "nodes": [],
    "accounts": {}
}

I then initialized the chain with geth --datadir ~/.ethereum/hackathon init genesis.json

and get the success message:

I1112 15:06:15.214815 ethdb/database.go:83] Alloted 16MB cache and 16 file handles to /home/mroon/.ethereum/hackathon/chaindata
I1112 15:06:15.221926 cmd/geth/main.go:299] successfully wrote genesis block and/or chain rule set: 78dec18c6d7da925bbe773c315653cdc70f6444ed6c1de9ac30bdb36cff74c3b

I then run geth, create an account and start the miner with miner.start()

This is how geth is started:

geth --datadir ~/.ethereum/hackathon --networkid 42 --port 30304 console 2>>hackathon-geth.log

and this is the error message in the log after after the miner starts:

I1112 15:07:26.044185 eth/backend.go:454] Automatic pregeneration of ethash DAG ON (ethash dir: /home/mroon/.ethash)
I1112 15:07:26.044308 eth/backend.go:461] checking DAG (ethash dir: /home/mroon/.ethash)
I1112 15:07:26.044689 miner/miner.go:119] Starting mining operation (CPU=8 TOT=9)
I1112 15:07:26.045255 ethash.go:259] Generating DAG for epoch 0 (size 1073739904) (0000000000000000000000000000000000000000000000000000000000000000)
I1112 15:07:26.632381 ethash.go:276] Done generating DAG for epoch 0, it took 587.138328ms
I1112 15:07:27.119837 miner/worker.go:288] Invalid header on mined block: GasLimit check failed for header -1 (1 > 0)

the first look OK but then there is this GasLimit thing.


texts: Calling a function of one Contract inside another Contract not workig correctly?

texts:
I have a problem like this. I am very new to solidity. I have tried an example that I was found by a Google Search in the remix editor. But I was unable to get any output like in the example.This is the tutorial that I followed

According to the tutorial, I create a two solidity file called Callee.sol and caller.sol. Here I am providing that callee.sol contract.

contract Callee {
    uint[] public values;

    function getValue(uint initial) returns(uint) {
        return initial + 150;
    }
    function storeValue(uint value) {
        values.push(value);
    }
    function getValues() returns(uint) {
        return values.length;
    }
}

And my caller.sol is looked like this.

pragma solidity ^0.4.6;

contract Caller {
    function someAction(address addr) returns(uint) {
        Callee c = Callee(addr);
        return c.getValue(100);
    }

    function storeAction(address addr) returns(uint) {
        Callee c = Callee(addr);
        c.storeValue(100);
        return c.getValues();
    }

    function someUnsafeAction(address addr) {
        addr.call(bytes4(keccak256("storeValue(uint256)")), 100);
    }
}

contract Callee {
    function getValue(uint initialValue) returns(uint);
    function storeValue(uint value);
    function getValues() returns(uint);
}

Firstly I deployed The callee.sol contract

Then I deployed the contract call caller.sol.

Then I copy the address of callee contract and call the function of caller contract like this but it gave a nothing as output.

Can someone help me to make this work? Thank you very much.


texts: Lost my computer and external hard drive with my keystone file

texts:
Last week my laptop bag was stole. It contained my laptop with my ethereum wallet and my external hard drive where i backed up my keystore file.  I'm fairly new to ethereum, I purchased 1 eth back in October and have been watching the price rise. I'm assuming I've lost it all but if anybody has any suggestions i'd love to hear them.

Thanks,
Curtis


texts: How do I make my private Ethereum network public?

texts: So after a lot of reading I was able to make my own private Ethereum network, most of the readings I did showed me how to test it privately, but none of them actually explained how to make it public, if I could get an explanation on how, or a link to a guide would be appreciated!


texts: Service for selling ERC20 Token directly for fiat?

texts:
So currently our ERC20 token is trading on several DEX's. There is quite some volume but some potentially interested people have given us feedback on the process being a little bit too much for them. (Sign up to a CEX, buy ETH, send ETH to DEX, trade ETH for Coin, send Coin to Wallet).

Are there any services to let people directly buy the token for fiat?

It does not have to be a full-blown (Centralized) exchange. Just a buy button and a price would suffice. But in a trustworthy way? Either with Ideal, Skrill, Paypall, Creditcard or something similar.

We can not offer tokens ourselves cause I think then we are actually entering the space of exchanges.


texts: How do I parse the transaction receipt log with web3.js?

texts:
The event parser in web3 provides a nice parsing functionality for events, and I use it for logging all events to a file, but it's very difficult to use for looking at individual events for a particular transaction for automated testing because it induces an unneeded and difficult to manage concurrency aspect when there doesn't need to be one.

When I get a transaction result with web3, I have the transaction receipt in hand and that's the perfect time to synchronously examine the result and apply pass/fail test criteria.

I would like to parse the log section of the receipt but can't find a function in web3 to do so.  Does it exist?


texts: is there any way to lower my propagation time? Right now i have +20 secs in propagation time average. I want to lower this as much as i can. I was thinking on connecting to some good reliable nodes to better this. Is this possible?


texts: For Recipient how do I store Sender's account address and Password of Recipient's own account in hashed from?

texts:
How to check following things using Solidity:

Password matching (hash formed)
if password matches then transfer take place


texts: Is it possible for send() in Solidity to fail if value is sent to a valid external account?

texts:
I want to use something like the following as a fallback for failed transfers:

if (!recipientAddress.send(amount)) {
    ownerBalance += amount;
}

After reading about using transfer versus send, it seems that, assuming the send doesn’t fail due to a bad address (if there is such a thing - I’m not entirely sure if transferring to an unclaimed address would fail) or insufficient contract balance, it’s only possible for the transaction to fail if 1) recipientAddress is a contract address and 2) the contract at that address has a fallback function that uses too much gas for the transaction to succeed.

Assuming that the transaction fails and that #1 and #2 above are correct, the recipient contract would never be able to receive value from the sending contract, so unless there is an alternative way to extract that value, it could potentially be lost in the contract forever.

I’m just trying to confirm my assumptions here in order to know whether I can rightly transfer the value to myself as the owner if the transfer fails or if I need to account for the possibility that an external user may have to attempt the transfer more than once.

Most of what I’ve read suggests that transfer is the preferred method for sending value, however, I don’t think I’ve seen this question addressed.  If my assumptions are correct, I’d think that send should be the preferred method.

UPDATE:

Here's a more full example of a transaction with multiple transfers:

function transferGameBalances(uint _gameId) external payable {
    Game storage game = gamesById[_gameId];
    require(game.status == GameStatus.GAME_OVER);
    require(msg.sender == owner || msg.sender == game.player1 || game.player2);

    if (!game.player1.send(game.p1_balance)) {
        ownerBalance += game.p1_balance;
    }

    if (!game.player2.send(game.p2_balance)) {
        ownerBalance += game.p2_balance;
    }

}


texts: using .call(): contradictory recommendations

texts:
Solidity documentation:

You should avoid using .call() whenever possible when executing another contract function as it bypasses type checking, function existence check, and argument packing.

Ethereum Smart Contract Best Practices:

It's recommended to stop using .transfer() and .send() and instead use .call().

Is there a consensus on which method is best?


texts:
When testrpc starts, it outputs the generated addresses, but all in lower case.
What's a lightweight way to get their EIP55 checksummed format?


texts: Confirming transactions on my own blockchain

texts:
I have gone through this guide to create my own Ethereum smart contract on my own private network. I have created my own network, I have a smart contract code ready, I have Mist installed to deploy the contract, but the problem is - contract is stuck in "creating contract" mode (with 0/12 confirmations).

Now, i'm the only miner, of course, and I have been mining for the last 2 hours on the network (have mined 5000 ethers on the same account that deployed the contract), but I haven't confirmed the smart contract and i can't grasp why.

I have created two contracts, one with default amount of gas and the second with maximum amount of gas, both are still being confirmed with 0 confirmations so far.

So, my questions are -

1) How to confirm the smart contract and why is it not being confirmed? One of the reasons I think might be that when I start Mist, it says 1000 blocks out of 711000 are synced. But in the guide it said that when we are on our own network, we don't have to care about syncing anymore.....

2) Is more of an additional question - how can I connect my second computer to the private network to mine too? Is it enough to transfer the genesis.json and chaindata files and just connect on the other computer with "geth --datadir=./chaindata/" and "geth attach ...." commands?

Thanks


texts: How to find the source code of my contract which is not yet verified

texts:
I had created a token using eth based blockchain via
remix.ethereum.org
But I need to verify the source code ,but I am not having the backup copy of source code
How can I see the source code of the token .
Please let me know


texts: How to set an array of struct in the function param

texts:
this is the function :

  function setListObjects(ContractObject[] memory ContractObjects)public{
    delete objects;
    ContractObject memory newObject;
    for (uint i = 0; i < ContractObjects.length; i++) {
        newObject = ContractObject({
            id:objects.length+1,
            title:ContractObjects[i].title,
            description:ContractObjects[i].description
            });
        objects.push(newObject);
    }
}

but when i generate java class with web3j there is an error Unsupported type encountered: tuple
the problem that in my application i have to set all the array in one transaction . So what is the solution ?


texts: Viewing token contract address in mist wallet

texts:
My question:

How do I view the Contract address of a token in the mist wallet?

Elaborating:

Lets say I deploy a new token on the mist wallet. The Token is then visible in the account that I used to deploy it with the amount of tokens associated with that account. Though I don't see an option that shows me that new tokens Contract address

On etherscan.io, you can query tokens by the Contract address:

https://etherscan.io/token/Qtum

I'm not sure if there is an interface option in the mist wallet (preferable) or if geth has to be used directly or something else, and what the command might be in that case.


texts: Convert ethereum balance getting in biginteger to ether

texts:
public BigInteger getBalance(String address)
{
    /*Web3j web3j  */

   createEthreumConnection();
   EthGetBalance ethGetBalance = null;
   try {
      ethGetBalance = web.ethGetBalance(address, DefaultBlockParameterName.LATEST).sendAsync().get();
   } catch (InterruptedException e) {
      logger.error("Interrupted Exception "+e);
   } catch (ExecutionException e) {
      logger.error("ExecutionException Exception "+e);
   }
   return ethGetBalance.getBalance();
}

I am using the above code for getting the ethereum balance but the balance fetched in given format 4555500000 , I want to be shown as Ethereum balance.For example Bitcoin j provides  MonetaryFormat.BTC.noCode().format(addressBalance)


texts: Unable to send ether from a contract to an account

texts:
I am unable to send ether from the following contract to a recipient address.

contract MoneyFountain{

    address owner;
    uint256 sendAmount;

    function MoneyFountain(){
        owner = msg.sender;
        sendAmount = 100000000000000000;
    }

    function getBalance() returns (uint){
        return address(this).balance;
    }

    function sendWei(address recp) returns (bool){
        recp.send(sendAmount);
    }
}

I am able to put this contract on a private blockchain and also populate the contract balance to 10 ethers to begin with.

web3.fromWei(eth.getBalance("0x171fa8740cbd7ffaec96109b5d35172556a96886"),"e}

  10

After the successful execution of the function sendWei(), if I check the balance of the recipient it doesn't show the balance to be transferred. The contract and the balance of the recipient remain the same.


texts:
For a light client (geth --light or parity --light) running the light client protocol what are the port requirements?

Incoming: Does a light client expose a port where he accepts incoming connections and that need to be opened in the firewall (I would assume not)?

Outgoing: And vice-versa outgoing which ports need to be opened so that a light client can connect to other full-node peers?


texts: Unpredictable states error when refactoring smart contracts

texts:
Ethereum smart contract functions are limited to around 16 local variables. When they exceed that number, stack is too deep error is generated.

The solution is to refactor the large functions into smaller ones. For example:

Contract A{
   function B(p1,p2,p3...pn){
   }
}

Can be developed as:

Contract A{
   function B1(p1,p2){
   }
   function B2(p3,p4){
   }
   ...

}

Now assume that some functions are dependent on the results of others. In other words, the change in state caused by a function affects how another one acts.

This issue I am thinking of is unpredictable state discussed in this paper which states:

  In general, when a user sends a transaction to the network in order to
  invoke some contract, he cannot be sure that the transaction will be
  run in the same state the contract was at the time of sending that
  transaction.

How can we ensure that a user that wants to transact with function B1 then wants to transact with function B2 without someone else changing the state caused by transacting with B1 again?


texts: Finding and Using Solidity Libraries (ie. Math functions)

texts:
How do I find and use any existing Solidity libraries like you might in Javascript?

For example, Math functions: How do I implement the equivalent of Math.sqrt(x) in a solidity function?

Related: What is --libraries doing in that second question (if relevant here)?

I looked at the docs and answers below, but they didn't seem to answer this. Thanks.

How to import solidity libraries in mix?

Out of gas error deploying library


texts: How can I perform float type division in solidity?

texts:
How can I achieve proper division of two integers in solidity?

Suppose I perform : 3/2 the solution provided is 1 and not 1.5

please help.


texts:
Anyone who bought DAOs in the last two weeks of The DAO crowdfunding phase paid more than 1 ether (ETH) per 100 The DAO tokens (DAO). The ETH amount in excess of 1 ETH per 100 DAOs was stored in The DAO's extraBalance account. The balance of the extraBalance account has now been transferred into the curator's multisig wallet.

As described in How do I convert my The DAO tokens into ethers using the withdrawal contract after the hard fork?, The DAO token holders can currently convert their DAOs into ETH at a rate of 100 DAO = 1 ETH.

How do I get a refund for the amount I paid in excess of 1 ether to 100 The DAO tokens?

The DAO Refunds

How do I convert my The DAO tokens into ethers using the withdrawal contract after the hard fork?
[THIS] How do I get a refund for the amount I paid in excess of 1 ether to 100 The DAO tokens
How do I get a refund for my The DAO tokens that was split into a child DAO?
How do I convert my The DAO tokens into ethers on the Ethereum Classic chain?
How to conditionally send ethers to another account post-hard-fork to protect yourself from replay attacks

See also:

Which accounts contributed to The DAO's extraBalance account?


texts: How to factor in decimals when using division and remainders

texts:
math is not my strong suite so I have a question for anyone that understands solidity's mathematical operations.

_

I have the following situation:

Token is priced at 0.001 Ethereum.
Token has 18 decimals.

Example purchase A (code at the bottom):

Person A deposits 0.01 Ethereum.
Amount deposited divided by price is 10.
So Person A gets 10 tokens, but we have 18 decimals. So it should be 10e18, not 10. How do we get this? (see code)

_

Example purchase B (code at the bottom)

Person B deposits 0.0001 Ethereum
Amount deposited divided by price should be 0.1 if done on a calculator, but a simple division in solidity only returns 0. I understand this is due to solidity not denoting decimals by a dot notation, so the answer should ultimately become 1e17

Code situation A

 function FooBar() public returns (uint){
    // 1 Token will cost 0.001 eth.
    uint256 _tokenPrice = 1e15;

    // Incoming ethereum is 0.01.
    uint256 _ethereumSent = 1e16;

     // This should net us 10 tokens.
    uint256 _totalTokens = _ethereumSent / _tokenPrice;

    // So this returns 10, but we want 1e19 because of the fact that our token has 18 decimals.
    return _totalTokens;
}

Code situation B

 function FooBar() public returns (uint){
    // 1 Token will cost 0.001 eth.
    uint256 _tokenPrice = 1e15;

    // Incoming ethereum is 0.0001.
    uint256 _ethereumSent = 1e14;

     // This should net us 0.1 tokens.
    uint256 _totalTokens = _ethereumSent / _tokenPrice;

    // So this returns 0, but we want 1e17 because of the fact that our token has 18 decimals.
    return _totalTokens;
}

How do I get the desired results? Thanks in advance, I'm more then willing to provide any additional information.


texts: Following the Hardhat tutorial, I get this error: TypeError: ethers.getSigners is not a function

texts:
I am following this tutorial https://hardhat.org/tutorial/testing-contracts.html and I get this unexpected error:
const { expect } = require("chai");
const { ethers } = require("ethers");

describe("Token contract", function() {
  it("Deployment should assign the total supply of tokens to the owner", async function() {
    const [owner] = await ethers.getSigners();
    const Token = await ethers.getContractFactory("Token");

    const hardhatToken = await Token.deploy();

    const ownerBalance = await hardhatToken.balanceOf(owner.address);
    expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);
  });
});

$ npx hardhat test

TypeError: ethers.getContractFactory is not a function


texts: What reputation systems are implemented on Ethereum?

texts:
I'm looking into finding some sort of reputation system on Ethereum. Are there any projects out there already that do this? I found a DEVCON1 video about reputation systems and a few people discussing it briefly, but not really any basic proofs of concepts.

Is Augur something that I should look at for this?


texts: Is Ethereum fast sync feasible to get logs

texts:
I want to get the logs of an contract address by filtering the even with transfer Event. I cant use Infura for its restrictions and limits. So i want to sync my own ethereum node for myself.
Since my own requirement from the node is to query its database for transfer event so will a Fast Sync node will be enough for me or do i have to go for Full SYNC mode ?


texts:
is it possible to check for a contract if a new block is created without calling a function? Means an automatically getter. A Live-update from the chain.

"function () internal"
maybe. Somthing like this.

uint public a;
 function (){
    a = block.number;
 }

Thanks.


texts: IPC python unix-socket unavailable on windows

texts: I want to use the IPC interface between Python and geth. I use windows. But it seems that the unix-socket which IPC makes use of is not available in the windows version Python, how to solve this problem?


texts: Is there any price for storing data in contracts?

texts:
I want to create contract, which will be able to store data like array of:

struct Funder {
        address addr_first;
        address addr_second;
    }

How can I calculate gas fee for transactions which inserts additional Funder to my array ?

Should I pay more and gas for each insertion or I should always pay a fix gas price for all insertions to my storage ?

For example, if I have to pay 10 Gas for first insertion, how many gas should I pay when I'll have thousands of Funders and want to insert another one?


texts: the tx doesn't have the correct nonce. account has nonce of: 12 tx has nonce of: 3 - Ganache

texts:
I am trying to run my simple contract with different parameters (in the form of encoded signatures) and intends to put multiple transaction into ONE block. If I set Ganache GUI with automine option, it works perfectly but with one transaction in ONE block. However, if I set timedelay (i.e. say 2/3 sec) to enable multiple trxs into one block, then i am facing problem situations;
1. If I send my transaction with await keyword, then it works perfectly (but put one trx in one block, which i don't want) .
2. If i send my transactions without await keyword, then i put multiple trxs into one block, however then it give captioned error.

Here is code:

async function finalDeploy(r){ // this function deploy my contracts
  for(i=0; i<constructorParams.length; i++) {
// console.log("constructorParams", constructorParams[0])
// console.log("myBin", myBin[0])
    const options = {
      data: '0x' + myBin[r]+constructorParams[i],
      gas: 5000000,
  };
  const signed = await web3.eth.accounts.signTransaction(options, privateKey1);
  const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
  console.log("Contract: " +r+" is deployed at  " +receipt.contractAddress);
  contractAddressess.push(receipt.contractAddress)

  }

}

async function finalSettersFunctions(){ // here i am calling setter functions of already deployed contracts
  var myFunc;
  var  myContAddr ;
  for(i=0; i < contractAddressess.length; i++) {
      myContAddr = contractAddressess[i]
    for(j=1; j<finalSetters[i].length; j++) {
          myFunc = finalSetters[i][j];
          console.log("function name: ", myFunc);
            try {
              //await web3.eth.sendTransaction( // if i enable this then ONE trx/ONE block
                 web3.eth.sendTransaction( // this makes multiple trxs/ONE block, but gives error
                {from:account1,
                to:myContAddr,
                data: myFunc
                    }, function(err, receipt) {console.log("Normal Setters: ",receipt)});
            } catch (error) {
              console.log(" Normal Setters: ERROR !");
            }
    }
  }
}

async function main() {

  for(r=0; r<contractFile.length; r++) {
      var myReceipt = await finalDeploy(r);

        console.log("============All  Setter Functions of Contract No. ", r);
        var myget = await finalSettersFunctions();

    console.log("Contract no. : "+r+ "  completed !")
  }
  }

  main().then(() => {
    console.log("ALL has been DONE !")
  })

Here is error:

UnhandledPromiseRejectionWarning: Error: Returned error: the tx doesn't have the correct nonce. account has nonce of: 12 tx has nonce of: 3


texts:
EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, userContract.getContractAddress().substring(2));

I am trying to recover the event response that a solidity smart-contract return me. Searching in the web I find here post. And works, but the problem is that I dont now what method I have to call to return just the string that de contract send me.

Something like:

System.out.println(filter.getMessage());


texts: who has any idea about this error please?

texts: Error: Returned error: VM Exception while processing transaction: revert SafeERC20: low-level call failed -- Reason given: SafeERC20: low-level call failed.


texts: How to authenticate user using passphrase?

texts: While creating ethereum account(geth) account we need to enter the passphrase for respective account. Is there any way to authenticate the user using that passphrase from a front end?


texts: How to build an ethereum based wallet with custom UI?

texts:
I have been interested in ethereum for quite some time now and have always wanted to learn ethereum development.
I decided to create my custom erc20 tokens i was able to create 2,00,000 tokens.

Now i am planning to take it a little further by building my custom erc20 standard based wallet to send and receive or buy these tokens using ethereum through the wallet.

Can someone please point me in the right direction???...


texts: How should I store user's password in a smart contract?

texts:
First I thought I could easily use private like:

mapping (address => bytes32) private userPassword;

and so just check if the entered password is right:

function enter(bytes32 password) {
   if (password == userPassword[msg.sender])
      //do smth
}

But then I read this in solidity docs:

  Everything that is inside a contract is visible to all external
  observers. Making something private only prevents other contracts from
  accessing and modifying the information, but it will still be visible
  to the whole world outside of the blockchain.

So if I got it right, even if I use "private" visibility still everyone can see values of stored passwords. Then how should I store information that shouldn't be for public?


texts: How do smart contracts get information about real world events?

texts:
How do smart contracts probe information about the real world?

A smart contract's execution can be contingent on real world events such as who will win a football match (this is a betting contract) or what the price of oil is in 90 days (a financial contract). How do smart contracts get this information?


texts: `emit ThisHappened` vs `ThisHappened` do we need to write `emit`?

texts:
From my experience you can declare events with capital letter.
eg: ThisHappened(address user, bytes32 act);

Then you can call it by just writing: ThisHappened(user, "ATE_HAMBURGER");

But recently I saw a contract writing emit ThisHappened(user, "ATE_HAMBURGER");

What is the difference? Which one should I use?


texts: Smart contract function not returning expected output

texts:
I'm quite new at this and I'm learning both Solidity, Javascript and React to play around with smart contracts. My contract ran well in Remix and in a local test net. I ran a bunch of tests using Mocha and everything went well.

My problem lies when I'm trying to fetch data using a .call() function. This is the code in the React/Javascript part (callback function from a button):

checkAccount = async () => {
   const data = await tacosavings.methods.getAccount().call();
   const { 0: money, 1: timeLeft } = data;

   this.setState({
      message: `Your account data ->
      Tacos: ${web3.utils.fromWei(money, 'ether')} ether -
      Timelock left: ${timeLeft} seconds`,
   });
};

In my smart contract the function goes like this (accountExists is a modifier but not relevant to this I think):

    function getAccount() external view accountExists returns (uint256, uint256) {
        if (accountData[msg.sender].timeLock < now) {
            uint256 timeRemaining = 0;
        } else {
            timeRemaining = accountData[msg.sender].timeLock - now;
        }
        return (accountData[msg.sender].savings, timeRemaining);
    }

The problem lies in that in Remix my return value makes sense, but in React either as a console log or in the "website" its a non-sense value:

  Your account data -> Tacos: 3963877391197344453575983046348115674221700746820753546331.534351508065746944 ether - Timelock left: 862718293348820473429344482784628181556388621521298319395315527974912 seconds

Any ideas?

Many thanks in advance =)!


texts: Solidity: Understanding the security risk of sending back money with send

texts:
I'm looking at the auction example here https://solidity.readthedocs.io/en/develop/solidity-by-example.html

I'm confused by this code

    if (highestBidder != 0) {
        // Sending back the money by simply using
        // highestBidder.send(highestBid) is a security risk
        // because it can be prevented by the caller by e.g.
        // raising the call stack to 1023. It is always safer
        // to let the recipient withdraw their money themselves.
        pendingReturns[highestBidder] += highestBid;
    }

Can someone explain this risk in more depth? This seems kind of annoying that a smart contract would need to have the recipient make a call to get their money instead of automatically sending it but maybe I'm misunderstanding this.


texts:
I have a desktop app that accepts payment from user in ETH and provides it some service for a certain amount of time depending on the amount.

For that the user needs to sign the transaction in the inbuilt wallet which is not very trustworthy from users perspective because they have to put their private keys in order to sign the transactions.

Also tx id submission is not possible because he can use some other users tx id in a certain timeframe.

How can I solve this in these techniques?

Can I put metamask in my Desktop App (C# Dot Net)?
Can I call metamask from outside application?
How can a dapp solve this problem?
Can I push some intent from my desktop app to Web Browser?

I would like to push the transaction from the desktop app to the browser for signing.

I just don't like to handle the private keys for the user but wanna verify him according to the payment he made.


texts: How many functions allowed per contract? + solidity

texts:
I deployed a contract to ropsten and tried to call a method from frontend, but was getting

  TypeError: Cannot read property 'call' of undefined

So I checked my instance via this.Test.deployed().then((instance) => { console.log(instance) } to see if I have the function, but this particular function was not there!

It's a public view returns function that returns a boolean. I have several public view returns functions in the contract, but I have no idea why this one was omitted. I didn't even get an error while creating a contract to ropsten. Is there a limit or something?

** Edit **

From Frontend:

  checkPrizeReceived(id: number, price: number): Promise<any> {
    this.Test.setProvider(this.web3.currentProvider);
    return this.Test.deployed().then((instance) => {
      console.log(instance)
        return instance.checkPrizeReceived.call(id, price);
    })
    .then((value) => {
      return value;
    })
    .catch((e) => {
        console.log(e);
    });
  }

Solidity:

  function checkPrizeReceived(uint256 id, uint price) public view returns (bool) {
    for (uint i = 0; i < better[msg.sender].length; i++) {
      if (better[msg.sender][i].id == id && better[msg.sender][i].price == price) {
        if (better[msg.sender][i].receivedPrize) {
          return true;
        }
      }
    }

    return false;
  }


texts: Can I make a ERC20 transer after receiving and before N confirmations?

texts: Let's suppouse A user send tokens to B user. It may be hard to consider it to be confirmed yet. At this point B send the tokens received to another address. Could this transaction be successful? Is there any solution to increase the probability of success for the second transaction?


texts: Writing a file and linking to blockchain

texts:
I've found parts of a smart contract and I have an idea how to add things but I'm currently stuck. Maybe you can help me with that.
The contract looks as following:

pragma solidity 0.4.15;

contract monitoring {

uint8 public temperature;
address sensor;
address led;

event Instruction (address device, string instruction);

function monitoring (address _sensor, address LED ){
    sensor = _sensor;
    led = LED;
}

function updateTemp(uint temp){
    if(msg.sender != sensor) throw;
    temperature = temp;
    if (temperature > 90) {
        instruction(led, "ON");
    {
    else instruction(led, "OFF");
}
}

What I want to improve is, that after the event occurs (temperature raises above 90), a file with information about the event (like temperature, time of the day) gets written to some file and than the file gets hashed (with md5 or so) and the hash is written to a blockchain transaction.

Is that actually possible to do? If so, can you please give me an advice how to start?
Thanks a lot in advance! :)


texts: How to use Ganache, Remix IDE, MetaMask, and Web3js without Truffle

texts:
I am having an issue migrating a contract using Oraclize API to Ganache from Truffle.

However, everything is working fine when running the contract from Remix IDE via MetaMask. As I want to write the frontend of the dapp, how to do that without migrating the contract into Ganache from Truffle?


texts: How are people using ERC20 to tokenize assets

texts:
Hey guys been looking a lot into tokenization of assets wondering how this is possible with ERC20 (Seeing a lot of people use it and keen to understand) how would you represent an asset with each token representing a % of equity if you had multiple assets?
How would the blockchain know what asset you are invested in with multiple assets if you are using the ERC20 Token?


texts: In the current version of Ethereum Smart Contracts can call each other. It is planned to introduce Shards in Ethereum 2.0. But I can not find any information about how smart contracts are able to interact with each other if they are located in different shards


texts:
i am trying to send a request for my contract function to web3:

my code snippets is here:

const W3 = require('web3');
const express = require('express');
const ethTx = require('ethereumjs-tx').Transaction;

let web3, contractAddress, contractABI, contract, fromAdd, myData, estGasPrice;

function connectContract(){
    const provider = new W3.providers.HttpProvider(`${process.env.INFURA_ROPSTEN_ADDRESS}${process.env.INFURA_ROPSTEN_KEY}`);
    web3 = new W3(provider);
    contractAddress = process.env.LBT_CONTRACT_ADDRESS;
    contractABI =JSON.parse(process.env.LBT_CONTRACT_ABI);
    contract = new web3.eth.Contract(contractABI, contractAddress);
    console.log(web3.eth.accounts.privateKeyToAccount(process.env.TEST_WALLET_PRIVATE_KEY).address);
    fromAdd = web3.eth.accounts.privateKeyToAccount(process.env.TEST_WALLET_PRIVATE_KEY).address;
}

const router = express.Router();
router.post('/', async (req, res, next) =>{
try{
await connectContract();

myData = contract.methods.freezeAccount(req.query.target).encodeABI();

web3.eth.estimateGas({
    to: contractAddress,
    data: myData
 }).then(function(e_gas){
    estGasPrice =e_gas;
 });

const rawTx = {
    nonce: web3.eth.getTransactionCount(fromAdd)+1,
    gasPrice: estGasPrice,
    gasLimit: web3.utils.toHex(2100000),
    to: contractAddress,
    data: myData
  }
const tx = new ethTx(rawTx);
tx.sign(new Buffer(process.env.TEST_WALLET_PRIVATE_KEY,'hex'));

const serializedTx = tx.serialize();
const raw = '0x' + serializedTx.toString('hex');
web3.eth.sendRawTransaction(raw, function(hash) {
res.send(hash);
});

}catch(err){
    next(err);
}});
module.exports = router;

but I got an error :

Error: Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: [object Promise]1
    at Object.exports.toBuffer

how I send the raw transaction?

thank you.


texts:
I am testing a contract, when I run the truffle migrate command, in my deplyment contract located in the migrations folder the following error appears:

var HelloWorld=artifacts.require (“./HelloWorld.sol”);
                                  ^

SyntaxError: Invalid or unexpected token

I am using solidty 0.5.0, What is wrong with the syntax of the .js file.


texts: How to identify two different erc20 token in solidity contract?

texts: If I want to develop a dapp, and in that along with ethereum users will have the option of contributing with ERC20 tokens, how can i identify tokens from each other cause as per my understanding anyone can create ERC20 token with same name and symbol, so how to make sure that we are receiving real tokens?


texts: Accessing 'constant' variables not working

texts:
I need to access some constant variables in a smart contract, but I'm not being able to.
Here's my code:

decimals = await contractInstance.methods.decimals().call();

'decimals' is a constant in a ERC20 contract deployed in Ropsten.
I thought the compiler generated getters for those automatically, but I'm getting this error:

TypeError: contractInstance.methods.decimals is not a function

Is there another way to fetch a constant except from it's default getter?
Note: The contract is already published and it don't have an explicit method to get the 'decimals' constant.


texts: How can we organize storage of a folder or object tree in Solidity?

texts:
Inspired by Garbage collection

A hierarchical storage pattern of objects inside objects is a pretty common device. How could one organize such a thing and avoid problems with increasing gas cost at scale?


texts: Run my code on Ropsten network without using Infura

texts:
As I understood, Infura is a remote node give us the ability to interact with the network if we do not want to download the full node in our machine.
If I understood that correctly, can I download the full Ropsten node in my machine and communicate with Ropsten network from my machine without using a intermediate like Infura
If yes, how I can connect to ropsten from truffle.js to deploy my smart contract on ropsten?
I did research and found that I can download the full node using:
geth --syncmode "fast" --cache=1048 --ropsten --rpc --rpcapi "eth,net,web3" --rpccorsdomain '*' --rpcaddr localhost --rpcport 8545 console

It will take time to sync the full node in my machine.
If that correct ? if yes, how can I fund the accounts to deploy the code ? can I use the MetaMAsk account ?
Thanks


texts:
From the looks of things, most ICOs are scams. It's an easy way to take in money and once it's in there isn't much incentive for the founders to continue working?

How is it possible to do an ICO where the founders only get paid when they achieve certain milestones?

Are there examples of trustworthy ICOs that limit the amount of fraud committed by the founders with mechanisms built into the smart contract/funding procedure?


texts: How can I use "@" (at sign) syntax with Remix?

texts:
I've seen multiple times Solidity contracts, which are using import "@somename/.../SomeContract.sol" syntax. Here's the example:
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract TestContract is IERC20 {
    uint asdasd;
}

How can I use this syntax with Remix? When I'm trying to use Remix (solc 0.5.17), I'm getting the following error:


texts: web3.js-1.0.0-beta.36 - I can not connect to INFURA

texts:
Help with the solution

Installed the web3.js-1.0.0-beta.36 package on the hosting server.
Register and receive from Infura https://mainnet.infura.io/v3/myadress
3.Where and what should I register to properly connect web3 to Infura

I would be grateful for any help.

In the Index.js file I change and line 55 gives me an error, what did I do wrong?


texts: web3.eth.sendTransaction unknown account error

texts:
I am running a node locally on the Rinkeby blockchain.

I have an account on the node at the address 0xcA4E218Eb3954f899FE5d8E0B9ddcf3E402E86e7. This account has 3 eth.

I have another account that I generated through web3.eth.createAccount at the address 0x680A47A1D2080Ce349160c0A12B0326259bB7B04. This account also has 3 eth.

When I try to run the below, I get the error: unknown account. Thoughts?

this.web3.eth.sendTransaction({
      from: '0x680A47A1D2080Ce349160c0A12B0326259bB7B04',
      to: '0xcA4E218Eb3954f899FE5d8E0B9ddcf3E402E86e7',
      value: '5000'
    }).then(function (receipt) {
      console.log(receipt)
    }).catch(console.log)


texts: NFTs with fractionalized ownership and royalties in perpetuity

texts:
Is it possible to code an NFT-compliant smart contract which has the following properties?

There are multiple owners instead of just one
Royalties are paid out to all owners in perpetuity, across all secondary market sales

Currently here is what I have tried: I created an ERC-721 compliant token, and issued ERC-20 tokens against it (essentially fractionalized it). Whoever holds the ERC-20 tokens are then fractional owners of the said NFT. However, I had to wrap the NFT in a separate smart contract in order to issue the ERC-20 tokens against the asset. Now once/if this NFT is sold to a new buyer, the ERC-20 tokens are redeemed and each owner gets their share of the proceeds. There is no way - under this scheme - to enforce royalties in perpetuity for the original owners.
Can an industry expert provide an illustrative example of how my original question can be accomplished?
And if the current standards do not allow this to happen, getting that knowledge would be good too.
I read various literature that NFTs solve the royalty issue, so I was trying to experiment with all the possibilities. I'm a originally a server-side dev, and a newbie in the smart contract universe (thus the noob question).


texts: Is it possible for a contract to erc20 approve another contract?

texts: I want my contract (#1) to be able to approve another contract (#2) to transfer erc20 tokens from #1 to #2. Is this possible?


texts: Uniswap Router deployment error: "UniswapV2Router02" -- Cannot create instance of UniswapV2Router02; no code at address 0xxxxxxxxx

texts:
I am trying to fork Uniswap and deploy on Ropsten testnet for educational and testing purposes. From what I gathered, it seems that we need to first deploy the UniswapV2Factory contract, followed by the UniswapV2Router02 contract. I cloned both from here and  here respectively. I haven't made any changes to the code. I can deploy the factory contract just fine using truffle. However, I am getting the following error while deploying the router contract.:

Error:  *** Deployment Failed ***
"UniswapV2Router02" -- Cannot create instance of UniswapV2Router02; no
code at address 0xXXXXXXXXXXXXXX.

This is the script I am using to deploy UniswapV2Factory:
const Factory = artifacts.require("UniswapV2Factory.sol");

module.exports = async function (deployer, network, addresses) {
  await deployer.deploy(Factory, addresses[0]);

};

and the code to deploy UniswapV2Router02:
const Router = artifacts.require('UniswapV2Router02.sol');

module.exports = async function (deployer, network, addresses) {
    const WETH_ADDRESS = '0x0a180a76e4466bf68a7f86fb029bed3cccfaaac5';
    const FACTORY_ADDRESS = '{factory address}';

    await deployer.deploy(Router, FACTORY_ADDRESS, WETH_ADDRESS);
}

I have changed the solidity compiler version to 0.5.16 for the factory and 0.6.6 for the router.


texts:
I understand that dapps are executed on the EVM and that the hardware requirements for Ethereum are low (aside from hardware space).

However, I do not understand what the overall performance of dapps is;
For instance, when developing a mobile app I know that the smartphone's hardware sets the limitations regarding the app's complexity.

How does that translate to smart contracts / dapps?

Are all computational resources added up because all nodes execute the smart contract?


texts: Conflicting reports on sync mode and inability to see balances

texts:
I've been trying to maintain a full node for several months. It seemed to be working until I noticed zero balances this morning. etherscan.io site confirmed that balances are not zero, so investigating further, I see on my node that in spite of having accumulated a terabyte of blockchain, and until recently been able to view balances properly:

> eth.getBlock("latest").number
 0

But:

> eth.syncing
{
   currentBlock: 8225916,
   highestBlock: 8226042,
   knownStates: 85829054,
   pulledStates: 85828145,
   startingBlock: 8224824
}

The process running this has always been:

31300 pts/12   Sl+  222:33 /cnodes/engines/bin/geth --syncmode full --cache=2048 --rpc --maxpeers 100 --verbosity 2

Yet I see messages logged like this:

 WARN [07-26|07:10:11.117] Dropping unsynced node during fast sync  id=711b6ab8f303771e conn=dyndial addr=103.75.212.222:30303  type=Geth/v1.8.2-stable-b8b9f7f4/linux-amd64/go1.9.4

I am wondering what I might have done to put it in this state, perhaps by restarting geth in bad circumstances such as after running out of space and providing more.  I have always specified full sync.  This is certain because it is script driven and the option is hard coded.
I'd much appreciate any enlightenment that anyone can offer.


texts: Can one smart contract purchase > ethereums total market cap?

texts:
Let's say I have a special diamond that's worth more than the total market cap of Ethereum. If I want to connect that diamond to the Ethereum blockchain (through a unique serial number) to verify its owners during every transaction it makes, would it be possible?

If yes, how can the payment be made? It wouldn't be possible to buy all ethers and use them to buy the diamond since the value of the diamond is higher, but would it be possible to make the payment through a regular bank transfer? Is it possible to connect a smart contract with a bank transfer?


texts: How to ensure the authenticity of the block header obtained by the light node

texts: When I join the Ethereum network, I ask for block header data from neighboring nodes. How can I guarantee the reality of data？What if the neighbors conspired to give me bogus data？


texts: From ENS Name to hash AND print in console

texts:
I'm just studying about Ethereum, ENS and and and..
Actually I try to compute an ENS .eth Name to a hash.
In
https://app.ens.domains/name
I baught a ENS .eth Name with the Ropsten Testnetwork.
Now I have some things like registrant and controller (which is obviously my Ropsten ID).

So far so good. My aim is e.g. to ask in console what the hash of my .eth adress is and vice versa.
I try to program this with the web3.py libary but I don't have any clue how to resolve this.

Could someone give me a hint

Cheers


texts: How can users call the functions of an ERC20 token that was created by another contract (within a crowdsale contract)?

texts:
Using Ethereum wallet if I create a token and deploy it I can then interact with it and use the functions of that token (e.g. transfering tokens).

However, if I deploy a crowdsale contract and that contract creates the tokens by calling the constructor of the token contract within it I cannot interact with the tokens. I have added the tokens to the watch list using the name, symbol, decimals and contract address, so that I can see correct balances for my wallets, but I cannot use the tokens' functions (such as the transfer function).

How can I make these token functions usable?


texts: how can i get details of transactions from any block number without using event?

texts: Without using event i want to fetch all the details of how many transaction with transaction id are contained in any specific block by just putting block number?


texts: Inside a smart contract, is it possible to get latest mined block's number and its hash?

texts:
As following answer for How can I find out what the highest block is? guided: we can get the latest mined block's number and its hash inside geth as follows.

> eth.syncing.currentBlock
569367
> eth.getBlock(eth.syncing.currentBlock).hash
"0xac51e27c3fe38af1a0aeb2867a741ba6aa16780e435a586d934ccea3a71874b1"

[Q] Inside a smart contract, is it possible to get the latest mined block's number and its hash? or should I keep an array inside my contract and when new block is mined, externally (my_contract.addNewHash(<some_hash>)) should I put its hash into my array for my contract to read from?

I have tried following keywords from Solidity's website: https://github.com/iurimatias/embark-framework/wiki/Solidity on Solidity Browser and Populus, for example: block.number, block.blockhash, but I do face with following error:

Untitled:6:17: Error: Expected identifier, got 'Semicolon'
    block.number;

Thank you for your valuable time and help.


texts: So, I have this token called XBT, Elastic Bitcoin, in my wallet. 0x64fB96d0395f6bf105F35233911e3dF2C5bf4Ce8 Is the contract address. My address is 0x9B3De9eF1AbB57750e762e8c0762BF86a2F21033. Etherscan says that I have 9 of them, each worth $741. This is surprising, because MetaMask says I have .00014 of them, worth .01107. Other wallets say other things entirely. What is going on here and what is the true value?


texts: I think I have been scammed with a fake token on uniswap. Yesterday I bought a safepal token in exchange for ethereum. After I started to suspect I tried to swap back the safepal token to ethereum. When I try to swap again to ethereum I get this message “The transaction cannot succeed due to error: Undefined. This is probably an issue with one of the tokens you are swapping”. This is the contact address 0x06d05A559027FE3a405CCA1d48C4504906fB8a39 . I was reading it and I don’t understand where the swapping limitation is and if there is some chance to swap back to ethereum. If anybody can help me to recover my funds I would be very grateful. Thanks.


texts:
I want to sign and verify a transaction offchain, but I can't really find a proper example/documentation online from start to finish that explains the whole process. Can somebody point to some reference?

If not, and if you do know how to do this, Can you illustrate it with a simple example that would sign a transaction to call the following function of a contract? and take into account that the verifier should be a different  account than the signer.

contract simpleContract {

 function simpleContract() public {
 creator = msg.sender;
 }

 uint public value;

 function testingStateChannel(uint simpleValue){
 value=simpleValue;//function to be called in offline signed transaction
 }

 function getSimpleValue() view public returns (uint){
  return value;
 }
}

I would appreciate some solution that signs using Web3j (nodejs) or alternatively geth solidity.


texts: Closed, Creating a method to airdrop ERC20 Token B to the holders of ERC20 Token A

texts: I've been attempting some form of solidity code to automate the airdropping of Token B to the holders of Token A almost all day, but I still couldn't find much that works. How could I do this?


texts:
I have a few questions about the way the blockchain syncs.

I noticed on a couple of posts while researching that it's possible to start the block chain from a certain block. It was suggested that if you had a small quantity of files that contained blocks say 1800000 - 1850000 in the right folder, then the sync would start from that number as opposed to 0.

This seems like a good shortcut if true, can anyone confirm this?

If it is true, I am wondering if there is any benefit to having the full blockchain as opposed to just a fraction. Would hashing speeds be increased?


texts: Deploying ERC 725 (Blockchain Identity IDs) on Quorum?

texts:
I refer to ERC 725 -- Blockchain for Identity. From a smart contract code angle, it looks to be just another smart contract that I deploy onto the blockchain.

Am wondering if Quorum can be used to deploy blockchain identity at scale?

References:
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-725.md


texts: How can I find all registered ENS domains and subdomains?

texts:
I would like to determine all of the active ENS domains and their subdomains, from ".eth" on down.

I've read over the ENS spec and searched the web, but I haven't found a way to do it.

So I suspect that either it's not possible, or else really hard?

Also, so far I've been using go-ethereum and github.com/wealdtech/go-ens in trying to do this work.

Thanks for any ideas.
Robert


texts: Remix & Metamask: displaying more than one account

texts:
I'd like to test a contract on Remix and since it uses Oraclize, I can't use the javascript VM. So I'm connecting to Ropsten by selecting Injected web3 as environment on Remix.

The problem is that I need to make more than 1 account available for testing, but Remix will only load the currently selected account on Metamask.

Is there a way to access more accounts so de dropdown box allows me to switch between them?

I already tried switching accounts on Metamask but then Remix will need to refresh in order to load the current account, which resets the UI. And I know that I could load the contract again by entering its address, but the problem is that his whole process takes a lot of time for Remix to load the new selected account.


texts: Does it make sense to make messenger on blockchain?

texts:
Chatting, messaging usually implies privacy. Does it make sense to send transactions that are visible on blockchain to everyone?

Or the content of messages is not visible to everyone, just the fact that 2 people exchanged messages?


texts: Recover public key from sign generated by AWS Cloud HSM - Golang

texts:
I am signing a transaction by using a private key in AWS Cloud HSM. But not able to recover the correct public key from the signature. Every time I try to run ECRecover method, it generates different public key.

I am able to retrieve the R and S from ECDSA signature generated by AWS Cloud HSM in the following code:

import (
  "github.com/btcsuite/btcd/btcec"
  ethcrypto "github.com/ethereum/go-ethereum/crypto"
)
// SignatureValues returns signature values [R || S]
func (e *Ethereum) SignatureValues(sig []byte) (r, s *big.Int, err error) {
    r = new(big.Int).SetBytes(sig[:32])
    s = new(big.Int).SetBytes(sig[32:64])
    return r, s, nil
}

And below code snippet tries to find the correct signature to be verified:

    sig := make([]byte, 65)

    denTwo := big.NewInt(2)
    rightS := big.NewInt(0)
    curve := btcec.S256()

    /*
        URL: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2.md
        All transaction signatures whose s-value is greater than secp256k1n/2 are now considered invalid.
        The ECDSA recover precompiled contract remains unchanged and will keep accepting high s-values; this is useful
        e.g. if a contract recovers old Bitcoin signatures.
    */
    rightS = rightS.Div(curve.Params().N, denTwo)

    if rightS.Cmp(S) == -1 {
        S = S.Sub(curve.Params().N, S)
        log.Println("S: ", S.String())
        rbytes, sbytes := R.Bytes(), S.Bytes()
        copy(sig[32-len(rbytes):32], rbytes)
        copy(sig[64-len(sbytes):64], sbytes)
        log.Println("Result : ", verifyECRecover(hash.Bytes(), sig, expectedPubKey))
    } else {
        rbytes, sbytes := R.Bytes(), S.Bytes()
        copy(sig[32-len(rbytes):32], rbytes)
        copy(sig[64-len(sbytes):64], sbytes)
        log.Println("Else Result : ", verifyECRecover(hash.Bytes(), sig, expectedPubKey))
    }

    verification := ethcrypto.VerifySignature(expectedPubKey, hash.Bytes(), sig)

Below code method is VerifyECRecover:

func verifyECRecover(hash, sig, expectedPubKey []byte) bool {
    for v := 0; v < 2; v++ {
        sig[64] = byte(v)
        if pubkey, err := ethcrypto.Ecrecover(hash, sig); err == nil {
            if bytes.Equal(pubkey, expectedPubKey) {
                log.Println("Matched")
                return true
            }
            log.Println("Not Matched")
        } else {
            log.Println("Error: ", err)
        }
    }
    return false
}

I am not able to get the correct public key, so that I can submit the transaction to ethereum blockchain. Can anyone help me in solving this?


texts: Do Ethereum and Bitshares have similar concepts or technology?

texts:
In the Bitshares official website they're explaining the functionality of the tool and in general look like Ethereum.

What makes Ethereum different of Bitshares?


texts:
Anybody explains what does this statement means,
'Blockchain is not a snapshot of current state'.


texts: VS Code Syntax error when emitting events in Solidity 0.4.21

texts:
I'm having a syntax error in VS Code in the parts where I emit events using new notation for Solidity v0.4.21.

Remix doesn’t raise any errors, though.

My User Settings in VS Code contain "solidity.compileUsingRemoteVersion": "latest", and compiler doesn't raise error on emit itself, rather gives this message:

Syntax error: Expected "!=", "%", "%=", "&", "&&", "&=", "*", "*=", "+", "++", "+=", ",", "-", "--", "-=", "/", "/*", "/=", ";", "<", "<<", "<<=", "<=", "=", "==", ">", ">=", ">>", ">>=", ">>>", "?", "^", "^=", "|", "|=", "||", comment, end of line, or whitespace but "(" found.

Here's how it looks like (2nd emit event is ok for some reason):


texts: What can smart contract creator of Token on Ethereum Platform do to modify, change, upgrade or screw everybody on a DeFi platform?

texts:
Let's say an anonymous creates a Token called "baked" with Total supply of 1 million, and he keeps only 10k, and I buy the rest 990,000
He then uploads the Token on Decentralized Exchanges such Uniswap, Sushiswap, Quickswao, Panckaswap, etc.
Then me and everybody start adding Liquidity into all of them Decentralized exchanges, (they all provide you with a receipt, so you can claim you share, so there is no lost)
What can smart contract creator do to screw everybody? (the contract was audit and is "LEGIT")
Wouldn't be the same if the creator of the smart contract of Chainlink decides all the sudden to mess up with everybody?
The contract is public for everybody to see, and audit, would it make a difference if nobody has access to the source code?


texts: Expected token Semicolon got 'Identifier' Transfer(msg.sender, _to, _value);

texts:
function transfer(address _to, uint256 _value) {
    if (balanceOf[msg.sender] < _value) throw;                // Check if the sender has enough
    if (balanceOf[_to] + _value < balanceOf[_to]) throw;      // Check the overflows
    if (frozenaccount[msg.sender]) throw;                     // Check if frozen
    balanceOf[msg.sender] -= _value;                          // Subtract from the sender
    balanceOf[_to] += _value                                  // add the same to the recipient
    Transfer(msg.sender, _to, _value); (right here error!)                        // notify anyone listening that this transfer took place
}

all code
https://gist.github.com/Sexstasy/86e8b243422aef64c3182fbd0ef1671e


texts: How can i automatically divide payments from mining

texts: I run a mining farm along with other partners. Using eth-proxy I can only set one payout address for each machine. I'd like to setup a contract so that any payments that go to the primary mining payout address are automatically split up and sent to 3 addresses, with each address getting a percentage.


texts: Type uint256 not decrementing in a struct data type

texts:
I have a basic struct:

struct Test {
  uint256 rank;
}

Stored in a mapping:

mapping(bytes32 => Test) store;

I am trying to decrement the 'rank' of a specific Test from the mapping:

Test storage test = store[key];
test.rank--;

The rank of the corresponding struct in the mapping doesnt change and I cannot figure out why.

I also tried:

Test memory test = store[key];
test.rank--;
store[key] = test;

But none seem to work. Any hint is much appreciated thanks in advance.


texts: Using home brew to install ethereum but it keeps returning a make error

texts: I am using home brew to install  ethereum but it keeps returning this error. Is there anyway I can fix it?


texts: How can I refer to my actual ether balance in a smart contract?

texts: Not the tokens created in a contract but the balance which I allocate in the genesis.


texts: MetaMask verification screen doesn't show amount or token when I use 'approveAndCall' to transfer tokens to a contract

texts:
When I use 'approveAndCall' to transfer tokens to a contract, the MetaMask verification screen doesn't show the amount, or the token name.

let contract = new web3.eth.Contract(gsERC20abi, '0x1f0735E0CaA3e2dc0f6C213274981FbF9D8F4CDA');
contract.methods.approveAndCall("0x9AF3BC7541D38B729F46fdd47B403AF5B229f6CF", 6, web3.utils.fromAscii("0")).send({from: "0xaBd70Cb55617EBC738607E0786aBE76Ad61e2f37"})
.on('transactionHash', function(hash){
  console.log(hash);
});

The MetaMask verification screen shows "0" as the amount for the "APPROVE AND CALL" process, and doesn't show the token name.
The tokens are successfully transferred from the active account to the contract, but the MetaMask verification screen doesn't show what is about to happen. That is not good!

However, when I instead transfer tokens to an account, the MetaMask verification screen correctly shows the amount and the token name:

let contract = new web3.eth.Contract(gsERC20abi, '0x1f0735E0CaA3e2dc0f6C213274981FbF9D8F4CDA');
contract.methods.transfer("0x2f4Edafe16509913198950226Bf148616D91BeE3", 3).send({from: "0xaBd70Cb55617EBC738607E0786aBE76Ad61e2f37"})
.on('transactionHash', function(hash){
  console.log(hash);
});


texts: Solidity: How to replace specific string position with letter?

texts:
I would like to replace a letter at a specific position of a string with another letter.

function _stringReplace(string memory _string, uint256 _pos, string memory _letter) internal pure returns (string memory) {


texts: Why is my private ethereum network stuck at "Recalculated downloader QoS values" while trying to mine?

texts:
I'm using Mac OS High Sierra version 10.13.6

My customgenesis.json file is this.

{"config": {
"chainId": 15,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0 },"nonce": "0x0000000000000042","timestamp": "0x00","parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000","extraData": "0x00","gasLimit": "0x08000000","difficulty": "0x0400", "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000","coinbase": "0xd77821c8b92e3e29bc63c8f2a94a6c6a64b28b53", "alloc": {
"0xd08658a4e33bf6ca786b9870d91ec51a0dc72e56": {"balance": "10000"} }}

After creating the customgenesis.json, I ran the following command

geth --datadir ./mychaindata init ./customgenesis.json

This created my blockchain directory.
After this I ran the following command to start the private network.

geth --rpc --rpcapi="db,eth,net,web3,personal" --rpcport "8545" --rpcaddr "127.0.0.1" --rpccorsdomain "*" --datadir ./mychaindata --nodiscover --verbosity 4 --unlock 0

I even tried the following command to start the private network. And tried with and without --nodiscover flags.

geth --datadir=.\mychaindata\. --rpc --rpccorsdomain "*" --nodiscover --unlock 0 --mine

Once I attach to the pic file using a different console, and start mining using the command miner.start()

I also tried specifying 100 threads using miner.start(100). Ended up getting the same results.

I thought maybe the difficulty was set high and hence my CPU could not mine. So I ran `etc.getBlock("latest").

Any help or input is appreciated,
Thank you.


texts: How to call a function with params and check them

texts:
I want to create a smart contract that users can send a number to and receive an amount of ether.

function airdrop(uint val) public payable {
    require(airdrop == true);
    if (val == 0x31){
        msg.sender.transfer(1 ether);
        airdrop = false;
    }
}

If users send a 1 they get the ether. How can I do this?


texts: ERC-1155 safeTransferFrom() issue: contract doesn't have permission to send tokens from itself

texts:
I have a function in an ERC1155 contract that looks like this:
function foo(uint _id, uint _amm) external{
    safeTransferFrom(address(this), msg.sender, _id, _amm, "");
}

Assume the contract does in fact have the tokens it's attempting to send as it does in the real non-simplified code.
Also I have the onERC1155Received and onERC1155BatchReceived functions copied over from the Open Zeppelin holder code here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/utils/ERC1155Holder.sol
And yet, remix reverts the function because it doesn't have approval to send the tokens. But it's sending it from itself. Anything I am missing here? I'm assuming it has to do with the holding code.


texts:
I had nice running latest geth (1.10.3) and I did a clean exit ctrl+C (it did exited quite fast which is unusual), then started again and geth runs but not syncing and constantly gives warning
Served eth_getBalance  err="mising trie ......."
I thought on database corruption and did removedb (only main) and then I rebuild from ancient db via snapsync.. quit fast....but I still have this
Served eth_getBalance err="invalid argument 1: blocknumber too high"
what could be cause and how to solve it?
Thanks


texts: Since solidity has not float types, how does it computes products between "floating point numbers" and ints?


texts: ipfs.files.add(Buffer) function causing TypeError: Cannot read property 'add' of undefined

texts:
I am trying to upload an image to ipfs using ipfs.files.add() function
but it is causing me this error

Uncaught TypeError: Cannot read property 'add' of undefined
at App.onSubmit (App.js:70)
at HTMLUnknownElement.callCallback (react-dom.development.js:147)
at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
at invokeGuardedCallback (react-dom.development.js:250)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
at executeDispatch (react-dom.development.js:571)
at executeDispatchesInOrder (react-dom.development.js:596)
at executeDispatchesAndRelease (react-dom.development.js:695)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:704)
at forEachAccumulated (react-dom.development.js:676)
at runEventsInBatch (react-dom.development.js:844)
at runExtractedEventsInBatch (react-dom.development.js:852)
at handleTopLevel (react-dom.development.js:5025)
at batchedUpdates$1 (react-dom.development.js:19916)
at batchedUpdates (react-dom.development.js:2246)
at dispatchEvent (react-dom.development.js:5105)
at interactiveUpdates$1 (react-dom.development.js:19978)
at interactiveUpdates (react-dom.development.js:2267)
at dispatchInteractiveEvent (react-dom.development.js:5081)

The code:

captureFile(event){
 event.preventDefault();
 const file=event.target.files[0];
 const reader=new window.FileReader();
 reader.readAsArrayBuffer(file);
 reader.onloadend = () => {
 this.setState({buffer:Buffer(reader.result)});
 console.log('buffer',this.state.buffer);
 }

}
onSubmit(event){
 event.preventDefault();
 ipfs.files.add(this.state.buffer, ( error , result ) => {

 if(error){
   console.error(error);

 }
 else{
   console.log("success");
 }
this.setState({ipfshash : result[0].hash});
console.log('ipfshash',this.state.ipfshash);
 }

 );
 }


texts: Can I create 100 unique addresses for the same wallet?

texts: Can I create say 100 unique Ethereum addresses for the same wallet/smart contract? I can then assign the different addresses to 100 different affiliates.


texts: How do I upload a folder of smart contracts to Remix?

texts: I'm pretty sure this used to be a feature. What am I missing?


texts:
I still have an old Ether.li wallet. Any recovery I tried failed. Possibly because I don't know enough. I have the address, keys etc but I am stuck. The old Parity/Mist route does not seem to work for me because Mist is not available anymore and parity has changed beyond recognition,..
Does anyone have any hints, tips, tricks? - Happy to pay for help.


texts: Ethereum Wallet sync completed and ETH balance went to 0

texts:
I ran Ethereum Wallet for the first time on my Macbook Pro and, as it was syncing with TestNet, I selected Develop -> Start Mining. I saw the ETH balance increase steadily to 65 but then, it seemed that just when the sync completed, ETH balance went to zero, and has stayed at zero since then. I tried stopping and re-starting mining but that did not help.

Then, I noticed Develop -> Toggle Developer Tools -> Wallet UI. Clicked on that and noticed the following error in the console:

Failed to clear temp storage: It was determined that certain files are unsafe
for access within a Web application, or that too many calls are being made on file
resources. SecurityError

This seems to be related to the issue. Searching by this error message did not bring up any existing posts here, so I decided to post this question. Can anybody help throw some light on this?

Update: Just noticed that my ETH balance is now 6.88. Maybe the Javascript error can be ignored? Not sure why initially, balance was increasing in steps of 5 ether, then went to 0 and increasing very slowly now. My guess is that, by default, the syncing and mining started on the Main net and then I switched to Test net, it went back to 0. The low volume on Test net could be the reason for it taking a long time for any ETH balance to build up.

Update 2: I saw the following text today at https://github.com/ethereum/go-ethereum/wiki/Mining, which is more likely to be the correct reason of what I saw.

  Note that it will happen often that you find a block yet it never
  makes it to the canonical chain. This means when you locally include
  your mined block, the current state will show the mining reward
  credited to your account, however, after a while, the better chain is
  discovered and we switch to a chain in which your block is not
  included and therefore no mining reward is credited. Therefore it is
  quite possible that as a miner monitoring their coinbase balance will
  find that it may fluctuate quite a bit.

I will wait for some time in case someone more knowledgeable has something more to add to this. If not, then I will convert this update to an answer.


texts: WEB3 web3.personal.listAccounts over IPC Callback

texts:
I am trying to call web3.personal.listAccounts. It  can only be called asynchronously.

I get this error
Error: You tried to send "personal_listAccounts" synchronously. Synchronous requests are not supported by the IPC provider.

Does anyone know the syntax to call this asynchronously?

Where does the callback function fit here?

Thank you


texts: Is it possible to write the ACL smart-contract?

texts: I wonder, is it possible to create Access Control List and change user rights by smart-contract in private blockchain? Can I set up the security policy by smart-contract?


texts: Can't call another contract constant function in Remix in Web3 provider mode, but it works in Javascript VM

texts:
Remix behaves differently when running Javascript VM and web3 provider mode.

I have two contracts:

contract ERC20Basic {

  function totalSupply() public view returns (uint256){}
  function balanceOf(address who) public view returns (uint256){}
  function transfer(address to, uint256 value) public returns (bool){}
  event Transfer(address indexed from, address indexed to, uint256 value);
}

and AegisMarketing contract which is calling functions from ERC20Basic.

I have a problem calling AegisMarketing GetBalanceTest function.

function GetBalanceTest() public constant returns (uint256)
{
      return token.balanceOf(address(this));
}

which in ERC20Basic is defined as follows:

  function balanceOf(address _owner) public view returns (uint256 balance) {
    return balances[_owner];
  }

If I compile and deploy those contract in Remix in Javascript VM mode then everything works fine. I get correct value running both AegisMarketing.GetBalanceTest() and also ERC20Basic.balanceOf() function.

When I deploy in my truffle to local geth or via Remix Web3 provider to my local geth AegisMarketing.GetBalanceTest always returns 0,but when I check balance of AegisMarketing contract in ERC20Basic itself I get correct value.

General idea is that AegisMarketing contract is using ERC20Basic token contract to airdrop tokens to some accounts. AegisMarketing contract must have some positive balance in ERC20Basic contract to be able to aidrop those tokens and this is what I am trying to check.

The whole project is here:
https://github.com/robertmagier/AegisMarketing

AegisMarketing contract is in contracts/AegisMarketing.sol

ERC20Basic token is in contracts/Token.sol

This is how it looks in Remix. I checked many times that I am checking correct Contract address in balanceOf function. And it works in Javascript VM mode in Remix.


texts: Unfulfilled Promise From A Metamask Transaction

texts:
I'm having a problem with my JS code pausing on the let result line.

Metamask prompts me to approve the transaction initiated in the line (which I do), but then doesn't proceed any further.

As the await keyword forces the code to pause until the promise is fulfilled, it appears as if the promise is not being fulfilled.

handleButtonPress: async function(event) {

    console.log(1);

    let account = await web3.eth.getAccounts();

    console.log(account);

    let result = await App.contracts.Marketplace.methods.createStorefront('store2', 'shoe store2').send({from: account[0]});

    console.log(2);

}

Any ideas? Cheers.


texts:
Im trying to write a python script that can generate a new wallet for that user, but I need to be able to keep the private key.

I followed this : Stack overflow answer
And got these results:

import os
from ethereum import utils
key = utils.sha3(os.urandom(4096))
print key
Out[5]: 'L\xf7\x98\x06\xb9\xbe>?
c\x88\xd3\xa7\x05\xdd\xe8AtNe\xf3\xe7Pc\xed\xd8L~\\\xcc\rq\x18'
raw = utils.privtoaddr(key)
print raw
Out[7]:
'n\x98V8\x05\xa1\x05\x9b\x18\xca%\xb3\xed\xd0\xd5\xa9I\xf8\x97\x15'
add = utils.checksum_encode(raw)
print add
Out[9]: '0x6e98563805A1059B18ca25B3edd0d5a949f89715'

So, I was able to get an address, but I'm not exactly sure what am I seeing here in the "key" and "raw" variables

Os is Ubuntu 16.4, running python 2.7.12
Note that this is a small personal project for learning, so I don't really mind any "security" issues

Edit:
I was able to use this to create to do what I needed, I will leave this question open since Im still interested about my first way.
https://github.com/vkobel/ethereum-generate-wallet


texts: What is timelock crypto and how can it be used for random number generation?

texts:
In this video Vitalik Buterin talks about timelock crypto and that it's his favorite option for provably fair random number generation https://youtu.be/p5qwbOkCZSc?t=4958.

Can anyone explain what timelock crypto is and how it can be used for RNG?


texts: Script with web3.eth.getAccounts() never ends

texts:
I have a little script just with the following function:

const Web3 = require('web3');
var web3Provider = new Web3(new Web3.providers.WebsocketProvider('ws://127.0.0.1:3001'));
const web3 = new Web3(web3Provider);

web3.eth.getAccounts().then(e => console.log(e));

But when I receive the callback, the script is never closed, it continues running (doing nothing). How can I stoped it? why it happens?


texts: Is there a way to pass helpful error messaging from contract to web3?

texts:
Does anyone know if there is way to pass helpful error messages from a contract to web3? For example:

require(value > balance); // would be great if second arg was message

When testing with truffle I only get VM Exception while processing transaction: revert

I guess something I could do is to pass a uid to my function from the client thats created right before the call and emit an event with helpful messages and match uid's? for example:

event ErrorMessage(bytes32 uid, string msg);

function doSomething (uint value, bytes32 uid) {
    if(value > balance) {
        ErrorMessage(uid, 'SomeErrorCode');
        revert();
    }
}


texts:
How are Ethereum contracts tested? I've seen Truffle which referrers to itself as an Ethereum development framework. Are there any other frameworks and what is their level of maturity? Is there a de facto standard framework used by most contract developers?

How would one go about testing the Greeter contract (https://chriseth.github.io/browser-solidity/) for example?


texts: Running a full Parity node with SSD disks in a RAID 10 setup?

texts:
I am planning to run a new full node, from scratch, using Parity.

From what I understand, it is imperative to use SSD disk(s) in order to do be able to do initial sync and keep up with the network.

However, I am unable to find any references to feasibility/performance of syncing + running a full node with 4 SSD disks (Samsung SM863a) in a RAID 10 setup.

Would it be able to handle the I/O load, or it is better to run single SSD? Would RAID setup actually wear the disks more/sooner?

I have tried running a test setup, on a server (32GB RAM, of which I allocated most to caching options in Parity, with 16GB cache-size) with 4 HGST HDDs, in RAID 10, but after 3 days of running it is around block 2,700,000 and is slowing down, so it would take around 60 days at this rate to fully sync.

Many posts that I found always refer to HDDs being a problem and apparently SSD disk is the way to go, but I really don't want to invest into a new setup just to find out that it will again sync at the very slow speed.

Any experiences and/or advices are very welcome :)


texts: How to loop through an array of addresses and send ether

texts:
I am trying to figure out how, after adding addresses to the addressArray Array via the addAddressandShareAmount function, can I loop through each address and send each address 1 ether
via the payShareHolders function? Thanks.
pragma solidity ^0.6.0;

contract MyWallet {

    address[] addressArray;
    uint[] shareAmountArray;

    function receive() external payable{
    }

    function addAddressandShareAmount(address payable adrs, uint numberOfShares) public {
        require(msg.sender == 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4);
        addressArray.push(adrs);
        shareAmountArray.push(numberOfShares);
    }

    function getPosition(uint index) public view returns (address) {
        return addressArray[index];
    }

    function payShareHolders(address payable address1, uint256 amount1) public {
        require(msg.sender == 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4);
        for(addressArray[0]; addressArray[addressArray.length]){
            address.transfer(1 ether);
        }
}


texts:
Suppose you're trading against an AMM with a static invariant, such as Uniswap v2. I define "static" as meaning the invariant containing no dynamic parameter in the price curve. A good example for a dynamic parameter is time (specifically block.timestamp in Solidity).
Does it cost more in AMM fees to split a trade into multiple pieces? If yes, why? If no, why?


texts: How to pass command line arguments in truffle exec

texts:
How to pass command line arguments to <file.js> when using truffle exec? --

truffle exec <file.js> <arg1> <arg2> ...


texts:
I've just been trying to run the web3.eth.getBlock request as a test.

If I set my web3 provider to https://api.myetherapi.com/eth then the call is successful and returns the information about the block. However myetherapi has request limits so I figured I'd install geth and run my own node for this.

I installed geth and let it synch. Changed my web3 provider tocalhost http://localhost:8545 and I just get the following:

  Unhandled rejection Error: Invalid JSON RPC response: "".

myetherapi set provider:

web3.setProvider(new web3.providers.HttpProvider('https://api.myetherapi.com/eth'));

local provider:

web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

Am I missing something key here? Thank you for the help.

var Web3 = require('web3');
var web3 = new Web3();
//not working provider.  returns the above error
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

//this provider works but it is myetherapi with api limits.
//web3.setProvider(new web3.providers.HttpProvider('https://api.myetherapi.com/eth'));
web3.eth.getBlock(5099447);


texts: Is it possible an address would have two types of balance?

texts:
I have developed a smart contract such that there are two types of tokens i.e. energy and power. I need to transfer each of them separately to an account address and as a result each address needs to have these two values (energy and power).

But when I define two types of balances for an address, i receive the following error :

Error: Undeclared identifier. Did you mean "balances"?
    return balancesPw[_owner];

I defined balances as follows:

mapping(address => uint256) balances;
mapping(address => uint256) Pwbalances;


texts:
Is there a cut-off where a variable name uses more memory? For instance:

uint public priceOfEthYesterday9AMUSAET

vs

uint public pEth

One is more descriptive, but if it's costing me gas I don't want to do this.


texts: Code A Contract To Accept A Different Token (Other Than ETH)

texts:
I'm developing a DApp for Decentraland that will accept payments in their ERC-20 token MANA. How can I code a smart contract to accept a token other than Eth? How can msg.value know the value of a different token?

Also, how can I store MANA in the smart contract (as address(this).balance)?


texts: How do signed transactions in a single Ethereum node's transaction pool propagate to mining nodes?

texts:
How does a transaction get from a regular node to the rest of the network?

What are the incentives for regular nodes to broadcast signed transactions?


texts: Multi-signature contract with offline signing

texts:
Is it possible to create a multi-signature contract that would not require a transaction for every signature (since this is quite expensive for a higher number of transactions)?
Is it possible to collect signatures offline and broadcast all of them in one on-chain transaction?
Thanks


texts:
I want to encode the parameters needed to call a contract method.
In web3js I would use web3.eth.abi.encodeParameters(types, values);
I need to do the same in python I found a function called encodeABI() which takes arguments: fn_name, args=None, kwargs=None, data=None
Unfortunately the documentation for this method is missing. So my question is how to encode these parameters using web3py?


texts: How to retrieve ETHs sent to a contract?

texts:
Lets see this simple contract:
contract MyContract {

    receive() external payable {
        require( msg.value > 0 );
        // Thank you but how can I take this ETH later if I need (not now)?
    }

}

Lets say I need to store all received ETH and later decide to give it to someone. How to command the Ethereum contract to "transfer" my ETH to someone?


texts:
I need to compare dates in solidity, so as to complete a business rule. There is no date type in solidity which ca be used to store date and perform calculations on it.
So help in this regard will be very great.


texts:
I'm going to try to put this in simple. This is the code of my contract:

pragma solidity ^0.5.0;

contract Lottery {
    address public manager;
    address[] public players;
    event Deposit(address _from, uint value);

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

    function enter() public payable {
        require(msg.value > .01 ether, 'Not enough ether');
        players.push(msg.sender);
    }

    function numberPlayers() public view returns(uint) {
        return players.length;
    }
}

And this is the code of my test:

const lottery = artifacts.require('Lottery');

contract('Lottery', accounts => {
    let instance;

    beforeEach( async () => {
        instance = await lottery.deployed();
    });

    it('should have as manager the account which deployed', async () => {
        const manager = await instance.manager.call();

        assert.equal(manager, accounts[0]);
    });

    it('should create a player if the player send some ether', async () => {
        const payment = web3.utils.toWei("0.02", "ether");
        await instance.enter.sendTransaction({from: accounts[1], value: payment});
        const numberPlayers = await instance.numberPlayers.call();
        const player = await instance.players(numberPlayers - 1);

        assert.equal(player, accounts[1]);
    })
});

Everything works fine but if I comment the Deposit event in the line 6 like this:

pragma solidity ^0.5.0;

contract Lottery {
    address public manager;
    address[] public players;
    // event Deposit(address _from, uint value);

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

    function enter() public payable {
        require(msg.value > .01 ether, 'Not enough ether');
        players.push(msg.sender);
    }

    function numberPlayers() public view returns(uint) {
        return players.length;
    }
}

I'm getting the next error:

1) Contract: Lottery
       should create a player if the player send some ether:
     Error: Invalid number of parameters for "enter". Got 1 expected 2!
      at Object.InvalidNumberOfParams (/Users/adrian.ferrereses/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/~/web3-core-helpers/src/errors.js:32:1)
      at Object._createTxObject (/Users/adrian.ferrereses/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/src/index.js:699:1)
      at constructor.detectNetwork.then.network (/Users/adrian.ferrereses/.nvm/versions/node/v10.15.3/lib/node_modules/truffle/build/webpack:/packages/truffle-contract/lib/execute.js:170:1)
      at process._tickCallback (internal/process/next_tick.js:68:7)

I'm pretty new in solidity, so I do not know if I'm doing something wrong or if I've encountered an error in version 0.5 of the solidity compiler.

These are the versions of my environment:

Truffle v5.0.15 (core: 5.0.15)
Solidity v0.5.0 (solc-js)
Node v10.15.3
Web3.js v1.0.0-beta.37

If you want to test this issue by your self, you can download the code from this repository:
https://github.com/ardiadrianadri/lotter-project

Thank you very much everyone for your time


texts:
I have recently started learning solidity. I added a function showMessage() like below:
function showMessage() public view returns(string memory) {
        return "This is a constant";
    }

In the truffle console when I call it helloworld.showMessage() it gives error:
truffle(ganache)> helloworld.showMessage()
evalmachine.<anonymous>:0
helloworld.showMessage()
           ^

Uncaught TypeError: helloworld.showMessage is not a function
    at evalmachine.<anonymous>:0:12
    at sigintHandlersWrap (node:vm:273:12)
    at Script.runInContext (node:vm:140:14)
    at runScript (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/console.js:270:1)
    at Console.interpret (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/console.js:285:1)
    at bound (node:domain:416:15)
    at REPLServer.runBound [as eval] (node:domain:427:12)
    at REPLServer.onLine (node:repl:834:10)
    at REPLServer.emit (node:events:376:20)
    at REPLServer.EventEmitter.emit (node:domain:470:12)

The method is right there as you can see here the output which is generated if I print helloworld variable:
 },
    events: { allEvents: [Function: bound ] },
    _address: '0xEb1799BA2295143d0A85FF6939c53fEC3ED42eaC',
    _jsonInterface: [ [Object], [Object], [Object] ]
  },
  getMessage: [Function (anonymous)] {
    call: [Function (anonymous)],
    sendTransaction: [Function (anonymous)],
    estimateGas: [Function (anonymous)],
    request: [Function (anonymous)]
  },
  setMessage: [Function (anonymous)] {
    call: [Function (anonymous)],
    sendTransaction: [Function (anonymous)],
    estimateGas: [Function (anonymous)],
    request: [Function (anonymous)]
  },
  showMessage: [Function (anonymous)] {
    call: [Function (anonymous)],
    sendTransaction: [Function (anonymous)],
    estimateGas: [Function (anonymous)],
    request: [Function (anonymous)]
  },
  sendTransaction: [Function (anonymous)],
  send: [Function (anonymous)],
  allEvents: [Function (anonymous)],
  getPastEvents: [Function (anonymous)]
}

Below is my entire contract:
pragma solidity 0.5.16;

contract HelloWorld {
    string private message = "hello world";

    function getMessage() public view returns(string memory) {
        return message;
    }

    function setMessage(string memory newMessage) public {
        message = newMessage;
    }

    function showMessage() public view returns(string memory) {
        return "This is a constant";
    }
}

The rest of the functions work fine.
Update:
NO I was wrong. After updating the contract and rebuilding and migrate, it is saying every function undefined after compiling and deployment. In Truffle console I initiated as:
let helloworld = HelloWorld.deployed(
helloworld.setMessage('mssg')

It worked first time.


texts: How many nodes do I need in a Quorum Private Blockchain?

texts:
I want to deploy a private blockchain using Quorum on Azure, create some ERC721 Tokens and send them various accounts inside the Private Blockchain.

How many nodes do I need for a Private Blockchain like that?