texts: How to test events that were sent by inner transaction / delegate call?

texts:
Usually, using truffle I can check for events like this:

    let { logs } = await myContract.doSomethingImportant( xxx );

    // 1500 tokens are expected to get
    expectEvent.inLogs(logs, 'myImportantEvent', {
      arg1: 111,
      arg2: 'and so on'
    });

However, logs contains only the events that was fired directly inside of the contract function withdrawVestedTokensByTimestamp:

function doSomethingImportant(uint256 x) public returns(uint256) {
    // ... do something else here ...

    emit myImportantEvent(x, amount);

    return amount;
}

However, if in this function a token transfer will happen or another function is called, which would fire events itself, they don't appear in the logs.

Running tests with truffle test --show-events will list all of the expected events, but how can I catch them inside truffle test?


texts:
I have a marketplace. I wanted to make a sales receipt for each item sold. The sales receipt will indicate
address_receipt,nameOfGood, amountOfGood,Price, sumPrice,address_transaction. What should I effectively implement through? Through an array? in solidity maybe arrays in an array? or through a struct? I need that when the buyer's address is given at the entrance, his sales receipts should be displayed. thanks in advance


texts: Why is creating a uint8 more expensive than a uint256?

texts:
Assume a contract:

contract A {

    function b() constant returns (uint8 result) {
      result =1;
    }
}

When I replace uint8 result with uint256 result then the creation of the contract gets 804 Gas cheaper:

        gasUsed
uint8     47631
uint256   46827

How does this work?


texts: Unable to verify Solidity contract code on etherscan.io

texts:
I know this question has been asked many times before. I've read loads of answers, but nothing seems to work for me. I first tried to verify the source code of a much larger, more complex contract, but it didn't work, so I wrote a very simple tiny contract in Solidity:

pragma solidity ^0.4.17;

contract SimpleTest
{
    string public blablabla;
    function SimpleTest() public
    {
        blablabla = "Hello world!";
    }
}

As you can see, I'm not using any constructor arguments, import statements or libraries. I compiled and deployed it using Solidity 0.4.17 from inside Parity. Optimization was enabled. I did not use one of the nightly builds.

Contract creation transaction:

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

The contract in question:

https://etherscan.io/address/0x5a8b57a6cf17a196e000eca4481257d5d3025636

Link to the verification page:

https://etherscan.io/verifyContract?a=0x5a8b57a6cf17a196e000eca4481257d5d3025636

The error message I get from etherscan.io is:

  Sorry! The Compiled Contract ByteCode for 'SimpleTest' does NOT match
  the Contract Creation Code for
  [0x5a8b57a6cf17a196e000eca4481257d5d3025636]

  Contract name(s) found: 'SimpleTest'

  Unable to Verify Contract at this point time.

I've analyzed the bytecodes a little bit, and I found that:

The input data of the contract creation transaction is exactly equal to the bytecode I got from Parity.
The bytecode that the etherscan.io verifier produces is similar to the bytecode from Parity, and thus also similar to the input data of the contract creation transaction.
The bytecode on the contract page on etherscan.io is much shorter than the other bytecodes.
All the bytecodes contain 2 large strings of 00 bytes, except the bytecode on the etherscan.io contract page, it only contains 1 large string of 00 bytes.

I really have no idea what's going on here. Can anyone help?


texts: Are functions in contracts visible to everyone who has the block chain?

texts:
I have an experience with back end development and I am just getting started with Etherium, but I am a bit confused about something.

In Back End development, we mostly assume (if everything goes right) that the user has no way of seeing the actual code being run (So its kept proprietary). I might expose an endpoint to the user to request my service, but they have no way of actually seeing the code being run by me.

However, I've read that everything on the Etherium block chain is public, so I am a bit confused about how you would keep your code proprietary?

For example, suppose I implemented an image recognition service in solidity, where I receive and image and return the type of image to the user. What prevents a user who has my block chain to look at my code, copy it, and make a new block entry of his own with my code in it?


texts:
I've been playing with Token contracts, so far so good, however once the Ether is sent and the tokens created, what happens to the Ether?

I have some Ether on the contract address, how do I withdraw it?

I guess it's not about the contract code but about the interface, I've been using Ethereum Wallet. The send funds screen only allows to fund the contract, not send from it.


texts:
I am trying to work out when ETH is needed and hence when the modifier payable is needed in a function. I read through the "documentation" and various jumbled up references to payable, but I cannot see any clear statement about when ETH is needed and when payable therefore is needed.

I assume that payable is needed when a state variable is modified. Is there any other condition requiring ETH and hence the word payable to be stated?

From what I know now -

State Variable Update - ETH needed - payable specified

Other variable actions (eg local, or reading only) - no ETH needed - payable not specified.


texts: Enum type in interface function declaration

texts:
I understand that you "cannot define enums" in an interface contract; but, in the contract that I am working with, some of the function declarations require an enum type as an input or output parameter. The following will not compile.

interface Interface {
    enum EnumType { Option, OtherOption }
    function initiateProvider(bytes32, EnumType, uint256, uint256);
    function getProvider(address, bytes32) view returns (EnumType, uint256, uint256);
}

Is it best to just define the enum in the contract and call it an abstract contract instead, or is there another way to do this?
Is there any real difference in it being an abstract contract vs an interface, or is this just a difference in terminology?


texts: Doing some work on google bigquery ethereum data and am a bit confused by traces vs transactions. It seems that transactions are a subset of traces? with more info?


texts:
I'm still new to ethereum development, and when trying to execute call() on a created contract, I'm receiving varying results. Sometimes the call works, and other times it returns the error Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
Every time I execute the call it's with the same code. The ABI contains the function, and the contract address is returned from another contract method execution. Sometimes restarting the local Besu node makes it work and other times it doesn't.
I'm lost on what is the actual problem or how to fix it. Last time I encountered this error, there was a problem with the ABI, but that's not the case this time. Another time the address was the issue, but I can track the address being passed correctly from the contract creation to the input in the function.
ABI contains the function:
    {
      "inputs": [],
      "name": "timeLeft",
      "outputs": [
        {
          "internalType": "uint256",
          "name": "",
          "type": "uint256"
        }
      ],
      "stateMutability": "view",
      "type": "function"
    },

Solidity function:
    function timedOut() public view returns(bool) {
        return block.timestamp - creationTime >= timeoutInSeconds;
    }

    function timeLeft() public view returns(uint256) {
        if(timedOut()) {
            return 0;
        } else {
            return timeoutInSeconds - (block.timestamp - creationTime);
        }
    }

Front end JS call:
    async getTimeLeft() {
        await this.setupIfNot();
        console.log(await this.contract.methods.timeLeft());
        let time = await this.contract.methods.timeLeft().call();
        time = parseInt(time);
        console.log("dkljf: " + time);
        return time;
    }

When logging await this.contract.methods.timeLeft() it returns the transaction object that clearly shows call() as an available function. Because of the varying results with no code changes, I'm really confused and not sure what to do to fix it.


texts: can only change header's extra data to mine a new block?

texts: Fix 'nonce' and 'mixDigest', only change 'extra' to mine a new block.


texts: How can DApp developers profit from their work?

texts:
Suppose that I make a new, cool DApp that gets very popular. In order to cover development costs and make some profit, I charge users of the app a small quantity which is required to use to app - all dealt by the contract, automatically. But, since all code is open source, someone can - and will - just copy my app, remove the charge part and publish it again on the blockchain, for free.

How can developers profit from DApps if anyone can fork them and make it 100% free?


texts: Why did Ethereum design Ethash instead of using an existing memory-hard hash function?

texts:
Ethereum uses the Ethash hash function for proof-of-work. It was designed specifically for this purpose by Vitalik based on previous work by Thaddeus Dryja.

The main rule they teach you in a crypto class is: never roll out your own crypto. Why not take any of the existing memory hard hash functions? From scrypt used in Litecoin and its forks to any of the PHC competition finalists (also, Zcash later chose Equihash, designed by the authors of the PHC winner, for its PoW).

I did not find any academic papers with cryptanalysis of Ethash. This analysis elaborates on why password hashing and PoW are not entirely the same task, but still gives no rationale for designing a new algorithm.

Ethash serves its purpose well for now, but what if a critical vulnerability is found? For a recently developed algorithm without years of cryptanalysis behind it it seems likely compared to more established alternatives.

What was the rationale behind choosing to design a new hash function for Ethereum's PoW?


texts: this coin is about to launch to a huge amount of people and i think it's a scam. can anyone take a fast look?

texts:
this coin will be pumping a lot in a couple of hours and i trully believe it's a scam. But i'm not sure how to check.
Can anyone take a look at the contract and check if there's a mint function or anyhing that could rug it ?


texts: Is there a limit to the function call output?

texts:
I have a simple contract for storing string tuple of ipfs hashes data in the array

pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;

contract Store {
    string[] public objects;

    function setData(string memory x, string memory y) public {
        objects.push(x);
        objects.push(y);
    }

    function getDataAtIndex(uint256 index) public returns (string memory, string memory) {
        return (objects[2 * index], objects[2 * index + 1]);
    }

    function getCount() public returns (uint count) {
        return objects.length / 2;
    }

    function getAllData() constant returns (string[]) {
        return objects;
    }
}

I am using getAllData() to get the whole array at once. When the size
of the array is small, everything works just fine. But when I have
large array, it raise an error

  web3.exceptions.BadFunctionCallOutput: Could not decode contract function call getAllData return data b'' for output_types ['string[]']

Do you know what causes the problem?

Is there better way to store large amount of ipfs hashes in one contract? Or is it better to store it in more contracts and search through all of them?


texts:
I want to compile a smart contract (solidity code) in Java. Currently I am using the web3j library. When I run the method web3j.ethCompileSolidity(contract) I'm getting the following error: The method eth_compileSolidity does not exist/is not available

I created the following code to compile a smart contract at runtime:

EthCompileSolidity ethCompileSolidity = web3j.ethCompileSolidity(contract).send();
Map<String, EthCompileSolidity.Code> compiledSolidity = ethCompileSolidity.getCompiledSolidity();

The method web3j.ethGetCompilers() doesn't work either. It's returning the following error: The method eth_compileSolidity does not exist/is not available

On Github I read something about deprecated eth_compile methods.

Is there still a way to compile smart contracts in Java using this library?


texts: Solc compatibility with various versions of Geth

