texts: A few times ago I bought ethereum with anycoindirect.eu.  They send it to my address but the problem now is when I want to sell it I don't find the private key anymore?  Is it lost?  I only have a transaction ID from the anycoindirect.eu.  I also see with blockchain the coin are still in my address.  Thx for the help!


texts: using event in contract vs web3 on 'receipt' event

texts:
whats the difference between using events in my contract to execute something if event is emitted or executing the function when the transaction is mined?
Is there any case in which event may be emitted but transaction fails to be mined?


texts: Sent to PRIVATE address in etherwallet instead of ACCOUNT address

texts: I have sent ether to my PRIVATE ADDRESS instead of ACCOUNT ADDRESS in myetherwallet - What do I do? Please HELP!!!


texts:
I use geth to run an ethereum node and mist to compile contract. Allways have worked fine until I change to the next version of Geth. Now I use version 1.7.3.

The problem is that Mist is still looking for version 1.7.2

How can I tell mist to look for version 1.7.3?


texts: Tracking transaction attempts/failed attempts sent to a contract from unknown parties

texts:
In light of the recently killed parity library and how the person responsible went around randomly trying to kill contracts, is there a way of monitoring smart contracts for attempted and potentially malicious transactions sent by unknown parties?

For successful transactions, we can watch for events.  (This helps to monitor and alert for any critical actions, such as LogOwnerChange or LogPayment)
If you originate a transaction, you can check for its success by checking
the transaction receipt. So the sender can check.

So my question is, is there any way to
   monitor for unknown / random transaction requests/attempts being sent
   to the contract, that have failed? (other than manually checking Etherscan)


texts: Help with adding Function Balance of - tokens to owner

texts:
How do I modify this so that all created tokens go to Owner (the one who  receives funds to the Beneficiary address). I assume this contract is one requiring change.

contract ERC20Basic {

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

}


texts: Cannot set property 'defaultAccount' of undefined

texts:
I am trying to run a DApp with metamask enabled , but this error surfaces .
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My TOKEN</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>

    <script type="text/javascript" src="./abi.js"></script>
    <script type="text/javascript">

    var MyToken;
    var Web3;
      $(document).ready(function(){

      window.addEventListener('load', async () => {
        // Modern dapp browsers...
        if (window.ethereum) {
            window.web3 = new Web3(ethereum);
            try {
                // Request account access if needed
                await ethereum.enable();
                // Acccounts now exposed
                web3.eth.sendTransaction({from : web3.eth.defaultAccount});
            } catch (error) {
                // User denied account access...
            }
        }
        // Legacy dapp browsers...
        else if (window.web3) {
            window.web3 = new Web3(web3.currentProvider);
            // Acccounts always exposed
            web3.eth.sendTransaction({from : web3.eth.defaultAccount});
        }
        // Non-dapp browsers...
        else {
            console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
        }
      });
      Web3.eth.defaultAccount = "0xCc525f550792D2c8154077B7F4a261dd024638C9";
          const address = '0x44e38857745536fC9d17dE71974512a250f9DF9b';
        MyToken = new Web3.eth.Contract(abi, address );
      });

Any help would be greatly appreciated.


texts:
I've done this before a million times, but I can't figure out why I can't connect to a remote host anymore.

I've setup a basic Ubuntu 16.04 VM on Digital Ocean, isntalled Geth on it, and started a new private network on it using:

geth --dev --datadir="." --maxpeers 30 --identity "VM_NODE" --ipcapi="admin,db,eth,debug,miner,net,shh,txpool,personal,web3" --rpcapi "db,personal,eth,net,web3" --port="30303" --rpccorsdomain="*" --networkid=999777 --rpc --rpcaddr="0.0.0.0" console

I then created a new account and started mining using miner.start(1) and then got my admin.nodeInfo:

> admin.nodeInfo
{
  enode: "enode://31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff@[::]:48298",
  id: "31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff",
  ip: "::",
  listenAddr: "[::]:38647",
  name: "Geth/VM_NODE/v1.5.8-stable-f58fb322/linux/go1.7.3",
  ports: {
    discovery: 48298,
    listener: 48298
  },
  protocols: {
    eth: {
      difficulty: 14643008,
      genesis: "0xe5be92145a301820111f91866566e3e99ee344d155569e4556a39bc71238f3bc",
      head: "0x4aaceb68f863da428a6375814a4a00bbde5ac9111b1a05210af4585a06908e27",
      network: 999777
    },
    shh: "unknown"
  }
}

I then set up a private network with the same genesis file locally (on OSX) and try to connect with the remote network using a couple different ports:

> admin.addPeer("enode://31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff@178.62.254.13:8545")
true
> admin.addPeer("enode://31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff@178.62.254.13:30303")
true
> admin.addPeer("enode://31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff@178.62.254.13:48298")
true
> admin.addPeer("enode://31b424ffd9808996a2aea1f6da85e3996a9860c4ccf998114a9df28cebfcb7390c98cd1bcd9e1124f814646c3201cd7c4d6df15a6fd63a7c5408522a812b56ff@178.62.254.13:38647")
true

It seems to connect fine, but I don't seem to have a connection:

> net.peerCount
0
> admin.peers
[]

I've tried setting up a new VM two times, and I've restarted the network on both sides and tried many different setups, but it doesn't seem to work.

Does anybody know why it doesn't connect? All tips are welcome!

ps. Anybody is welcome to try connect to my VM. The ip address is in the calls to admin.addPeer above.


texts: Is it possible to mine my own txs with no fees?

texts:
It seems like minimum tx fee is around .001$ in Ethereum (maybe a little bit less) but I was wondering about the possibility of performing zero fee transactions, mining them by myself. Obviously, sending txs with gasPrice = 0 is useless because miners are not going to give them any priority, but ...

What if I change that priority in my own node?
Can I specify somehow on geth to mine with priority my own zero fee
transactions?
Is it possible to send transactions with gasPrice = 0?


texts: Required Understanding for Developing Ethereum Based Application

texts:
I am trying to get the understanding needed to develop an Ethereum based application.

Lets say if I want to develop an inventory system. Here are the basic operations
Purchase inventory, Maintain stock, vendor and Inventory Issue transactions to various departments.

So help me understand the basic design structure while implementing it in Ethereum block chain.

Just to start with what all contracts will be needed

Contract for Inventory stock operations

-> Struct to hold inventory data
-> Struct to hold Departments
-> Vendors will be basically an Ethereum blockchain user
-> initialize inventory
-> add departments
-> buy inventory
-> issue inventory

Should this blockchain be created in a private ethereum blockchain (i.e. lets say with a networkid starting with 5 and common across all nodes) as developing for a specific company
Each vendor should be registered in that blockchain network and have some ether balance

Like in case of a regular centralized application following kind of structure is expected
1. Table structure to maintain following - Inventory, Vendors, Departments, PurchaseOrders, IssueOrders etc.

My question maybe a bit vague but intention is to understand the perspective of the basic design strategy in case of blockchain based applications


texts: local private chain account, switch to test net, start to lose ether?

texts:
I built a local private chain, and created an account via geth.
Then I switched to test net from metamask.

After that, the account started to lose ether. People sent the ether in that account to other accounts.

It doesn't really matter since it's a test net. But I don't understand how it was done.

No one should have access to my private key, right? How do they transfer my test net ether to other accounts?


texts: solidity state variables lost after web3 connection reset

texts:
I setup an Ethereum 2 node system using geth and implemented a web3 client that talks to the 2 nodes.

what it looks like: Node A, Node B

I have a EthereumClient JS file where I start 2 web3 clients that talk to both nodes A and B as follows:

this.A = new this.web3.a.eth.Contract(abiDefinition);
this.B = new this.web3.b.eth.Contract(abiDefinition);

I then deploy the contracts (ensured I deploy it on A and reuse the same address to deploy on B as well)

Here's the contract I am using -

contract getSchwifty {
  struct myData
  {
    string actualData;
    bool dataFlag;
  }

  mapping(string=>myData) records;

  function addData(string id, string hashData) public {
    if (records[id].dataFlag != true)
    {
        records[id].actualData = hashData;
        records[id].dataFlag = true;
    }
  }

  function getData(string id) external view returns (string) {
        if (records[id].dataFlag == true)
           return records[id].actualData;
        else
           return "NULL";
  }

}

Now, I add some data to it using addData  and then retrieve it using the getData call. It works. No issues.

However, I now restart EthereumClient JS. (from where all these things are done). Basically, the web3 connection to the Ethereum nodes gets restarted.

Now, when I do the same getData operation mentioned above, it always returns Null instead of giving the correct data.

So, basically it looks like if the web3 connection to the Ethereum nodes is reset, the solidity member variables are also going away.

Any tips on what the issue could be? Please note that I am not restarting the actual Ethereum nodes itself - just the web3 client that talks to the Ethereum node


texts: Does the gas limit (not gas price) affect how quickly a transaction is mined?

texts:
Is there any advantage is setting higher gas-limit (not gasprice --> gas-limit)?
I know you have to set at least as much as that the smart contract needs to execute, but isn't this amount always the same?


texts: Difference between tokensToSend() and OperatorSend()?

texts:
I read eip777 but have no idea what's difference between tokensToSend() and OperatorSend().
Could you please clarify them for me?
Thank you.


texts: Receiving unknown token into smart contract

texts:
I was wondering if its possible to recognize one way or another a token that is sent to the smart contract, without token being previously registered?

Cheers,
Casper


texts:
I've seen a few tutorials that explain how to write contract code right inside the Parity's web interface. However, web interface says it's deprecated, and when I open the desktop UI, it doesn't have any option to open an editor.

Is it possible to write/test/deploy a contract using the Parity UI program?


texts: How to know, if a particular ethereum address exist?

texts: I want to know if a particular ethereum address exist or not. Is there any way using web3.js


texts:
I was testing my ganache compiler to see if it is working and I came across the most ridiculous set of errors
This is my code:
pragma solidity ^0.5.0;

contract Token {
  string public name = "My Name";
}

