texts:
I'm programming my first Eth Contract, I'm facing a problem, the gas consumption ( estimated ) of the buy method is going really to high ( Quickly > N million gas before getting the "Maximum gas allowance exceeded" error. )

To be quick, the idea is the following:

There is a map ( 2D map ) with multiple zones that you can own ( called units here, this is why I maintain a "unitsToState" obvious mapping ).
You can purchase multiple adjacent zones at once, so a "Block" is created.
So when you purchase a new Block the contract must check if all the units inside are empty ( unitsToState[x] == 0 ). When the block is purchased, these states are set to 1.

I don't explain too much details here, because I guess the problem is mainly "Solidity" bad algorithm programming from me.

This method can be executed with arround 500k gas for fromX, fromY, toX, toY that represent a small zone, but when those are far from each other, I got the "Maximum gas allowance exceeded" error during my gas estimation .. So really I guess there is a problem ..

```
    ...

struct Block {
    address owner;
    uint fromX;
    uint fromY;
    uint toX;
    uint toY;
    string imageUrl;
    string redirectUrl;
    string text;
    bool removed;
}

uint size = 100;
mapping (uint => uint) unitsToState;
Block[] public blocks;
uint public areaPrice;
uint public areaPerUnit;

...

function buy(uint fromX, uint fromY, uint toX, uint toY, string imageUrl, string redirectUrl, string text) payable public {
    require(fromX >= 0);
    require(fromY >= 0);
    require(fromX <= toX);
    require(fromY <= toY);
    require(toX < size);
    require(toY < size);

    // Here do check of collisions.
    for (uint i = fromX; i <= toX; i++) {
        for (uint j = fromY; j <= toY; j++) {
            require(getUnitsToState(i*size*size + j) == 0);
        }
    }

    uint width = toX - fromX + 1;
    uint height = toY - fromY + 1;
    uint areaCount = width * height * areaPerUnit;
    uint price = areaCount * areaPrice;
    require(msg.value >= price);

    Block memory b = Block(
       msg.sender,
       fromX,
       fromY,
       toX,
       toY,
       imageUrl,
       redirectUrl,
       text,
       false
    );
    blocks.push(b);

    // Registrer units states.
    for (i = fromX; i <= toX; i++) {
        for (j = fromY; j <= toY; j++) {
            unitsToState[i*size*size + j] = 1;
        }
    }
}

...

EDIT:
The problem seems to be in greatest part from the part after "// Registrer units states.". But ... it doesn't really help me as long as I needs to do that ..


texts:
I have a token that has 8 digits, so the output is 4762575931 instead of 47.62575..

How can i change this so this works on UI and for metamask input?

I know there is the function to wei but this is for 18 decimals.

What do i do for 8 decimals?
I dont see a conversion for 8 decimals


texts: How do I check in solidity if interface is supported?

texts:
In the new ERC721 documents (erc721.org), the interface says that one of the functions should be:

        /**
        * @dev Returns `true` if the contract implements `interfaceID` and`interfaceID` is not 0xffffffff, `false` otherwise
        * @param  interfaceID The interface identifier, as specified in ERC-165
        */

        function supportsInterface(bytes4 interfaceID) external view returns (bool);

Does anyone have examples of this function in use and where it pulls the interfaceId from?

I have this base code written to check that it has a function, but how do a check an entire interface?

function ERC721() {
    supportedInterfaces[this.supportsInterface.selector] = true;
}

function supportsInterface(bytes4 interfaceID) external view returns (bool) {
    return supportedInterfaces[interfaceID];
}


texts: Insufficient funds when using 'signTransaction' but not when using 'unlockAccount'

texts:
I am trying to execute a transaction on a private network, using my account.

The general flow:

  Web3.js --> Parity node --> Private network

The transaction:

  Invoke a method in a contract deployed beforehand

My first approach was to unlock the account, and then send the transaction.

The procedure:

Create a transaction object for the method (see Web3 docs).
Unlock the account using my password (see Parity docs).
Send the transaction object (see Web3 docs).

My code:

let transaction = contract.methods.myFunc();
let options = {
    from: ACCOUNT_ADDRESS,
    gasPrice: GAS_PRICE,
    gas: await transaction.estimateGas()
};
await web3.eth.personal.unlockAccount(ACCOUNT_ADDRESS, ACCOUNT_PASSWORD);
await transaction.send(options);

This seems to work just fine.

However, I have later realized that unlocking my account leaves a serious security breach, as others might be able to submit requests during the time the account is unlocked. Of course, this may be prevented in several different ways I suppose (for example, by checking the sender's IP). But I believe that I would be better off executing it without unlocking the account (i.e., instead of creating a problem and then trying to solve it, avoid the problem to begin with).

So my second approach is to sign the transaction, and only then send it.

The procedure:

Create a transaction object for the method (see Web3 docs).
Sign the transaction with my account's private key (see Web3 docs).
Send the signed transaction string to the Parity node (see Web3 docs).

My code:

let transaction = contract.methods.myFunc();
let tx = {
    to: contract._address,
    data: transaction.encodeABI(),
    gasPrice: GAS_PRICE,
    gas: await transaction.estimateGas()
};
let signedTransaction = await web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction);

However, executing the code above results with the following error:

Insufficient funds.
The account you tried to send transaction from does not have enough funds.
Required 63611 and got: 0.

Obviously, since the first approach completes successfully, there shouldn't be any issue of insufficient funds here.

Can anyone please explain what I'm doing wrong?

Thank you!


texts: What benefits exactly we get from using gas in the network and why do we need it?


texts: Creating a token order book without costing gas

texts:
I'm building a DApp for ERC721 collectibles. I want to make it more like rarepepewallet.com than CryptoKitties:

RarePepeWallet has an order book for each token, matching asks with bids, just like any ol' exchange.
CryptoKitties does not; you can't place buy orders under a set sale price. Only a 'Buy Now' option.

So for my DApp, if I end up storing the order book data on the blockchain, it might cost gas for every order placed, even if it doesn't end up a successful ask/bid.

What are some ways I can circumvent this? Is 0x a possible solution?


texts:
Here is what i've done: I have create a project this way:
truffle unbox react
npm install @openzeppelin/test-helpers

I have keep SimpleStorage.sol sample contract and here is my test file:
const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const {expect} = require("chai");

const SimpleStorage = artifacts.require("./SimpleStorage.sol");

contract("SimpleStorage", accounts => {

  it("my test", async () => {
    const simpleStorageInstance = await SimpleStorage.deployed();

    await simpleStorageInstance.set(2, { from: accounts[0] });
    const ret = await simpleStorageInstance.get();
    expect(ret).to.equal(new BN(2));
  });
});

I get this error:

AssertionError: expected <BN: 2> to equal <BN: 2>

I do not understand !
<BN: 2> is the same thing than <BN: 2> !
Which does this assertion fails ?
Thanks


texts: estimateGasPrice succeeds but sending a transaction fails?

texts:
I have a simple contract with a function (simplified for the sake of discussion):
function test(address tokenAddress, address userAddress) external {
        IERC20 token = IERC20(tokenAddress);
        uint256 b = token.balanceOf(userAddress);
        require(b > MIN, "not enough");
        // Do more things which write data to blockchain
    }

I decide to call this function by reading the data ahead of time using eth_call in my client (which verifies that balance is good) and then I send the transaction (i'm using web3 in all of this).  The balance can of course change from the time that my client sees it and decides to call my contract so I have the guard in the contract to fail fast.
What seems to be happening is that I trigger the function, call estimateGas (which succeeds), and then attempt to send the transaction which fails with 'not enough'.  Am I missing something here?  If the balance is not correct or not what I expect, shouldn't estimateGas fail as well if the transaction failed?  It's unclear to me how estimateGas is succeeding.
Are they reading two different versions of the chain or something?


texts:
I'm a newb at Ethereum Wallet for sure, but as best I can tell it's useless. I  can create accounts ok, but that's it. I originally sync'd with the blockchain the first time, but since then I'm always out of sync by about 600K blocks no matter how many peers are connected. Mining on testnet for hours produces nothing. I can't create a wallet because I need ether to pay for the contract, and geth is always near or at the top of my memory usage among processes despite producing nothing. I'm eager to use this platform and get in the game, but this thing is basically wallpaper for me. Does anyone have suggestions?

Maybe this will help. I typed the following at my command line: get --testnet console

and got:

C:\Users\I'mBIG\AppData\Roaming\Ethereum Wallet\binaries\Geth\unpacked>geth --testnet console
I0327 20:18:01.525140 node/config.go:445] Failed to start Ledger hub, disabling: libusb: not found [code -5]
I0327 20:18:01.526141 ethdb/database.go:83] Allotted 128MB cache and 1024 file handles to C:\Users\I'mBIG\AppData\Roaming\Ethereum\testnet\geth\chaindata
I0327 20:18:01.683689 ethdb/database.go:176] closed db:C:\Users\I'mBIG\AppData\Roaming\Ethereum\testnet\geth\chaindata
I0327 20:18:01.686694 node/node.go:176] instance: Geth/v1.5.9-stable/windows/go1.7.4
I0327 20:18:01.686694 ethdb/database.go:83] Allotted 128MB cache and 1024 file handles to C:\Users\I'mBIG\AppData\Roaming\Ethereum\testnet\geth\chaindata
I0327 20:18:01.766701 core/genesis.go:95] Genesis block already in chain. Writing canonical number
I0327 20:18:01.766701 eth/backend.go:276] Successfully wrote custom genesis block: 41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d
I0327 20:18:01.768702 eth/backend.go:187] Protocol Versions: [63 62], Network Id: 3
I0327 20:18:01.768702 eth/backend.go:215] Chain config: {ChainID: 3 Homestead: 0 DAO: <nil> DAOSupport: true EIP150: 0 EIP155: 10 EIP158: 10}
I0327 20:18:01.771704 core/blockchain.go:219] Last header: #643824 [338826d9…] TD=399626631294546
I0327 20:18:01.771704 core/blockchain.go:220] Last block: #643824 [338826d9…] TD=399626631294546
I0327 20:18:01.771704 core/blockchain.go:221] Fast block: #643824 [338826d9…] TD=399626631294546
I0327 20:18:01.773706 p2p/server.go:340] Starting Server
I0327 20:18:03.969550 p2p/nat/nat.go:111] mapped network port udp:30303 -> 30303 (ethereum discovery) using UPNP IGDv2-IP1
I0327 20:18:04.018693 p2p/discover/udp.go:227] Listening, enode://a5faacd06a381de0895a7cae118e1cc5113a92618d35b39829198f146e73c259a0833a3b4dfcd1fdad82396d3a0b1aed743b0e79b4885a063942370fec750de7@198.72.238.217:30303
I0327 20:18:04.019668 p2p/server.go:608] Listening on [::]:30303
I0327 20:18:04.026672 node/node.go:341] IPC endpoint opened: \\.\pipe\geth.ipc
I0327 20:18:04.070213 p2p/nat/nat.go:111] mapped network port tcp:30303 -> 30303 (ethereum p2p) using UPNP IGDv2-IP1
Welcome to the Geth JavaScript console!

instance: Geth/v1.5.9-stable/windows/go1.7.4
coinbase: 0x127829fcd841134d9b949edf0feb4646f0cdd4e1
at block: 643824 (Mon, 27 Mar 2017 20:12:59 PDT)
 datadir: C:\Users\I'mBIG\AppData\Roaming\Ethereum\testnet
 modules: admin:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0


texts:
Suppose i have a loop.
Here user is a struct of which player is an address.

address[] memory addrs = new address[](n);
for(uint i=0;i<n;i++){
addrs[i] = user.player;
}
 return addrs;

This is a view function so i know i wont have to pay to run it.
Is this going to fail if the value of n increases beyond a point?
Im confused about the gas block limit.


texts: How to send erc20 token with web3 without smart contract abi?

texts:
I created a token in the Ropsten network.  It wants abi.json when transferring with Web3. But the token I created did not give it.
My token etherscan link https://ropsten.etherscan.io/address/0xe4bcb47da515d78a05de9f0861808fa97284129c
Verification failed. I want to make a transfer with node js web3 without verification. How can I do that?


texts:
Some time ago, a vulnerability was discovered in IOTA because the team implemented the cipher algorithm by themselves instead of using open source (more tested) implementation.
I can conclude Ethereum cipher is very secure since the platform stores a lot of money already.
But, anyway, does anyone know if the ECDSA and KECCAK-256 were implemented by Ethereum (e.g. Geth) team or not?


texts: bitwise multiplication to reduce gas cost

texts:
This is the multiplication method from the SafeMath library.
   /**
    * @dev Returns the multiplication of two unsigned integers, reverting on
    * overflow.
    *
    * Counterpart to Solidity's `*` operator.
    *
    * Requirements:
    * - Multiplication cannot overflow.
    */
   function mul(uint256 a, uint256 b) internal pure returns (uint256) {
       // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
       // benefit is lost if 'b' is also tested.
       // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
       if (a == 0) {
           return 0;
       }

       uint256 c = a * b;
       require(c / a == b, "SafeMath: multiplication overflow");

       return c;
   }

Could this be done using the shift operators in Solidity to reduce the amount of gas consumed?

If yes, what would the necessary changes look like?


texts: Is it safe to move the .ethereum data directory?

texts: I just bought a new 1TB SSD drive and I would like to move my .ethereum directory from the 60GB to the 1000GB HD. Is it safe to simply move the directory?


texts: Where's the best place get smart contract development help, quickly?

texts: I've tried gitter. It take like 3 hours get to get help.


texts: What is a recursive calling vulnerability?

texts:
What is a recursive calling vulnerability exactly?

When creating smart contracts, DAOs or DAPPs, what measures can I take to ensure I am not vulnerable?


texts: What are "smart tokens" and how do they differ from regular tokens?

texts:
On June 12, 2017, The Bancor Network's ICO allocated 39.6 million Bancors in exchange for 396,720 Ethers. These new tokens are being described as the first "smart tokens" in the blockchain world.

What makes them smart?
And in what ways do smart tokens differ from regular tokens?


texts: How to recieve notification of incoming transaction in metamask mobile in real time

texts: I have a erc-20 token in the ropsten testnet and i am using my metamask for admin my token, and i just want to recieve a notification via sms, to take screenshot, whatsapp or another way frendly user, when i recieve an incoming transaction in the metamask mobile app instantly whe the transaction is confirmed.


texts: Who generates/computes the block header and other details such as ParentHash, TxHash, etc.? I refer to  above image for details but I am not sure who generates these details.


texts:
How do I calculate the gasfee for a call to a function, which increments an uint globally?
uint index;

function addUp () public returns (uint result) {
        index += 1; // increment value
        result = index; //return it
 }

Where should I start to get an answer for my question?


texts: creating and array using type Big.Int and counting the sum of all integers inside it

texts:
Im communicating with a smart contract trying to get the balances from a list of addresses. I then want to get the sum of all balances but I am stuck on actually creating the array to store all the balances.. I need a type of big.Int but have no idea how to create it for my array. so far my code is:

balances := make([]int, 0)

for _, address := range getAddresses {
    getAddressBalance, err := token.BalanceOf(&bind.CallOpts{Pending: true}, address)
    balances = append(balances, getAddressBalance)
}

and the error i get is

cannot use getAddressBalance (type *big.Int) as type int in append


texts: Is it possible for miner to tamper with the results when executing smart contracts?

texts:
When Miner A executes the smart contract, a result is generated and broadcast to the entire network. I want to know if this result may have been tampered with. If this is possible, how do other miners judge the authenticity of this result?
Hope you can give me some help, thanks!


texts:
I'm encountering this error when calling a function that returns a string stored in the contract.
This is the ABI
{
"inputs": [],
"name": "getContractName",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
The weird thing is I have another contract in the project that also has a function that returns a string stored in the contract and that one does not trigger the error when calling it, its ABI being identical to what's above.
I am on the right network, and if I take the variable in which I store the contract and log it in the console, I can see that it contains the problematic function. I also succeed to call a function that returns a bool on this contract.
What additional information should I provide to figure this out? Thanks for dropping by ^^


texts: Is there a penalty for having a ETH 2.0 Staking node go down?

texts: For some proof of stake blockchain systems, there is a penalty if the node goes down during staking. Will there be some sort of penalty if an ETH 2.0 staking node went down? And if there isn't how does it stop stakers from power up and down their node to mess with the network?


texts:
I am sending ETH to a contract as follows:

web3.eth.sendTransaction({from: sender, to: address, value:amount, gas:300000, data:"1234"});

In my fallback function, I can see msg.data has the following value (as expected):

"0x1234"

The trouble is (and I've been at this for hours...) how do I convert this into a uint holding the value 1234?

Here's my attempt that sorta works (i.e. doesn't):

function bytes2uint(bytes _data) constant returns(uint){
    uint i=0;
    uint dec=0;

    for (i = 0; i < _data.length; i++) {
        byte e=_data[_data.length-i-1];
        uint f=uint(e);
        f=((f/16)*10)+(f%16);
        dec+=(f*(100**i));
    }
    return dec;
}

I am able to successfully convert "0x1234", "0x123456", "0x12", etc. (i.e. an even number of digits). However, when I try "0x123" or "0x12345" (for example), the trailing digit is somehow getting truncated?


texts: How to expose the underlying web socket connection from the WebSocketProvider?

texts:
Using web3.js version 1(beta) and using the WebsocketProvider to make a connection via

const Web3 = require('web3')

const web3 = new Web3('ws://localhost:8546')
const provider = web3.providers.WebsocketProvider

const { connection } = provider

==> connection is undefined

looking at the source for the WebsocketProvider I can see it's got a connection object

function WebsocketProvider(url)  {
  var _this = this;
  this.responseCallbacks = {};
  this.notificationCallbacks = [];
  this.connection = new Ws(url);

  this.addDefaultEvents();

  // LISTEN FOR CONNECTION RESPONSES
  this.connection.onmessage = function(e) {
    /*jshint maxcomplexity: 6 */
    var data = (typeof e.data === 'string') ? e.data : '';

    _this._parseResponse(data).forEach(function(result){

      var id = null;

      // get the id which matches the returned id
      if(_.isArray(result)) {
          result.forEach(function(load){
              if(_this.responseCallbacks[load.id])
                  id = load.id;
          });
      } else {
          id = result.id;
      }

      // notification
      if(!id && result.method.indexOf('_subscription') !== -1) {
          _this.notificationCallbacks.forEach(function(callback){
              if(_.isFunction(callback))
                  callback(null, result);
          });

          // fire the callback
      } else if(_this.responseCallbacks[id]) {
          _this.responseCallbacks[id](null, result);
          delete _this.responseCallbacks[id];
      }
    });
  };
}

Curiously I can't actually find the source code for this in GitHub, the above comes by logging web3.providers.WebsocketProvider

Questions

At what point is the connection actually made,
how can I expose it such that I can attach error and other handlers to make a more reliable connection, and
Where is the source code for this, given it's nowhere to be found in github.com/ethereum/web3.js


texts:
I'm having issues syncing my geth node to the Morden testnet after the recent protocol change.

Everything was working fine on Monday - today I downloaded geth-1.4.18 and attempted to sync but any time I launched geth syncing would start then I would receive a Bad block error followed by a gas used error after which geth appeared to become stuck.

I've renamed my testnet directory and I'm currently in the process of redownloading the entire testnet chain from scratch (not using --fast) however I'm worried about what I should do in the event that this also becomes stuck.

Anything I should try to be able to sync with my old testnet chaindata?


texts:
I'm having an issue with time synchronization on Parity. This is the error I get under status and time synchronized, "Unable to reach time API: NTP error: NTP server is not provided.. Make sure that your clock is synchronized."

I'm using Windows 7. I tried syncing my computers time again but it still says that.

When I go to time.is though it says, "Your time is exact!The difference from Time.is was -0.115 seconds (±0.082 seconds)."

Does anyone know how I can fix this issue? Thanks.


texts: How to save big data on ethereum smart contracts

texts: It's been some time since I started figuring this out. I'd really appreciate your ideas and opinions. I'm building an app on ethereum smart contract. But the thing is There might be so huge big data. For example, I have an mapping in eth smart contract, and there might be the case when this mapping property might need to save 1,000,000,000 records. I think smart contract would blow or gas price would be super huge. I don't know can smart contract handle that big data and Is it advisable? I've read about logs but i don't know well , if you could just give me ideas about logs and if it's easy or something like that. What I am asking is is it advisable to have so big data in smart contract like the one I mentioned?


texts:
SCENARIO:

I have the following code:

final String hostUrl = this.deployerProperties.getProperty("quorum.host.url");
final String hostPort = this.deployerProperties.getProperty("quorum.host.port");
final String host = hostUrl + ":" + hostPort;
final HttpService httpService = new HttpService(host);

this.admin = Admin.build(httpService);
this.quorum = Quorum.build(httpService);

final EthAccounts ethAccounts = this.quorum.ethAccounts().send();
final String ethFirstAccount = ethAccounts.getAccounts().get(0);
final PersonalUnlockAccount personalUnlockAccount = this.admin.personalUnlockAccount(ethFirstAccount, "").send();
if (!personalUnlockAccount.accountUnlocked()) {
    throw new IllegalStateException("Account " + ethFirstAccount + " can not be unlocked!");
}

final List<String> privateFor = null;
int sleepDuration = 2 * 1000;
int attempts =50;
final ClientTransactionManager clientTransactionManager = new ClientTransactionManager(this.quorum, ethFirstAccount, ethFirstAccount, privateFor);

//final ContractGasProvider contractGasProvider = new DefaultGasProvider();
final ContractGasProvider contractGasProvider = new PersonalGasProvider();

final Tokens tokens = Tokens.deploy(this.quorum, clientTransactionManager, contractGasProvider).send();

public class PersonalGasProvider extends StaticGasProvider {
    public static final BigInteger GAS_LIMIT = DefaultGasProvider.GAS_LIMIT;
    public static final BigInteger GAS_PRICE = BigInteger.ZERO;

    public PersonalGasProvider() {
        super(GAS_PRICE, GAS_LIMIT);
    }
}

When I execute the code. I get the following error:

  Exception in thread "main" org.web3j.protocol.exceptions.TransactionException: Transaction receipt was not generated after 100 seconds for transaction: 0xbb0792515b9b84bb6d41956925027db0d8b4636470c475987b882993a257f974
      at org.web3j.tx.response.PollingTransactionReceiptProcessor.getTransactionReceipt(PollingTransactionReceiptProcessor.java:51)
      at org.web3j.tx.response.PollingTransactionReceiptProcessor.waitForTransactionReceipt(PollingTransactionReceiptProcessor.java:29)
      at org.web3j.tx.TransactionManager.processResponse(TransactionManager.java:72)
      at org.web3j.tx.TransactionManager.executeTransaction(TransactionManager.java:51)
      at org.web3j.tx.ManagedTransaction.send(ManagedTransaction.java:87)
      at org.web3j.tx.Contract.executeTransaction(Contract.java:291)
      at org.web3j.tx.Contract.create(Contract.java:333)
      at org.web3j.tx.Contract.deploy(Contract.java:387)
      at org.web3j.tx.Contract.lambda$deployRemoteCall$10(Contract.java:496)
      at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:30)

This java code works randomly because 10% of the executions the code finish the execution succesfully. But The other 90% of the executions appear the error.

The flow is the following:

Quorum 7nodes example deployed into a remote server
Smart-contract wrappers packaged into a JAR
A simple code execute the wrappers deploy method

Any idea about what happend?

EDIT

With this chages the error persist and the IDE warn me about that deploy constructor is deprecated

final ClientTransactionManager clientTransactionManager = new ClientTransactionManager(this.quorum, ethFirstAccount, /* ethFirstAccount */null, privateFor, attempts, sleepDuration);
final Users users = Users.deploy(this.quorum, clientTransactionManager, BigInteger.valueOf(0), BigInteger.valueOf(30000000) /* contractGasProvider */).send();


texts: Why was the Constantinople hard fork postponed?

texts:
The Constantinople hard fork — really a network upgrade — was scheduled to happen today (January 16) at block 7,800,000.

Instead the upgrade was postponed.

What are the technical reasons for the postponement?


texts: How to make Parity work on my PC. "Parity can't run on your pc"

texts:
My blocks freeze at around the 760,000 mark, therefore I downloaded Parity's latest version to which I then received the message above. I have downloaded multiple versions of Parity to try and fix the error, so that I can run my ETH Wallet and receive ETH which I have purchased.

I haven't found anyone with the same issue so far, however I have seen a plethora of videos which describe how to download and run Parity with ETH wallet, and I followed these to the T. Therefore I cannot understand what is wrong.

ASUS Notebook
2GB RAM
I have 3GB free storage
Running Windows 10

If my specs are the issue, are there any suggestions to overcome this problem as I have paid for my ETH and not received as yet due to non-functional Wallet. If I bought it and sent it to my Wallet address before the block-data was fully downloaded will it clear my purchase so that I have wasted my money?


texts: Truffle/Web3: myContract.method.estimateGas causes BigNumber error

texts:
I get the following error when running truffle test:

{ BigNumber Error: new BigNumber() not a number: [object Object]
    at raise (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/node_modules/bignumber.js/bignumber.js:1177:25)
    at /Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/node_modules/bignumber.js/bignumber.js:1165:33
    at new BigNumber (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/node_modules/bignumber.js/bignumber.js:193:67)
    at new BigNumber (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/node_modules/bignumber.js/bignumber.js:203:25)
    at toBigNumber (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/lib/utils/utils.js:367:12)
    at Object.toTwosComplement (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/lib/utils/utils.js:378:21)
    at SolidityTypeUInt.formatInputInt [as _inputFormatter] (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/lib/solidity/formatters.js:40:38)
    at SolidityTypeUInt.SolidityType.encode (/Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/lib/solidity/type.js:188:17)
    at /Users/danielyakobian/.nvm/versions/node/v7.5.0/lib/node_modules/truffle/node_modules/web3/lib/solidity/coder.js:91:29
    at Array.map (native) name: 'BigNumber Error' }

I've narrowed the cause to estimateGas function called in the following code:

        return FlightFuture.deployed()
        .then((instance) => {
            future = instance;
            return future.offer.estimateGas();
        })
        .then((gas) => {
            transaction_options.gas = gas;
            console.log(transaction_options.gas);
            return future.offer.apply(this, valid_offer_params.concat(transaction_options))
        })

Im having trouble finding any documentation on how to call estimateGas on a contract function, any ideas what I'm doing wrong?


texts:
I got error when try to install solc using

npm install -g solc

here is the error:

erfans-MacBook-Pro:01 erfanandesta$ npm uninstall -g solc
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/solc
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/solc/node_modules
npm ERR! path /usr/local/lib/node_modules/solc
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/solc'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules/solc']
npm ERR!   stack:
npm ERR!    "Error: EACCES: permission denied, access '/usr/local/lib/node_modules/solc'",
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules/solc' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/erfanandesta/.npm/_logs/2018-12-06T07_44_32_823Z-debug.log

when i use sudo npm install -g solc it install successfully i now i got this error :

internal/modules/cjs/loader.js:605
    throw err;
    ^

Error: Cannot find module './smtchecker.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:603:15)
    at Function.Module._load (internal/modules/cjs/loader.js:529:25)
    at Module.require (internal/modules/cjs/loader.js:658:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/solc/solcjs:9:18)
    at Module._compile (internal/modules/cjs/loader.js:722:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)


texts: MasterChef contract - How to adapt masterChef to have buy back for each deposit TX?

texts:
Hi I actually try to modifiy this MasterChef from Blizzard :
https://github.com/blzd-dev/blzd-contracts/blob/master/contracts/MasterChefV2.sol
I wouldlike to take a part of fees to do a buy back on a specific token specified in a constructor for example when I will deploy MasterChef fo each user who deposit his LP :
// Deposit LP tokens to MasterChef for BLZD allocation.
    function deposit(uint256 _pid, uint256 _amount) public nonReentrant  poolExists(_pid) {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accBlzdPerShare).div(1e12).sub(user.rewardDebt);
            if (pending > 0) {
                safeBlzdTransfer(msg.sender, pending);
            }
        }
        if (_amount > 0) {
            pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
            if (pool.depositFeeBP > 0) {
                uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
                uint256 depositeFeeHalf = depositFee.div(2);
                pool.lpToken.safeTransfer(feeAddBb, depositeFeeHalf);
                pool.lpToken.safeTransfer(feeAddSt, depositeFeeHalf);
                user.amount = user.amount.add(_amount).sub(depositFee);
            } else {
                user.amount = user.amount.add(_amount);
            }
        }
        user.rewardDebt = user.amount.mul(pool.accBlzdPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }


texts: Usage of "storage" and "memory" keywords in struct declaration

texts:
I have recently ported my code to solidity 0.4.11 and have been noticing some warning errors upon declaring 'string' variables while declaring structs.

struct person {
    string name;
    string physicalAddress;
}

the warning I have been getting is:

Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence the warning.

Suggestions on how to get rid of this warning? Also I am trying to understand the usage of storage and memory keywords - could anyone help explain the utility patterns of these keywords?


texts:
im new to solidity and im trying to figure out the best way to splice an array.

in javascript you have:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

is there a similar way to achieve this in solidity?

the only way i think it would be possible is if you overwrite the value at the array index and replace that value with the value of the item at the next index... then do this for every following index value until the end of the array.

that method sounds like it could be expensive. does anyone have an suggestions of how to better achieve this?

the main thing i am trying to achieve is a way to keep the order of the array even though you can remove items from the middle.

suggestion 1

so thinking about it, how about using a list of structs. for example given a list of strings we want in an array, how about the data be stored into a struct with an additional bool field deleted.

struct Queue {
    string value;
    bool deleted;
}

Queue[] public listOfItems;

function deleteItem(uint index) public {
    Queue[index].deleted = true;
}

given that read operations are free on ethereum, i can get the client to request data from some index, if the data at that index has been marked as deleted, automatically request the subsequent index until a record is found that isn't deleted.

solution 2

i could use linked lists to achieve a similar functionality. this way if an item is to be marked as deleted, i could update the key of the next item in the array.

uint counter;

mapping (uint => string) public comments;

function addComment(string newComment) public {
    comments[counter + 1](newComment);
    comments[counter].nextItem = counter + 1;
}

function removeCommentWithId(uint commentId) public {
    comments[commentId - 1].nextItem = commentId + 1;
}


texts:
I found a chess game on github that uses contracts to implement all of the game logic. Is this a wise idea?

https://github.com/ise-ethereum/on-chain-chess


texts: delegateContract address getting reset on delegatecall using geth console

texts:
I've deployed the following contracts on the rinkeby testnet. They are completely separate with different addresses:

pragma solidity ^0.4.11;

contract Backend {

  address public delegateContract;
  address[] public previousDelegates;

  event DelegateChanged(address oldAddress, address newAddress);

  function Backend() {
    // constructor
  }

  function changeDelegate(address _newDelegate) returns (bool) {
    if (_newDelegate != delegateContract) {
          previousDelegates.push(delegateContract);
          var oldDelegate = delegateContract;
          delegateContract = _newDelegate;
          DelegateChanged(oldDelegate, _newDelegate);
          return true;
      }
      return false;

  }

  function add(uint256 var1, uint256 var2) {
    delegateContract.delegatecall(bytes4(sha3("add(uint256,uint256)")), var1, var2);
  }

}

and

pragma solidity ^0.4.11;

contract Delegate {

  uint public total;

  function Delegate() {
    // constructor
  }

  function add(uint256 var1, uint256 var2) {
    total = var1 + var2;
  }
}

I'm running some commands in the geth console, I successfully am able to set the delegateContract with changeDelegate function. Here are the commands in the console:

backend.changeDelegate(delegate.address, {from:sender})
"0x3a4e83d03b4c7367eb2ed61630c4809470d3ca5bdedbb02741da7701c0e14b29"
> backend.delegateContract.call()
"0x1eb1746e49ffc5fb38c20ce07242db3bae89c9eb"
> backend.add(1,1,{from:sender})
"0x8cbc47f9f8f2382c10a1d93c47eb9de3e2fb8f6c63b62c387096f6250311c58b"
> backend.delegateContract.call()
"0x0000000000000000000000000000000000000002"

When I run the add function, it seems to corrupt the previously set delegateContract address. When I call backend.total.call() no changes are happening.

Any idea why this is occurring?


texts: Why are Plasma child chains forced to be of UTXO type, and why not a regular ethereum chain running PoA or similar?

texts:
Been doing research in Plasma, and Ethereum side chains and something I've come across (but can't seem to find an explanation of) is why are all  Plasma child chains of UTXO type?

I'm wondering why not use child chains that aren't UTXO? Wouldn't it be possible to just build a PoA or other type of Ethereum network and broadcast the blocks to contracts on the mainchain?


texts: debug.traceTransaction() returns a empty structLogs: []. What might be the reason?


texts: Are new Opcodes approved in EIP's implemented in Solidity before they are introduced in a hardfork?

texts:
REVERT, STATICCALL, RETURNDATASIZE and RETURNDATACOPY are all approved and pending the next Ethereum hardfork as specified here

However, the Solidity changelogs shows all 4 of these opcodes entering the compilers services before the hardfork has happened?

Is this actually the case? How is this possible? Do all ethereum programs such as Geth and Parity introduce the opcodes before the hardfork also?


texts: What is the meaning of "memory is erased between (external) function calls"?

texts:
From the official documentation on the memory keyword:

  The second is “memory”, this is used to hold temporary values. It is erased between (external) function calls and is cheaper to use.

Can someone please clarify the meaning of between (external) function calls?

Does it mean between two function calls made from the offchain (e.g., via a web3 script)?

Or does it possibly mean that passing a memory array from a contract function to some other contract function is not reliable in the sense that the array will not be persistent across both functions?

To elaborate, my overall purpose is to change this:

uint[] private arr;
function func(uint arr0, uint arr1, uint arr2) public returns (uint256) {
    arr = [arr0, arr1, arr2];
    return otherContract.func(arr);
}

To this:

function func(uint arr0, uint arr1, uint arr2) public returns (uint256) {
    uint[] memory arr = new uint[](3);
    arr[0] = arr0;
    arr[1] = arr1;
    arr[2] = arr2;
    return otherContract.func(arr);
}

And although the first method works fine, I want to be sure that it is absolutely safe to do so, because I feel that using a storage array is a rather bad practice (let alone a more expensive method) in this case.

Thank you!


texts:
I'm learning about smart contracts currently and a bit confused as to how they really work.

My website allows users to send ETH from their wallet on site to another address off site. During which I'd like to deduct 1% for a fee on my website.

Is it possible via smart contracts to do this?

What I've done now using solidity is this developed this very basic contract:

pragma solidity ^0.4.18;

contract MultiSend
{
    function multiSendETH(address[] memory addresses, uint[] memory values) public payable
    {
        // Validate addresses and values match
        if(addresses.length != values.length)
        {
            return;
        }

        else
        {
            for(uint i = 0; i < addresses.length; i++)
            {
                address(addresses[i]).transfer(values[i]);
            }

            msg.sender.transfer(this.balance);
        }
    }
}

I have deployed it with a value of 1 wei via remix.ethereum.org successfully.

Is it possible to reuse the same smart contract over and over again everytime someone makes a withdraw from my website?

Or do I have to create the smart contract with a value equal to that of what is being withdrawn?

My issue is the smart contract takes a bit to get mined and become available so doing that method of funding it with the proper value being withdrawn and the time span to when the contract is available and can be executed will have some delay and be bad for user experience.

I was hoping it would be possible to reuse this smart contract and maybe add in a parameter of which wallet to send from? Is that possible?

Also is it possible to get the transaction ID from this line:

address(addresses[i]).transfer(values[i]);

Or is my understanding of smart contracts completely off?

I'd like to call this like:

addresses = ['0xTheirOutputAddress', '0xMySiteAddress']
fee = total * 0.01
values    = [total - fee, fee]
w3.contract.multiSendETH(addresses, values).call()


texts: ~/.ethereum takes a lot of disk space. What can I clean up without having to sync from scratch?

texts:
I am using cpp-eth on freebsd 10.3 with SSD and ~/.etherium takes about 41 Gb of disk space:

~/.ethereum # du -sh *
    4.0K    config.rlp
    41G     d4e56740
    0b      geth.ipc
    4.0K    keys.info
    4.0K    keys.info.salt
    16K     network.rlp

~/.ethereum/d4e56740 # du -sh *
    39G     12041
    2.8G    blocks

~/.ethereum/d4e56740/12041 # du -sh *
    6.9G    extras
    32G     state

Is there anything in these folders that I could remove without having to sync all over again? This is my first sync and I am still about 100 000 blocks short.


texts: Decoding Transaction input data in Nethereum

texts:
I'm using Nethereum and see this example of how to decode the Input data of a Transaction object.
http://playground.nethereum.com/csharp/id/1063
This looks like it assumes that you have to know which function data you're decoding.  I have the full contract ABI, but I don't know which function was called in this transaction.
Is there a way to decode the Input data without already knowing which function it is?  In EthersJs, for example, this is done simply with a ContractInterface.parseTransaction method call.
I'm also open to suggestions for other .NET based decoding solutions/libraries.


texts:
uint private seed;

// starts from 0 (including) to _length number (excluding)
function random(uint _length) private returns(uint) {
    seed = seed.add(block.timestamp.add(uint(msg.sender)));
    return uint(sha256(toBytes(uint(blockhash(block.number - 1)) + seed))) % _length;
}

function toBytes(uint256 x) private pure returns(bytes b) {
    b = new bytes(32);
    assembly {
        mstore(add(b, 32), x)
    }
}

How safe is this to be used for generating a random number?

I have a seed in there based on the previous generated random number which would make it pretty much impossible to track.

will this be expensive in terms of gas usage?


texts:
I'm using truffle v5.0.14 to handle my contracts.
All was well while developing with ganache, but when I wanted to deploy to the real network (a private one) I have problems with the account.

The node that I have to connect to prevents from unlocking accounts for rpc calls, so what is the correct way to load my account to truffle?


texts:
I am installing eth-netstats on a private network. I configured everything as the docs suggested, however the eth-net-intelligence api complains about a connection refused error:

2017-10-18 08:59 -05:00: [wsc] =✘= Socket error: { Error: connect ECONNREFUSED 192.168.137.101:80
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '192.168.137.101',
  port: 80,
  type: 'error',
  target:
   WebSocket {
     domain: null,
     _events: { error: [Function: onerror] },
     _eventsCount: 1,
     _maxListeners: undefined,
     _socket: null,
     _ultron: null,
     _closeReceived: false,
     bytesReceived: 0,
     readyState: 3,
     supports: { binary: true },
     extensions: null,
     _binaryType: 'arraybuffer',
     _isServer: false,
     url: 'ws://192.168.137.101/api/?_primuscb=Lylo2SH',
     protocolVersion: 13,
     _closeTimer: null,
     _closeCode: 1006 } }

The eth-netstats process is using only port 3000 , but not 80 (ws) or 443 (wss). I have been looking into the config and I can't find any parameter there that specifies the listening ip/port number for the websocket. Logically, there should be 2 ports open for listening, one for the browser and one for eth-net-intelligence-api to push the stats, but there is only 1 port, the 3000.

On the eth-net-intelligence-api I have this config file:

[
  {
    "name"              : "node-app",
    "script"            : "app.js",
    "log_date_format"   : "YYYY-MM-DD HH:mm Z",
    "merge_logs"        : false,
    "watch"             : false,
    "max_restarts"      : 10,
    "exec_interpreter"  : "node",
    "exec_mode"         : "fork_mode",
    "env":
    {
      "NODE_ENV"        : "production",
      "RPC_HOST"        : "localhost",
      "RPC_PORT"        : "8545",
      "LISTENING_PORT"  : "30303",
      "INSTANCE_NAME"   : "MY ETH",
      "CONTACT_DETAILS" : "1234567",
      "WS_SERVER"       : "ws://192.168.137.101",
      "WS_SECRET"       : "myethereum",
      "VERBOSITY"       : 2
    }
  }
]

What parameters do I have to modify in eth-netstats and eth-net-intelligence-api so the eth-net-intelligence process connects to the websocket of eth-netstats ???


texts:
I'm trying to get access to some data on the BSC using a websocket and the same methods as web3.
I've sucessfully sent the following to get the latest swap pairs created at the PancakeSwap Factory:
{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_getLogs\",\"params\":[{\"fromBlock\":\"0x6a54cb\",\"toBlock\":\"latest\",\"topics\":[\"0x0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9\"],\"address\":\"0xbcfccbde45ce874adcb698cc183debcf17952812\"}]}

How can I get a stream of newly-created pairs rather than specifying a start and end block? I've had no success with anything like the following:
{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"logs\",{\"address\":\"0xbcfccbde45ce874adcb698cc183debcf17952812\", \"topics\":[\"0x0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9\"]}]}

Would appreciate any pointers on this.


texts: Fallback function gets called when setting contract variables from external node

texts:
I’m a beginner in the Ethereum world and I’ve got some problems dealing with a SimpleStorage contract on my private testnet (http://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html).
In particular, if I create a contract instance and then call the set() function from the same node everything works.
But if I call the set() function from another node of my private testnet by using the following commands:

> var instance = web3.eth.contract(abi).at(contractAddress);
> instance.set.sendTransaction(21, {from: web3.eth.accounts[0]});

the function does not seem to work. More precisely, by simply adding some event listeners, I can notice that the fallback function gets called instead. Could anyone tell me why? What am I doing wrong?

Any help appreciated.


texts:
Inside a DAPP, I have been using

web3.currentProvider.publicConfigStore.on('update',...

to monitoring Metamask activity.

But in the new metamask-mobile such method does not exists.

There is a better way to listed for updates?

setTimeout seems a poor solution.

Tanks


texts:
I used that command for install my node

geth console --rinkeby --datadir=~/.gophersland_ethereum_r1 --port=30304 --cache=6048 --rpc --rpcport=8546 --rpcapi=eth,web3,net,personal syncmode=fast

After i created one wallet and transfer some quantity of ethereum for this wallet.
But, when i execute the command "eth.getBalance(eth.accounts[0])" the result is always 0.

But, if i checked the balance in etherscan the balance appears right.

Anyone can help me?


texts: Visibility of source code after contract verification

texts:
I have seen many verified smart contracts with there source code as visible. E.g. See Here.

Now as i want to test my smart contract on Ropsten Network before going live, is it not possible to deploy and verify my contract without having my source code viewable to other participants on Ropsten Network?

If yes, kindly guide me through it with a link to such a contract which is fully deployed with no shared source code and is running successfully on this network (or live network).

Thank you so much in advance!


texts: How to estimate gas for my function using web3 js only?

texts:
Hi this is my solidity function

function closeBid(string _product) public{
  }

I want to estimate gas for this function so in web3 js I called this like

var gas = MyContract.closeBid().estimateGas("Coffee",{from: web3.eth.accounts[0]});

But it throws InvalidNumberOfSolidityArgs(). How can I estimate gas for this function because this function consumes lot of gas. I have to make sure availability of gas for calling this function. Thank you.


texts:
I've deployed an ERC20 like this:

const fs = require("fs");
const Web3 = require('web3');
const testnet = 'http://localhost:8545';
const PrivateKeyProvider = require("truffle-privatekey-provider");
const privateKey = "privatekey";
const web3 = new Web3(new PrivateKeyProvider(privateKey, testnet));

I've created the json as:

solc TestToken.sol --combined-json abi,asm,ast,bin,bin-runtime,devdoc,interface,opcodes,srcmap,srcmap-runtime,userdoc > contracts.json

let source = fs.readFileSync("contracts.json");
let contracts = JSON.parse(source)["contracts"];

let contractInfo = contracts["TestToken.sol:TestToken"];
let abi = JSON.parse(contractInfo.abi);

let code = '0x' + contractInfo.bin;

let SampleContract = new web3.eth.Contract(abi);

console.log("Unlocking coinbase account");
const walletAddress = '0x123';
let password = "";
try {
    web3.eth.personal.unlockAccount(walletAddress, password);
} catch (e) {
    console.log(e);
    return;
}

SampleContract.deploy({
    data: code,
    arguments: [] // no parameter on constructor
}).send({
    from: 'walletAddress',
    gas: 1500000,
    gasPrice: '30000000000000'
}, function (error, transactionHash) {
    console.log(`error: ${error}`);
    console.log(`transactionHash: ${transactionHash}`);
})
    .on('error', function (error) {
        console.log(`error: ${error}`);
    })
    .on('transactionHash', function (transactionHash) {
        console.log(`transactionHash: ${transactionHash}`);
    })
    .on('receipt', function (receipt) {
        console.log(`receipt: ${receipt}`);
        console.log(`receipt.contractAddress: ${receipt.contractAddress}`);
    })
    .then(function (newContractInstance) {
        console.log(`newContractInstance: ${newContractInstance}`);
        console.log(`newContractInstance.address: ${newContractInstance.address}`);
    });

After that I try to get the balance for my wallet using that contract address and I get:

const contract = new web3.eth.Contract(minABI, tokenAddress);
contract.methods.balanceOf(address)
    .call()
    .then(value => show(address, token, value))
    .catch(console.error);

And I get:

Error: VM execution error.
Bad instruction 1c
    at Object._fireError


texts: Deploying Smart Contract with Oraclize to the test net

texts:
I'm having difficulty deploying my contract to the Rinkeby TestNet.

I made a local copy of the Oraclize API and saved it here:n//Users/simon/Documents/usingOraclize.sol

In the Ethereum Wallet application I've gone to Contracts->Deploy new Contract. Pasted my contract code which begins:

pragma solidity ^0.4.0;

import "usingOraclize.sol";

contract Voyager2 is usingOraclize {

And I receive the error Source "UsingOraclize.sol" not found. Can someone explain what path I need to provide to get the import working? I've tried many different variants of the above path.

Also, I came across this: oraclize_setNetwork(networkID_testNet). Is it necessary to call this in the contract before deploying?


texts: Should I maintain an array of all the valid keys in a given mapping?

texts:
I have a contract which maintains a map of valid wallets.

In this map, the keys are wallet addresses and the values are wallet parameters:

struct WalletParams {
    bool valid;
    uint x;
    uint y;
    uint z;
}

mapping(address => WalletParams) public map;

In order to keep track of valid wallets, I can do either one of the following every time I add a wallet:

Emit an event with the wallet address
Add the wallet address to an auxiliary array

Initially, I thought I should do both, in order to achieve the following goals:

Events can be used in order to perform specific queries and filter out specific wallets
The array can be used in order to be able to fetch all the wallets at any given moment

With regards to #2, I'm starting to think that perhaps events are sufficient for this purpose. In "traditional systems", an array would be the simplest way of course. But on the block-chain, I've figured, maybe the array is "scattered" across different blocks just like the events would be, so there shouldn't be any advantage in maintaining this array.

Is that correct?

If yes, then I should obviously get rid of the array, because of the natural downsides:

Additional gas cost
Additional code-complexity (which increases the chances for bugs)

Then I realized yet another advantage in an array:

I can easily retrieve the data via any standard wallet application, like MyEtherWallet, which would not be feasible via events.

So in short, is it a custom method to keep an auxiliary array of keys next to a map, or should I get rid of it and rely solely on events?

Here is my contract:

pragma solidity 0.4.24;

import "openzeppelin-solidity/contracts/ownership/Ownable.sol";

contract MyContract is Ownable {
    address[] public array;

    struct WalletParams {
        bool valid;
        uint x;
        uint y;
        uint z;
    }

    mapping(address => WalletParams) public map;

    event WalletUpdated(address indexed wallet);
    event WalletInserted(address indexed wallet);

    function insert_or_update(address wallet, uint x, uint y, uint z) external onlyOwner {
        WalletParams storage walletParams = map[wallet];
        if (walletParams.valid) {
            walletParams.x = x;
            walletParams.y = y;
            walletParams.z = z;
            emit WalletUpdated(wallet);
        }
        else {
            walletParams.valid = true;
            walletParams.x = x;
            walletParams.y = y;
            walletParams.z = z;
            array.push(wallet);
            emit WalletInserted(wallet);
        }
    }

    function getArray() external view returns (address[]) {
        return array;
    }

    function getCount() external view returns (uint) {
        return array.length;
    }
}

Thank you!


texts:
I'm messing around with contracts on my own private network with the command:

geth --dev console

If I want to start from a clean environment (i.e. delete all accounts on the private netowrk), how do I clear the cache?


texts:
I need a reliable ACID database with complex transactions. It is a hassle to do this in Java or other high level languages, especially if the database spans multiple systems and networks. For this purpose, I wanted to use the ACID features of smart contracts (if an error then the blockchain is rolled back) to implement my internal app (a one or two node private network).

Does this make sense? Will there be performance issues? I can wait a second or so before the response.


texts:
Currently the block time is around 17s but the confirmation time is even longer around 2-3 minutes. Moreover, as I understand even if the transactions-per-second are 7 we still need to wait the confirmation time before considering those transactions valid. Does this imply that the blockchain is not yet a viable solution for real time application?

An example of real time application could be a user that logs into the system through the blockchain and as it interacts with the system new transactions are added. Such system could be a video game for example.

Will someone ever build a very fast blockchain with confirmation times around the tens of milliseconds?


texts: Create contract in Go-ethereum with Solidity, "Hello world" program

texts:
I want to create contract in go-ethereum using Solidity, I started with "Hello world" program.

I create a private network:

$geth --genesis private.json --networkid 1234 --datadir /home/user/Documents/genesisdata  console

In here, I make a new account then I coded follow link https://www.ethereum.org/greeter.

var greeterSource ='contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() returns (string) { return greeting; } function test() returns (string){ return greeting; } }'

And I got: undefined

When I code without var like this:

greeterSource ='contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() returns (string) { return greeting; } function test() returns (string){ return greeting; } }'

I got:

  "contract mortal { address owner; function mortal() { owner =
  msg.sender; } function kill() { if (msg.sender == owner)
  selfdestruct(owner); } } contract greeter is mortal { string greeting;
  function greeter(string _greeting) public { greeting = _greeting; }
  function greet() returns (string) { return greeting; } function test()
  returns (string){ return greeting; } }"

So I continute code without var, I compile:

greeter = greeterContract.new(_greeting,{from:web3.eth.accounts[0], data: greeterCompiled.greeter.code, gas: 210000}, function(e, contract){
if(!e) {

  if(!contract.address) {
    console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");

  } else {
    console.log("Contract mined! Address: " + contract.address);
    console.log(contract);
  }

}
else{
console.log("Error:>>>>>>>>>>>>>");
console.log(e);
}

})

untill:

greeter.greet();

  TypeError: 'greet' is not a function
      at :1:1

I don't know, how to solve it.

Please show me the problem that I make in this process.

Thanks.


texts: Using sub-contract to simplify interface

texts: If I have a contract that has multiple payable functions, could I create additional contracts that use their default function to call the primary contract's specific function allowing the user to send funds direct from their exchange account and thus lowering the barrier for new users and avoiding requiring metamask etc.  So basically each payable function on the primary will have a corresponding contract that simply calls the correct primary contract function but I can still manage state inside the primary contract.


texts:
How are contracts executed on full nodes?

Do they run one by one on first-in first-served basis, or simultaneously in the isolated environments? If they run in parallel, I guess it may exhaust the resources quite quickly.

If they run in isolated sandboxes, is the stored data isolated as well? If so, how are data modifications shared among them, or they're not?


texts: Public key validation through private key

texts: What is a good way to validate that the public key claimed to belong to a particular user really belongs to him without revealing the associated private key? Can this be done with zero-knowledge proofs? or is there a better approach.


texts:
How does the cost of EVM memory scales?

I wonder how does the cost of EVM memory (not storage) scale?

Indeed, having read other QA's, the cost of memory is not a linear function, but should increase rapidly as more of it is allocated?

Having written the Floyd-Warshall algorithm in Solidity, which allocates an (n x n) matrix of uint's, I see that the gas consumption increases extremly fast. This is the case even for n = 24, where the gas usage is approximately 19085414.

pragma solidity ^0.4.11;

contract APSPBenchmark is usingOraclize {

    event OraclizeEvent0(string desc);
    event OraclizeEvent1(string desc, int[] apsp);

    int constant INF = -1;

    function APSPBenchmark() public payable {}

    /*
    * Local all-pairs shortest path
    */
    function localAPSP(int[] w) public {

        int[] memory apsp  = allPairsShortestPath(w);

        OraclizeEvent0("local");
        //OraclizeEvent1("local", apsp); // Infinity encoded as -1
    }

    /*
    * All-pairs shortest path
    */
    function allPairsShortestPath(int[] w) private constant returns(int[]) {
        uint i; uint j; uint k;
        uint n = babylonian(w.length);
        int[] memory d = new int[](n * n);

        for (i = 0; i < n; ++i) {
            for (j = 0; j < n; ++j) {
                d[i * n +j] = (w[i * n + j] >= 100 ? INF : w[i * n + j]);
            }
            d[i * n + i] = 0;
        }

        for (k = 0; k < n; ++k) {
            for (i = 0; i < n; ++i) {
                for (j = 0; j < n; ++j) {
                    if (d[i * n + k] == INF || d[k * n + j] == INF) continue;
                    else if (d[i * n + j] == INF) d[i * n + j] = d[i * n + k] + d[k * n + j];
                    else d[i * n + j] = min(d[i * n +j], d[i * n + k] + d[k * n + j]);
                }
            }
        }

        return d;
    }

    /*
    * Minimum of two values
    */
    function min(int a, int b) private constant returns(int)  {
        return a < b ? a : b;
    }

    /*
    * Babylonian sqrt
    */
    function babylonian(uint n) private constant returns(uint) {
        uint x = n;
        uint y = 1;
        while (x > y) {
            x = (x + y) / 2;
            y = n / x;
        }
        return x;
    }
}


texts:
Current situation

There is a geth sync service running on a windows 2016 server, in full mode.
It provides --rpc service, and accept request to create transactions.

For some network reason, it can't send the requests out any more.
When running eth.pendingTransactions, it's also not empty.
When running txpool.status, it shows there are still over 20 requests in the queue.

And, we have prepared a new linux server running the geth sync service also in full mode.
Now, we want to migrate the service from the old windows machine to new linux machine.

Questions

I would stop the old geth on windows first, then copy its keys to new machine, this is necessary, right?
Should I migrate the contents in the eth.pendingTransactions's output? And, if yes, how to migrate it?
Should I migrate the contents in the queue of txpool.status's output? And, if yes, how to migrate it?
Is there anything else I am missing?

(I asked another question about ethereum on Stackoverflow site, if you are interested could you also take a look: https://stackoverflow.com/questions/59340718/ethereum-which-syncmode-to-use-fast-or-full)


texts: How to confirm a multisig ETC contract wallet transaction that requires two account signers?

texts: I created a multisig contract wallet with Ethereum Wallet that requires two signatures well before the ETH/ETC hard fork. I'm just now coming back to try and move my ETC out of the 2sig contract wallet, but can't seem figure out how to confirm the transaction from the second signature account? Preferably looking for a solution that uses Parity or MyEtherWallet and not much code/command line.


texts: Ethereum : testrpc using different account for transaction

texts:
I am new to ethereum.
I have a simple contract (using solidity) where i am transferring limited number of amount.
I am able to send amount from default account to other account [Which is web3.eth.accounts[0] to other account]
how can i do the transaction from different account [from account 2 to account 3 and etc]. ?

is there any way to setting i can do to change the default account ?


texts:
I am trying to send ehter using this code

  web3.eth.accounts.wallet.add(privateKey);
  web3.eth.sendTransaction({
          to:someAddress,
          from:onwer,
          value:amount*1,
          gasPrice:result,
          gas:21000,
          nonce:nonce
       }).
  then(function (r) {
           res.json({
                 response:r
                })
  }).catch(function(err){
         res.json({error:err.message+"unknown tx"});
    });

I keep getting

error: unknown account

But I add sender wallet explicitly in this part

 web3.eth.accounts.wallet.add(privateKeyHere);
 result is fetched from  web3.eth.getGasPrice() Promise
 nonce is fetched  web3.eth.getTransactionCount(sender_address_here) Promise

What is wrong with the code ?

Can i send ether without sendSignedTransaction or other methods?

Which is the best (and most simple) method to send ether when you have private key using web3 ??

Thanks

EDIT 1
Account was create using

web3.eth.accounts.create();


texts:
By now i have developed few basic example apps to execute Ethereum contracts using truffle based web application in a private blockchain.

I have setup an IPFS node in my local. Able to upload files to IPFS and view on the IPFS gateway.

Now Looking for a sample code to connect my IPFS node from my truffle based web app and the perform add/view operations of documents from/to IPFS.

Here is what I am looking for
1. Believe have to install IPFS.js using npm
2. Start the IPFS daemon
3. Connect to my local IPFS Node
4. Modify the html interface to accept a file object
5. Invoke IPFS API to add the file in IPFS and get the hash
6. Store the hash in Ethereum blockchain
7. Change the html interface to accept the file specific hash value
8. Invoke IPFS API to get the file from IPFS based on the provided hash

Help is needed for steps 3, 5 and 8. If you could share a sample code to perform the same will be helpful.


texts: "public key" and "account" : are the same?

texts:
When I create a new account as follows :

web3.eth.personal.newAccount('pass').then(console.log);

-> pass is account password.

Then, I receive an account as follows :

0x15CaFbd23DEB631447D34de50e961B0049f4Df2B

Is this my public key ? And if so, How can I see my private key ?

Meanwhile, sometimes when I sent a transaction, I need to unlock my account by account password via ParityUI. Why do I need to do this only sometimes ?

And if I create an account without password as follows, what happens ?

web3.eth.personal.newAccount().then(console.log);


texts: Ethereum Mining Simplified (Gas price / mining fees)

texts:
I've been reading these in-depth explanations of how the gas prices are calculated and looked briefly at the spreadsheet with various variations of gas price per "function" which is still not really clear.
https://whattomine.com/
I'm using the calculator but it's asking for "fee (%)" and I'm still trying to figure out what that is.


texts: Do I have to unlock my account in geth to call a web3.eth.sign() in JavaScript?

texts:
I have:

A geth account
Access to web3 API

I want to:

Invoke the function, web3.eth.sign(coinbase, sha)

If I put this in a javascript file sign.js, and I call node.js, will it sign my message? Or does my geth account have to be unlocked? Can I unlock it in bash and then call node.js?

Thanks!


texts:
I have two questions regarding sidechain.

Q1. Do we need specific technology stack to create sidechain ?
Q2. Can any public blokchain can be use for sidechain ? also how can i use sidechain with Ethereum.

looking forward
Thanks!


texts: What are the main differences between off-chain, sidechain and state channel? And what are the use-cases of all of these?


texts: Solidity: VM Exception while processing transaction: invalid opcode - What happens?

texts: If VM Exception while processing transaction: invalid opcode is thrown, does it have the same effect than revert?


texts: Are there any examples of using precompiled contracts?

texts:
The thing is I want to create my own custom precompiled contracts, and use it in my private chain of ethereum.

Here is my code, but it is not right when I call hello.say() in geth attach line.

In geth side, I changed core/vm/contracts.go file, add my custom contracts.

var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
    common.BytesToAddress([]byte{1}): &ecrecover{},
    common.BytesToAddress([]byte{2}): &sha256hash{},
    common.BytesToAddress([]byte{3}): &ripemd160hash{},
    common.BytesToAddress([]byte{4}): &dataCopy{},
    common.BytesToAddress([]byte{10}): &nativehello{},
}

var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
    common.BytesToAddress([]byte{1}): &ecrecover{},
    common.BytesToAddress([]byte{2}): &sha256hash{},
    common.BytesToAddress([]byte{3}): &ripemd160hash{},
    common.BytesToAddress([]byte{4}): &dataCopy{},
    common.BytesToAddress([]byte{5}): &bigModExp{},
    common.BytesToAddress([]byte{6}): &bn256AddByzantium{},
    common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{},
    common.BytesToAddress([]byte{8}): &bn256PairingByzantium{},
    common.BytesToAddress([]byte{10}): &nativehello{},
}

var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{
    common.BytesToAddress([]byte{1}): &ecrecover{},
    common.BytesToAddress([]byte{2}): &sha256hash{},
    common.BytesToAddress([]byte{3}): &ripemd160hash{},
    common.BytesToAddress([]byte{4}): &dataCopy{},
    common.BytesToAddress([]byte{5}): &bigModExp{},
    common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
    common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
    common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
    common.BytesToAddress([]byte{9}): &blake2F{},
    common.BytesToAddress([]byte{10}): &nativehello{},
}

type nativehello struct{}

func (c *nativehello) RequiredGas(input []byte) uint64 {
    return 1
}

func (c *nativehello) Run(in []byte) ([]byte, error) {
    out := []byte("Native !!!")
    return out, nil
}

And in my test contract code:

pragma solidity ^0.5.0;

contract hello {
    string greeting;

    function bytes32ToStr(bytes32 _bytes32) public pure returns (string) {

    // string memory str = string(_bytes32);
    // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer"
    // thus we should fist convert bytes32 to bytes (to dynamically-sized byte array)

        bytes memory bytesArray = new bytes(32);
        for (uint256 i; i < 32; i++) {
            bytesArray[i] = _bytes32[i];
        }
        return string(bytesArray);
    }

    constructor () public {
       greeting = "hello";
    }

    function say() public  returns (string memory) {
        bytes32 out;
        bytes32 input;
        // bool success = true;
        // assembly {
        //     success := call(20000, 10, 0, input, 32, out, 32)
        // }
        (bool success, bytes memory returnData) = msg.sender.staticcall(abi.encode(3000, 10, input, input.length, out, out.length));
        if (success == true) {
            return string(returnData);
        } else {
            return "failed!";
        }

        //return greeting;
    }
}


texts: Why can't I withdraw tokens from etherdelta to myetherwallet?

texts:
I can't withdraw SIFT token from etherdelta to myetherwallet. I have upped the gas price and made sure I have anough ether in etherdelta and myetherwallet but it still says I'm out of gas. I am losing ether each time I try.
https://etherscan.io/tx/0x9b076789f1c0db1c18175b0869f9159ad5f2ade016aad855dcb18cf12de7e6fa


texts: API to get "total token left" of a custom token

texts:
If let say we launch a ICO using Ethereum blockchain, how can I check for total token left in the market?

The typical workflow will be like:

Investor send n ETH to my wallet
System will verify the amount of ETH sent by investor
System send custom token (XXX) to investor
System display total token left on the website

Any API that can get the XXX token left?


texts:
I keep getting following error:

  SyntaxError: Unexpected token “ in JSON at position 2

when I try to call following function, below is how I call it.

["ADDRESS","ADDRESS"],"STRING"

This is the function I'm trying to call.

    function demoteManyPeople(address[] people, string whyThough) external {
        require(people.length < 10);
        for (uint index = 10; index > people.length; index--) {
             qualifiedForDemote[people[index]] = false;
             DemotePeople(people[index], whyThough);
        }
    }


texts: Setting values of an byte array dynamically

texts:
If I set the values of an array as follows, am I wrong?

uint256 n = 0;
bytes32[n] example;

function getArraySize(uint256 arraySize) public returns(uint256 size) {

 size = arraySize;
 return size;

}

n = getArraySize(3);
example[n] = [bytes32("value_1"),bytes32("value_2"),bytes32("value_3")];

I get "parser error: expected identifier" for n = getArraySize(3); but I don't know what is wrong?

Note: This question is related to another question (the link bellow) where in its answer in note number 2, it is mentioned that in case of defining an array with dynamic size, it is not possible to set values of that array like this:

newObject(100, 3, [bytes32("location"),bytes32("price"),bytes32("sold")], [bytes32("Paris"),bytes32("50"),bytes32("yes")], address(0xE07b6e5a2026CC916A4E2Beb03767ae0ED6af773);

Related question link: Error Encoding Argument (remix)


texts: How to get all ethereum address list which have my token?

texts: I want a list of all ethereum address which have my ERC20 token in their account. Anyone have an idea how to get list address.  beause i want give divided to each account which have my ERC20 token.


texts: How to be notified with bad transactions when sending to a JSON-RPC server?

texts:
With Ubuntu, I've tried Wallet/Mist and MetaMask on Ropsten testnet: they both notify me with bad transactions before inputting my password. I've tried to do the same thing with a JSON-RPC server, in a normal way. The server proceeds to send bad transactions without any notice.

Regarding bad transactions, is there any way to have the same effect of Wallet/Mist/MetaMask with a JSON-RPC server?


texts: Generating a private key without a library

texts:
As far as I understand, a private key in the context of Ethereum is simply 256 random bits. The actual application of secp256k1 comes in when converting this to the public key, signing, etc. Based on this, is there anything wrong with generating a private key in python by simply doing the following (and doing any other operations using a library such as the web3 family) ?

import random
key = hex(random.getrandbits(256))

Or are there, for example, security issues when doing this?


texts: Can't use constructor() when deploying a contract from ethereum wallet

texts:
Take the following code:

pragma solidity 0.4.24;

contract TestCoin {
    mapping(address => uint256) public balanceOf;
    uint256 public totalSupply;

    constructor(uint256 initialSupply) public {
        totalSupply = initialSupply;
        balanceOf[msg.sender] = totalSupply;
    }
}

This code works fine locally and works fine in Remix. But when trying to deploy this contract from the Ethereum wallet I get the following error:

     Could not compile source code.
Expected identifier, got 'eth_compileSolidity'
    constructor(uint256 initialSupply) public {
               ^

This question was already asked here, Expected identifier, got 'eth_compileSolidity' constructor () public {. The question was never actually answered but the person who asked the question apparently fixed it.


texts: How to know the price of the day of ETH in USD by Oracles?

texts:
Consider in a contract the payer intends to pay recipient ETH based on USD (ex. the salary is 1 USD but paid by ETH).

So, if today contract needs to know equivalent value of 1 ETH in USD exactly at time of payment.

For this, contract needs to access to some external sources to know the price of the day of ETH in USD.

I want to use ex. THIS WEB SITE as data-source. How can I fetch the price of ETH from this website as an ex. integer value ?

Is there a sample of such contract / data-source as an example ?


texts: How to retrive the data which was sent to previous deployed contract?

texts: I want to access the data which i sent via a function during the previous contract instance . Is it possible to retrieve the data by the the contract instance or transaction hash ?


texts: Many people(one example) stated that "gas limit" of a block limited "gas limit" of transactions included in it. To verify, I downloaded a block (block number: 10185031) and added "gas limit" of all included transactions and found that the total sum of "gas limit" of all the transactions was much larger than "gas limit" of that block. The results are shown below.


texts: What function does ethereum mist wallet use to send custom tokens?

texts:
I have created my own currency(advancedToken) - ABC using the code given at
https://www.ethereum.org/token#full-coin-code

I have understood the transfer of coin using the contract function Transfer: It calls the transfer function in the code and executes it for the parameters.

But in the send tab of ethereum mist wallet, I can send my tokens - ABCs to another account just like I can send ethers.

What part of code enabled this ? What function of contract is called when ABCs are send ?


texts: ethereum 2.0 sharding, how does data travel around from one shard to the other

texts:
Shard 1 needs to contact shard 2 about a contract it has, how does it go about doing it? What's the "traveling salesman path" of least resistance to get to it?

Or am I misunderstanding how sharding works? I understand there is some sort of central chain, the "root" if you will or something along those lines.

What I am most confused about, is where the data is stored. On the nodes in the shard level or up another level. Who's responsible for keeping all the data intact? Are they compensated? Thanks.


texts:
What will happen if I use assert() inside the function inside() which is called from the function main() ?
If condition is true then control returns to function main() .  What if condition is false? Do it return back to function main() or  exit from the contract execution ?
As far as I know if the condition is false then It throws. This throws exit the function or exit the contract execution ?

function inside(){
      assert(x>y);

  }
  function main(){
      inside();

  }


texts: Who add a ERC-20 transaction to the blockchain?

texts: I'm totally new in the blockchain area and this problem nearly drives me crazy !In ethereum, there is a miner who was chosen by the consensus algorithm to add a block to the blockchain. I viewed the transaction details in https://kovan.etherscan.io/ and found the miner. However, I just can't understand by whom the ERC-20 transaction  is added ? The owner of the contract ? Please tell me if you know it.


texts:
I have two contracts. One to manage quests and one to manage units. These units have an uint exp and are mapped to an id by mapping(uint256 => Unit) public tokenToUnit;.
Now I want to use the Quest Contract to increase the exp from an unit inside the Unit Contract.

How can I edit an uint of a struct which is mapped to an id?

What I've tried:

Contract Units.sol

function addUnitExp(uint256 _unitId, uint256 _exp, uint32 _type) public {
    Unit storage _unit = tokenToUnit[_unitId];
    _unit.defense = _exp;
}

Contract Quests.sol

function addUnitExp(uint256 _unitId, uint256 _exp) public {
    UnitsInterface data = UnitsInterface(unitsContract);
    data.addUnitExp(_unitId, _exp);
}

Error: VM Exception while processing transaction: revert

PS: Etheremon is doing similar (increaseMonsterExp) here.

Thanks a lot :)

Code to reproduce:

Units.sol

pragma solidity ^0.4.24;
contract Units {
    uint totalUnits;

    mapping(uint => Unit) public idToUnit;

    struct Unit {
        uint id;
        uint exp;
    }

    constructor() public {
        Unit storage _unit = idToUnit[totalUnits];
        _unit.id = totalUnits;
        _unit.exp = 0;
        totalUnits++;
    }

    function increaseUnitExp(uint _id, uint amount) public {
        Unit storage obj = idToUnit[_id];
        obj.exp = amount;
    }
}

Quests.sol

pragma solidity ^0.4.24;
contract DataBase {
    function increaseUnitExp(uint _id, uint amount) public;
}
contract Quests {

    DataBase dc;

    constructor(address _dataContract) public {
        dc = DataBase(_dataContract);
    }

    // gate way
    function increaseMonsterExp(uint _id, uint _amount) public {
        dc.increaseUnitExp(_id, _amount);
    }

}


texts:
I have this warning in Remix Analysis tab for a basic send funds function:

function sendFunds(address receiver, uint amount) onlyOwner {
    if (this.balance < amount) throw;
    receiver.send(amount);
}

  Remix warning: Gas requirement of function () unknown or not constant.

I don't see why the gas cost would be unknown.

Can you help me out? Is there really a problem?

There is also this error which I think has no place there:

  Error: Type "address" not supported for state variable.

address public owner;


texts:
i still don't get the idea behind the "if you send 100 ERC20 to a contract, they're stuck there and these 100 ERC20 are lost forever"..
i really don't get.. like,  a contract has an address and a wallet like any normal acccount. if we send ERC20 to a contract, why don't we use the transfer method for example to take the token stored in the smart contract to some other account address.
Can anyone example this point to me ? thnx in advance.


texts: How to configure a default parameter for a deployed contract in truffle?

texts:
This is a follow-up question to How can I use deployed with a constructor argument

For testing purposes with mocha, I would like to configure my default deployed contract so that it is instantiated with the correct parameter. Is there a way to configure truffle / pudding so that the contract is always deployed with a certain parameter value?


texts: Need help on ethstats app for private net

texts:
have anyone used the --ethstats for private net? I am trying to use it but I see below in the geth logs

Stats server unreachable err="websocket.Dial ws://host:port/api:
unexpected EOF"
Stats server unreachable                 err="websocket.Dial
ws://host:port/api: dial tcp host:port: connect: connection refused"

I have started the app eth-netstats app with below command

PORT=port WS_SECRET=secret npm start

I see the app does not receive any data
Can someone help me on this


texts: How do I efficiently install truffle and ganache-cli in a docker container?

texts:
Say I want to run a container with ganache-cli and truffle globally installed for dev purposes.
I have this first attempt Dockerfile
FROM node:15-alpine

RUN mkdir -p /home/node/app

WORKDIR /home/node/app

COPY . .

RUN apk add -t .gyp --no-cache git python g++ make &&\
    npm install -g truffle ganache-cli &&\
    npm install &&\
    apk del .gyp

ENTRYPOINT [ "/bin/sh" ]
CMD [ "./entry.sh" ]

which executes entry.sh at start:
#!/bin/bash

ganache-cli -m "test test test test test test test test test test test junk" -h 0.0.0.0 --secure &

sleep 2

truffle migrate --network develop

wait

and this works, for sure; but I want to make the process of building the image as fast as possible. Do someone knows how can I improve this Dockerfile?
UPDATE: I am installing this Docker image within a container. There is no cache between builds because a new container is created everytime. This is know as Docker-in-Docker.


texts: Listing transactions in a private blockchain?

texts:
In a private blockchain, is it possible to list the transactions based on from and to parameters in a transaction.

Is it possible to check the latest transaction from or to an address?

Also, is it possible to check the time of a specific transaction?

Since all this data is in the blockchain, can we do this through the javacsript console in geth?


texts: I am new to web3 development. I have seen the word 'hard fork' in web3.js documentation, but I never understood it fully. I also noticed that hardfork is used a lot when talking about chains and different ethereum networks. I am not sure it if is related, but I would like to know what exactly is a hard-fork.


texts: In Solidity, Modifiers & Mapping variable are stored where - storage or memory?

texts: In Solidity, Modifiers & Mapping variable are stored where - storage or memory ?


texts: ERR_SSL_PROTOCOL_ERROR while connecting private blockchain

texts:
I'm working with private blockchain, and facing some issue with SSL configuration.
The system has two components:

The private blockchain that is configured on the VM.
The web application that initiating transactions.

There is the truffle config file of web app:
development: {
 host: "<serverIPAddress>",
 port: 8545,
 network_id: "*",
},

Provider configuration:
var web3 = require('web3');
web3 = new web3();

var provider = new web3.providers.HttpProvider(
        "http://" + truffleConfig.networks.development.host +
        ":" + truffleConfig.networks.development.port
    );

web3.setProvider(provider);

Issue:
Web application runs with HTTPS, and hence it gives an error when connection to the blockchain.
this request has been blocked the content must be served over https

If I use "https://" + truffleConfig.networks.development.host +, the error is
ERR_SSL_PROTOCOL_ERROR

Is there any way we can fix this issue?
It is working if we run web app with http, but we need to run web app with ssl only.


texts: cannot verify the contract address because of compiler version 0.4.9 not available in etherscan verify contract

texts: My compiler version is solidity 0.4.9, but i am not able to verify my contract address on etherscan verify contract, the reason is 0.4.9 is not in the list compilers...please tell me the solution to verify the contract.


texts: Embedding ETH Wallet Address into Webpage

texts:
Hey is there a quick way to embed an Ethereum wallet address and a button into my existing website so as to allow people to send in their ETH donations to me?

Or do I need to go through the whole npm install everything-in-the-world process, meaning web3, HD-wallet-provider, etc., then write up a whole contract, include the ABI code in my .js file - just to allow this fairly simple sendTransaction functionality?

Or am I over-thinking this?


texts:
How do you inspect the properties and methods of a web3 object in web3.py?

In Node.js, if I type in the name of my web3 instance and press enter, the object is printed in the console. I am able to see all properties. However, when I do the same in a python3 console, the following is returned in the console <web3.main.Web3 object at 0x10d563bd0>.

How can I see everything else?


texts: How can I restore my Mist wallet if I forgot password?[Windows]

texts:
Lets say, I have Mist on Windows, but I cannot remember what password I used for my wallet there. However, I am almost sure that it is some of passwords I usually use or their combination(like pass1+pass2, or even pass1+pass2+pass3). I tried pyethrecover, but it seems to be broken, also it requires to install python, but I don't want too install anything.
So how can I restore my password?


texts: Is it possible to use low mining complexity to remove some certain transaction in the past?

texts:
I have a question that has concerned me for a long time. It relates to the security and reliability of the blockchain applications.

Let's assume I want to build an application that uses Ethereum or some other blockchain platform. At first there will be only one mining machine so to keep the mining time adequate the block mining complexity should be not too high. I know that the mining time of one block is about 10 mins for bitcoin. After some time the other mining machine joins mine so the complexity should be adjusted automatically.

Let's suppose that my application is responsible for the real estate sales so it should be very reliable and safe to use. But what if some hackers decide to cheat a bit and remove some certain sale facts from the blockchain after the transaction has been confirmed, added to the blockchain and the money have been transfered also. As soon as they have hashing power bigger than the hashing power of those two machines they can do it by recalculating hash of the block they're interested in and the blocks that follow after. It won't be too difficult to do because the complexity has not been too high yet. And after they build their own blockchain version they can continue to support it and mine new blocks to make all the other participants accept this version of the blockchain. It is possible because of the requirement to accept the longest blockchain in the whole decentralized network. To keep it the longest one attackers just need to have enough hashing power and they already do. So a buyer is left without his money and a house he paid for.

This example can be projected to any type of blockchain applications.

So the question is - how to protect against this type of attack? Is there a way that Ethereum eliminates such abnormal situations? If yes, where can I read about it?


texts: Can you create a constant (read-only) state variable in Solidity?

texts:
Can you declare a constant variable in Solidity?

const uint answer = 42;

Or is the only way to do it with a const function?

function GetAnswer() constant returns(uint ret) {
  return 42;
}

I know you could always create a normal public variable and then just not have any setters in the code, but this is not immediate obvious from the declaration, so it seems preferable to explicitly declare a variable as a constant or read-only if the language supports it.


texts: VS code Expected identifier, got 'LParen'solc

texts:
I keep getting this error/warning on my vscode when I emit events and build constructors.

or

After a bit of googling I understand it is something about my compiler, since solc <0.4.18 does not support these features. This thread says I have to update truffle to fix this problem. Although, I'm not using truffle at all. I have

"solidity.compileUsingRemoteVersion": "v0.4.25+commit.59dbf8f1",

on my vscode settings and on my terminal I have

> $ solc --version
> Version: 0.4.25+commit.59dbf8f1.Linux.g++

Would appreciate any help.


texts: Payable: Sent - Hold amount - Sent_back mechanism (Refund)

texts:
[Q] When following transaction get called: Bank.pay({"from": eth.accounts[0], "value": 1});, who retrieves the money, does the owner of the contract? (Sorry I get lost who actually gains the money). And later on how could that money transfer back to the sender on another function call(this could be viewed as a refund process)?

I would like to carry out following scenario, if possible.

Client A sents some money (lets say 1 wei) to the contract's function, via Client_A calls following: Bank.pay({"from": eth.accounts[0], "value": 1}).
That money should be locked to be used by the gainer until payMeBack() is called. Basically owner of the money is not allowed to spend msg.value => 1 wei.
When Client_A calls following: Bank.payMeBack(): Contract's function will send back the money(imagine is refund process) to Client A, if condition passed. If condition fails, now lock on money should be removed and money is gained by the contract and owner of the money could spent it.

Example contract:

pragma solidity ^0.4.8;

contract Bank{
    address client;
    uint gainedWei;
    function pay() payable {
       client    = msg.sender;
       gainedWei = msg.value;
    }
    function payMeBack() {
     if(<some condition check>)
        //Some how it has to send back ether to client-A. We know the address we would like to send and the amount.
    }
}

Thank you for your valuable time and help.


texts:
If I ran Hera on my ETH node instead of the EVM, will it break the
node? I.e., is it buggy?
Are there significant performance differences between Hera and
the EVM as of right now?
I cannot find any critique / evaluation of Hera anywhere online, can
someone provide some resources?

Thank you.


texts: How to display the result returned from Oraclize's _callback function in dapp frontend?

texts:
I am using testrpc as client and truffle as development framework.And also using ethereum-bridge for Oraclize.

This is the contract code.I have downloaded the 'Oraclize API' (oraclizeAPI_0.4.sol)from the Oraclize github repo.I have added this file to the truffle contracts folder, and rename the file to usingOraclize.sol.And it is imported in the given contract.

  pragma solidity ^0.4.0;

  import "./usingOraclize.sol";

  contract ApiCall is usingOraclize {

        uint public DieselPriceUSD;

        function ApiCall() {

                OAR = OraclizeAddrResolverI(0x9851eb2d10b765d8857e7e1b060bc1eb166e89f2);
        }

        function __callback(bytes32 myid, string result) {
                if (msg.sender != oraclize_cbAddress()) throw;
                DieselPriceUSD = parseInt(result, 2);
        }

        function update() payable {
                oraclize_query("URL", "xml(https://www.fueleconomy.gov/ws/rest/fuelprices).fuelPrices.diesel");
         }

     }

The XML file in the link 'https://www.fueleconomy.gov/ws/rest/fuelprices' is as follows.

     <fuelPrices>
          <cng>2.06</cng>
          <diesel>2.57</diesel>
          <e85>1.93</e85>
          <electric>0.13</electric>
          <lpg>2.68</lpg>
          <midgrade>2.58</midgrade>
          <premium>2.82</premium>
          <regular>2.33</regular>
  </fuelPrices>

I have compiled the contract using 'truffle'

The Oraclize return the result diesel price as '2.57' using ethereum-bridge.

I want to use the result in index.js file to display it in frontend.How to use the result in dapp frontend?


texts: What does this code return? block.timestamp / 1 days

texts:
function today() private view returns (uint256) {
    return block.timestamp / 1 days;
}

Why do we need this function?


texts: Destination address does not receive all of sent Ether. Some wei was lost when I sent small amount of ether

texts:
When I sent 1000000000 wei, the destination address received only 999997440. 2560 wei was lost. Can you tell me how I can fix it? Where did 2560 wei disappear to?

(Balance before Send)
Source: 211109215254170802845
Destination: 124492759039157024777

(Balance after Send)
Source: 211109110253170802845 (-105001000000000) <= As expected. It includes value and fee.
Destination: 124492759040157024777 (+999997440) <= Not as expected. I expected 1000000000 since I sent 1000000000. 2560 wei was lost.

https://ropsten.etherscan.io/tx/0x70bc34dd4a845f07d49edb60b951df8ca926ef9f357c191f981e96276471168c

Update 1

I sent 0.1 Ether. Then the destination address received 0.1 Ether as expected. Seems it might be related to how much ether I send.


texts:
I've used metamask with web3.js multiple times before, with no issue. It's simple to integrate it, like discussed here: https://github.com/ethereum/web3.py/blob/master/docs/providers.rst

How does one do this for web3.py?


texts: How can a proxy contract create another contract?

texts:
A simple proxy contract looks like:

contract Proxy {
    function forward(address to, uint value, bytes data) {
        if (!to.call.value(value)(data)) {
            throw;
        }
    }
}

Using to zero [like forward(0, 0, data)] doesn't work.  Can a proxy contract create an arbitrary contract?

Can this code be modified or what's the Solidity inline assembly to do the job?


texts: Authenticate transaction in Web3.js application with password

texts:
I have a simple web3.js based app and like to call a method from an contract.

For this method an authenticaten is needed. I found some examples in the web using web3.eth.accounts.signTransaction
But in this case, I need the private key.

Waht I need is something like web3.eth.personal.unlockAccount, which unlock the account not for an time range, but for the transaction only.

Is this possible?


texts: How can I authenticate the caller of a function?

texts: I want to let any instance of a specific contract call a function, but no instances of any other contracts. Is such a thing possible? Maybe checking the hash of the bytecode of the calling contract msg.sender?


texts: How do smart contract communicate with other?

texts:
As we all know that an external account can send a transaction to smart contract. But I'm confused when it comes to how contracts talk with each other.

Contracts that exist within the global scope of Ethereum’s state can
talk to other contracts within that same scope. The way they do this
is via “messages” or “internal transactions” to other contracts. We
can think of messages or internal transactions as being similar to
transactions, with the major difference that they are NOT generated by
externally owned accounts. Instead, they are generated by contracts.
They are virtual objects that, unlike transactions, are not serialized
and only exist in the Ethereum execution environment.1

I fully understand what it mean in the quote. But my question is HOW ? Are there some examples of smart contracts in Solidity show how contracts communicate with each other via "message"?