texts: I'm looking for information about what minimal version of solc is compatible with geth, including older versions of geth (1.6+).


texts: There are many proposals of adding precompiled contracts for different reasons. I do not, though, understand why a precompiled contract would be more efficient than an actual contract. If that is the case, doesn't that mean that the EVM isn't sufficiently optimized? What is stopping Ethereum of compiling every contract; perhaps using LLVM?


texts: Can I generate an identical address on main net as in test net?

texts:
I mistakenly sent a small amount of ETH from an online exchange to my local wallet address on Ropsten testnet. Obviously main net to test net will not work. Thus my ETHs are lost.

I think of a way of recovering my ETHs. I use Parity as my wallet software. Since Parity generated the test net address in the beginning, if I can generate the same address on the main net, I can get my ETHs back.

To generate an address, there should be an algorithm and a private key. Since Parity generated the test net address, the private key is probably stored somewhere in my machine. I guess the private key is probably some sort of encoding of my password.

If I look through the source code, I should be able to find what is the algorithm and where is the private key (or how my password should be encoded)

Is this thinking right? If there are mistakes in my thinking, I might not as well go for it. It might cost a lot of time.


texts: Could give ethereum network upgrade solutions?

texts: As we known, the ethereum have soft and hard fork to upgrade network. If we modify the private ethereum code, how to notify other nodes to upgrade their geth? What if they do not upgrade the network?  In the technical opinion, could you give some solutions to upgrade the ethereum network ? And is there any other solution to upgrade the ethereum solutions ?


texts: In the Art of DAO challange, I could not understand the use of "Approve".

texts: Should it not be such that as soon as I send the ether to any DAO, I will immediately receive the tokens ? So what is the use of approve here ?


texts: Truffle test: could not find local build/contracts

texts:
I have create a truffle project with this command:
truffle unbox react

I have run this commands:
npm install @openzeppelin/contracts
npm install @openzeppelin/test-helpers
npm install @openzeppelin/test-environment

I have removed all files in tests/ folder. I have kept sample contract SimpleStorage.sol in contracts/ folder.
I have wrote this test and i put it in a file in tests/ folder:
const { BN, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { accounts, contract } = require('@openzeppelin/test-environment');
const SimpleStorage = contract.fromArtifact('SimpleStorage');

describe('SimpleStorage', function () {

}

I compile and launch the tests (no error at compile step)
truffe compile
truffle test

i get this error:

Error: Could not find local build/contracts when looking for local
artifacts

Any idea ?


texts:
Is it possible to return multiple values inside a for cycle? I mean, without knowing the number of output (it will be dynamically increased every time an array will be filled), is it possible to represent every element of that array as output of a function?

Something like this

function getList() view public returns (string, address) {

    for (uint i = 0; i < arrayOfStringValues.length; i++){

        return (arrayOfStringValues[i], arrayOfAddressValues[i]);}
}

I tried to do this, but the function returns only the first "couple".


texts: Conformance test suite for ERC-721 smart contracts

texts:
Entities like Open Zeppelin offer "well tested and audited" (I'm paraphrasing) open source Solidity code for common patterns such as ownership, ERC20 tokens, etc.

Are there any such entities (or just normal developers) who are, in the same vein as Open Zeppelin, open sourcing rigorous tests for code that is supposed to comply with the popular ERC standards?

Specifically, I've written some ERC721 compliant code, and I'm wondering if there are really good truffle test modules for this code. Would probably be more rigorous than what I'd write, and would definitely save me a lot of time and effort.


texts: Code to check if address have received token?

texts: Please I am currently learning how to build dapps and I need a code that checks an address to see if a token payment have been receive... Anyone please?


texts: How to call a function from deployed contract to another contract?

texts:
I created a basic ERC20 token contract and deployed in rinkeby testnet and I got the contract address now I want to call transfer() function from this deployed contract to another contract without importing the deployed contract in it. Instead of importing I have to use contract address directly.
Can anyone help me regarding source code.
Thanks in advance.


texts: How do I get github to syntax highlight Solidity code?

texts: I uploaded a smart contract written in Solidity to github but it is not syntax highlighted. Instead it looks like a regular text file. I would like syntax highlighting to be shown on Github. How do I achieve that?


texts:
Yesterday we did a test. We launched around 1500 transactions simultaneously to our test private blockchain.

They all went through perfectly, all at almost the same time (with correct and consecutive nonces, from 5 different addresses).

In the genesis file, our private network is configured with these parameters:

"gasLimitBoundDivisor": "0x400",
"maximumExtraDataSize": "0xF4240",
"minGasLimit": "0x1388",
"difficulty": "0x20000",
"gasLimit": "0x5B8D80"

And the estimated gas for each transaction was around 44500 wei.

According to my calculations, with this gasLimit and this cost, around 130 transactions could fit per block, but the amount that actually filled the block capped at 16.

Our nodes are 2 cores with 8GB of RAM.

Are our calculations wrong? why so few tx fitted into a block?

Thanks!


texts: i want to get data from the transaction hash i tried many codes at last i am getting boxes in the output

texts:
1) First, I got the input

console.log(web3.eth.getTransaction('0x725fc75264726f409793164e336e7d5ed35df8d2be469a0cc1a3a8cc4756b9b9').then((i) => console.log(i) ));

2) I manually pasted the input from the data,  in  both abi encoder and toAscii methods

console.log(abiDecoder.decodeMethod("0x0b3ee5dc000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000119fbd8f9c700000000000000000000000000000000000000000000000000000000000000036d64760000000000000000000000000000000000000000000000000000000000");

 console.log(web3.utils.toAscii("0x0b3ee5dc000000000000000000000000000000000000000000000000000000000000........................."))

my output

>åÜ@ûØùÇmdv

but I have inserted

  "mdv",1233

my solidity code

 pragma solidity ^0.4.17;

contract hotelbooking {

struct hotel {
  string HotelName;
  uint256 BookingNumber;
}

hotel[] HotelBookings;

function  HotelTranscation(string _HotelName,uint256 _BookingNumber) public {

  hotel memory temphotel = hotel(_HotelName,_BookingNumber);
  HotelBookings.push(temphotel);
}

    function GetHotelBooking(uint _num) public view returns(string, uint256) {
        return (HotelBookings[_num].HotelName, HotelBookings[_num].BookingNumber);

    }

1) Everything is working fine when using index for getting the data.

2) But I want to get the data by using transaction hash, please help me.

3) I have used online compiler remix to develop the code.


texts: Do I need to be synced to the blockchain to create a contract?

texts:
I haven't been able to run the Greeter contract on the live network and am referring to these excellent Q&As for guidance. I have a feeling that it's because my client hasn't finished syncing with the blockchain yet. I confirmed that I have 0.1 ether in my account (enough to pay for gas) using an online blockchain explorer, but this isn't reflected yet when I check the balance via command line (still reports 0 balance).

Do I have to finish syncing in order to deploy the contract?


texts: fatal error when try to serve geth in ipc

texts:
I have initialized my own genesis block and started
geth --datadir pom

Then I want to use "personal" so I started
geth --nodiscover --ipcpath pom/geth.ipc --networkid 31337 --rpc --rpcaddr 192.168.225.235 --rpcport 22000 --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3,quorum,raft --port 21000

and I'm receiving the error
Fatal: Error starting protocol stack: genesis mismatch: 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3 (leveldb) !=  (ancients)

I don't understand this error and I'm searching the google and some link says re initialize the chain. So I have deleted and initialize the genesis many times. Can someone help to solve this error? Thank you.


texts: Can I have someone submit my transaction to the network, so I don't have to pay the gas fee (in ether)?

texts:
My account is a new account with 0 ether. I just received 100 of ERC20 tokens. I would like to send these 100 tokens to the other account. However, since this account does not have any ether in it, so it cannot submit any transaction to the network.

I wonder, is it possible to have someone (3rd party account) submit my transaction transferring 100 tokens from this account to the other one. I don't want to transfer any ether to this account to make it possible to merely submit 1 transaction.


texts: How to create an Ethereum side-chain aka pegged chain?

texts:
With the ETH at an all time high and the gas price still at 20G Wei Ethereum transactions are becoming uneconomical.

We want to create an accounting system based on smart contracts which would simply cost too much to run on the Ethereum main net.

The solution we came up with is to create a new public Ethereum blockchain based on PoS and publish all the block hashes on the mainnet. This reduces the transaction count by an order of magnitude while ensuring that anyone can verify that we are not cheating.


texts: How to issue two different tokens from one crowd sale?

texts:
I have a project in mind and I want to have a crowd sale where two separate tokens are issued.

The simple flow is this. Send X ETH > X token_A. Use token_A as a way to vote. There will be X amount of voting wallets that the person can choose from. Once all of that persons token_A are deposited(voted with) the person will receive Token_B which will have another use.

My first thought would be just have 2 tokens created and issued right off the bat. Is that possible? I just liked the idea of almost forcing the votes before receiving the second token.

I wouldn't even know where to begin to have the second token issued once all of token_A are spent. Not sure how you could track it all should they be spread among the available voting wallets.

Has anyone done something similar to this? Is it even possible?

I appreciate any help or suggestions.


texts: Truffle migration deployment: Transaction was not mined within 50 blocks

texts:
I am running my own Ethereum client node (Open Ethereum 3.0.1). I am using Truffle migrate to deploy my smart contract to MainNet. However, the contract deployment is taking too long. The result from the migration command is below:
kevins-mbp:AuthentoFile_Repo kevinm$ truffle migrate --network mainnet --reset

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Migrations dry-run (simulation)
===============================
> Network name:    'mainnet-fork'
> Network id:      1
> Block gas limit: 9990236 (0x98705c)

1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > block number:        10288818
   > block timestamp:     1592471208
   > account:             0xaAF66209133056F1f7285D6cDb61Cf21D135f300
   > balance:             0.1797474439
   > gas used:            210237 (0x3353d)
   > gas price:           2 gwei
   > value sent:          0 ETH
   > total cost:          0.000420474 ETH

   -------------------------------------
   > Total cost:         0.000420474 ETH

2_deploy_contracts.js
=====================

   Deploying 'AuthentoFile'
   ------------------------
   > block number:        10288820
   > block timestamp:     1592471211
   > account:             0xaAF66209133056F1f7285D6cDb61Cf21D135f300
   > balance:             0.1769681859
   > gas used:            1362266 (0x14c95a)
   > gas price:           2 gwei
   > value sent:          0 ETH
   > total cost:          0.002724532 ETH

   -------------------------------------
   > Total cost:         0.002724532 ETH

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