This is the console:
SyntaxError: Unexpected identifier
    at wrapSafe (node:internal/modules/cjs/loader:1024:16)
    at Module._compile (node:internal/modules/cjs/loader:1072:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at Object.require (node:internal/modules/cjs/helpers:92:18)
    at Function.load (/usr/local/lib/node_modules/truffle/build/webpack:/packages/config/dist/index.js:161:1)
    at Function.detect (/usr/local/lib/node_modules/truffle/build/webpack:/packages/config/dist/index.js:150:1)
    at Object.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/compile.js:68:1)
    at Command.run (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/lib/command.js:136:1)
    at Object.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/packages/core/cli.js:57:1)
    at __webpack_require__ (/usr/local/lib/node_modules/truffle/build/webpack:/webpack/bootstrap:19:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/webpack/bootstrap:83:1
    at Object.<anonymous> (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:89:10)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47
Truffle v5.1.63 (core: 5.1.63)
Node v15.5.0

I feel like it has to do with other files I have open and not the code itself. What do you think?


texts: What is the best way to interact with ERC20 contract via web3js?

texts:
I've trying to set up a dev environment for an ERC20 token. I configured my backend (NodeJS) and created a basic ERC20 token using Truffle and OpenZeppelin. Everything is fine, I was able to persist my contract into Rinkeby network. I already set up the Web3JS integration in my backend code (I'm using Infura) and I have the contract address in my hands. So now I want to interact with my contract via the backend.

My question is: How and what is the best way to interact with the contract?

I was able to interact with my Rinkeby contract using web3js a couple of day ago, but I had to paste the whole contract ABI into webpage (web3js instantiation). I don't believe it is the best way to interact with the contract and I didn't find any example of better way to do it.

Thanks in advance!


texts: How to create a snapshot of ERC-20 token balances?

texts: Token holder snapshots are useful for airdrops, dividends and such. How to create one?


texts: How can you calculate gas cost on an iteration of something such as updating balances on 1000 token holders?


texts: How to add an enode with Ubuntu and Parity UI?

texts:
I have a problem of parity syncing and some one suggest me to use an enode as follows :

enode://147573f46fe9f5cc38fbe070089a31390baec5dd2827c8f2ef168833e4d0254fbee3969a02c5b9910ea5d5b23d86a6ed5eabcda17cc12007b7d9178b6c697aa5@37.120.168.56:30303

The question is how to use this node ? I work with Ubuntu. Is there any specific command for this ?


texts: Why is an account not accepting the Ether sent to it?

texts:
If you check out the account 0xe358b3b9f29c67cb810c5184e6fde27d66ce036c you will see several incoming transactions with 100 Finney each. Yet the overall balance is 31 Finney. How is that possible?

If I imagined this were my account, and I were just confirming transactions with a block explorer, how could I figure out whether a transaction is really funding my account? Where did the 100 Finney go and why?


texts:
Using web.js, I can query the event logs of a contract using the "web3.eth.filter" method.  The documentation states that this method accepts an object with a "topics" property, which is says are "An array of values which must each appear in the log entries".

My question, can I match a substring of a topic?  For example, say I have an event like this:

event AddedEntity (
    string indexed _title
    string indexed _contents,
    uint256 indexed _id
);

and I fire that event in the smart contract like so:

AddedEntity("Week 34", "Interesting Data", 142);

Can I search the contract's event logs for the keyword "Interesting" and expect a match?  Or will I only find a match if I search for "Interesting Data"?


texts: Pending state of deploying contract on Kovan network

texts:
I am deploying my contract into Kovan network and faced with issue. When execute truffle migrate command it is go on blockchain and waits for confirmation:

2018-01-11 18:36:55   TRACE own_tx  Signer: Awaiting confirmation... (1).

Meanwhile in parity ui parity signer asks to unlock the account. After enter the password it goes into pending state. The assumption is it waits another block to use its hash for sign, though at this moment system in this pending state already 30 minutes.

Any insights?


texts: EVM - How is it connected to the Blockchain?

texts: I have a few problems understanding the software architecture of the Blockchain. For me Blockchain is the database where all transactions, receipts, balances, etc are stored. But how is the connection to the EVM? Is the EVM responsible for changing the Blockchain database? When a full node receives a transaction or a new block. It processes the transactions with the EVM. Is the internal storage of the EVM the Blockchain or what is the internal storage of the EVM? When it is not the Blockchain, is the EVM only responsible for processing the transaction and sending a receipt back to the blockchain so it can do an update? Are there two instances - the blockchain (database) and the evm (processor)- or one instance the evm which includes the blockchain database? I hope you know what I am trying to say here.


texts:
I've been involved with Ethereum for few months and am getting really excited about the functionalities it offers. Actually I'm trying to develop some contracts and deploy on the blockchain.

I use both Linux ubuntu 14.04 and Windows 7 for my Ethereum tests and hacks.

I'm just getting this nasty issue with Mix - every time I try to open a new project it freezes and crashes.

I also get these errors on startup:

http://pastebin.com/jJTzDVpT

Can anyone help me sort this out?


texts: Who is paying for a transaction within a contract?

texts:
Let's assume I do a transaction to a contract function with my external account, then I have to pay gas for this transaction.

If the function within the contracts makes now a transaction on his own to write something to an other contracts, who is paying then for this?

I was testing this in my truffle develop environment and it looks like my account just paid for the transaction to the first contract, not for the second transaction.

I also didn't send any Ether to the first contracts before. But the second transaction worked as well.

Are transaction from contracts free?
Or is this just a special behaviour in my test environment to make thing easier?

edit:

The contract makes a simple transaction, something like this:

contract First {
    Second secondContract;
    uint test;

    function setSomething(uint _testValue) external {
        secondContract.set(_testValue); //also set a uint within contract 2
        test = _testValue;
    }
}

If I add the following line in my test, the result is 0 Ether because I never send Ether to this contract.

console.log(`Contract balance: ${web3.fromWei(web3.eth.getBalance(firstContact.address))}`);

The test still works and if i read the value from the second contract I also get the right value back.


texts: any 3rd party service that can get all transaction?

texts:
3rd party service recommended
have any 3rd party service that can get all transaction of address?
because from my research the web3 cant get the full transaction by account.


texts: Is it secure to rely on 'now' or 'block.timestamp' for the deadline of an ICO?

texts:
I am planning on launching an ICO and have been reading through the security recommendations for writing solidity contracts.

My ICO checks if the deadline has been reached by using

if(now >= deadline){
    isClosed = true;
}

From looking at the other answers on here, I have gathered that a miner with significant power can manipulate the time if there was such incentive for him to do so (i.e. if the contract depends on the timestamp).

Would it be secure to use 'now' in my contract if it is simply checking to see if time has passed the deadline? Which in turn, would release funds only to specified people (so the miner would have no incentive to maliciously alter time)?

PS: I realise there are similar Q&A's out there, but given the recent hype with ICO's I feel it may be appropriate to clarify this for myself and future ICO developers with the case of specifying a deadline.

Thanks everyone.


texts:
I call

let inst = contract.deployed()

and then on inst I can then call

mybn = units.then(function(inst) {return inst.getBN()}

mybn looks like this

BN { negative: 0, words: [ 1, <1 empty item> ], length: 1, red: null }

and if I run mybn.toNumber() I get the error letting me know mybn.toNumber is not a function


texts: Solidity compiler command-line utility (solcjs) various problems

texts:
I am trying to compile a file using solcjs from a command-line, and running into various problems.

First of all, I need to supply in the command-line all the files that are imported by the primary file.

Otherwise I get ParserError: Source "SomeFile.sol" not found: File not supplied initially.

But when I do supply these files, I get a bunch of other problems.

The main issue seems to be the fact the one of the imported files resides in a sub-folder.

First I noticed that I cannot use a backslash, i.e., can only use a slash (I should emphasize that I am running on Windows).

So I've fixed that.

Then I noticed that I cannot use a relative path, i.e., must use the full path of the file.

So I've fixed that too.

I was able to detect and solve these problems by attempting to compile that specific file by itself.

Now back to my original goal - once I specify this file in the list of files passed to solcjs, I keep getting that File not supplied initially error.

Here is the command line that I am using:

solcjs --optimize --bin --abi -o build C:/project/util/file1.sol file2.sol main.sol

When I compile each one of the imported files separately, I get abi and bin files inside the build output directory:

solcjs --optimize --bin --abi -o build C:/project/util/file1.sol
solcjs --optimize --bin --abi -o build file2.sol

But no matter what I do, I am unable to compile the main file.

Compiler version is 0.4.15+commit.bbb8e64f.Emscripten.clang.

Thank you.


texts:
I made an ethereum tx with 21 gwei gas price. It is now pending since more then one hour. Theoretically when adoption increases and therefore more txs happen and everybody must set enough gas to be included in the Block my tx will never be confirmed due to the genious (sarcastic) blocksize limit (btw flawed system).

1) What can I do now to make my tx invalid?

2) Will my tx be removed from all mempools after some time if it gets not confirmed?

3) Before my tx I had 0.4 ETH. After my tx (which is pending now) it shows in MEW 0.1 ETH tough it is pending. Can I just withdraw ally my funds and send the tx again with a higher gas price and therfore make my old tx invalid due to no funds. WOuld MEW allow that?

EDIT: The tx now got confirmed even tough there are 21 pages of tx that payed a higher gas-price in the mempool.

4)  Whats the logic behind that?


texts: Truffle test case to unit test withdrawal pattern

texts:
How can I test the withdraw() function in a truffle javascript test case for the below contract?

The problem is, If I use the msg.sender from the same contract, the before and after balance will be same.

Is there a way to create a new test contract and use it to call the withdraw function from the javascript test case?

pragma solidity ^0.4.18;

import "./ConvertLib.sol";

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

    event NewDeposit(address _from, uint256 _value);

    function MetaCoin() public {
        balances[tx.origin] = 10000;
    }

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

    function deposit() payable {
        balances[msg.sender] += msg.value;
        NewDeposit(msg.sender, msg.value);
    }

    function withdraw() {

        if ( ! (msg.sender.call.value(balances[msg.sender])() ) ) {
            throw;
        }

        balances[msg.sender] = 0; // Please don't worry about re-entrancy for now.
    }
}

Withdrawal Pattern


texts: Is there a way to retrieve invalid Ethereum based tokens that were sent to MyEtherWallet?

texts:
I am in desperate need of help!
I have accidentally sent InvestFeed tokens ($ift) to my MyEtherWallet, which appears to be unable to hold those tokens. Is there any way for me to get these tokens back?
I already contacted the support of the exchange from which i sent the IFT tokens. Their response was:

  You may be able to recover these yourself though by importing the private key from your IFT into your ETH wallet. If you have a look online you should be able to find instructions on how to do this.