Starting migrations...
======================
> Network name:    'mainnet'
> Network id:      1
> Block gas limit: 9990236 (0x98705c)

1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------
   > transaction hash:    0x77eac6bee9baeb315e7e52d31d13a9ab4241676c2ec2b4a5e7cf2071281ffe1a

Error:  *** Deployment Failed ***

"Migrations" -- Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!.

    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:364:1
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)

As you can see, the contract deployment was not completed.
I ran this 2 times so now I have the following pending transactions (at least 8+ hours old). The tx hashes for these pending tx are:

0xc0a28527f1fcebc0bdf9ae18479831eaf026b350420a3134bcd14b44f520b812
0x77eac6bee9baeb315e7e52d31d13a9ab4241676c2ec2b4a5e7cf2071281ffe1a

Will these transactions ever get mined? On my Ethereum node I see these as Pending Transactions.
My Ethereum client is not configured to do any mining, so I am assuming that a miner on the network will eventually try to mine these transactions?
Any help/insight would be very much appreciated.


texts: How to offer free DApps for users without any barriers?

texts:
How to offer decentralized applications or services for users without introducing any barriers like

running a full ethereum node?
enabling rpc api on the node?
explaining the user which rpc cors domain to set?
telling the user to buy ether to pay the gas fees?

I want to create a service, running on ethereum infrastructure but the user should not be limited by hurdles like buying ether to interact with the blockchain.

Is this possible to offer free services, where for instance a smart contract pays for the user's transaction fees?


texts: Account balance does not decrease after send ether

texts:
For example here is my example function in smart contract:

function adoptCreeptomas(uint256 beastQuantity, address referrer
) public payable whenNotPaused {
    msg.sender.transfer(50);
}

And then I try to test this contract:

describe("adopted creeptoma", async function() {
    it('adopted', async function() {
        let instance = await CreeptomaPresale.deployed();

        let pre = convertEther(getBalance(investor));
        await instance.adoptCreeptomas.call(beastQuantity, 0 {from: investor, value: ether(100)});
        let after = convertEther(getBalance(investor));
        console.log("before: " + pre + "--after: " + after);
    });
});

The printing log is: before: 100--after: 100

Here is my getBalance method:

export function getBalance(address) {
    return web3.eth.getBalance(address)
}

I don't know why balance of account doesn't decrease. Please help me.

Thanks


texts: Implement Web3 and IPFS on server side (backend)

texts: How do I implement Web3 and IPFS on the server side (backend)? I am able to implement on client-side (using web3.js and ipfs.js in HTML script tags) for localhost. However, it fails when I run the same for my https server. Any help appreciated! Thanks!


texts: Buying directly from smart contract at the the same block the liquidity is provided

texts:
I am trying out buying new listing from uniswap but bots always rally the price so high that it just doesn't make sense to enter until the market is fully cooled off.
I have found and application called Limitswap to buy when the price starts being available on uniswap BUT it does not purchase from the same block that liquidity got provided(most probably).
I am trying to understand if there is a way to buy coins before they are listed on uniswap and at the time when the liquidity is provided(meaning at the same block as liq. got provided) directly from the Etherscan Write contract tab or with python program. Any ideas would be highly appreciated.


texts: where can I find the original Ethereum's (DAO's) genesis file?

texts:
Where can I find the source code (genesis.json) of the genesis block for Ethereum's main net (i.e the DAO's) ???

Looking for any .json file within the source code didn't produce any results. This file must produce the hash = 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3, which is the hash of the genesis block.


texts: TypeError: No Matching declaration found after variable lookup

texts:
I am adding a MintToken Function to a standard ERC20 token. I have added the appropriate owner contract and the contract I want to deploy inherits that ownership. However, I keep getting this error.

function mintToken(address target, uint256 mintedAmount) onlyOwner {
    balanceOf[target] += mintedAmount;
    totalSupply += mintedAmount;
    Transfer(0, owner, mintedAmount);
    Transfer(owner, target, mintedAmount);
}

TypeError: No matching declaration found after variable lookup.
    balanceOf[target] += mintedAmount;
    ^-------^

Any help in this matter would be appreciated.


texts: How to calculate circulating supply for geth private network?

texts: SUBJ. I have geth private network with custom reward progression and looking for a way to calculate circulating supply.


texts: How do I perform a hot migration of a Quorum+Tessera node from one host to another?

texts:
I'm trying to perform a hot migration of an existing Quorum+Tessera node on a RAFT cluster from one host to another.
Is it possible to start a replicated quorum node with the same Tessera key pair as an existing node and have both receive all ongoing private transactions?
I've tried to join the existing RAFT cluster with a new node but same Tessera key pair as the node, but it doesn't seem to pick up any new transactions which were transacted against the existing node.


texts: Is there a service for User Credit Card -> Eth -> Contract on a chain?

texts:
So I have a nice contract infrustructure set up. I have an webserver that interacts with it and provides web pages to my users. I do not want to deal with PayPal\Credit cards myself - I want to have some intermidiary service to get funds from users cards and transfer them (after commission) to my contract payable.

So the logic would look like this:

User wants stuff,
User clicks Pay,
User gets transfered to Card\Payment page of the intermidiary service
Intermidiary service calls my contract on the blockchain with my payable method
I see the transaction and provide goods to user.

Are there such Intermidiary services already out, are there any with at least 10-100+ user base?


texts: ERC223 Token doesn't transfer while working with data field in transfer() function

texts:
Instead of showing tokens the output shows Internal transactions or just contract interactions. what changes are needed to transfer tokens to any other ERC223 receiver contract?

  function transfer(address _to, uint256 _value)public returns (bool success){

    if(isContract(_to)){
        return transferToContract(_to, _value, "0x0");
    }
    else{
        return transferToAddress(_to,_value, "0x0");
    }
 }

 function transfer(address _to, uint256 _value, bytes memory _data)public returns(bool success){

    if(isContract(_to)){
        return transferToContract(_to, _value, "0x0");
    }
    else{
        return transferToAddress(_to, _value, "0x0");
    }
 }

 function isContract(address _addr) public view returns (bool is_contract) {
    uint length;
    assembly {
        length := extcodesize(_addr)
    }
    return (length>0);
  }

 function transferToAddress(address _to, uint256 _value, bytes memory _data) public returns(bool success){
   require(balanceOf(msg.sender) > _value );
   balances[msg.sender] = balances[msg.sender].sub(_value);
   balances[_to] = balances[_to].add(_value);

   emit Transfer(msg.sender, _to, _value, _data);
   return true;
 }

function transferToContract(address _to, uint256 _value, bytes memory _data) public returns(bool success){

    require(balanceOf(msg.sender) > _value );

    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);

    ERC223ReceivingContract erc223Object = ERC223ReceivingContract(_to);
    erc223Object.tokenFallback(msg.sender, _value, _data);

    emit Transfer(msg.sender, _to, _value, _data);
    return true;
}

Is there any problem with the receiver contract solidity file? Here is the code of my Receiver Contract file.

contract ContractReceiver {

   address public sender;
   uint256 public value;
   bytes public data;

   function tokenFallback(address _to, uint256 _value, bytes memory _data) public {
     sender = _to;
     value = _value;
     data = _data;
    }
}


texts:
With the price of ethereum going up my contract is getting too expensive for what i am using it for. What i need is a contract where a string is stored and retrieved whenever needed. My current code is

contract demo {
   string public name = "some32bitString";
   function returnValue() constant returns (string){
      return name;
   }
}

Is there a workaround? or some other way to make this less expensive? Currently on etherscan the tx fee is 0.00693.


texts:
For example, if I have:

mapping(address => Tickets[]) ticketEntries;

Can there me multiple tickets belonging to the same address in the ticketEntries mapping? ie:

ticketEntries[0] = (0x100..., ticket1);
ticketEntries[1] = (0x100..., ticket2);
etc...


texts: Roll back current block to a prior block

texts:
For testing purposes I want to create some blocks on my computer, not broadcast them to the network, and then rollback my current block in Parity.

In git you would do it like this:

Edit some files
git commit -am 'First test commit'
Make more edits
git commit -am 'Second test commit'
git reset --hard HEAD~2

That is exactly what I want to accomplish in Parity. For this question I am only concerned about the rollback part.


texts:
Testing out oraclize for a smart contract.

function __callback(bytes32 _myid, string result) public {
   if (msg.sender != oraclize_cbAddress()) revert();
    // emit LogOraclizeID(bytes32ToString(_myid));
    // string memory number = result[0].data;
    emit LogQueryEvent("Are we firing here boys?");
    emit LogRandomNumber(result);
}

// This is NOT truly random. Just a proxy for basic testing.
function random() public payable returns (uint) {
    if (oraclize_getPrice("WolframAlpha") > address(this).balance) {
        emit LogQueryEvent("Please send some ETH along to make transaction.");
    } else {
        // string memory numTokensToString = uint2str(tokens.length);
        // string memory queryString = "random number between 0 and ".toSlice().concat(numTokensToString.toSlice());
        // oraclize_query("WolframAlpha", "random number between 0 and 2");
        emit LogQueryEvent("Oraclize query was sent, standing by for the answer..");

        oraclize_query("WolframAlpha", "random number between 0 and 2");

    }
    // return uint(keccak256(abi.encodePacked(block.difficulty, now, tokens.length)));

}

Trying to improve randomness on a particular contract. The __callback doesn't appear to fire. Testing this in remix.

Is this an issue with how I'm setting up the call, or a limitation of remix?


texts:
I have a test contract that emits events. I'd like to create a web app that shows a list of all created events + new ones as they arrive. I'm using Meteor app connected to geth 1.4.10 through rpc. The code is:

var filter = web3.eth.filter({fromBlock:0, toBlock: 'latest', address: contract.address, 'topics':[topic]});
filter.watch(function(error, result) {
  // attach event to list
  console.log("Event: " + result);
});

It seems to work, however there's a huge (above a minute) delay to get the events that are already created in the callback. I'd like to show a list immediately or almost immediately when the page is loaded and then keep updating as new events come. Is this the correct way? How can I reduce the delay?


texts: Return each struct value from a key inside a mapping, where the key is also a value from array inside another mapping

texts:
I have a project that I'm working on and I'm trying to figure out a way to do as the title says. I'm looking for the easiest and/or cheapest way(gas wise) and since I'm stuck I'm open to better ways to structure my code. The main idea is to create a dApp using truffle and metamask where once a submission is accepted the bountyPoster can send the initial amount to the accepted bountyHunter. These are the two requirements are being tough for me at the moment :
"I am able to view a list of bounties that I have already posted.
By clicking on a bounty, I can review submissions that have been proposed."
My initial idea was to connect every new Bounty struct to it's bountyId ,
connect every new Submission to the bountyId it's submitting to and connect every bountyId with many submissions overall by their corresponding submissionId's. Then figure out a way to return the submissions inside the getBountySubmissions func. That's where I'm right now.

pragma solidity >=0.4.25 <0.6.0;

contract BountyHunters {

    enum SubmissionStates {Accepted, Pending, Rejected}
    enum BountyStates { Open, Closed }

    address owner;
    uint public bountyId;
    uint public submissionId;

    mapping(address => uint[]) public myBounties;
    mapping(uint => Bounty) public newBounties;
    mapping(uint => uint[]) public mySubmissions;
    mapping(uint => Submissions) public subs;

    struct Bounty {
        uint bountyId;
        uint bountyAmount;
        address poster;
        string description;
        BountyStates bountyState;
    }

    struct Submissions {
        address bountyHunter;
        string description;
        SubmissionStates subState;
    }

    constructor() public payable {
        msg.sender == owner;
    }

    modifier onlyOP {
        require(newBounties[bountyId].poster == msg.sender, "You must be the owner of the post");
        _;
    }
    modifier onlyNotOP {
        require(newBounties[bountyId].poster != msg.sender, "You are not allowed to submit to your own bounties.");
        _;
    }
    modifier isOpen {
        require(newBounties[bountyId].bountyState == BountyStates.Open);
        _;
    }

    function postNewBounty( string memory _description, uint _bountyAmount)
    public
    payable
    returns (bool) {

        require(_bountyAmount > 0);
        require(msg.sender.balance >= _bountyAmount);
        bountyId++;
        myBounties[msg.sender].push(bountyId) - 1;
        Bounty memory newBounty = Bounty(bountyId, _bountyAmount, msg.sender, _description, BountyStates.Open);
        newBounties[bountyId] = newBounty;

        return true;
    }

    function proposeSubmission(uint _bountyId, string memory _description) public onlyNotOP isOpen returns (bool success) {
        require(bountyId >= 0 && _bountyId <= bountyId);

        submissionId++;
        Submissions memory newSubb = Submissions(msg.sender, _description, SubmissionStates.Pending);
        mySubmissions[_bountyId].push(submissionId) - 1;
        subs[submissionId] = newSubb;
        return success;
    }

    function getBountySubmissions(uint _bountyId) public view onlyOP returns (
        address bountyHunter,
        string memory description,
        SubmissionStates subState) {

    }

}

Should I try looping through each submissionId and from there loop through each struct, or there is a better logical way to go with this?
Do I have to loop through the structs here in the contract or there is an easier way when I reach deployment phase?
Any help is much appreciated. Thank you for your time.


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

texts:
I'm trying to transfer some test ether from one Metamask address to another
using the private key that I exported from it. But it always return a error code of -32000 with a message of 'Invalid sender'.

import web3
import json
from eth_account import Account
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://ropsten.infura.io/v3/apiKey'))
acct = Account.privateKeyToAccount('Private key from Metamask')
nonce = w3.eth.getTransactionCount(acct.address)
transaction = {'
to' : toAccount,
'value': 1000000000,
'gas': 2000000,
'gasPrice': 234567897654321,
'nonce': nonce,
'chainId': 1
}
key = acct.privateKey
signed = w3.eth.account.signTransaction(transaction, key)
w3.eth.sendRawTransaction(signed.rawTransaction)


texts: What is the impact on my Dapp performance when subscribing to events?

texts: What would be the expected performance impact on my Dapp if I subscribe to a lot of events from different contracts? I'm not sure how the event process work. The performance would decrease while processing all the events data but what about just listening for them?


texts: I need some help to recover lost ether on myetherwallet

texts: a couple of years ago I transfered some eth from Binance to myetherwallet to benefit from EoS and KeOs ( with hindsight I shouldn't have done as binance covered them) - notwithstanding I am not a technical person and inbetween that and time elapsing and metamask/my ether wallet upgrading I have lost the private keys to this wallet and therefore transaction. I believe I may have the Jason manifest file and I have the advanced KYC at binance for proof of providence - I think I would like to be able to reverse the transaction back onto binance ( have full KYC there) - or recover the ether if there is another route - can anyone help in any way?


texts: Is each Ethereum address shared by (theoretically) 2 ** 96 private keys?

texts:
Summary

This is an extended question to How are ethereum addresses generated?.

In Ethereum, a private key is 256-bit long, but an address is only 160-bit long. By "Pigeonhole Principle", it guarantees that some unique private keys map to the same address. Theoretically, 2 ** 96 unique private keys maps to one address on average.

Question

If 2 private keys map to the same address, do they both gain access to the same address? Can they both used to transfer Ether from that address to another?

Details

According to @tayvano's answer, a private key is 256-bit long, and any 256-bit string is a valid private key:

  Every single string of 64 hex are, hypothetically, an Ethereum private key that will access an account.

Therefore, there are 2 ** 256 valid private keys (the key space is 2 ** 256).

A public key is 512-bit long. However, since each of them is derived from its own private key, there are only 2 ** 256 valid public key, and thus the key space is 2 ** 256.

The public key is then feed as the input of Keccak-256 (pre-standard SHA3) hash algorithm. The output of Keccak-256 is a 256-bit string, therefore it could be treated as a one-to-one mapping in key space. (The hash space is 2 ** 256)

However, an Ethereum address is obtained from the least significant 160-bit of the Keccak-256 hash. This cuts the key space to 2 ** 160.

As a result, the process of generating an address from a private key is a function of a 256-bit value to a 160-bit value, which guarantees duplicates.

You may be interested

What if I had the private key that had the public address of a contract?
Are addresses between different networks (testnet) interchangeable?


texts: Create multiple tokens for a unique property

texts:
here is the idea:

we assign a set of unique tokens to a company and then we allow people to buy some tokens and  get partial ownership of that company. How can I achieve this? I was thinking of using ERC721 to create a non-fungible token for the company but I want a set of tokens not just one token.

Any suggestions? Thanks in advance.


texts: Failed to pass ether from one account to another in truffle with testrpc

texts:
I have a sample contract with one function:

pragma solidity ^0.4.0;

contract Test {

    function sell(address transferTo) public {
        transferTo.transfer(1000);
    }
}

I use testrpc and truffle to deploy and execute contract:

Test.deployed().then(instance => instance.sell(accounts[1], {from: accounts[0]}))

and command fails with exception on VM level:

Error: VM Exception while processing transaction: revert
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70604:12)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70449:12)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:70159:18)
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:315621:13)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:314196:9
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:331156:36
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43303:16)

Any thoughts what was going wrong? Seems like this function represents what docs says.


texts: Getting complete storage of a contract using geth client

texts:
I found at here, that it is possible for a client to get the value from storage of a contract at a particular index using eth.getStorageAt(contract_address, index) interface. I wanted to ask

  Is it possible to download the complete storage of a smart contract using geth client?

I tried writing a script consisting of a loop to execute this call repeatedly, but the problem with this approach is that for out of range index it always returns 0x0 which is ambiguous if the client does not know the size of the storage. Which leads me to the question

  Is it possible to find the size of the storage occupied by a smart contract?


texts: How does the stack depth attack make a send() silently fail?

texts:
From a blogpost on security from Christian Reitwiessner:

Because of the maximal stack depth of 1024 the new bidder can always increase the stack size to 1023 and then call bid() which will cause the send(highestBid) call to silently fail.

So it seems that you can prepare the stack that a send() will fail but the contract will still continue its execution and terminate.

What is the rational behind this behaviour and is it possible to "attack" more than one send() or would a second send() cause an exception if the first already failed "silently".


texts: Truffle : Call that returns contract is returning tx

texts:
Using Truffle v3.2.1 and solidity 0.4.4

I have an issue with a Factory contract (that create some kind of contract), to simplify my factory contract look like this :

contract HelloFactory {
  uint nbContracts;

  function HelloFactory() {
    nbContracts = 0;
  }

  function createHS() returns (HelloSystem contract) {
      HelloSystem ret = new HelloSystem();
      nbContracts++;
      return ret;
  }
}

The HelloSystem contract code is not relevant to the issue.

using truffle console I made a new Hello Factory :

var aHelloFactory;
HelloFactory.new().then(el => aHelloFactory = el);

I can check that there is no HelloSystem contracts created within my factory yet:

aHelloFactory.nbContracts.call().then(console.log)
// OK : prints 0

Now I try to create a new HelloSystem contract from the factory

var hs;
aHelloFactory.createHS().then(el => hs = el);
// KO : Prints transaction ? (correct me if i am wrong)
// { tx:

'0xba9dc273cc13425303436d4f2eeee9c852b99aefa5026d3a37ccfabd17232204',
  receipt:
   { transactionHash: '0xba9dc273cc13425303436d4f2eeee9c852b99aefa5026d3a37ccfabd17232204',
     transactionIndex: 0,
     blockHash: '0xd04d6c10cf48995903283dccde31cd5712de2029578c7eb00edc852ac475083c',
     blockNumber: 148,
     gasUsed: 249136,
     cumulativeGasUsed: 249136,
     contractAddress: null,
     logs: [] },
  logs: [] }

I am expecting a contract as return of function,
What am I doing wrong ?


texts:
I'm trying to learn Solidity and trying to access remix web page (using MacBook pro), the page loads but it halts after that and I cannot scroll up and down the page to see the code.

Do I need to install anything to use online remix compiler?

If the question is irrelevant, please let me know before downvoting, so I'll remove it.

Edit: I'm using Safari web browser (with default setting).


texts:
In Ethereum, how can I get a notification when someone make a transaction to my address?

I found there's a way of scanning the blocks by rpc. Is there any other way, like using a public API?

I have tried blockcypher.com, but its webhook is not working when I test.


texts:
I am trying to get Token Balance using plain javascript, no nodejs or web3.