I'm afraid they misunderstood me, as i have no idea what this particular support member is talking about.

I have searched the internet for a while now to find a solution to this problem and finally decided to ask in a forum.

Please apologize if this isn't the forum for these types of questions.

Help is very appreciated!


texts:
Due to out-of-gas during deployment, I plan to split one large contract into two: contract A to keep state and is not meant to store any ETH, any state change functions are modified to be allowed to call from contract B only

Contract B is meant to receive/withdraw ETH and be public facing. Its withdraw function will validate the corresponding state in contract A before proceeding with msg.sender.transfer(_validatedAmount).

The question is: Could there be any pitfall of this design to split state and ETH into two contracts this way?


texts: Why does Ethereum plan to move to Proof of Stake?

texts: The initial version of Ethereum (Frontier) uses a Proof of Work based consensus algorithm, but I see that there are plans to implement a Proof of Stake based consensus algorithm called "Casper" in a future version of Ethereum.  What is the motivation for the move to implement Proof of Stake in Ethereum, when no other major blockchain is currently using this technology?


texts: Contract A has a function that depends on Contract B's state. How does concurrency work for these two contracts?

texts:
I was thinking about a scenario where one contract depends on another contract's state.

For example, contract a may want to decide on its next state update based on the current state of contract b by calling contract b's read function.

But what happens if:

Alice triggers this function on contract a.
At the same time (In the same block) Bob triggers a function that updates the state on contract b.
When this function from contract a tries to get the state from contract b, it could be that the state has already changed for contract b because of Bob's transaction from step 2 has already executed BEFORE Alice's transaction, or it could be Bob's transaction hasn't executed yet.

So it looks like there can be two different scenarios depending on the order in which Alice's function and Bob's function gets executed within the same block. Am I missing something?

How do people deal with this situation?


texts:
Hi guys, i need help!

Trying to make a func that converts string-presented float with 2 dec to uint * 00

etc. if _s = "970452.22" result must be "97045222"

but i do something wrong (when i try to execute it tells me "gas limit exceed 3000000")

contract testfunction {

    string public converted;

    function stringFloatToUnsigned(string _s) payable {
        bytes memory _new_s;
        uint k = 0;

        for (uint i = 0; i < bytes(_s).length; i++) {
            if (bytes(_s)[i] == '.') { continue; }

            _new_s[k] = bytes(_s)[i];
            k++;
        }

        converted = string(_new_s);
    }
}


texts:
Got this in pseudo-code (Solidity like...) from audit of past work of person from our company, in short it seems to be withdrawing first and adding later. Maybe not a good idea, especially since it's using "call" judging by the 34050 gas and not transfer?

function withdraw(uint256 amount) payable:
  require amount <= balanceOf[msg.sender]
  balanceOf[msg.sender] -= amount
  call msg.sender with:
     value amount wei
       gas gas_remaining - 34050 wei
  if ext_call.success:
      log Withdrawal(
            address src=_wdamount,
            uint256 amt=caller)
      return 1
  require balanceOf[msg.sender] + amount >= balanceOf[msg.sender]
  balanceOf[msg.sender] += amount
  return 0


texts: Is it possible for a mapping to run out of space?

texts:
Can storage mappings in a contract run out of space? Say that mapping was keyed to an address and the value as the following struct:

User
  bytes32 name
  uint8 age

Theoretically, if there was a user mapped to every possible address, would it ever run out of space? What if the struct had more variables?

Also, side question but on the same note. Do dynamic arrays have a max number of items? Can they only hold up to uint8 worth of items?


texts:
i don't know why i get this problem, anybody who can helps thanks a lot

pragma solidity ^0.4.21;

contract MathContract {
    function mulAtoB(uint a, uint b) pure public returns(uint) {
        return a * b;
    }
}