With web3 and nodejs I can do:

exports.getTokenConfirmedBalance = function(node, query, abi) {
    return new Promise((resolve, reject) => {
        try {
            var provider = new web3.providers.HttpProvider(node.url);
            var w3 = new web3(provider);

            var tokenContract = new w3.eth.Contract(abi, query.token_address, {from: query.pub_address});

            tokenContract.methods.balanceOf(query.pub_address).call().then(function (balance) {
                resolve(balance);

            }).catch(function(error) {
                reject(error)
            })

        } catch(error) {
            console.log(error);
            reject(error.message);
        }
    })
}

Any suggestions?


texts: Discrepancy between Etherscan.io and Google Big Query information

texts:
I noticed that there are large discrepancies between the balances of addresses in Etherscan vs Google Big Query.
Also some addresses that are listed in Etherscan are not existing in the balances table in GBQ. Does anybody know why?


texts: Is this the best platform for general use?

texts:
I joined in because I saw a moral position I valued at ethereum.org. My initial post was poorly expressed - my apologies for that. I have tried for 2 months to set up for mining and continually get responses from geth stating there are various problems preventing me from synching. I updated to geth 1.8.1 and after 48 hours get the same reports. My PC (AMD A12-9800 RADEON R7 4 CPU cores, 8 GPU cores, 8Gb RAM) has been online all of this time, and been processing. I would like to create my own crypto-currency without regard to its value in the real world, but I need to know the platform for doing so is both credible and works. The command I entered (after stopping a run using geth 1.7 and installing 1.8.1) is
geth --cache=6144 --syncmode "fast" --datadir     "D:\Users\Mike\AppData\Roaming\Ethereum" --etherbase "0xc..."
and the most recent output is:
INFO [02-25|10:01:50] Imported new state entries               count=384  elapsed=0s        processed=22196723 pending=19162 retry=0   duplicate=8656 unexpected=47101
INFO [02-25|10:02:02] Imported new block headers               count=2    elapsed=16.067ms  number=5153154 hash=ef8ede…972dc1 ignored=0
INFO [02-25|10:02:09] Imported new state entries               count=1152 elapsed=12.019ms  processed=22197875 pending=18982 retry=0   duplicate=8656 unexpected=47101
INFO [02-25|10:02:15] Imported new block headers               count=1    elapsed=5.008ms   number=5153155 hash=d043a1…a93f3a ignored=0
INFO [02-25|10:02:29] Imported new state entries               count=1152 elapsed=11.017ms  processed=22199027 pending=18883 retry=0   duplicate=8656 unexpected=47101
WARN [02-25|10:02:42] Rolled back headers                      count=321  header=5153155->5152834 fast=5153083->5152834 block=0->0
WARN [02-25|10:02:42] Synchronisation failed, dropping peer    peer=a979fb575495b8d6 err="retrieved hash chain is invalid"
INFO [02-25|10:11:27] Regenerated local transaction journal    transactions=0 accounts=0
INFO [02-25|11:11:27] Regenerated local transaction journal    transactions=0 accounts=0

Thanks Mike


texts: What are the benefits of abstract contracts?

texts:
I've seen similar questions, but none answer why people use abstract contracts. I come from a non-OOP JavaScript background, so I have some trouble understanding these things.

From the docs:

pragma solidity ^0.4.0;
contract Feline {
    function utterance() public returns (bytes32);
}
contract Cat is Feline {
    function utterance() public returns (bytes32) { return "miaow"; }
}

What is the benefit of defining Feline here in the first place?
The only benefit I can think of is if you have many different kind of feline contracts and you want to make sure they all include utterance() I guess? But I really cannot think of any such situations...

Are there benefits I'm not seeing? Coming from my background you'd want to avoid things like this, where you just want a Banana but get a Gorilla holding it, along with the entire Jungle...

PS: The question is not the difference between interfaces and abstract contracts.


texts: Search in Address[] if exist the same address sender

texts:
I want to check if the Address sender is already in Address[]. If true, then do not allow this address to make the payment.

Contract Hello {
  address[] internal Pool;

  function () public payable {
  require(msg.value * 10 == 1 ether);

  if (msg.sender already exist in address[]){
    revert();
    Rejected();

  } else {
    Pool.push(msg.sender);
  }
 }
}

Thank you!


texts: Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)

texts:
The client side application always throws the above error. I have connected the ganache account(by copying the private key)also with the correct port number in Metamask extension as well as in the truffle-config.js file but the error seems consistent.

    App={
    contracts:{},
    loading:false,

    load: async() => {
        await App.loadWeb3();
        await App.loadAccount();
        await App.loadContract();
        await App.render();
        // await App.renderTask();

    },
    // https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8

    loadWeb3: async () => {
        if (typeof web3 !== 'undefined') {
          App.web3Provider = web3.currentProvider
          web3 = new Web3(web3.currentProvider)
        } else {
          window.alert("Please connect to Metamask.")
        }
        // 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({/* ... */})
          } catch (error) {
            // User denied account access...
          }
        }
        // Legacy dapp browsers...
        else if (window.web3) {
          App.web3Provider = web3.currentProvider
          window.web3 = new Web3(web3.currentProvider)
          // Acccounts always exposed
          web3.eth.sendTransaction({/* ... */})
        }
        // Non-dapp browsers...
        else {
          console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
        }
    },

    loadAccount: async() => {
        App.account= web3.eth.accounts[0];
        console.log(App.account)

    },

    loadContract: async() => {
        const todoList = $.getJSON('TodoList.json');//Getting the smart contract json file
        //To do operations with our contract using truffle we need to do this
        App.contracts.TodoList = TruffleContract(todoList);
        App.contracts.TodoList.setProvider(App.web3Provider);//Also need to set the provider of web3
        //Creating a (deployed)contract instance from the actual blockchain of type App.
        //Check that the same variable 'todoList' is used to get the json file too

        App.todoList = App.contracts.TodoList.deployed();// <<<<-------- Here is the error I guess
    },
    render: async() => {
        //To Prevent double render
        if(App.loading){
            return
        }
        //Update app loading state
        App.setLoading(true);

        //Then render account
        $('#account').html(App.account)

        //Then update loading state
        App.setLoading(false);
    },
    setLoading:(status)=> {
        App.loading=status;
        const loader=$('#loader');
        const content=$('#content');

        if(status){
            loader.show()
            content.hide()
        }else{
            loader.hide()
            content.show()
        }

    },
}
$(()=>{
    $(window).load(()=>{
        App.load()
    })
})

I have mentioned with <<<---- comment where the error occurs exactly
I'm newly learning blockchain from this tutorial. Please help me out.Thanks in advance :)


texts: Is there any way to connect a console to Browser-Solidity's JavaScript-VM?  I'd like to send JS calls to contracts.


texts: Batch transactions for MetaMask using sendAsync

texts:
I have MetaMask working nicely - it's so cool! However, I have a (react) form that gathers in lots of information and creates 14 distinct calls to sendTransaction. Hence, I (currently) get 14 popup windows from MetaMask, asking me to accept those transactions. In fact, exactly like this situation: https://github.com/MetaMask/metamask-plugin/issues/1000

...which I see was 'solved'. So I know it's possible to batch requests, but my question is how? Basically, how should I form the sendAsync call? For instance, say I had these three transactions:

myContractObject.doSomething(name,type)
myContractObject.doSomethingElse(hash)
myContractObject.doSomethingElseEntirely(key)

What would my call to web3.currentProvider.sendAsync look like?


texts: How to generate a new token for ERC1155?

texts:
Developing an ERC1155 contract, how to generate an address for a new token?

I need to create an API function like function createToken() returns (address). How?

Should I just use an incrementing-by-one value starting from 1?


texts: Truffle contract compilation from STDIN or something like this

texts:
My contracts have some methods that used only for testing i.e. exposes some internal contract data and I do not want to deploy it to live network. for now Solidity does not supports C-style preprocessor instructions like #if/#else. But on npmjs I found module preprocessor that does exactly what I want.

Only one question remains - how to compile contract after preprocessing? Obviously I cannot replace original contract and in the same time want to keep resulting artifacts file with same name as original contract. Maybe it is possible to compile contracts from stdin so I can chain preprocessor output to truffle input?


texts: web3 alternative languages (aside from javascript)?

texts: Are there any implementations of web3 that are not in Javascript but preferably a compiled language with full multithreading support?


texts: Share private data and prevent data forwarding

texts: Let's say A has some private medical records of patients and B is a pharmaceutical company who wants to view medical records from A to find out the effect of a particular drug on the patients (run a drug evaluation logic to get performance statistics of a particular drug). A wants to share the private data to B but wants to prevent B to forward (leak) the data to other organizations.  How can this problem be solved with blockchain?


texts: How many Smart contracts have been published? how many times have those smart contracts been executed?

texts:
Does anyone know approximately how many (production) smart contracts are out there and how many times smart contracts have been executed in total? I'm okay with order of magnitude (10,000s, 100,000s, etc.) for my purpose.

Regards,
Raj


texts:
Couple of test transaction in the Rinkerby network failed due to insufficient gas during execution. I assumed that these transaction where failed since I was not able to find them on the pool or queue.
When I use the eth.getTransaction() command it returns null.

Is the blockchain keeping track of these failed transactions?
Where can I find these failed transactions?
If the getTransaction method returns null, can I assume that my transaction has failed?


texts: Is there a "gas penalty" for using too many asserts in a contract?

texts:
I'm at a very puzzling scenario.

While using Remix, I noticed that adding a few asserts has caused a significant increase in execution cost (from ~50K to ~59K). And not only did it increase the execution cost of the updated function, but also of any other (public) function!!!

The only solid conclusion that I came up with, is that there's a "gas penalty" which takes effect as soon as the global number of asserts in the contract exceeds a certain threshold. BTW, the exact same behavior occurs when I replace the asserts with requires.