Error parsing /Users/yuwei/Desktop/1110/demo1/abcd/contracts/Migrations.sol: ParsedContract.sol:7:14: ParserError: Expected identifier, got 'LParen'
  constructor() public {

YuweideMacBook-Air:abcd yuwei$ truffle version
Truffle v4.1.4 (core: 4.1.4)
Solidity v0.4.21 (solc-js)


texts: All cases when Solidity compiles to invalid jump destination

texts:
Solidity generates EVM bytecode that leads to an invalid jump destination when:

throw is used
... ?
... ?

Can the above list be completed, with examples?

To explain the first item, throw in Solidity source code, gets compiled to EVM bytecode that leads to an invalid jump destination.  (Of course it assumes that the throw is not in dead code that might be optimized away.)  What are all the other scenarios that belong in the list?


texts: One general contract for all or spawn new one for each instance?

texts:
What be the advantages vs. disadvantages or running a general contract or spawning a new one for each instance. Let say, that I am providing a contract so people can create their own crowdfunding. Every time that a new crowfunding is created with the contract, is it better to spawn a new contract with "new" keyword, with its own data structure. Or is it more practical to keep a general structure with all the crowdfunding instances?

In my application, there will not be an interaction between the different instances.

In your experience, what should one look for when taking this type of decision.


texts: How long does it take to process a BNB for ETH swap on 1 inch exchange?

texts: I just swapped BNB for Ethereum on 1inch Exchange using metamask and that was over 2 hours ago. Currently up to 2477 block confirmations and counting. is this normal? how long does this usually take?


texts:
Can any one help me to find the solution, if I received a Ether in my wallet, I should be able to send 1% back to the Payee automatically?

Thanks
Amit M


texts: How can I do abi.encodePacked in Python or PHP?

texts:
Just concatenating strings doesn't work.
Keccak::hash(10 . $address, 256) is what I'm doing atm.


texts: Augur v2 trading fee relation to Open Interest

texts: How does the fee paid by traders to reporters relate to Open interest in Augur v2?


texts: testrpc throwing error "This has not yet been implemented"

texts:
I am using testrpc & truffle to build a test local blockchain. I am getting below exception while I run 'truffle test'.

Could you please help me.

Thanks,

ERROR:jsonrpc.manager:API Exception: {'message': 'This has not yet been implemented', 'args': ('This has not yet been implemented',), 'type': 'NotImplementedError'}
Traceback (most recent call last):
  File "/home/sarath/.local/lib/python2.7/site-packages/jsonrpc/manager.py", line 108, in _get_responses
    result = method(*request.args, **request.kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/testrpc/server.py", line 33, in inner
    return rpc_fn(*args, **kwargs)
  File "/home/sarath/.local/lib/python2.7/site-packages/testrpc/testrpc.py", line 158, in eth_newBlockFilter
    raise NotImplementedError("This has not yet been implemented")
NotImplementedError: This has not yet been implemented


texts:
Need this architecture

    {
      address1 => [struct1, struct2],
      address2 => [struct1, struct2, struct3,],
      address3 => [struct1, struct2, struct3, struct4, struct5],
      ...
    }

My Attempt

contract Gallery{
uint public emojiCount;
struct Token {
    uint token;
    string ipfsHash;
}
mapping (address => Token[]) public emoji;

function addEmoji (uint _token, string _ipfsHash) public {
   emojiCount ++;
   emoji[msg.sender].push(Token(_token, _ipfsHash));
 }
}

How do i return Struct array so that i can save Images IPFS String according to user account address [msg.sender] .

How is this possible in solidity
Thanks in advance


texts: Connecting Geth to Private (Parity-based) Blockchain

texts:
I have a private network running with three Parity nodes.  Each one of these uses the same chain spec file and I invoke parity with a unique network id.

With geth, I know to use the --networkid flag but it doesn't seem to be connecting to the other nodes.  And why should it?  It doesn't have the chain spec file.

How do I give geth the information in the chain spec file, such as the enode info, etc.?

EDIT I see that this has been marked as duplicate.  Unless I really did hit "submit" twice or something, I think the user is thinking of this thread:
Parity Chain Spec file in Geth?

It's quite obvious that these are significantly different questions, so I'm sure no further explanation is necessary.


texts: Possible maximum size of a website built from smart contracts

texts:
This article titled "Real World Use Cases for Ethereum" (here at blokt.com) mentions one interesting use case for smart contracts: web hosting.

The article says that

  Using Ethereum, web hosting could become a decentralized,
  network-based business.  In other words, a website would be hosted by
  the entire Ethereum network, making it virtually impossible to take
  down or tamper with.

This sounds like an interesting possible real-life use case for smart contracts, but many websites have requirements for available network bandwidth or the ability to host downloadable files (e.g. PDFs).

Assuming though that at least a small(ish) website is technically feasible, is there any information on what might be the maximum size of a website built from smart contracts?


texts: issue with persistence of blockchain data in ganache-cli

texts:
a request for these users (Richard Horrocks, Achala Dissanayake, shane, flygoing ), please read the questions completely and understand them... then answer them if you actually know something about the topic....before flagging them as duplicate, if you do not know the topic...please move to something you know something about on rather than giving wrong information just to score points

I am trying to use the persistence of blockchain data across invocations of ganache-cli. In summary,

Invoke ganache with --db and -m flags like so: ganache-cli --db /xyz/ganachedata -m <same mnemonic across invocations> -e 1000
Then, using web3.js, I create a new contract contract#1.
Kill and restart ganache with the same command invocation parameters as in #1
Now when I try to refer to contract#1 in my application, it tells me contract#1 does not exist.
However, If I try to create a new contract, the new contract gets assigned the same address that was assigned to contract#1 in the first invocation.
I also see that new contract was again created in block#1, so it looks like ganache-cli did not initialise blockchain from the data that was left by previous invocation of ganache-cli.

What I am doing wrong??


texts: What to do if Metamask doesn't show a deposit because it's an "internal transaction"?

texts:
This is a follow-up on the question "Do all transactions show in Metamask wallet?" from Sky Hayward, in which Sky asked about transactions that show up as successful on etherscan, yet the ether doesn't appear in one's Metamask wallet.  Ismael answered, "Unfortunately internal transactions are not displayed by Metamask.  See this report: https://github.com/MetaMask/metamask-extension/issues/565 .  Sadly, the link shows that this has been a known issue since 2016!
It seems like this makes Metamask unusable.  I tried to withdraw some ETH from an account at Blockfi to my wallet.  Blockfi apparently sent the ETH as a "smart contract", and for some reason it shows up as an "Internal txns" on etherscan.  Supposedly it was successful.  But Metamask doesn't acknowledge it.
I understand that theoretically, the ETH are now owned by my wallet, regardless of what Metamask thinks.
But I can't use them because Metamask doesn't credit them to me.  What do I do?


texts: How include Nethereum in an existing C# project as library

texts:
I try to include nethereum as a library in my C# project, so I have access to the appropriate functions (create transaction data, sign transaction data and so on...) for communicate to an arbitrary Ethereum Infura Node.
As a programming environment, I use an IDE which is very similar to Eclipse.
This is my intension: How create transaction raw data for using "eth_sendRawTransaction" in C#
In short, a C# embedded device which try to comunicate with a GO# device (Infura Ethereum-Node)^^

Thank you very much for your help :)


texts:
So I'm trying to setup my private node environment, I've got a startnode.sh script which looks like this:

  geth --networkid 4224 --mine --minerthreads 2 --datadir "." --nodiscover --rpc --rpcport "8545" --port "30303" --rpccorsdomain "*" --nat "any" --rpcapi eth,web3,personal, net --unlock 0 --password ./password.sec --ipcpath "~/.ethereum/geth.ipc"

When I try to run the script, I can see that all other variables are correct except my ipc path, which is for some reason always being set to the local repository where I execute the script:

INFO [03-15|22:32:27] IPC endpoint opened url=/home/lovro/ChainSkills/private/geth.ipc


texts: compile contract success but some function don't work once it's deployed

texts:
I tried to modify someone works that I found in stackexchange for learning reference. I was going to make shoppinglist contract, it could be compiled but when I deployed the contract, getitemcount, shopping loop, and shoppinglists functions couldn't work. The problem is when I add a new shopping item, it's recorded in shopping items but not for shopping list.
here is my script.
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

contract MyContract{
struct item{
    string itemname;
    uint itemprice;
}

mapping(address => item) public shoppingitems;
address[] public shoppinglist;

event shoppinglog(address item, string name, uint price);

function addshoppingitem(address itemID, string memory itemname, uint itemprice) external{
    shoppingitems[itemID] = item(itemname, itemprice);

}

function getitemcount() public view returns(uint count){
    return shoppinglist.length;
}

function shoppingloop() public {
    for(uint i=0; i<studentList.length; i++){
        emit shoppinglog(shoppinglist[i], shoppingitems[shoppinglist[i]].itemname, shoppingitems[shoppinglist[i]].itemprice);
    }
}
}

I guess, the problem is come from shoppinglist variable that isn't defined properly, but I can't debug it. can somebody help me?thanks.


texts: How to keep up with the gas price in a backend service

texts:
I have a small nodesjs app that is writing to a contract every now and then.

It works, but i had to manually check the current gas price and deploy afterwards.

What can I do to automate that? I dont want to hardcode the gasprice but set one dynamically that gets my TX through (in average) in one hour.


texts:
I create my contract with the following code:

pragma solidity ^0.5.0;

contract Coin {
    function sayHello() public view returns(bytes32) {
        return "Hello";
    }
}

truffle-config:

module.exports = {
  rpc: {
      host: "localhost",
      port: 8543
  },

  networks: {
    development: {
      host: "127.0.0.1",     // Localhost (default: none)
      port: 8543,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
      from: "0x3242587c258109ed8722d667501d2116f08e91d1",
      gas: 2100000
    },
  },

  mocha: {
  },

  compilers: {
    solc: {
    }
  }
}

And I migrate it with truffle migrate on my private network and it outputs:

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

   Replacing 'Coin'
   ----------------
   > transaction hash:    0x0c9476750b030a7e8ee35678643573e3f941292d3909bbb33a5248185c307774
   > Blocks: 0            Seconds: 0
   > contract address:    0x71A258BE260db4397d5AA32aa7F1BcbB7f03C071
   > block number:        10230
   > block timestamp:     1561343003
   > account:             0x3242587C258109eD8722d667501d2116F08e91D1
   > balance:             9.87546732
   > gas used:            502220
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0100444 ETH

   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.0100444 ETH

Summary
=======
> Total deployments:   2
> Final cost:          0.01527226 ETH

So I deployed it successfully, right?

Then I tried to interact with the contract with the following code

const Web3 = require('web3');
const Web3Accounts = require('web3-eth-accounts');

const web3 = new Web3(Web3.givenProvider || 'http://localhost:8543', null, {});

const coinbase = "0x7bd59507b55d46eb874e6a2f8ee4befa123e414e";
const owner = "0x3242587c258109ed8722d667501d2116f08e91d1";
const abi = /*abi*/
var coin = new web3.eth.Contract(abi, "0x71A258BE260db4397d5AA32aa7F1BcbB7f03C071",
    {defaultAccount: owner, defaultGasPrice: '20000000'});                   // Contract object

const main = async () => {
    try {
        let reply = await coin.methods.sayHello().call({from: owner});
        console.log(reply);
    }
    catch(error) {
        console.error(`error: ${error}`);
    }
};

main()
    .then(() => { console.log("done"); })
    .catch(err => { console.log("Failed with error: " + err); });

It outputted:

null
done

my envs:

  "dependencies": {
    "web3": "^1.0.0-beta.55",
    "web3-eth-accounts": "^1.0.0-beta.55"
  }

I started my private network with geth --port 3000 --networkid 58343 --nodiscover --datadir=./blkchain --maxpeers=0 --rpc --rpcport 8543 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner"

I just start in the blockchain world. Please forgive me if this is a dumb question.


texts: How to reverse byte order in uint256 or bytes32?

texts: Need to convert BigEndian to LittleEndian or vice versa.


texts:
I was playing with web3.eth.accounts.create() and web3.eth.accounts.wallet.create functions, and reading web3 docs about it. I know that an externally-owned account is the same as a wallet, you have an adddress and a private key associate to it.
I have been reading similar posts like this or this but they don't explain the difference between:

web3.eth.accounts.create
web3.eth.accounts.wallet.create

Are both analogous and give a similar result?
With both I get the same properties:
 - address: "0x..."
 - encrypt: function encrypt(r, n)
 - privateKey: "..."
 - sign: function sign(r)
 - signTransaction: function signTransaction(r, n)


texts:
Im installed quorum with tessera but when i need to attach to any node using command $ ./attach.sh 1 show error "Fatal: Unable to attach to remote geth: dial unix qdata/dd1/geth.ipc: connect: no such file or directory"
Any one can help me .... thanks


texts:
I had approximately 7600 DAO tokens sitting in my Mist wallet. After the hard fork, I sent these tokens to another Ether account in another wallet that I keep on a currency exchange site.

Here is the Etherscan
transaction record:
0xe7f042a442f8eddd13d2b2aba6b871eea31f28c53eea5df49ad6ff89e35702da

The transaction appears as unconfirmed in Mist, and the DAO tokens or their ETC equivalent are not displayed in the receiving wallet.

How can I reclaim my Ether?


texts: Why did my withdrawal from EtherDelta fail?

texts: I have 10 VERI coins on EtherDelta. I tried to transfer them to my wallet so I can then make my next move to transfer them to somewhere else. Over 4 hours has passed and these tokens have not moved with a warning of a bad jump destination. https://etherscan.io/tx/0x818345b40e95433f6c98e2f7ac3c11d51900dbd6c1ce61a7ec1f9e42053a6865


texts:
What is the specification of the 'this' keyword in Solidity?
How does it work?

Sample code from Solidity Features · ethereum/wiki Wiki

contract Helper {
  function getBalance() returns (uint bal) {
    return this.balance; // balance is "inherited" from the address type
  }
}


texts: web3.eth.personal.unlockAccount requires 3 arguments

texts:
I am using following code to unlock an account.

 web3.eth.personal.unlockAccount(address, password);

But I get an error message:

  Error: Invalid Arguments length: expected: 3, given: 2


texts: What is deployed smart contract address in solidity?

texts:
In remix IDE when we deployed the contract there is address on it.
What is that address and what that address is used for?
Like Ethereum account address is use for transaction and identify the user on blockchain network .


texts: I have setup the metamask plugin on my browser successfully. Now i need some test ethers to test the things. I tried to get some from here : http://faucet.ropsten.be:3001/  and https://faucet.metamask.io/But i am not getting ethers in my account. Can somebody help me out? Thanks in advance


texts:
I'm totally new to JS. I'm developing on ios and we need to use Web3js in our program. It's ok to call js function in obj-c. However, I use 'require' to import Web3js modules, it throws 'ReferenceError: Can't find variable: require'. I know it's about Nodejs runtime. I also tried to use browserify to build web3js ,but it showed some "Cannot find module ''web-core" from xxxx" error.

here is my code.
obj-c code:

NSString* path = [[NSBundle mainBundle] pathForResource:@"bridge/src/index" ofType:@"js"];
jsFunc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

JSContext* jsContext = [[JSContext alloc] init];
[jsContext evaluateScript:jsFunc];
JSValue* func = jsContext[@"getAddress"];
JSValue* = [func2 callWithArguments:@[@"0x8730f6ad1c0d387644590966bdbfedba44fe250118df0f97f11190ad5727b312"]];

js:

function getAddress(prvKey)
{
  try{
      var Web3 = require('../../3rd_party/web3.js-1.0.0');
      var web3 = new Web3();
      return web3.eth.accounts.privateKeyToAccount(prvKey);
     }
  catch (e)
  {
      return e;
  }
}

I know webView is another way to invoke js functions. It's more strange. I wrote the followings in a html which is invoked by my webView.

function getAddress(prvkey)
{
   var web3 = new Web3();
   return prvkey;
   ...
}

It returns an empty string even if I use try-catch. I totally have no idea how to troubleshoot.

Anyone could help me how to use Web3js from obj-c?

Many thanks.


texts: Testing contract interactions with Truffle

texts:
I have 2 contracts, User and Registry, interacting and I want to test their interactions with Truffle. Currently my test(s) for User are

contract('User', function(accounts) {
  // many tests here which only depend on User contract
})

I now want to test the interaction between the user contract and a registry contract. The relevant parts of each are

User.sol

pragma solidity ^0.4.11;

import "./Registry.sol";

contract User {
    address owner;
    address reg;
    bool verified;
    Registry registry = Registry(reg);

    // Register in the system
    function register(bytes32 _id)
        onlyOwner
    {
        registry.register(_id);
    }
    function getContractAddress(bytes32 _id)
        onlyOwner
    {
        registry.getContractAddress(_id);
    }
    function getPublicAddress(bytes32 _id)
        onlyOwner
    {
        registry.getPublicAddress(_id);
    }
    function verify()
        onlyReg
    {
        verified = true;
    }
}

Registry.sol

pragma solidity ^0.4.11;

import "./User.sol";

contract Registry {
    mapping(bytes32 => address) ID;
    mapping(address => address) Contract;

    function register(bytes32 _id) {
        ID[_id] = tx.origin;
        Contract[tx.origin] = msg.sender;
    }

    function getPublicAddress(bytes32 _id) constant returns (address) {
        return (ID[_id]);
    }

    function getContractAddress(bytes32 _id) constant returns (address) {
        return Contract[ID[_id]];
    }

    function verify() {
        User requester = User(msg.sender);
        requester.verify();
    }
}

How can I write a test in which Registry is deployed so I can then test register(), getContractAddress(), etc?

I checked out the docs but didn't find examples there.

EDIT: Just to complement to answer that was given

I added this

contract('User', function(accounts) {
  var user
  var registry // new part based on your answer
  Registry.new().then((inst) => {
    registry = inst;
  })

  // Check contract was deployed
  it("Should retrieve deployed contract", function(done) {
      // test
  })

It works and further down I have a test to set/get reg address which works fine (which means by the time I call a method on the contract, the address is already there). The problem is in this test

// Should not find user
  it("Should not find user", function(done) {
    patient.getPublicAddress(web3.fromAscii("123456789"), {from:accounts[0], to:patient.address})
    .then(function(res) {
      assert.equal(res, 0);
      done()
    }, function(error) {
        // Force an error if callback fails.
        console.error(error)
        assert.equal(true, false)
        done()
      })
  })

it returns Error: VM Exception while processing transaction: invalid opcode. There is this question here but I didn't get how to make it work from there (though I did make the mappings public in Registry).


texts: How to let parity EVM execute just some blocks from a state?

texts:
I want to do an experiment using mainchain data. The experiment aims to test EVM performance.
So, I want to let EVM execute some blocks and measure the performance.

Are there some tools that can be used?


texts: error: replacement transaction underpriced - Nonce increment? how? Atomic transaction?

texts:
trying to send 2 transactions through infura to ropsten smart contract, but got the error: "replacement transaction underpriced". For my understanding its a Nonce increment problem...tried this code without success...
var Contract = require('web3-eth-contract');
const contract = new web3.eth.Contract(abi, contractAddress);

web3.eth.getTransactionCount(account, (err, txCount) => {

    const txObject = {
      nonce:    web3.utils.toHex(txCount),
      gasLimit: web3.utils.toHex(800000), // Raise the gas limit to a much higher amount
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      //value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
      //value: 1000000000000000000,
      to: contractAddress,
      data: contract.methods.function1(["...).encodeABI()
    }

    const tx = new Tx(txObject, { chain: 'ropsten' })
    tx.sign(privateKey)

    const serializedTx = tx.serialize()
    const raw = '0x' + serializedTx.toString('hex')

    web3.eth.sendSignedTransaction(raw, (err, txHash) => {
      console.log('err:', err, 'txHash:', txHash)
      // Use this txHash to find the contract on Etherscan!
    })
})

web3.eth.getTransactionCount(account, (err, txCount2) => {

    const txObject2 = {
      nonce:    web3.utils.toHex(txCount2),
      gasLimit: web3.utils.toHex(800000), // Raise the gas limit to a much higher amount
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      //value: web3.utils.toHex(web3.utils.toWei('0.01', 'ether')),
      //value: 1000000000000000000,
      to: contractAddress,
      data: contract.methods.function2("....").encodeABI()
    }

    const tx2 = new Tx(txObject2, { chain: 'ropsten' })
    tx2.sign(privateKey)

    const serializedTx2 = tx2.serialize()
    const raw2 = '0x' + serializedTx2.toString('hex')

    web3.eth.sendSignedTransaction(raw2, (err, txHash2) => {
      console.log('err:', err, 'txHash:', txHash2)
      // Use this txHash to find the contract on Etherscan!
    })
})

Should I put in transaction2:
nonce = web3.eth.getTransactionCount(contractadress?) + 1

or
web3.eth.getTransactionCount() + 0

I'm missing something, tried these options but I got other errors. These 2 transactions work when alone.
Are they possible to do in an atomic transaction, ie in the same block?


texts: Ethereum Miners and Gas - Analyzing Chain Data

texts:
Currently looking at https://medium.com/google-cloud/how-to-query-balances-for-all-ethereum-addresses-in-bigquery-fb594e4034a7 and in the SQL Query to calculate address balances there is a part for  tranasction feed debits miners incur? How does that work? Miners are spending gas to mine?

-- transaction fees debits
select miner as address, sum(cast(receipt_gas_used as numeric) * cast(gas_price as numeric)) as value
from `bigquery-public-data.crypto_ethereum.transactions` as transactions
join `bigquery-public-data.crypto_ethereum.blocks` as blocks on blocks.number = transactions.block_number
group by blocks.miner


texts: How to resolve the issue while trying to test my contract

texts:
I'm new to blockchain development and can't figure out what I have done wrong. This is my smart contract Election :
    pragma solidity ^0.5.0;

contract Election {
    struct Candidate {
        uint id;
        string name;
        uint votecount;

    }

mapping (uint => Candidate) public candidates;
uint public candidateCount;

  constructor() public {
  a=5;
   addCandidate("Candidate 1");
   addCandidate("Candidate 2");
  }
  function addCandidate (string memory _name)  private {
    candidateCount++;
    candidates[candidateCount]=Candidate(candidateCount,_name,0);

  }

}

This is a javascript file to test if there are exactly two candidates:
var elec=artifacts.require("./Election.sol");
contract("Election",function(accounts){
    it("initialised with two candidates", function(){
         var a;
        return Election.deployed().then(function(instance)
        {

            return instance.candidateCount.call();

        }).then(function(count){
            assert.equal(count.toNumber(),2);
        });

    });

});

This is the error I'm getting. Somebody please help.


texts:
I have bought some CTR Centra from Cryptopia Exchange and I want to store them in MyEtherWallet.
How do I do that


texts: send() or transfer() functions always fail

texts:
I created a few code below

pragma solidity ^0.4.19;

contract SendAndTransferExample {

    function SimpleSendToAccount() public returns(bool) {
       return msg.sender.send(10000000000000000000);
    }

    function SimpleTransferToAccount() public {
       msg.sender.transfer(10000000000000000000);
    }
}

I executed both functions using JavaScript vm and that result always same like that. first result when I executed send() function

and below result when I executed trasfer() function

transact to SendAndTransferExample.SimpleTransferToAccount errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value.  Debug the transaction to get more information.

I have no idea what was wrong. Seombody help me please.


texts: I downloaded the etherum wallet, how do you back it up wallet.

texts: I saw somewhere to copy your etherum key and email it to yourself. this way you have can find it. I would imagine this would be needed, say your computer gets stolen. Please if anyone has suggestions to protecting and backing up my wallet.


texts: How can we calculate swarm storage cost?

texts: I am trying to integrate ethereum to another fin-tech app, the basic idea is to store the transaction details on swarm and then pass the hash on ethereum network. I haven't used swarm earlier and I am wondering how to analyze operational cost for the storage?


texts: Corporate key store for storing private keys - Ethereum

texts:
Is there a device to store private keys of Ethereum in a corporate world? For example, employees of a company would identity themselves using their business-credential and this device could sign their transactions.
Something similar to: https://github.com/hyperledger/composer/wiki/HSM-Support

Thank you!


texts: How the data management is done in Ethereum blockchain?

texts:
Anyone who have a good idea about ethereum blockchain storage can send me some docs to get a good idea for myself?

i am in a full confused state.


texts: How to pass IERC20 as argument in solidity?

texts:
i'm trying to deploy sushiSwap on my local machine. but i don't know what should i pass a argument in constructor...
code is like...
pragma solidity 0.6.12;

import "./IERC20.sol";
import "./ERC20.sol";
import "./SafeMath.sol";

contract SushiBar is ERC20("SushiBar", "xSUSHI"){
    using SafeMath for uint256;
    IERC20 public sushi;

    constructor(IERC20 _sushi) public {
        sushi = _sushi;
    }

    // Enter the bar. Pay some SUSHIs. Earn some shares.
    function enter(uint256 _amount) public {
        uint256 totalSushi = sushi.balanceOf(address(this));
        uint256 totalShares = totalSupply();
        if (totalShares == 0 || totalSushi == 0) {
            _mint(msg.sender, _amount);
        } else {
            uint256 what = _amount.mul(totalShares).div(totalSushi);
            _mint(msg.sender, what);
        }
        sushi.transferFrom(msg.sender, address(this), _amount);
    }..

. so on


texts: Manual TX over Testnet - Error: exceeds block gas limit

texts:
I was trying to follow: https://github.com/ThatOtherZach/Web3-by-Example/wiki/Send-Ether-Transaction to create and broadcast my first transaction on the ethereum testnet rinkeby.

However, I am struggling for hours after I managed to create an Address and to fund it (https://rinkeby.etherscan.io/address/0x24003FbB79cfA541eE32C59ef3A7424541f4AA01). I also tried the ropsten testnet, and with all possible gasPrice/gasLimit combinations (not even commenting them out helps) but same errors all the time:

Error: Returned error: exceeds block gas limit

My code:

 // Add the web3 node module
var Web3 = require('web3');

// Show web3 where it needs to look for the Ethereum node.
web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/Whm5Ks3VGzJMBGHh4MEx'));

// An extra module is required for this, use npm to install before running
var Tx = require('ethereumjs-tx');

// Used to sign the transaction. Obviously you SHOULD better secure this than just plain text
var privateKey = new Buffer('265f303edd16be057608a0810414c2889c24e7ce8e9e4a88ae5b8a561c26935a', 'hex');

 // The receiving address of the transaction
var receivingAddr = ('0x29307EE93F49E9eB1425e40C9119b9Cb6e39d9B5');

// Value to be sent, converted to wei and then into a hex value
var txValue = web3.utils.numberToHex(web3.utils.toWei('0.001', 'ether'));
console.log(txValue);
// Data to be sent in transaction, converted into a hex value. Normal tx's do not need this and use '0x' as default, but who wants to be normal?
var txData = web3.utils.asciiToHex('hi');

console.log('gasprice1');

var rawTx = {
  nonce: '1', // Nonce is the times the address has transacted, should always be higher than the last nonce 0x0#
  gasPrice: '0x38d7ea4c68000', // '0x14f46b0400', // Normal is '0x14f46b0400' or 90 GWei
  gasLimit: '2100000', //'0x2710', // Limit to be used by the transaction, default is '0x55f0' or 22000 GWei
  to: receivingAddr, // The receiving address of this transaction
  value: txValue, // The value we are sending '0x16345785d8a0000' which is 0.1 Ether
  data: txData // The data to be sent with transaction, '0x6f6820686169206d61726b' or 'oh hai mark'
}

console.log(rawTx); // This is used for testing to see if the rawTx was formmated created properly, comment out the code below to use.

var tx = new Tx(rawTx);
tx.sign(privateKey); // Here we sign the transaction with the private key

var serializedTx = tx.serialize(); // Clean things up a bit

console.log(serializedTx.toString('hex')); // Log the resulting raw transaction hex for debugging if it fails to send

web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')) // Broadcast the transaction to the network
.on('receipt', console.log); // When a receipt is issued, log it to the console

If I use the values from https://github.com/ethereumjs/ethereumjs-tx
gasPrice: '0x09184e72a000',
gasLimit: '0x2710', I get:
Error: Returned error: intrinsic gas too low

Following error with this setup:
{ nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  from: '0xED54EbBC73C7fb8B6607547b7541D8799708D93B',
  to: '0xB29d0bDe21FF7f1a89eBEd0D9c40cA9f71119D7C',
  value: '0x38d7ea4c68000',
  chainId: '3',
  data: '0x737072656164' }

Error: Returned error: insufficient funds for gas * price + value


texts:
I'm trying to execute my first contract on Ethereum.  I've been able to compile and deploy one of Vyper's test examples of an auction.  I believe the contract is executed when a transaction is sent to it.  The thing I'm not yet understanding is when the constructor and the methods are called.  As I understand it the bytecode is sent to the nodes for computation, but I'm missing how/when/where the constructor and the methods themselves are called.  For instance, below I have a method called 'bid', but how does the transaction know how to call 'bid'?  I think I'm not quite understanding the entire process from transaction submission down to contract execution.  Thanks for your help!

beneficiary: public(address)
auctionStart: public(timestamp)
auctionEnd: public(timestamp)
highestBidder: public(address)
highestBid: public(uint256)
ended: public(bool)
pendingReturns: public(map(address, uint256))

@public
def __init__(_beneficiary: address, _bidding_time: uint256):
    self.beneficiary = _beneficiary
    self.auctionStart = block.timestamp
    self.auctionEnd = self.auctionStart + _bidding_time

@public
@payable
def bid():
    assert block.timestamp < self.auctionEnd
    assert msg.value > self.highestBid
    self.pendingReturns[self.highestBidder] += self.highestBid
    self.highestBidder = msg.sender
    self.highestBid = as_unitless_number(msg.value)


texts: ChainlinkClient.sol v0.8.0 NOT working (request.add("get", ""))

texts:
Im am relatively new to using ChainLinks ORACLE contract in solidity. I have recently managed to successfully integrate their VRFConsumerBase.sol in my consumer contract to generate random numbers. However, when i want to integrate and use their Client to make simple Get request to my API, it throws this error upon compiling
CompileError: TypeError: Member "add" not found or not visible after argument-dependent lookup in struct Chainlink.Request memory
I am currently using Truffle v5.1.65 & Sol 0.8.0. I am importing my ChainLink files as shown below :
import "@chainlink/contracts/src/v0.8/dev/ChainlinkClient.sol";

Here's My function :
    function uploadTokenDataToServer(NFT memory nft) public{

     require(LINK.balanceOf(address(this)) >= linkFee, "Not enough LINK - fill contract with faucet");

    Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.confirmUpload.selector);

    string memory finalURL = append(nft.ID,nft.creator,nft.desc) ;

    request.add("get", finalURL);

    return sendChainlinkRequestTo(oracle, request, linkFee);
}

It seems that the add function is not being detected when compiling. Any help would be greatly appreciated.


texts: Under what circumstance does CALL return nonzero?

texts:
Reading the yellow paper http://yellowpaper.io/ documentation for CALL.

  µ'_s[0] ≡ x
  where x = 0 if the code execution for this operation failed due to an exceptional halting, Z(σ, µ, I) = > or if µs[2] > σ[Ia]b (not enough funds) or Ie = 1024 (call depth limit reached); x = 1 otherwise.

Would all of these cases cause an exception and halt execution, therefore preventing CALL from returning?

It's like dropping a nuclear bomb with a greeting card attached... useless because the greeting card is gone on impact.


texts:
Wrapped Bitcoin (WBTC) is the first ERC20 token backed 1:1 with
  Bitcoin.

So there must be a mechanism to lock BTC in the Bitcoin network and mint WBTC in Ethereum. I read about custodians and merchants which are part of that mechanism. So can I also swap BTC to WBTC, or actually this flow is centralised?


texts: Check If address is actual token not just contract

texts:
Is there a way using web3 to check if an address is a token which also has a Symbol? With the getCode function I only found a way to check if its a contract but not a tradable token.
Regards


texts: How to initialize empty Drizzle instance and later provide contracts data

texts:
Following Drizzle documentation, Drizzle instance can only be created with:

const drizzle = new Drizzle(options)

Where the options is mandatory. And trying to not pass options will generate an error:

// The following will raise the error:
//   TypeError: Cannot read property 'contracts' of undefined
const drizzle = new Drizzle();

And when trying to pass an empty object {}, another error will be thrown:

// The following will raise the error:
//   TypeError: Cannot read property 'length' of undefined
const drizzle = new Drizzle({});

The idea is that: I want to create the Drizzle object in the constructor and later I will provide the data later dynamically:

var contractConfig = {
  contractName: "0x066408929e8d5Ed161e9cAA1876b60e1fBB5DB75",
  web3Contract: new web3.eth.Contract(/* ... */)
}
events = ['Mint']

// Using an action
dispatch({type: 'ADD_CONTRACT', drizzle, contractConfig, events, web3})

// Or using the Drizzle context object
this.context.drizzle.addContract(contractConfig, events)


texts: How is it possiblle - Although one or More Error Occured [Reverted] Contract Execution Completed?

texts:
How is it possible that the txn is reverted due to some error but completed?

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


texts: Questions about some details on Ethereum transfers and Gwei

texts:
I read up about Gas and Gwei but there are some things in practice that i don't understand / know what to do. I just started learning about Ethereum (received my first ETH coins today and started using Metamask and exchange markets( GDAX, Kucoin). Here are some questions i can't seem to figure out or be sure on my own...

When i transferred varying amounts of ETH from GDAX to Kucoin, the Gwei seems to be automatically set at 100+ (110 to 122). My understanding is that that is a pretty high Gwei and is not necessary. I can't seem to figure out how to adjust the Gwei value though. Is there a market exchange specific setting to adjust Gwei for xfering ETH?

Does the transfer fee vary at all depending on the amount of ETH transferred? I thought it would make sense for it to vary, but what i find is that i pay the same amount of fee even when i transfer a small amount of ETH.

The "Gas Used" amount also seems to remain constant for any amount of ETH xfer i tried (at 21,000). Is this a value that i can adjust? Or is it always set like this?

Well... maybe not just an ETH question but.. i'm missing a transfer i made to KuCoin. Since that particular xfer wasn't showing up on my Kucoin account, i went to Etherchain.org to check up using the transaction hash. It shows everything was ok: correct wallet address, 1819 confirmations in green text, confirmed in 58 seconds, etc... everything seems fine. But that xfer just hasn't been made into Kucoin. Is this a not-so-uncommon problem that has to do with Kucoin (like they somehow "lost" the incoming transfer or something)? How would you resolve such issues?

The whole Gas usage and Gwei thing seem a bit confusing... It seems though.. is Bitcoin more expensive when transferring? Also, the transfer fee doesn't depend on the amount you transfer, is that correct? This seems a bit.. unreasonable to me as a newbie, but i suppose there are reasons developers made it like that.. Is it always a better idea to transfer a large amount of ETH / BTC at once, instead of small amounts in multiple transactions?

Many noob questions.. hope you're not annoyed :) Thank you


texts: As the tittle says, I would like to make a demo but I don´t know if Quorum supports windows.


texts:
I have been reviewing keccak256 implementation and sha3-256 that follows the FIPS standard.  The sponge function is taking a while to set in, but I have noticed a difference in implementation :

I noticed web3.js uses crypto-js implementation of sha3: https://github.com/brix/crypto-js/blob/develop/src/sha3.js
From that  I gather the  var LFSR = 0x01;

which is set to 0x06 in sha3-256.  Am I correct in this observation?

What other differences are there?


texts: Invalid JSON RPC response: undefined, when running web3.eth.accounts (Node)

texts:
I'm very new Ethereum and trying to follow this tutorial:

https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2

But when I run:

web3.eth.accounts

I get an error:

Error: Invalid JSON RPC response: undefined
    at Object.InvalidResponse (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/errors.js:38:16)
    at HttpProvider.send (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/httpprovider.js:95:18)
    at RequestManager.send (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/requestmanager.js:58:32)
    at Eth.get [as accounts] (/Users/me/Ethereum/hello_world_voting/node_modules/web3/lib/web3/property.js:107:62)
    at repl:1:9
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:433:10)

Everything up until this worked.

Looks like an associated question here, but I don't have enough background to understand and follow it.

Error: Invalid JSON RPC response: undefined from node web3.js app

Can anyone point me in the right direction?


texts: Issue in type conversion : Explicit type conversion not allowed from unit256 to bytes1

texts:
I am trying to convert the unit to string using the method. I have the "TypeError" in the line. Please check the screen shot below for the error message.

function uint2str(uint i) internal pure returns (string memory) {
    if (i == 0) return "0";
    uint j = i;
    uint length;
    while (j != 0) {
        length++;
        j /= 10;
    }
    bytes memory bstr = new bytes(length);
    uint k = length - 1;
    while (i != 0) {
        bstr[k--] = byte(48 + i % 10);   ----> this is the place I get error
        i /= 10;
    }
    return string(bstr);
}


texts: is the code for the ETH contract available?

texts:
As the initial ETH coins were minted and not mined, the contract which was used must exist somewhere.

It would be very interesting to study this contract in order to verify how new ETH can be minted.

We all know of the rewards which are granted to miners when they discover a new block. Is that the only way to mint new ETH? And how can we be sure?


texts: Can you execute functions in Smart Contracts upon deployment?

texts:
I'm looking to execute functions in my smart contract immediately upon deployment to the blockchain. Yes I could probably program in a execution of the functions just after the code to deploy the smart contract, but it seems like a waste of gas, is there some more efficient way to do this. The contract is really simple.

    pragma solidity ^0.4.18;

contract EtherTransfer {

    address public owner;

    function transfer() public {
    owner = 0x627306090abaB3A6e1400e9345bC60c78a8BEf57;
    owner.transfer(1000000000000000000);
    }

    function() payable public {}

function kill() public {
        if (msg.sender == owner)
        selfdestruct(owner);
    }

}


texts:
I'm trying to create a mobile app that will

1) generate transactions

2) send them to my server as a string

3) and my server will relay that transaction to a Smart Contract on the Ethereum network.

I want to encrypt / sign these transactions on the client side (the mobile app) and then decrypt it on the Smart Contract side using a private / public key, so my plan is to hardcode the private key into the mobile app.

If the message is successfully decrypted by the Smart Contract, that should mean that it is a valid transaction coming from an authorized source. If the message decryption fails, that means it's a hacker and nothing will happen.

In this context, how would I generate a private / public key for just that one Smart Contract? Is there a way in Ethereum or can I just make up any rubbish I want? e.g. "abc123"


texts: TypeError: Library functions must be implemented if declared for solc compiler version ^0.6.0 library implementation

texts:
Suppose I have the following code:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;

library SomeLib {
    function add(uint256 a, uint256 b) public returns(uint256);
}

contract SomeContract {

    function calc(uint256 a, uint256 b) public returns(uint256) {
        uint256 ans = SomeLib.add(a, b);
        return ans;
    }
}

It works with no problem if my solc compiler version < 0.6.0 however, it fails to compile version >= 0.6.0 returns following:
TypeError: Library functions must be implemented if declared.

Any idea or something missing here?
Here are the setup:
$ npx truffle version
Truffle v5.1.56 (core: 5.1.56)
Solidity - 0.6.12 (solc-js)
Node v12.18.3
Web3.js v1.2.9


texts: What does it mean to use a 'pending' or 'latest' block for transactions or estimateGas?

texts: I understand what it means when reading the block chain (getting balances for example), but what it does it mean when sending transactions or estimatingGas(which sorta dry runs the transaction).  If you send 'pending' in an eth_call which writes to the block chain what affect does that have on the execution?


texts: Adding liquidity to pancakeswap on testnet failed with error 'TransferHelper: TRANSFER_FROM_FAILED

texts:
as mentioned in the header, I'm trying to add liquidity directly on the testnet pancakeswap contract with my own house token, but im recieving this error message:
 Failed with error 'TransferHelper: TRANSFER_FROM_FAILED

Here is the transaction details:
Im not sure what went wrong here, could someone point out my mistake?


texts: Error when Creating a Contract - related to Mapping

texts:
When I create a ABC_Creator Contract.   It gives the following error.   The code works fine for the intent.   Wondering why is this error showing up, what is the invalid opcode and what can be done to get rid of it.   Thanks,

pragma solidity ^0.4.17;

contract ABC {

    bytes32 public name;
    uint public value;

    function ABC(bytes32 _name, uint _val) public {
        name = _name;
        value = _val;
    }
}

contract ABC_Creator {

    ABC localABC;
    mapping (bytes32 => address[]) public abcMap;
    event Log(bytes32, uint);

    function createABC(bytes32 _name, uint _val) public {
        localABC = new ABC(_name, _val);
        abcMap[_name].push(localABC);
    }

    function getABCList(bytes32 _name) public {

        uint len = abcMap[_name].length;
        for (uint i = 0; i < len; i++) {
            Log(ABC(abcMap[_name][i]).name(), ABC(abcMap[_name][i]).value());
        }

    }

}


texts: would the world support a decentralised web

texts:
currently, there are a few dozens of applications with distributed ledgers running in the world.

For example, Ethereum wallet takes about 11GB of my storage. which is not little.
That is just one application.

how would you manage multiple ledgers on a single machine?
Do my localhost ledger have to contain the entire ledger?
Asking also from a CPU / GPU stand of point. can the world's devices handle this much traffic?


texts:
What is the easiest way to fill a storage array?

uint[4]  temp;
temp = [1,2,3,4];
>> TypeError: Type uint8[4] memory is not implicitly convertible to expected type uint256[4] storage pointer

As far as I understand the first line is read as a storage variable declaration, but inplace array assignment is applicable only to memory variables.

Is there a way to fill temp with specific numbers except for element-by-element assignment?


texts:
Ethereum was withdrawn from my wallet to the wrong address.
I am using metamask and decentralized wallet application.

The keystore file is stored in Apple could storage.

Mnemonic did not use or save anything except when backing up.

The wrong address is said to be unknown to the decentralized application service.

What are the possibilities?


texts: Can race conditions occur in PoA network?

texts:
I have the following contract deployed on my PoA network with two sealers, node1 and node2.

Let's assume a user, user1, submits a transaction with call to process() method to node1 and another user, user2, submits a similar transaction with call to same contract method to node2.

If node1 seals the block first, What will happen to user2's transaction? It won't be included in the block?

If a user knows which signer will seal a block next, He can submit a transaction to that sealer to win the race. Does PoA/Clique consensus employ some mechanism to overcome this?

pragma solidity ^0.4.7;

contract raceTest {

    uint8 x;
    constructor () {
       x = 1;
    }

    function process() public {
        require(x == 1);

        x = 0;
    }
}


texts: Why assert expends gas while require does not? (My intuition says te opposite is true)

texts:
Since assert corresponds to conditions that must never happen if the smart-contract code is correct my intuition tells me that someone calling an smart-contract that raises an assert must never be "punished" with gas expenditure since caller was not to fault. (Maybe nodes ought to black-list smart-contracts raising asserts and/or a mechanism be in place to allow to redirect new version/patched contracts with no assert).

On the opposite require corresponds to checks on the input data to functions, so my intuition tells me that invocation with incorrect data ought to be punished.

I think there is something I do NOT understand, or I just completely misunderstood the original intention of assert vs require.


texts: Parity syncing status for smart contract events with warp

texts:
So I'm trying to find the fastest way to fully sync a parity node in order to get all smart contract events, not just account states.

The problem I've found is that when parity has warp syncing enabled, the node will say it's synchronized, and the jsonRPC will allow you to successfully do any eth_getLogs call (or a web3 equivalent like web3.eth.contract.allEvents()), but with a freshly warped node, the data it sends back is incomplete (doesn't have all the events on the blockchain matching filter topics) without indicating any sort of errors (because the node doesn't even know about the data that it's missing yet). And as far as I can tell, there is no way to know if the response you get back is complete or not as long as parity is set to warp sync.

I tried to mitigate this problem by syncing parity with no-warp enabled, but after 3 weeks the node is still 500,000 blocks behind, and by my calculations will take another 2+ weeks to finish syncing which isn't acceptable (network/computation resources shouldn't be a problem as I'm running these on AWS C5.xlarge). I've also tried cloning entire VMs I have that are running fully synced parity nodes, but for some reason the cloned VMs have issues syncing in the future and holding connections to peers (even though I delete the network key and let it generate a new one)

I looked into Geth as a solution, and while initial syncing is fine, it's a deal-breaker because it doesn't have continuous db pruning after the initial sync so the DB size grows too quickly compared to parity with it's continuous pruning.

Basically my question is: How can I run/sync a parity node and be able to know if I have all contract events downloaded so I can make eth_getLogs calls and know if the data I get back is complete or not? Alternatively, is there a good way to clone my existing synced parity nodes?


texts: Sorting an Array of integer with Ethereum

texts:
I'm trying to have a simple array of integer sorted in Solidity but i couldn't find any real ressources so instead i'm trying to do it "the hard way" but so far with very little success.

Is anyone aware of anything that could help ?

This is what i've tried so far , but with no luck. Whenever i try it i'm getting out of memory errors.

  function quickSort(uint[] arr, uint left, uint right) private returns(uint[] _arr){
      uint i = left;
      uint j = right;
      uint tmp;
      uint pivot = arr[(left + right) / 2];
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      }
      if (left < j)
            quickSort(arr, left, j);
      if (i < right)
            quickSort(arr, i, right);
}

Anyone got something to share ?

Error is often " ERROR: invalid jump destination (PUSH1) "

Edit :

Same with :

function insertionSort(uint[] a){
 for (uint i = 1;i < a.length;i++){
  uint temp = a[i];
  uint j;
  for (j = i -1; j >= 0 && temp < a[j]; j--)
    a[j+1] = a[j];
  a[j + 1] = temp;
 }
}

edit 2 :

Fixed aswell

  function insertionSort(uint[] a)internal {
   for (uint i = 1;i < a.length;i++){
    uint temp = a[i];
    uint j;
    for (j = i -1; j >= 0 && temp < a[j]; j--)
      a[j+1] = a[j];
    a[j + 1] = temp;
   }
  }


texts: Creating a website with a wallet, similar to how etherdelta handles its exchange?

texts:
I don't have any intention of doing anything on the scale of an exchange. Just trying to do a little research into how difficult it would be and what technologies would be required.

Basically wondering how difficult it would be to set up a website with functionality similar to EtherDelta without the exchange. Just an account on the website with the balance of 1 token and the ability to withdraw/deposit that 1 token.

I'm completely unfamiliar with crypto, but thought of a fun little project I could muck around with, so trying to gauge how long it would take. The only hurdle I can think of is incorporating the token into the website.

Also, what technologies would be best for this? I've only vaguely looked into it as I figured just asking on here would be much quicker. I'm most familiar with PHP and vanilla JS. Is that possible, or would I have to use Node?

Thanks.


texts: how to setup multicurrency ICO / Crowdsale

texts:
I'm having difficulty finding information on how to setup a contract that accepts multi-currency like bitcoin, wave, ripple, etc. And also looking for a solution to distribute my tokens to these accepted coins.

A direction or links on how to setup these steps would be much appreciated.


texts:
My Dapp needs to dynamically deploy contracts. As such, I need to store the addresses of these contracts somewhere and opted for the following solution:

Log creation event
Retrieve contracts based on logs

The snippet which performs logging is this one:

event Created(address indexed _who, address indexed _to_whom, uint money, uint _max_duration);

//...

Created(msg.sender, _to_address, money_quantity, _contract_max_duration);

In web3.js I'm having a hard time trying to understand how to filter logs based on: Contract Type, _who parameter and eventually _to_whom parameter.

I'm getting all the logs (in js):

var filter = web3.eth.filter({fromBlock:0, toBlock: 'latest', topics: [/* ????!!! */]});

filter.get(function(error, result) {
   console.log(result)
})

In the console I get the hashes of 3 "topics" which I suggest, by reverse engineering, are the Contract Type hash and the other two indexed event parameters.

Let's say that I want to query for all events of type Contract Type having the current user as _who parameter. How do I do it? What do I insert in the topics argument?

Many thanks


texts: Add peers into a private blockchain network?

texts:
I have created a private blockchain network on windows OS by using two cmd console.

I am following this link in order to setup a private network.

Steps:

geth --datadir="d:/tmp/eth" -verbosity 6 --ipcdisable --port 30301 --rpcport 8101 console 2>> d:/tmp/eth/01.log

geth --datadir="d:/tmp/eth02" --verbosity 6 --ipcdisable --port 30302 --rpcport 8102 console 2>> d:/tmp/eth02/02.log

I have tried to add a peer by issuing the following command:

admin.addPeer("enode://f2157f8b90debf68e52bced6352cd08d942d24bdebc1ee734776f5560be86100bd256a5621868345799b044a5630c5cee3b40f1b105bdc03ce2da0be4e2c1dc1@0.0.0.0:30301")

Above command return true but when i check admin.peers it returns blank array.


texts: What's the maximum number of filters geth can hold and what happens when this maximum is met?

texts: Obviously, we should be calling uninstall on the filters we create on the node. However, assuming someone didn't uninstall them, how many are stored in memory and would there be a circular buffer to keep track of them that just stores the x most recent?


texts: How to connect IPC and RPC to transact fake ethers?

texts:
I have setup 2 nodes, 1 on testRPC and the other on geth(using cmd and mist).

How to sync both the nodes so that I can write a crowdfunding smartcontract for the accounts in both the private nodes to contribute?

Is it possible to connect by knowing RPC path and piping with IPC path using geth console?

Please explain how and where to get RPC path and also the method of piping required.


texts: What does the single line "_;" in OpenZeppelin's onlyMinter() function do?

texts:
In onlyMinter(), there is a line with only _;. I'm having troubles adding a minter address, so I'm just checking the various contracts that go into ERC721. The function is

modifier onlyMinter() {
    require(isMinter(msg.sender));
    _;
}

What does _; do? Is it an error?


texts: When using mapping, why use an address over bytes32?

texts: From an end user standpoint, they will never want to use the address for searching for mapped data when they could just submit a username for function parameters, so is there any specific reason why it would be better to use an address?


texts:
the javascript file  used to communicate with test-net :

$(document).ready(function(){

if (typeof web3 !== 'undefined'){
  console.log('Web3 found');
    web3 = new Web3(web3.currentProvider);
  } else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

$("#creatAccountSubmit").click(function(){
var count = $("#noOfAccount").val();
for (let index = 0; index < count; index++) {
  var accounts = web3.eth.accounts.create();
  console.log(accounts);

}
});
});

I am using ganache-cli as a local provider I don't know which web3 version it uses but the package.json file in my project folder seems to use 1.0.0

{
"name": "project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
  "web3": "^1.0.0-beta.30"
}
}

but after running the web page to create an account am getting an error

  "TypeError: web3.eth.accounts.create is not a function"

but the node consoles (it uses web3-1.0.0) I can run the same command,
How can I resolve this error, I think changing the web3 version used by ganache-cli will do the task but don't know how to do it?


texts:
I know that chaindata folder (on Mac OS X) stores the state as key/value database. But how is a block stored? Are transactions also stored as key/value pairs? If yes, how to identify which files belong to transactions and which files belong to state? I have a bunch of levelDB files 'ldb' under chaindata and I have no idea how to probe them, say using python levelDB bindings.

This question does ask a bit about the blockchain, however the answer does not particularly refer to how blocks are stored.

EDIT: I am concerned with low-level representation of transactions and blocks and how they are stored on disk. I understand that they are in RLP format from ethereum wiki. What exactly I am looking for is which files belong to blocks (and transactions) and which don't.


texts: Limitations of JavaScript api on client side?

texts: I notice that the Ethereum Javascript API allows the development of client side web based apps. Are their limitations or security gotchas to be aware of when developing such an app? Parts of the API that are really meant for server side JavaScript such as nodejs?


texts:
Normal transfer works normally with this erc20 token: https://etherscan.io/address/0xe9e74bae31892b6b1c000e009c93438dbd14d723#code
When withdrawing from the Etherdelta contract: https://etherscan.io/address/0x8d12a197cb00d4747a1fe03395095ce2a5cc6819, it uses too much gas and the transaction fails. Looking at the geth trace it does this when it gets to SSTORE. Example transaction where this happens: https://etherscan.io/tx/0x86f1bb1cdd200723662026b59db4dbd91cf24a5a7a785574d3ae4188baeb14ae
This contract has a mint function and it seems before that was used withdrawing from Etherdelta worked normally: https://etherscan.io/tx/0x0e2705298acf45f36cc74a56f881280d49c40e0917fd2c5872f52998985cb446

Can anyone explain what is happening?

There is a similar contract that does not have this problem: https://etherscan.io/address/0xee609fe292128cad03b786dbb9bc2634ccdbe7fc#code


texts: Verifying Smart contract in testnet bscscan/ bscscan

texts:
Compiler debug log:
Error! Unable to generate Contract ByteCode and ABI (Expected library(ies) but one or more was not provided)
Found the following ContractName(s) in source code : Address , Context , IBEP20 , IPancakeFactory , IPancakePair , IPancakeRouter01 , IPancakeRouter02 , Ownable , ReentrancyGuard , RewardToken , SafeMath , Utils
But we were unable to locate a matching bytecode (err_code_2)
For troubleshooting, you can try compiling your source code with the Remix - Solidity IDE and check for exceptions


texts: Is there any lightweight JS library that generates Ethereum addresses from 256-bit private keys?

texts: I have a 256-bit private key and I want to get its public address without having to install Geth (which is quite heavy) on the machine. Is there any small JS lib that does that?


texts:
I want to implement a voting approach and already watched some tutorials. My question is: Is it possible to send out voting tokens to voters that also gather data about the voters? Like for example age or gender? How would the concept of this contract look like?

Thanks in advance!


texts: Can Solidity access the gaslimit (not just the remaining gas)?

texts: Solidity has access to the remaining gas via msg.gas which changes from line to line. But I would like to know if I can access the initially submitted gasLimit. Is that possible in Solidity?


texts: Checking Reentrancy Vulnerability in smart contracts

texts:
According to the Ethereum Smart Contract Best Practices, race conditions can occur across multiple functions, and even multiple contracts, any solution aimed at preventing reentry will not be sufficient and they said to focus on the finishing internal work first. Few posts from Ethereum Stack Exchange says Race condition is not a much problem as system is designed that way.

So basically, does race condition really a problem here or its just a wrong term which is being used to describe the system.

Also if I want to develop some tool to check whether my program has reentrancy vulnerability, what would be the best possible solution to this? Do I really need to scan the code to find if we are allowing calls to external contracts?

Thanks in advance.


texts: Recover 5 year old ethers from old wallet

texts:
I have an older (~5 years) ETH wallet I stashed away. Everything's changed so much since then, wonder if someone would clue me in on how to go about recovery.
I know the wallet address, I've verified the currency still exists there. I have my keystore folder with the key file. I don't have the password (back then I believe they were on passwords and not passphrases) but I'm pretty sure I can guess it without much trouble.
So, how do I go about this now? What current wallet software might support loading of the old keyfile, allowing me to enter the password, and finally managing the available funds once the password is correct?


texts: How does smart contracts work on the blockchain?

texts:
I am quite new to ethereum and its blockchain but I do know what bitcoin is and what is the bitcoin blockchain. One of the still mysterious concepts around the blockchain is the integration of smart contracts. what are these exactly and how do they work on top of the ethereum blockchain.

Note : I read the blog post of Vitalik about the smart contracts and DAOs, DACs, ...  yet the idea of the Judge J who will be sort of a broker between the two contract parties was not really clear which made me post this question.

Any ideas ?


texts:
I'm currently creating my first dApp, and have some trouble understanding the storage of data of smart contract on the Ethereum blockchain. I've altered the react basic code by adding a constructor. As can be seen in the first image. Now by my understanding when interacting with the smart contract every variable that is public will be stored on the blockchain. Now I try testing it in truffle but cannot find the value in question. Example of the transaction can be found in image #2. Can someone please explain to me where the data is actually stored on the blockchain or is it encoded?
P.S. I do know that storing large amount on the blockchain is fairly costly.


texts: Generating random number in Solidity without Chainlink

texts:
Hello I'm well aware there are plenty of threads around discussing different methods. Just curious and wanted to ask directly here because feel like the situation might be different. Essentially I'm trying make it so whenever someone calls out funds from the contract the amount they get varies from 0 to 100, but obviously my current method is flawed depending on now.
I've been reading into ChainLink VRF but looks like the fees could be a bit annoying. Just curious if there's any other methods anyone knows of, otherwise my other option was to lock the balance if it goes close to current block reward and users will just have to cash out more often then. It's doubtful many users will even get a balance above block reward, but I'd like to explore my options.


texts: What are the challenges in creating a peer2peer coin flipping contract in ethereum?

texts:
I wish to make a contract that will allow two (eventually possibly more) people to gamble on essentially flipping a coin using ethereum. One person will not be "gambling against the contract" but another user of the contract.

Is this possible considering the fact that the blockchain data is public? Both parties should supply randomness and, for example, they both have to supply a 1 or a 0 and, if they are both the same, A wins and otherwise B wins. Will it be possible to stop a malicious party from seeing the first party's input and supplying biased input itself?

Would a limit on the time between the two parties submitting work? Any hacky solutions or musings are welcome.