My current Solidity version is 0.4.16+commit.d7661dd9.Emscripten.clang, and I am compiling with optimization enabled. However, it seems to happen on previous compiler versions as well (I've tried a few of them, down to v0.4.11).

Unfortunately, I am unable to reproduce this problem within a minimal working code snippet, and pasting the entire contract here would probably mess up the entire question. So if possible to get an answer (or any other suggestion regarding the source of this problem) without a coding example, then I would be grateful.

Thank you very much.


texts: Some Truffle tests not running after truffle init (Mac OSX) Uncaught TypeError

texts:
I am trying to build a DApp using Truffle. I have installed Testrpc and Truffle globally with NPM. I ran testrpc in a terminal window and ran truffle test. I get 2 passing and 3 failing tests. The three failing tests are:

TestMetacoin testInitialBalanceUsingDeployedContract:

TestMetacoin testInitialBalanceWithNewMetaCoin:

and

Contract: MetaCoin should send coin correctly:

each is failing with the same message:

Uncaught TypeError: Cannot read property '1' of undefined
  at /usr/local/lib/node_modules/truffle/node_modules/ethjs-abi/lib/index.js:139:34
  at Array.map (native)
  at Object.decodeEvent (/usr/local/lib/node_modules/truffle/node_modules/ethjs-abi/lib/index.js:138:6)
  at /usr/local/lib/node_modules/truffle/node_modules/truffle-contract/contract.js:73:38
  at Array.map (native)
  at Object.decodeLogs (/usr/local/lib/node_modules/truffle/node_modules/truffle-contract/contract.js:44:19)
  at Object.callback (/usr/local/lib/node_modules/truffle/node_modules/truffle-contract/contract.js:172:35)
  at /usr/local/lib/node_modules/truffle/node_modules/truffle-contract/node_modules/web3/lib/web3/method.js:142:25
  at /usr/local/lib/node_modules/truffle/node_modules/truffle-contract/node_modules/web3/lib/web3/requestmanager.js:89:9
  at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:119:13)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:64:18)
  at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:354:12)
  at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:509:12)
  at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:469:24)

I am sure I am missing something simple, any help is appreciated.

Edit:  So it looks like for some reason in the decodeEvent method is getting nil for topics in the failing tests.  This is my first experience with truffle or daps so I am not really sure how to remedy this but I will keep digging.


texts: List of publicly available ethereum nodes (geth debug rpcapi)

texts:
As a fun of Remix Debugger, it's necessary to connect to geth nodes with debug API turned on.
I'd like to know if there is list of such nodes.


texts: Why does additional data storage within L2 increases transactions per second?

texts:
Referencing the statement:
"This (Shard chains version 1) reduces the data needed for a transaction. Combine this with all the extra data availability provided by shards and you get 100,000 transactions per second." (Ethereum Official Page)
I am wondering why (/how) additional storage provided through devices is increasing the rate of transactions per second?
My assumption was that just computing power is increasing the transaction speed. Which peace in the puzzle am I missing?


texts: Calling function of external contract and passing bytecode

texts:
I am trying to understand different methods of invoking functions of another smart contract (which is already deployed on the blockchain).

Please see example below (call data/bytecode based on using 5 as lucky number).

pragma solidity ^0.4.17;

contract DeployedContract {
    uint public result = 0;

    function add(uint input) {
        result = result + input;
    }
}

contract Proxy {
    address deployed_contract = 0x123;

    function call1(uint lucky_number) {
        deployed_contract.call(bytes4(sha3("add(uint)")),lucky_number);
        // fails
    }

    function call2(uint lucky_number) {
        deployed_contract.call(bytes4(sha3("add(uint256)")),lucky_number);
        // success
    }

    function call3(uint lucky_number) {
        deployed_contract.call(0x1003e2d2,lucky_number);
        // success
        // when debugging in remix, call data is 0x1003e2d20000000000000000000000000000000000000000000000000000000000000005
    }

    function call4() {
        deployed_contract.call(0x1003e2d20000000000000000000000000000000000000000000000000000000000000005);
        // does not compile: TypeError: Invalid rational number
    }

    function call5(bytes32 data) {
        // using call data from above (see call3), when using bytes32 as type, data is truncated to 0x1003e2d200000000000000000000000000000000000000000000000000000000
        deployed_contract.call(data);
        // fails, since bytes32 truncates data
    }

}

Questions:

Why is uint256 as parameter necessary (see call2), even though the function definition is add(uint)?
call4(): uses the exact call data as is generated with call3(), not sure how this could be done otherwise?
call5(): any ideas on how to achieve this?

Looking forward to understand this better, appreciate if somebody could give me some pointers. Cheers!


texts: Solution for mapping corporative credentials with Ethereum account

texts:
I need a solution for mapping corporative credentials (like Active Directory) to users of a "corporative Ethereum account".
In other words, all users of the company may use the same Ethereum account. So, I would like to have a signer application that anyone with a corporative credential can use. I need to log who is using the signer to submit the transactions to the blockchain. What are some solutions to that?
Thank you


texts: Ethereum Smart contract calling a function in another smart contract that has a address payable return value give error

texts:
I am new to solidity. Anyway, I have written the following smart contract:

pragma solidity >=0.4.22 <0.7.0;

contract SP {

    address BlockAddress;
    bytes32 _Mhash;

    function verifyHash_ASM(bytes32 _MHash) public returns (address payable Validator_address) {

        bytes4 sig = bytes4(keccak256("verifyHash(string)"));
        assembly {
            // move pointer to free memory spot
            let ptr := mload(0x40)
            // put function sig at memory spot
            mstore(ptr,sig)
            // append argument after function sig
            mstore(add(ptr,0x04), _MHash)

            let result := call(
              15000, // gas limit
              sload(BlockAddress_slot),  // to addr. append var to _slot to access storage variable
              0, // not transfer any ether
              ptr, // Inputs are stored at location ptr
              0x20, // Inputs are 32 bytes long
              ptr,  //Store output over input
              0x20) //Outputs are 32 bytes long

            if eq(result, 0) {
                revert(0, 0)
            }

            Validator_address := mload(ptr) // Assign output to Validator_address var
            mstore(0x40,add(ptr,0x24)) // Set storage pointer to new space

        }
        //PayTokens(Validator_address, User_address, RepTokens);
        //return Validator_address;
    }

When I call the verifyHash_ASM function and parse the byte32 value 0x33c897fb3febb48f0a8a9ff79518057a9943ed879d644bba81a8a1050ccfaa4f which is equivalent to the one assigned in another contract and call the same function in that contract, I get the following error:

"transact to SP.verifyHash_ASM errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.  Debug the transaction to get more information."

The status is: "0x0 Transaction mined but execution failed"

Please note that I executed the function without values in Remix. I have also tried executing this by adding gas values and changing the function to "payable",but I still got this error.

The compiler I am using is 0.5.11 and the execution environment is JavaScript VM
in Remix.

Your help and support is much appreciated

Thank you


texts: Building TransactionRoot from a single transaction

texts:
I'm trying to follow through the trie construction for transaction data - and the multiple resources online seem quite conflicting!
Let's consider transaction
https://etherscan.io/tx/0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060
which happens to be the very first Ethereum transaction ever.
This resides in a block #46147, which contains the transaction root:
0x4513310fcb9f6f616972a3b948dc5d547f280849a87ebb5af0191f98b87be598
Now. Using https://emn178.github.io/online-tools/keccak_256.html I can easily recreate the transaction hash (0x5c504e...) from the RLP of the transaction itself:
f86780862d79883d2000825208945df9b87991262f6ba471f09758cde1c0fc1de734827a69801ca088ff6cf0fefd94db46111149ae4bfc179e9b94721fffd821d38d16464b3f71d0a045e0aff800961cfce805daef7016b9b675c137a6a41a548f7b60a3484c06a33a
But I'm still very baffled on how to get to the TxRoot (0x451331...)
Presumably the trie has only one Node - mapping 0 to, well.. hash? full list?
Either way, I've tried multiple combinations - and couldn't get at the hash stored in the block header.
What hashes to 0x4513310fcb9f6f616972a3b948dc5d547f280849a87ebb5af0191f98b87be598?


texts: Problem compiling/deploying Solidity contract

texts:
I am trying to compile and deploy simple contract :

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

var source = "" +
"contract test {\n" +
"   function multiply(uint a) returns(uint d) {\n" +
"       return a * 7;\n" +
"   }\n" +
"}\n";
var compiled = web3.eth.compile.solidity(source);
console.log(compiled);

Based on documentation I was expecting sth like this :

"test": {
"code": "0x605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056",
"info": {
  "source": "contract test {\n\tfunction multiply(uint a) returns(uint d) {\n\t\treturn a * 7;\n\t}\n}\n",
  "language": "Solidity",
  "languageVersion": "0",
  "compilerVersion": "0.8.2",
  "abiDefinition": [
    { ...

but what I get is :

  0x606060405260308060106000396000f3606060405260e060020a6000350463c6888fa18114601c575b6002565b346002576007600435026060908152602090f3

I am not sure how to create new contract out of that as examples I found say I should do sth like that

var greeterContract = web3.eth.contract(compiled.test.info.abiDefinition);

 var greeter = greeterContract.new(_greeting,{from:web3.eth.accounts[0], data: compiled.test.code, gas: 1000000}, function(e, contract){

any ideas what I did wrong?

P.S. I am using Parity as provider


texts: Javascript Web3 sendTransaction not working

texts:
I wrote the following to interact with a Geth node. Got Error: authentication needed: password or unlock. Is there any way to bypass that? I don't want to use private key in my code either. Can I interact with the node directly to send transaction or sign message?

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));

web3.eth.sendTransaction({
    from: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    to: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    value: web3.toWei(2, "ether"),
    nonce: '0x1',
    gasPrice: '0x5b9aca00',
    gasLimit: '0x56f90',
}, function(err, transactionHash) {
    if (err) {
        console.log(err);
    } else {
        console.log(transactionHash);
    }
});


texts: I put some money into MetaMask. I put a bid on a Punk. I cancelled the bid, but I did not seem to get the money back? Do I lose the gas on withdrawn bids?


texts: Where can I find Ethereum raw transactions?

texts: For Bitcoin, I can use this site to find the hex encodings of raw Bitcoin transactions. Where can I find something similar for Ethereum?


texts: Contract [Contract's name] not found on network ID: 5777

texts:
I am using truffle with drizzle.

In the contract folder I provide a file that includes two contracts
A that is a factory contract and
B that is created through one of A's functions

After compiling and migrating, I get two contract files as json:
A.json, B.json

The factory contract gets deployed, however when I run my client,
I can see in the following error in the console:

Contract B not found on network ID: 5777

and

index.js:1375 uncaught at _callee at _callee
 at contractsSaga
 at takeEvery
 at addContract
 TypeError: Cannot read property 'contractName' of undefined

When inspecting B.json I see that ABI is provided and  contract name
is specified in the file.

Question:
Should B get deployed to be accessible and if so, how to proceed when I want only A to be able to deploy B and only if a certain function is called? Not mentioning A can deploy multiple Bs.

Thanks


texts: What is the advantages of using Oraclize for the development of an ICO Smart contract? doesn't it just add unnecessary complexity?


texts: How do I enable web3 in Coinbase wallet?

texts:
I am building a very simple dapp.  At first I want to initiate web3 on the webpage and then enable it so that I can access web3.eth.getAccounts().

MetaMask, and Opera Mobile both have a window.ethereum.enable() function which will prompt the user to allow the webpage to access the wallet. Once they do that, I can call web3.eth.getAccounts, like this:

    ethereum.enable().then(() => {
        web3.eth.getAccounts((error, accounts) => {
          console.log(accounts)
        })
      })
    }

Coinbase Wallet (aka Toshi) doesn't have window.ethereum.enable, (or equivalent) so I can't access getAccounts()

Anyone know how to get it to work?


texts:
I am trying to import these lines on solidity and compile it with solc
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IERC20.sol';

Every time I run the compile.js I get this error.
{"errors":[{"component":"general","formattedMessage":"mysample.sol:4:1: ParserError: Source \"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol\" not found: File import callback not supported\nimport '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
\n^-------------------------------------------------------------------------^
\n","message":"Source \"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol\" not found: File import callback not supported","severity":"error","sourceLocation":{"end":135,"file":"mysample.sol","start":60},"type":"ParserError"},
{"component":"general","formattedMessage":"mysample.sol:5:1: ParserError: Source \"@uniswap/v2-periphery/contracts/interfaces/IERC20.sol\" not found: File import callback not supported\nimport '@uniswap/v2-periphery/contracts/interfaces/IERC20.sol';
\n^-------------------------------------------------------------^
\n","message":"Source \"@uniswap/v2-periphery/contracts/interfaces/IERC20.sol\" not found: File import callback not supported","severity":"error","sourceLocation":{"end":200,"file":"mysample.sol","start":137},"type":"ParserError"}],"sources":{}}

The code for compile.js used
const path = require('path');
const fs = require('fs');
const solc = require('solc');

const mysamplePath = path.resolve(__dirname, 'contracts', 'mysample.sol');
const source = fs.readFileSync(mysamplePath, 'utf8');

console.log(solc.compile(
  JSON.stringify({
    language: "Solidity",
    sources: {
      "mysample.sol": {
        content: source
      }
    },
    settings: {
      outputSelection: {
        "*": {
          "*": ["evm", "bytecode"]
        }
      }
    }
  })
));

I have no idea why the compiler can not find the uniswap import. How do I resolve this?


texts: How to get the transaction hash once it is mined?

texts: In JavaScript (web3.js), how do I get the transaction-hash corresponding to a function executed in my smart contract?


texts: Call to mint using openzeppelin CappedToken. Failing on Ropsten

texts:
I have a token created using OpenZeppelin library. I use the CappedToken contract.

My code is :

pragma solidity ^0.4.18;

import 'openzeppelin-solidity/contracts/token/ERC20/CappedToken.sol';

contract YLBToken is CappedToken {
    string public name = "My Token Beta";
    string public symbol = "MTB";
    uint8 public decimals = 18;

    function YLBToken(uint256 cap) CappedToken(cap) {
    }
}

Using truffle I compile and test it. I migrated to Ropsten.

I created a web page to run it.

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
        <script type='text/javascript'>
            var deployedContract;
            const ADDRESS = "0xcbcc819866a24a777b0c076d4922c127de9ecb06";
            const ABI = MY_ABI;

            // Init and detect metamask
            window.addEventListener('load', function () {
                if (typeof web3 !== 'undefined') {
                    web3 = new Web3(web3.currentProvider);
                    currentAccount = web3.eth.accounts[0];
                } else {
                    // set the provider you want from Web3.providers
                    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
                    console.log("Metamask or similar not detected");
                }

                deployedContract = web3.eth.contract(ABI).at(ADDRESS);
                deployedContract.mint(currentAccount, parseInt(1000) * 1000000000000000000, { from: currentAccount, gasPrice: web3.toWei(1, 'gwei') }, function (error, result) {
                    if (!error) {
                        console.log("Mint result = " + result);
                    }
                    else {
                        console.log(error);
                    }
                });
            })
        </script>
    </head>
    <body>
    </body>
</html>

I expect Metamask to open and after clicking submit to mint 1000 tokens on the owner address, just to test is working fine. I have it running into a webserver.

But this is what Metamask shows :

I have no clue why Metamask shows this message. Using truffle test the mint function works fine. Using Metamask pointing to localhost:8545 and running testrpc in a console also worked fine.

Can someone point me to a solution?


texts: What is the significance of memory keyword in this example

texts:
contract sample {
     uint32 count;

     struct example {
         uint32 value ;
     }
     mapping(uint32=example) mapper;
     event trackInt(uint32);
     event trackObj(uint32);

     function test() {
         example memory  obj;
         obj.value = count +1;
         mapper[count]=obj;
         count++;
         trackObj(obj.value);
         trackInt(count);

     }

     function getCount() returns (uint32) {
         return count;
     }

     function get(uint32 id) returns (uint32) {

         example obj = mapper[id-1];
         return obj.value;
     }
}

Even after calling the test() function several times, I am able to retrieve the details in the struct even though obj is of type memory . Could someone clarify how it works?


texts: Sent Ether does not reach recipient on Testnet (Morden)

texts:
I'm trying to send Ether from an account of mine to a friend's account. I'm using the Ethereum Wallet application on Windows, my friend uses the Ethereum Wallet application on a Linux VM. The network seems to recognize the recipient account. When I send Ether to that account, transaction is completed on my side, but my friend never receives the Ether.
Do you have any idea what could be the problem ?

Note: sending Ether from my account to another account of mine works well.

Thanks


texts: what is the protocol used in commuinication between ethereum blockchain nodes?

texts:
Let's say that we have many blockchain nodes managed by parity clients.
what is the protocol used in communication between those nodes?


texts: Is allocating a portion of tokens to the dapp creator after a crowdsale a bad business move?

texts: Will this lessen the integrity of the dapp?  Will people trust the company less?


texts: How to connect Parity to Miner using Stratum & LAN & solo mining?

texts:
I am testing Parity with Stratum (is in beta):

Parity is running and fully synchronized, on Foundation Chain, on a machine of the LAN (192.168.5.11), started on terminal with:

sudo parity --author 0037a6b811ffeb6e072da21179d11b1406371c63 --stratum --stratum-interface=0.0.0.0 --stratum-port=8008

Miner (Claymore) is working on the LAN (192.168.5.12) and started with:

sudo ./ethdcrminer64 -epool http://192.168.5.11:8008 -mode 1

Firewalls disabled on both Parity's and Miner's machines.

Miner reports not possible connect to http://192.168.5.11:8545

Miner is working fine in a pool. Just doing some tests with solo mining and my Parity Node.


texts: I have a DAO wallet with 1100 tokens - how can I get that into Coinbase as ETH?

texts:
I know my wallet's address, I have saved my wallet file, and I have the password for my wallet. Other than that, I know nothing. I know the hard fork was a success, but I don't know if The Dao is still going to operate, or if the goal is to simply refund everyone's ETH, etc. I don't have any ETH or DAO related software installed and have never used any.

Note: I've read the answers on such questions as How to withdraw Ether from The DAO?, but none of that makes any sense to me. I don't know how (or even what tool to use) to "transfer [my] DAO Tokens to an exchange and sell them", or which exchange to use.


texts: Programmatically getting an Ethereum address for a raw hex private key

texts:
Let's assume one has a private key in a raw hexadecimal format:

# Not a real key
ddc64840388bc5f2bc9d40a29b35ae3c41a8cdf9ee1dfdc5a46414e3db3de2db

How one would get the corresponding Ethereum account from a UNIX command line?


texts:
I'm using this contract code and want to create ico contract. But when I create contract code and try to transfer eth I'm getting error. I can't transfer ethereum to ico contract address.

Warning! Error encountered during contract execution [Bad jump destination]

can you help me ?

pragma solidity ^0.4.6;

import "./ABCToken.sol";
import "./SafeMath.sol";

ABCToken public ABCToken;

// Address of the founder of ABC.
address public founder = 0x3311111111111111111111111111111111111133;

// Address where all tokens created during ICO stage initially allocated
address public allocationAddress = 0x2111111111111111111111111111111111111111;

// Start date of the ICO
uint public startDate = 1524528001;

// End date of the ICO
uint public endDate = 1535068801;

// Token price without discount during the ICO stage
uint public baseTokenPrice = 10000000; // 0.001 ETH, considering 8 decimal places

// Number of tokens distributed to investors
uint public tokensDistributed = 0;

/*
 *  Modifiers
 */
modifier onlyFounder() {
    // Only founder is allowed to do this action.
    if (msg.sender != founder) {
        throw;
    }
    _;
}

modifier minInvestment(uint investment) {
    // User has to send at least the ether value of one token.
    if (investment < baseTokenPrice) {
        throw;
    }
    _;
}

/// @dev Returns current bonus
function getCurrentBonus()
    public
    constant
    returns (uint)
{
    return getBonus(now);
}

/// @dev Returns bonus for the specific moment
/// @param timestamp Time of investment (in seconds)
function getBonus(uint timestamp)
    public
    constant
    returns (uint)
{
    if (timestamp > endDate) {
        throw;
    }

    if (startDate > timestamp) {
        return 1499;  // 49.9%
    }

    uint icoDuration = timestamp - startDate;
    if (icoDuration >= 16 days) {
        return 1000;  // 0%
    } else if (icoDuration >= 9 days) {
        return 1125;  // 12.5%
    } else if (icoDuration >= 2 days) {
        return 1250;  // 25%
    } else {
        return 1499;  // 49.9%
    }
}

function calculateTokens(uint investment, uint timestamp)
    public
    constant
    returns (uint)
{
    // calculate discountedPrice
    uint discountedPrice = div(mul(baseTokenPrice, 1000), getBonus(timestamp));

    // Token count is rounded down. Sent ETH should be multiples of baseTokenPrice.
    return div(investment, discountedPrice);
}

/// @dev Issues tokens for users who made BTC purchases.
/// @param beneficiary Address the tokens will be issued to.
/// @param investment Invested amount in Wei
/// @param timestamp Time of investment (in seconds)
function fixInvestment(address beneficiary, uint investment, uint timestamp)
    external
    onlyFounder
    minInvestment(investment)
    returns (uint)
{

    // Calculate number of tokens to mint
    uint tokenCount = calculateTokens(investment, timestamp);

    // Update fund's and user's balance and total supply of tokens.
    tokensDistributed = add(tokensDistributed, tokenCount);

    // Distribute tokens.
    if (!ABCToken.transferFrom(allocationAddress, beneficiary, tokenCount)) {
        // Tokens could not be issued.
        throw;
    }

    return tokenCount;
}

/// @dev Contract constructor
function ABCICO(address tokenAddress, address founderAddress) {
    // Set token address
    ABCToken = ABCToken(tokenAddress);

    // Set founder address
    founder = founderAddress;
}

/// @dev Fallback function
function () payable {
    throw;
}

}


texts: Opcode error when interacting with smartcontract in geth

texts:
Initially, I was working locally with ganache and the smart contracts were working correctly. Then I tried to work on geth and I get the following error:
Traceback (most recent call last):
  File "manager.py", line 165, in <module>
    ui.start_application()
  File "manager.py", line 142, in start_application
    self.register_user()
  File "manager.py", line 68, in register_user
    manager.register_user()
  File "manager.py", line 16, in register_user
    self.blockchain.RegistrationContract.registerUser()
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/registrationContract.py", line 11, in registerUser
    tx_receipt= self.contract.functions.registerUser().transact({'from': User.address})
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/contract.py", line 1151, in transact
    **self.kwargs
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/contract.py", line 1454, in transact_with_contract_function
    txn_hash = web3.eth.sendTransaction(transact_transaction)
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/eth.py", line 264, in sendTransaction
    get_buffered_gas_estimate(self.web3, transaction),
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/utils/transactions.py", line 84, in get_buffered_gas_estimate
    gas_estimate = web3.eth.estimateGas(gas_estimate_transaction)
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/eth.py", line 305, in estimateGas
    [transaction],
  File "/mnt/c/Users/Achilleas/Dissertationnew/application/env/lib/python3.6/site-packages/web3/manager.py", line 112, in request_blocking
    raise ValueError(response["error"])
ValueError: {'code': -32000, 'message': 'invalid opcode: SHR'}

The geth script I use is the following:
geth --rpc --rpccorsdomain "*" --rpcapi "db,eth,net,web3,personal" --datadir ./chaindata/
 --nodiscover --rpcport "port" --rpcaddr "address" --networkid "id" --identity "identity" --unlock
"account_address" --allow-insecure-unlock --mine --minerthreads=1

"User.address" in the error message is the same address with "account_address" in geth script.
I did not change anything in the code. Do I need to sign the transaction (the account is unlocked)?


texts: Using the correct/best solc version with Truffle and general tooling setup

texts:
I haven't worked with Truffle/Solidity for a while and I am trying to get my environment/toolchain configure correctly. I have some questions regarding the compiler config.

I was originally not setting the compiler config options in truffle-config.js and recently set it to 5.5 which appears as if it caused Truffle to download a new Docker image, and compilation seems to have slowed down, or at least running the full test suite is quite a bit slower.

I am working on an a project and have been setting the pragma as

pragma solidity ^0.5.5;

My truffle config block:

  // Configure your compilers
    compilers: {
    solc: {
      version: "0.5.5",    // Fetch exact version from solc-bin (default: truffle's version)
      docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      settings: {          // See the solidity docs for advice about optimization and evmVersion
       optimizer: {
         enabled: false,
         runs: 200
       },
       evmVersion: "petersburg"
      }
    }
  }
  }

And my solc output:

solc --version
solc, the solidity compiler commandline interface
Version: 0.5.12+commit.7709ece9.Darwin.appleclang

Does this look correct? Are there any obvious improvements?

Project repo: https://github.com/alanwilhelm/upgradeable_token


texts: truffle migrate --network rinkeby: Error encountered, bailing. Network state unknown

texts:
All works with the local testrpc instance.

Now trying to deploy to rinkeby via the Infura site using the HDWalletProvider.
Everything looks trivially configured... (unless I need to specifically unlock an account?)

But the migration doesn't work, failing on the 1_initial_migration.js which is a tiny contract.

 > truffle migrate --network rinkeby
Using network 'rinkeby'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
Error encountered, bailing. Network state unknown. Review successful transactions manually.
exceeds block gas limit
 >

Anyone else see / resolve this ?


texts: Is this notice to update to Geth 1.6.6 via windows.net legitimate?

texts:
A few days ago when opening Ethereum Wallet version 0.8.9 I received popup windows notifying me to update the Wallet to 0.8.10 and Geth to 1.6.6. Here is a screenshot of the latter:

This notice directs me to windows.net, but it appears github is the official repository and that the latest version is 1.6.7, not 1.6.6. Additionally, I am no longer receiving this notice, Ethereum Wallet > 'Check for Ethereum node updates...' has no effect, and Ethereum Wallet > 'Check for updates...' opens a window (after a brief waiting-animation) reporting, "No update found. You are running the latest version of Ethereum Wallet." However, I'm still using 0.8.9 according to Ethereum Wallet > 'About Ethereum Wallet'.

Is it simply not showing updates at the moment due to limitations (or blocked ports?) of the public business's hotspot that I am now checking at? (The notice appeared using a different non-public Internet connection.) Is windows.net an official download mirror for the Ethereum community?


texts:
I built a token by creating a smart contract for it, and have successfully connected to it, which is on a Ethereum test-net. Using web3.js I have been able to send token from one account to another account, score! However, I'm having a hard time finding a tutorial on how to add Ether to your token, to give it an actual monetary value. From what I understand, part of the beauty of creating tokens on a decentralized P2P ledger network otherwise known as a blockchain, is that it gives you a secure way to transact any infinite number of abstract things. But how do you give those tokens actual value? Do you tie some amount of Ether to your token, and state in your smart contract how much ether one of your tokens is worth?

Or do you explicitly set your smart contract up to pull ether from an account automatically when they send token from their wallet to another wallet? In either case how do you accomplish that? I have seen that some functions have payable  on them, and this may be the key to what I need. Could anyone help me out?


texts:
I'm having trouble testing a contract using truffle.   I have the latest version of truffle installed as well a TestRPC.

It's to my understanding that the latest version of truffle comes with a client for testing SmartContracts so TestRPC isn't needed any more.

I have a simple contract my Migrations looks like so:

var Migrations = artifacts.require("./Migrations.sol");
var OrdersFacilitator = artifacts.require("./OrdersFacilitator.sol")

module.exports = function(deployer) {
  deployer.deploy(Migrations);
  deployer.deploy(OrdersFacilitator);
};

When I run truffle develop I see that 10 test accounts are created.

  Accounts:

  (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57

  (1) 0xf17f52151ebef6c7334fad080c5704d77216b732
  //...

My Truffle js is configured like so:

networks: {
  development: {
    host: "localhost",
    port: 9545,
    network_id: "*"
  }
}

When I run the name of my contracts I can see its deployed with the information:

//...
class_defaults:
{ from: '0x627306090abab3a6e1400e9345bc60c78a8bef57',
 gas: 6721975,
 gasPrice: 100000000000 },
currentProvider:
 HttpProvider {
   host: 'http://127.0.0.1:9545/',
   timeout: 0,
   user: undefined,
   password: undefined,
   headers: undefined,
   send: [Function],
   sendAsync: [Function],
   _alreadyWrapped: true },
network_id: '4447' }

the Network Id and the port seem to match the configuration fine, and I can see the information when I type the contract name, However when I try to gain access to it though

var facilitator;
OrdersFacilitator.deployed().then(x => facilitator = x);

I Get an Error:

  OrdersFacilitator has not been deployed to detected network (network/artifact mismatch)

I've tried deleting the build folder and migrating all with the --reset flag but that doesn't seem to work. How can I Tested my deployed contract


texts:
I managed to setup Ethereum private network (using clique, Quorum's RAFT and IBFT) and managed to connect them to my own DApp via metamask.
Now I am wondering, how to make the network that I just setup as a service so that others(public) can use my node. Something like Infura or Quicknode. Could anyone outline how to do this?
Thank you.


texts: Building a raw contract transaction with ethers.js

texts:
Can't find any good documentation on creating a raw transaction with contract data in ethers.js. The equivalent in web3 is adding the encodeABI on the data property. Any guidance on this?
This isn't working:
data = myContract.interface.functions.myFunction(value);
const tx = {
   ...
   data
   ...
}

It doesn't seem to recognize this is a function (even though i see the data property there).


texts: Native mobile Dapp - Sign transactions with user wallet

texts:
I'm starting a new project that involves a mobile Dapp and I have a question regarding signing transactions.

Every mobile Dapp post that I read about offered two solutions:

Use a Dapp browser, such as Status or Trust, or
Develop a wallet inside the app

The first solution involves developing for browsers, less features and the experience is not the same. And the second forces the user to use another account (I get that accounts are free, but come on I don't want another one, transfer from my wallet to start, save the seed, etc.).

I guess that I could allow to use the mnemonic but that is also a pain in the bottom.

My question is simple, is it possible for users to use their own wallet (assuming they have it on the same phone) to sign transactions of my Dapp? If users have already Toshi/Coinbase, Status, Trust, is there any way they can use it to sign transactions from my Dapp?

Maybe I'm too biased with Metamask, but I think it would be great to be using a mobile Dapp, and when I want to call a smart-contract, that my wallet (i.e: coinbase) would pop-up and show my what I'm about to do and confirm it.

Anyway, many thanks in advance!


texts: Why do we have to "deposit" into a decentralized exchange?

texts:
On a centralized exchange (like coinbase), I understand why we have to deposit money into it in order to trade.

But about decentralized exchange, as I've read about, it has some kinds of "atomic swap", which swaps tokens "cross chain".

So why do we still have to deposit our tokens into the decentralized exchange?


texts: How to understand the storage process in solidity?

texts:
What is the meaning of :
require(newKittenId == uint256(uint32(newKittenId)));

Edit:

Complete relevant code:

uint256 newKittenId = kitties.push(_kitty) - 1;

// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
require(newKittenId == uint256(uint32(newKittenId)));