texts: How can I carry out the operation of "withdrawing eth from an ERC20 contract into a wallet" from the onchain (i.e., from another contract)?

texts:
In MainContract, I need to perform an atomic transaction which includes the following:

Transfer eth from Contract1 (which is an ERC20 contract) into a given address
Change a state variable in Contract2

I'm having problem implementing the first part.

At present, what I have in mind is to add this in Contract1:

address public mainContract;

constructor(address _mainContract) public {
    mainContract = _mainContract;
}

function withdraw(address _to, uint256 _value) external {
     require(msg.sender == mainContract);
     _to.transfer(_value);
 }

And then to call function withdraw from a function in MainContract:

function execute(address _to, uint256 _value) external {
     require(msg.sender == owner);
     contract1.withdraw(_to, _value);
     contract2.update();
 }

But since Contract1 is an ERC20 contract, I was hoping there would be a cleaner way.

Given that I'm the owner of all contracts here, is there a way for me to directly transfer eth from contract1 to the specified address _to?

Something like _to.transfer(_value, {from: address(contract1)}) perhaps?

Thank you!

Note: The reason why I've mentioned the second part (contract2) here, is because otherwise you could tell me something like - "well, just do it from the offchain and get it over with". I need both operations to take place within a single transaction, in order to make sure that nothing else happens in between.


texts: How to setup the account manager type to sign transactions in Go?

texts:
TL;DR:
I've setup a private Ethereum node, and I want to send a signed transaction to it. By reading the docs I know that there's an account Manager type which can access a Wallet type which has a SignTx method that I want to use for this purpose. I'm having an issue setting up the account Manager type to begin this process.

The Problem:

The NewManager function requires a type which implements the Backend interface. The problem here is that I can't find any docs describing (accurately) how to initialize an account Manager with a Backend. The only backend available in the account source is SimulatedBackend meant for testing (source: https://github.com/ethereum/go-ethereum/tree/3fa0fa713bc1508835bdecd7dea78ff09803e327/accounts/abi/bind/backends).

What I've tried:

The docs (here: https://github.com/ethereum/go-ethereum/wiki/Native:-Account-management#keystores-from-go) say that one can be initialized this way:

am := accounts.NewManager("/path/to/keystore", accounts.StandardScryptN, accounts.StandardScryptP);

However, it does not compile as the accounts.StandardScryptN and accounts.StandardScryptP do not exist, and when replaced with their integer equivilents (2 and 1 respectively), the compile error states that the keystore path argument ("/path/to/keystore") does not implement the Backend interface, which makes sense. My guess is that the docs are not updated, and because of that the NewManager function cannot compile with these arguments.

Docs for the NewManager type for reference: https://godoc.org/github.com/ethereum/go-ethereum/accounts#NewManager

Question:

Does anyone know how to initialize the account manager correctly to begin signing transactions in Go?


texts:
There are electrum wallet for LTC.

I basically need a wallet that can generate multiple addresses.

I also need to be able to store the wallet as seed of words.


texts: How bad is it to change a function inside ERC721 interface?

texts:
I'm creating a NFT and I want the transferFrom function to be payable. In order to do so I need to edit the ERC721 interface and make that function payable also there.

If I do so everything compiles smoothly, but my question is:
 - Will other platforms don't accept my token as a standard ERC721 token? How do other platforms (eg. wallets as Trust Wallet) recognize that my token is a standard ERC721?
 - Is there a better way to do this without editing the ERC721 interface? There is this discussion but no real solution: https://github.com/OpenZeppelin/openzeppelin-contracts/issues/1015


texts: web3.eth.sendSignedTransaction - transaction not located

texts:
I am using web3.eth.sendSignedTransaction and infura.io on mainnet. I want to call my smart contract's whitelisting function. I have no problems calling this function directly, however, when using web3 to call it, a transaction hash is produced, but it is never located. e.g.
https://etherscan.io/tx/0x5d127fde285fc4821eb99dceb1a96ac1122a1dd543c92f8685fd19f51aa95a6c

It seems like a gas issue, but I have tried with many different gas prices and limits, what else could be the problem?

Sometimes I get the error "Error: Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!"

exports.addToWhitelist = function(req, res) {

var web3 = new Web3(new
Web3.providers.HttpProvider('https://mainnet.infura.io/' +
process.env.INFURA_KEY));

 var userAddress = req.user.ethereumAddress;

  var ownerAddress = process.env.OWNER_ADDRESS;

  var helper = {
        ensureBuffer: function(bufferOrString) {

            if (typeof bufferOrString === "string") {
                return new Buffer(bufferOrString, 'hex');
            } else {
                return bufferOrString;
            }
        }
    };

  var key = helper.ensureBuffer(process.env.PRIVATE_KEY);

  var userAddress = req.address;

  var crowdsaleAbi = JSON.parse('[{"constant":false,"inputs":[{"name":"_buyer","type":"address"}],"name":"addToEarlylist","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]');

  var crowdsaleContract = new web3.eth.Contract(crowdsaleAbi, process.env.CROWDSALE_CONTRACT);

  web3.eth.getGasPrice().then(function(result)
    {
      var methodData = crowdsaleContract.methods.addToEarlylist(userAddress).encodeABI();

      var fTx = {
            nonce: 0,
            gasPrice: 0,
            gasLimit: web3.utils.toHex(800000),
            data: methodData,
            from: ownerAddress
          };

      fTx.gasPrice = web3.utils.toHex(result);

      console.log('gas price: 40 gwei');

      web3.eth.getTransactionCount(ownerAddress)
        .then(function(result) {

          fTx.nonce = web3.utils.toHex(result + 1);

          var txx = new Tx(fTx);
          txx.sign(key);

          console.log(fTx);
          var sTx = txx.serialize();

          web3.eth.sendSignedTransaction('0x' + sTx.toString('hex'))
          .on('transactionHash', function (hash) {
              console.log("trans hash: " + hash)
          })
          .on('receipt', function (receipt) {
              console.log("receipt: " + receipt)
          })
          .on('confirmation', function (confirmationNumber, receipt) {
               console.log("conf: " + confirmationNumber, receipt)
          })
          .on('error', (e) => {
              console.log("Sending Error: " + e)
          });

        }).catch(function(error) {console.log(error)});;

    }).catch(function(error) {console.log('gas price error ' + error)});

}


texts: My disk has only 1 GB free - how can I use the Linux Ethereum Wallet?

texts:
I just downloaded the Ethereum Wallet for Debian Linux (I have Ubuntu 16.04).
It appears to be downloading a lot of blocks: it now says that there are 3,310,606 blocks, and the number is decreasing. I also see a new .ethereum folder in my home folder, which is now over 602 MB in size and increasing.

I am almost out of memory on my laptop. Is there a way to use Ethereum (including some simple smart contracts) without using so much memory?


texts: Website to generate Ethereum Hash of a PDF file

texts:
I would like to ask a user to generate a "Keccak-256" or "Keccak-512" (Ethereum versions of SHA3) of a PDF file. Is there a recommended website with a good GUI to generate that?

The user would input a PDF file and the system will return "Keccak-256" or "Keccak-512" of this file.

Obs.: I know I can program a service to that. It is just a MVP.


texts: What's the Convention used to get a Contract's ABI uploaded to a Node.js Server instance?

texts:
I'm still a brand new student of Ethereum, and I'm trying to figure out How to instantiate a Contract from a Node.js instance using Web3. I'm also using the Truffle Suite but for development/Testing purposes Only.

What I need to know is how can I get a Contract's ABI into a Node.js standalone Project?

I know I could just Upload it as a JSON file, or I could also use the solc library to compile the .sol Contract File... the latter option appears to be a fine choice as long as I only need to do it once (like when the server starts/re-starts for example)

I'm wondering what is the Best Practice for doing this? I can't find a concrete answer regarding this matter.

Thank you.


texts: How to Mine Ether and use Ethereum on Windows?

texts: Which programs should be installed and what do you need to do to start mining Ether and use Ethereum?


texts: Can we pass string values to the contract which holds bytes 32 only in solidity?

texts: My contract can hold only array of type bytes32 only. How can we store string values as well?


texts:
Why do I keep on getting this error when I try to send ether from one of my accounts to the other? Note that when I send it between other accounts the same code works, I have checked the balance and it shows that there is actually sufficient balance. So, what's going on here? When it works it outputs: failed to check for transaction receipt, when it doesn't work it outputs: unhandled promise rejection warning.
code:

var Web3 = require('web3')
web3 = new Web3('https://ropsten.infura.io/hqRzEqFKv6IsjRxfVUMH')
const account1 = '0x0539B9c9C886e93778542B553C64cb5EAfB902b1'
const account2 = '0xca7F442c44b079dd07324C9c7eDfe348b92f46c9'
const privatekey1 = Buffer.from('c986afe0XXXXXXXXXXXXXXXXXXXXXXXXXXca1aed18981b' , 'hex')
const privatekey2 = Buffer.from('1311767cXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb97bbfee1cf7fd2411e2d8' , 'hex')
web3.eth.getTransactionCount(account2 , (err, transCount) => {
const txObject = {
nonce: web3.utils.toHex(transCount) ,
from: account1 ,
to: account2 ,
value: web3.utils.toHex(web3.utils.toWei('0.00001' , 'ether')) ,
gasLimit: web3.utils.toHex(21000) ,
gasPrice: web3.utils.toHex(web3.utils.toWei('10' , 'gwei'))
  }
var tx = new Tx(txObject , {chain:'ropsten', hardfork: 'petersburg'})
tx.sign(privatekey1)
const serializedTransaction = tx.serialize()
const raw = '0x' + serializedTransaction.toString('hex')
 try{
  web3.eth.sendSignedTransaction(raw).on('receipt', console.log)
  catch(error) {
   console.log(error)
}
})

Command prompt outputs:

  C:\Users\HP\Desktop\block chain\js>node broadcastingatransaction
  (node:4308) UnhandledPromiseRejectionWarning: Error: Failed to check for transaction receipt:
  {}
      at Object._fireError (C:\Users\HP\node_modules\web3-utils\src\index.js:57:17)
      at C:\Users\HP\node_modules\web3-core-method\src\index.js:272:27
  (node:4308) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 34)
  (node:4308) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


texts: eth.getCode is returning "0x" at contract's address


texts:
I'm a beginner and I need to sign the data with metamask，Find the document https://learnblockchain.cn/docs/web3js-0.2x/web3.eth.html#sign
then In the browser's debug desk ，i try run
web3.eth.sign('0xB2b63803188fb6efafD83FE67bec878eD4d8940B','data',console.log)

metamask responded to my request，and popped up the prompt
But after I confirm it，No return value
If anyone knows, please help me，thanks


texts: Is there a site to find out all about source code go-ethereum? I want to learn fully about the Ethereum blockchain.I want to learn private blockchain to learn more.


texts: Claymore miner 15.0 crashes on Ubuntu 20.04. Used to work on Ubuntu 16.04 and Claymore 14.7

texts:
Trying to mine with Claymore v15.0 on a Radeon RX 580 GPU on Linux Ubuntu 20.04.
I have recently upgraded Ubuntu from 16.04 to 20.04 and had extreme difficulty installing OpenCL. But once having done that, I am relatively sure that OpenCL is indeed working. I know this because I am CPU mining Monero with xmrig and I turned on the GPU option and it has been mining successfully for several uninterupted days.

I add this because Claymore v15.0 crashes my computer after about 3 minutes. (The xmrig miner is not running while I try Claymore.) I am using the same ethermine account I used while back on Ubuntu 16.04. I updated the same configuration from that era also.

Here is my shell script:

#export GPU_FORCE_64BIT_PTR=0
export GPU_MAX_HEAP_SIZE=100
export GPU_USE_SYNC_OBJECTS=1
export GPU_MAX_ALLOC_PERCENT=100
export GPU_SINGLE_ALLOC_PERCENT=100

./ethdcrminer64 -epool us1.ethermine.org:4444 -ewal 0xc539B4a9727F4Af781B016b18289eAA317f8b322.joe -epsw x -mode 1 -li 5 -lidag 2 -tt 80 -ttli 85 -tstop 90 -tstart 50 -r 180

I tried adding several parameters to control the temperature and trottle the speed. They make no difference and the miner crashes with or without those extra parameters. Below is the CLI session. I killed it so I can copy and paste before my computer crashes. I couldn’t help notice that the total speed is zero. Hashes per second is zero.
I can only think I have misconfigured Claymore 15.0 or OpenCl is not as properly installed as I had thought. Or, my graphics card is bad – but that shouldn’t be as I’ve proved to myself it works while using it with xmrig.
Thanks in advance for thinking with me.

����������������������������������������������������������������ͻ
�                Claymore's Dual GPU Miner - v15.0               �
�              ETH + DCR/SIA/LBC/PASC/BLAKE2S/KECCAK             �
����������������������������������������������������������������ͼ

ETH: 5 pools are specified
Main Ethereum pool is us1.ethermine.org:4444
At least 16 GB of Virtual Memory is required for multi-GPU systems
Make sure you defined GPU_MAX_ALLOC_PERCENT 100
Be careful with overclocking, use default clocks for first tests
Press "s" for current statistics, "0".."9" to turn on/off cards, "r" to reload pools, "e" or "d" to select current pool, "x" to select GPU, "z" to find best -dcri values
OpenCL initializing...

AMD Cards available: 1
GPU #0: Ellesmere (Radeon RX 580 Series), 8000 MB available, 36 compute units (pci bus 65:0:0)
GPU #0 recognized as Radeon RX 480/580
POOL/SOLO version
AMD ADL library not found.
GPU #0: algorithm ASM 1
No NVIDIA CUDA GPUs detected.
Total cards: 1

You can use "+" and "-" keys to achieve best ETH speed, see "FINE TUNING" section in Readme for details.

ETH: Stratum - connecting to 'us1.ethermine.org' <172.65.218.238> port 4444 (unsecure)
ETH: Stratum - Connected (us1.ethermine.org:4444) (unsecure)
ETH: Authorized
ETHEREUM-ONLY MINING MODE ENABLED (-mode 1)
ETH: eth-proxy stratum mode
Watchdog enabled
Remote management (READ-ONLY MODE) is enabled on port 3333

You did not specify -dcri values directly, so they will be detected automatically
Automatic detection of best -dcri values started, please wait...

Setting DAG epoch #341(3.66GB)...
ETH: 06/10/20-20:17:42 - New job from us1.ethermine.org:4444
ETH - Total Speed: 0.000 Mh/s, Total Shares: 0, Rejected: 0, Time: 00:00
ETH: GPU0 0.000 Mh/s
Setting DAG epoch #341 for GPU0
Create GPU buffer for GPU0
ETH: 06/10/20-20:17:46 - New job from us1.ethermine.org:4444
ETH - Total Speed: 0.000 Mh/s, Total Shares: 0, Rejected: 0, Time: 00:00
ETH: GPU0 0.000 Mh/s
ETH: 06/10/20-20:17:48 - New job from us1.ethermine.org:4444
ETH - Total Speed: 0.000 Mh/s, Total Shares: 0, Rejected: 0, Time: 00:00
ETH: GPU0 0.000 Mh/s
ETH: 06/10/20-20:17:48 - New job from us1.ethermine.org:4444
ETH - Total Speed: 0.000 Mh/s, Total Shares: 0, Rejected: 0, Time: 00:00
ETH: GPU0 0.000 Mh/s
Quit signal received...
Quit, please wait...


texts:
If there is a large drop in the US dollar value of ETH over a substantial period, one can assume that people will be deterred from staking ETH because they could lose money (USD) on the stake.

Is there any mechanism in Ethereum proof-of-stake which maintains the incentive to stake under such circumstances?


texts:
My ICO crowdsale contract had

  Contract Warning! Error encountered during contract execution [Reverted]

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

https://etherscan.io/address/0x1b2f1ddb9696bb6869999636121277c271f6f23c#code

Does anyone know what issue and help ?


texts:
I have been having issues since the geth update. Mist first gave me the error that I should install the newest update manually, and when I downloaded it and tried to install it, I was unsuccessful.

I saw somewhere on here that deleting the old geth.exe file from "%APPDATA%\Ethereum Wallet\binaries\Geth\unpacked" and changing it with the new one would solve the problem, but I am even unable to find this path in my system.

Any answer would be helpful. Thanks!


texts: How to create an iterable key->value structure in Solidity?

texts:
I am trying to create a framework for users to offer generic goods for sale. For example, a single generic item (a Gizmo) might have 14 people selling it for different prices and from different parts of the world. To enable this, I need to manage a list of prices, kept in storage, that can be queried by a web3.js-driven frontend.

Something like a mapping would be best:

uint productId;  // Set automatically for each product
uint memberId;  // Set automatically at join
uint price;  // Prices are in US cents

/* (productId => (memberId => price)) */
mapping (uint => mapping (uint => uint)) priceLedgers;

/* Pseudo-JavaScript below */
for (var i=0, i < priceLedgers[productId].length, i++) {
    // List of members with their prices here.
}

Maybe aonther way to explain what I am trying to do is with Python.

priceOffers = {}
priceOffers[1] = 234
priceOffers[45] = 99392
priceOffers[23] = 111

>>> priceOffers
{1: 234, 45: 99392, 23: 111}

>>> for key, value in priceOffers.iteritems():
    print(key, value)
(1, 234)
(45,99392)
(23, 111)

productId = 34
priceLedgers = {}
priceLedgers[34] = priceOffers

Is this possible in Solidity?


texts: Is Raiden network only suited for ERC20 token transfers? Does / will it support other token standards (e.g., ERC223) or simple ETH payments?


texts: Denial attacks by submitting transactions with strategically calculated gas prices

texts:
As can be understood from the title, there is a specific form of denial attack where specific transactions are blocked by submitting transactions with strategically calculated gas prices.

Example 1: Livepeer Token Distribution (MerkleMine)

  looks like a miner(s) is "snatching" txns. You submit proofs to mine
  LPT, and they immediately submit the same ones with higher gas to get
  it confirmed first. While in the end it's impossible to entirely
  prevent this, (whoever get a proof for an account confirmed first gets
  the LPT), will look at what we can do to update the UX of the web
  miner so that it doesn't lead to a bad experience or as much lost gas.

  - Doug Petkanics on the Livepeer Discord Channel

Example 2: FOMO3D Long First Round

  There's quite a bit of interesting fud in which players have decided
  round #1 was "stolen" or "hacked" or that someone "cheated". This is
  laughably false, and the reality of what occurred is actually so
  brilliant that although you already wish you had thought of it
  yourself, you'll wish a bit harder after i explain it.

  A bot did not win Fomo3D Round #1, a manual player did with
  transactions they triggered manually or were directly babysitting.
  They spent about 40-50 eth over the last week penetration testing...
  not the game, but the bots that were playing the game. Why try to
  break the game when you just have to be more clever than the other
  players right?

  They used this to pinpoint a flaw in the way the bots were playing hot
  potato with the timer. Most the bots use various eth gas APIs, which
  report the averages ,or the fast gas prices per block. But don't
  correct very quickly to large gas spikes or individual transactions.
  They figured this out, analyzed it, and formatted a method to trick
  both the "Fast" gas prices and the "standard" gas prices the bots were
  using on the network to lock them out of the final win.

  What occurred was the following: The player purchased about 4,800,000
  Gas for 15 Gwei (About 60% of each block) They then purchased about
  2,700,000 Gas for 190 Gwei (About 35% of each block) Then bought up
  the rest of the gas in the block for 500 Gwei (That last 5% chunk)

  Now, they panicked... a lot, and didn't manage to do this flawlessly.
  But they did manage it in a rough enough manner to make two things
  happen. 1). If you notice, the average gas price across that block was
  not 500 gwei, it was actually much less around 40ish or so, this is
  the price bots were submitting transactions for.  The winner did this
  a couple times, and then started paying very large amounts for all
  three to block out the other transactions. They did not pull this off
  flawlessly, but it did work long enough to trick the bots.

  2). The miners, were picking up the 60% and 35% transactions almost
  automatically because the user was paying a very high price for a
  large amount of gas. This means that the remaining transactions were
  now competing with that last 5%, which actually was a gas price of
  500.

  None of the bots were submitting 500 gwei transactions, because the
  average they were following was much lower,  so none of them beat that
  player. Your "Hack" was really just the bots getting ABSOLUTELY OUT
  FUCKING SKILLED. The same issue won't occur again because the botters
  will now know how they lost and fix it.

  It was quite impressive actually, and you should applaud the player
  that pulled it off. One of the absolutely coolest ways the round could
  have ended was this player manually outplaying the bots themselves.

  - Justo on the FOMO3D/POWH3D Discord Channel

My question is: Is there a specific name for this type of attack?


texts:
I have installed ethereum and geth (1.9). It is running and

  geth --version

the result is:

> Geth
>     Version: 1.9.5-stable
>     Git Commit: a1c09b93871dd3770adffb177086abda1b2ff3af
>     Git Commit Date: 20190920
>     Architecture: amd64
>     Protocol Versions: [63]
>     Network Id: 1
>     Go Version: go1.13
>     Operating System: darwin
>     GOPATH=
>     GOROOT=/Users/travis/.gimme/versions/go1.13.darwin.amd64

I also see the size of the chaindata growing (under ~/Library/Ethereum).

However, opening a console (by geth attach) and asking:

> eth.accounts

i'm getting: []

Is there a way the extract data from the mainnet like accounts, blocks, transactions etc. directly by using geth (no 3rd party tools)?


texts: message: 'invalid argument 0: json: cannot unmarshal hex string without 0x prefix into Go struct field SendTxArgs.value of type *hexutil.Big'

texts:
I am using a JSON RPC request and source code is as follows:
var options ={
    url: "http://127.0.0.1:8545",
    method: "POST",
    headers: {"Content-Type":"application/json"}
};
var tx = {from: req.body.fromaddress,  to: req.body.toaddress,  value: web3.utils.toWei(req.body.amount, "ether")};
    options.body = JSON.stringify({"jsonrpc":"2.0", "method":"personal_sendTransaction", "params":[tx, req.body.password], "id":"curltest"});
    callback = (err, response, body) => {
        if (!err && response.statusCode == 200) {
            const data = JSON.parse(body);
            console.log(data);
            res.send(data);
        }
        if (err) {
            console.error(err);
            res.send(err);
        }
    };
    request(options, callback);


texts: MetaMask: how can I access the web3 object locally and use my own node?

texts:
I am new to Ethereum and was looking for a way to run my dApp in Chrome instead of Mist.

I encountered Metamask, which would in theory fit my needs perfectly. However, from a basic web point of view, it looks like Metamask is a proxy to an Ethereum node and web3 APIs, meaning all my blockchain dApp data would go through them.

Is Metamask working this way ?
If yes, how could I use Chrome to develop my dApp, or rather how can I access the web3 object locally ? (I'm already running a json-rpc node)

My concern here is security and not relying on third parties.


texts:
I'm currently working with Ethereum and smart contracts. I see that a contract can define events and emit them. Each event defines no target, so I assume it will be broadcast. But I wonder how to listen to these events from a nodejs server or web client. Do I have to poll Ethereum nodes continuously for determining if my event is dispatched or not. Is there any way to dispatch event directly to a target (like web callback or web hooks)?

Thank you!


texts: Truffle fails to migrate an Oraclize contract into Ganache

texts:
I have a contract that is using Oraclize.

When deploying the contract from the Remix IDE into Ganache/Ethereum-bridge via MetaMask, the contract is fully functional. However, when trying to migrate the contract from Truffle into Ganache/Ethereum-bridge, I am getting the following error:

Running migration: 2_deploy_contracts.js
  Deploying ContractOne...
  ... (TX_ADDRESS)
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: The contract code couldn't be stored, please check your gas amount.

Note, TX_ADDRESS is the transaction address I masked here.

My 2_deploy_contracts.js file:

var ContractOne = artifacts.require("./ContractOne.sol");
module.exports = function(deployer) {
  deployer.deploy(ContractOne, "FROM ADDRESS");
};

truffle.js file:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*", // Match any network id,
      gas: 4700000,
      gasPrice: 40
    }
  }
};

Tried changing the gas amount, adding the gas amount into the deployer - nothing works. At this moment, I suspect the issue is in Oraclize contract using abstract functions, though I'm not sure. What could be the source of this error?

UPD: It seems that the issue is in __callback() function of Oraclize, though I don't know how to fix it.


texts: How to start writing a smart contract in eWASM?

texts:
There are many tools and repositories under https://github.com/ewasm

What are the main steps to writing a smart contract in eWASM?  What are the main components involved?


texts: Cannot catch every event (logs) from contract - catch a couple of random events instead

texts:
My contract has a transaction which fires an event. I was able to catch every event when I was sending transactions manually.

But now I'm sending 100 transactions in cycle and get only 2..5 events. Yes, randomly - which puzzles me the most. I get a random quantity of events and random last event caught every time I run my code. Please see the console output below.

Tried to add a pause between transactions. The longer the pause the more events are caught. This puzzles me too - don't understand why this matters for events.

My .sol contract

contract Example {

    uint32 public value;

    event ValueSet(uint);

    function setValue(uint32 val) {
        value = val;
        ValueSet(val);
    }

}

My python code (sorry for the long code - was afraid to mess it up shortening)

class MyContract:

    address = ""
    filter = ""

    def __init__(self):
        self.c = EthJsonRpc('127.0.0.1', 8545)

    def deploy(self):

        # get contract address
        compiled = '6060604052610.....' # shortening it here.
        contract_tx = self.c.create_contract(self.c.eth_coinbase(), compiled, gas=3000000)
        self.address = self.c.get_contract_address(contract_tx)

        # set new filter
        params = {
            "fromBlock": "0x01",
            "address": self.address
        }
        self.filter = str(self.new_filter(params))

    def send_transaction(self, foo, value):
        tx = self.c.call_with_transaction(self.c.eth_coinbase(), self.address, foo, value)
        return tx

    def new_filter(self, params):
        return self.c.eth_newFilter(params)

    def listen(self):
        return self.c.eth_getFilterLogs(self.filter)

def main():
    my_contract = MyContract()
    my_contract.deploy()

    #sending transactions which trigger events
    for i in range(100):
        my_contract.send_transaction('setValue(uint32)', [i])
        time.sleep(1) # the more time the more events are caught

    # retrieve all logs from the filter
    logs = my_contract.listen()

    print repr(logs)
    print "Quantity of events: " + str(len(logs))
    if logs:
        print "Data: " + str(int(logs[-1]['data'], 16))

Console output

[
   {
      u'type':u'mined',
      u'blockHash':u'0xac739ae0feac68eae0cddb5216ef64c7931821cf26db327c85bd3da16f947f44',
      u'transactionHash':u'0x4d2465e9b978a275cca63fb9129a5da8f7a9dcc9b2c6e8b717ecf734be7ab950',
      u'data':u'0x0000000000000000000000000000000000000000000000000000000000000026',
      u'topics':[
         u'0x012c78e2b84325878b1bd9d250d772cfe5bda7722d795f45036fa5e1e6e303fc'
      ],
      u'blockNumber':u'0x0223',
      u'address':u'0x9062a6b9299af4bdb535a5ecdbfeb8a28e6cf4c1',
      u'logIndex':u'0x00',
      u'transactionIndex':u'0x0'
   },
   {
      u'type':u'mined',
      u'blockHash':u'0x1014603151080201cc26990c6b4f1dd01a5b65545b19a570a01c9ad11532c7f2',
      u'transactionHash':u'0xe79af54c765368e73e3c9ca996de667e43363e92856ca234459633fda86c77ca',
      u'data':u'0x000000000000000000000000000000000000000000000000000000000000005f',
      u'topics':[
         u'0x012c78e2b84325878b1bd9d250d772cfe5bda7722d795f45036fa5e1e6e303fc'
      ],
      u'blockNumber':u'0x025c',
      u'address':u'0x9062a6b9299af4bdb535a5ecdbfeb8a28e6cf4c1',
      u'logIndex':u'0x00',
      u'transactionIndex':u'0x0'
   }
]
Quantity of events: 2
Data: 95

Related

How to list transactions from account address?

How can I create a listener for new transaction with Ethereum RPC calls?

Creating eth_newFilter topic listeners with Python

Why asking

I'm trying to write a code which will save contract event to a database in "live" mode (catch new events) and in "retrospective" mode (retrieve all contract events). And just want to understand how events work.

I'm using ethjsonrpc with testrpc (Ethereumjs).

Thank you very much!


texts: How do I use web3js 1.0.0 in geth 1.9.0? I want to import an account whose address, private key and passphrase I have in my geth node

texts:
I am at Geth/v1.9.0-stable-52f24617/linux-amd64/go1.11.5

web3JS version is giving :

> web3.version
{
  api: "0.20.1",
  ethereum: "0x2712",
  network: "4",
  node: "Geth/v1.9.0-stable-52f24617/linux-amd64/go1.11.5",
  whisper: undefined,
  getEthereum: function(callback),
  getNetwork: function(callback),
  getNode: function(callback),
  getWhisper: function(callback)
}

I have an account address, private key and passphrase and now want to import it into in my geth account.
One way I got is using

**web3.eth.accounts.wallet.add()**

but, this is not working with the current version I have, it is giving me
    undefined


texts: Why aren't the peer-to-peer connections transitive?

texts:
In a private blockchain network, if there are three nodes - A, B, and C

A is connected to B

B is connected to C

But, why is A not connected to C?

Wouldn't that make the connections and ultimately the network more reliable?


texts: Go Ethereum - get the enode before starting geth

texts: I need to get the enode of my geth nodes before I start them up.. is there any way to do this via a command other than actually starting up the node ?


texts: Changelly: confirmation of BTC/ETC transaction although ETC never arrived

texts: Recently, I used Changelly to exchange BTC for ETC. Inadvertently, I made a mistake typing in the address of my ETC wallet (a 3 instead of a 2). Changelly informed me that the 'transaction is complete', nevertheless, I have no ETC in my wallet. What can I do? Thanks in advance.


texts:
I'm pretty new to the BC and specifically Ethereum world and I'm just starting to scratch the surface of the potential applications of this powerful technology.
As I'm approaching to build my first project ever I'd like to create a simple dApp to validate data on the db of a web platform.
Basically this dApp would have two functions:

The first posts the SHA-256 hash of a data on the BC;
The second retrieves a specific hash stored on the BC and validates it against the one stored in the db  to check if it has been altered or not.

Obviously the amount of hashes would start from one and scale continuously over time as new data are entered on the db.
What would be the best way to achieve my goals? Would a Distributed Hash Table be the right fit? And lastly what would be the transaction costs of this solution?
Thanks in advance for helping me.
Looking forward to your advice.


texts:
I have setup 3 rig's With GPU mining and I'm currently averaging around 25 - 30  MH/s with my test setup. The rig is setup using QTminer and I can see that ETH is coming in to my account and I have tried to do a transfer of 0.2 ETH from ethermine that was successfull as I see the amount in my balance.  (https://www.etherchain.org/account/0x9003c372d2e1b1e8b4d27ecf415bf70c9739bfce)

Now, here is the question.
When I use geth or the "etherium wallet" I get a Balance of 0.
When I I og to the etherchain (or any other) i get the correct Balance.
As far as i can see the wallet and Geth is synced.

can anyone help me out here with some tips on how to fix this, and how to transfer funds to my wallet after I this is fixed.

Geth info:
Version: 1.4.10-stable
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.6.2
OS: windows
GOPATH=
GOROOT=c:\go

Etherium wallet is Version 0.8.1


texts: How to transferFrom an external erc20 token with IERC20?

texts:
Currently, I try to send Wrapped ETH from my account to a contract address by using IERC20. But it returned an error on Remix. By the way, I could call token.balanceOf(msg.sender) but can't execute token.transferFrom(msg.sender, address(this), amount) somehow.
My code is below
pragma solidity ^0.6.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0/contracts/token/ERC20/IERC20.sol";

contract Test2 {

        IERC20 public token;

        constructor(address _token) public {
        token = IERC20(_token);
        }

        function getBalance() public view returns(uint) {
            uint balance_ = token.balanceOf(msg.sender);
            return balance_;
        }

        function deposit(uint amount) public {
            require(amount <= token.balanceOf(msg.sender), "you don't have enough balance.");
            token.transferFrom(msg.sender, address(this), amount);
        }

}

And ERC20 token I want to send is Wrapped ETH. So I copied the WETH contract and deployed on Remix before I deployed this contract. And when I deploy the above contract I add deployed
WETH contract address as an argument of the constructor.
The error message is always like below on Javascript VM on Remix IDE. But this error message doesn't tell what the real problem is. making my contract payable doesn't make sense and I checked that the balance I own is always more than I want to send.
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.
WETH contract is here but actually which erc20 I use doesn't matter because I tried the same thing with other deployed ERC20 tokens and even external LINK contract on the Ropsten net (https://ropsten.etherscan.io/address/0x20fe562d797a42dcb3399062ae9546cd06f63280)

contract WETH9 {
    string public name     = "Wrapped Ether";
    string public symbol   = "WETH";
    uint8  public decimals = 18;

    event  Approval(address indexed src, address indexed guy, uint wad);
    event  Transfer(address indexed src, address indexed dst, uint wad);
    event  Deposit(address indexed dst, uint wad);
    event  Withdrawal(address indexed src, uint wad);

    mapping (address => uint)                       public  balanceOf;
    mapping (address => mapping (address => uint))  public  allowance;

    function() public payable {
        deposit();
    }
    function deposit() public payable {
        balanceOf[msg.sender] += msg.value;
        Deposit(msg.sender, msg.value);
    }
    function withdraw(uint wad) public {
        require(balanceOf[msg.sender] >= wad);
        balanceOf[msg.sender] -= wad;
        msg.sender.transfer(wad);
        Withdrawal(msg.sender, wad);
    }

    function totalSupply() public view returns (uint) {
        return this.balance;
    }

    function approve(address guy, uint wad) public returns (bool) {
        allowance[msg.sender][guy] = wad;
        Approval(msg.sender, guy, wad);
        return true;
    }

    function transfer(address dst, uint wad) public returns (bool) {
        return transferFrom(msg.sender, dst, wad);
    }

    function transferFrom(address src, address dst, uint wad)
        public
        returns (bool)
    {
        require(balanceOf[src] >= wad);

        if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
            require(allowance[src][msg.sender] >= wad);
            allowance[src][msg.sender] -= wad;
        }

        balanceOf[src] -= wad;
        balanceOf[dst] += wad;

        Transfer(src, dst, wad);

        return true;
    }
}

Please help me if you know what the problem is! thanks!


texts: Working with structs in Solidity and web3js

texts:
I'm trying to interact with this contract via web3.js.

Something like this answer seems to be the right path to take, but I can't figure out how to implement that logic in my contract.

When getAdopters() is called, I see the following error in my browser's console:

invalid solidity type!: tuple[16]

Here's the code where getAdopters() is called:

  markAdopted: function(owners, account) {
    var adoptionInstance;

    App.contracts.Adoption.deployed().then(function(instance) {
      adoptionInstance = instance;

      return adoptionInstance.getAdopters.call();

    }).then(function(owners) {
      for (i = 0; i < owners.length; i++) {
        if (owners[i] !== '0x0000000000000000000000000000000000000000') {
            $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
            var loc = document.getElementById('owned-by');
            loc.innerHTML += owners[i];
            console.log(valueOf(owners[0]));

        }
      }
    }).catch(function(err) {
      console.log(err.message);
    });
  },

Ultimately, how can I return the fields of the struct as separate return variables, and then access them using web3.js?


texts: Is it possible to create an "engine" in ethereum/solidity?

texts: I would like to create a lottery. For that I would need to have a repeating payout event every 1h or 24h -> is this even possible with Solidity/Ethereum?


texts: How to retrieve transactions' info such as gaslimit and gasprice from Etherscan?

texts:
This link shows the latest 500k transactions, and by clicking each one it opens a page with its info including gaslimit, gasprice, usedgas etc.

https://etherscan.io/txs

How can i retrieve the information for all the 500k in an automatic way, because it is tedious and not practical to do so manually.


texts:
I would like to generate raw transactions in golang without any go binding and I'm wondering if there is library to dynamically encode my argument parameter using go?

https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

Using this resource it look like it would be a huge amount of work to dynamically encode each param manually for every type of data available.

Is there a way to do this?

Again I'm not looking for Ethereum Go bindings since i need to return the raw unsigned transaction data.


texts: is it possible to start a private chain from a specific height?

texts:
I am running a private chain with a height of 4,80,000. Now I want to change the reward rules and other configurations.

If I build geth with new parameters, the new executable will not recognize the old datadir and chain starts with eth.blockNumber = 0;

So for this,I want to start from blockNumber 4,80,001, i.e. don't want to lose the blockheight. (however, I have planned to find balances of all the accounts on the nodes and start with pre-allocated amount to those balances).

Is it possible?
Can I start from a specific height?


texts: If we reinitialize ethereum blockchain (running using geth) will we loose all the data?

texts:
I am running private blockchain using geth and my miners has stopped mining the data. A few days back I have removed old files from .ethash folder ... I am just wondering if that could be the reason that my miners are not working anymore.
Also, somewhere I read that I can remove .ethash folder completetly and the restart the blockchain but my concern is if I will restart the chain then will I loose existing data of chain?
Am I right and is there anything I can do?


texts: How to transfer ETH between 2 ETH addresses using GETH (without keystore/JSON file)

texts:
I have 2 ETH addresses (P and N) and a ETH Node (synchronized and running 24h with GETH client).
I do not have ETH on the node address (address N)
I do have ETH on my address P.
Need transfer from address P into address N using private key of address P.
I want to use my Terminal command line on my machine running GETH to transfer ETH from address P to address N.
How to do it?

P.S. without using MIST or MyEtherWallet


texts: Solidity and JavaScript merkle tree verification does not work

texts:
The problem is that the calculated rootMerkle in solidity doesn't match the one in javascript and i can't figure out why.

My javascript code is the next. It can be seen that it verifies good here.

const MerkleTree = require('merkletreejs')
const keccak256 = require('keccak256')

const buf2hex = x => '0x'+x.toString('hex')

const leaves = ['0x00000a86986e8ba3557992df02883e4a646e8f25 50000000000000000000', '0x00009c99bffc538de01866f74cfec4819dc467f3 75000000000000000000', '0x00035a5f2c595c3bb53aae4528038dd7a85641c3 50000000000000000000', '0x1e27c325ba246f581a6dcaa912a8e80163454c75 10000000000000000000'].map(x => keccak256(x)).sort(Buffer.compare)
const tree = new MerkleTree(leaves, keccak256)
const root = tree.getRoot()
const hexroot = buf2hex(root)
const leaf = keccak256('0x1e27c325ba246f581a6dcaa912a8e80163454c75 10000000000000000000')
const hexleaf = buf2hex(keccak256('0x1e27c325ba246f581a6dcaa912a8e80163454c75 10000000000000000000'))
const proof = tree.getProof(keccak256('0x1e27c325ba246f581a6dcaa912a8e80163454c75 10000000000000000000'))
const hexproof = tree.getProof(keccak256('0x1e27c325ba246f581a6dcaa912a8e80163454c75 10000000000000000000')).map(x => b$
console.log(hexroot)
console.log(hexleaf)
console.log(hexproof)

const verified = tree.verify(proof, leaf, root)
console.log(verified)

and the console output

0x0c8879b51283eb6a63e3ab339ae7771cdf410721556a300c0bb3a444aa2f8da5
0xdbd6fa463060a653969989f334f15d9f98575e52c3deeadac6d6abc269ae37a4
[ '0xec80acebb7b19acb852d258701fab8084200f069fca87127db146d694018a3a2',
'0xc25c23aa0f6518c0a443affc45a63232b544e8a070ccdf2f2947f28688027f25' ]
true

The part of the solidity code verifying the merkle tree is the next:

function checkProof(bytes32[] proof, bytes32 hash) view internal returns (bool) {
    bytes32 el;
    bytes32 h = hash;

    for (uint i = 0; i <= proof.length - 1; i += 1) {
        el = proof[i];

        if (h < el) {
            h = keccak256(h, el);
        } else {
            h = keccak256(el, h);
        }
    }

    return h == merkleRoot;
}

The problem is that h (the calculated root with proof and leaf) and merkleRoot (supplied root) does not match. Can you see where is the problem? Thank you very much.


texts: How can I export/show private key on parity cli?

texts:
I did this command on parity

parity --chain mainnet account new

I got the address but,
How can I export or see the private key?


texts:
In Casper will miners still be required to power the EVM and execute contracts?
Will miners still receive rewards from gas but not rewards from transaction verification?
Will EVM contract execution still use the GPU or will it use the CPU now?


texts: How would Ethereum payment channels solve transaction rate limitations in real life scenarios?

texts:
The context is that I am looking into a business plan to implement ERC20-token based payment at standard merchant terminals, plus corollary services including loyalty, and looking at transaction throughput.

Apparently VISA can process tens of thousands of transactions per second whereas Ethereum is limited to the tens, as long as Proof-of-Work is being used, and assuming we are talking about the core network only not Raiden etc. (Would love to hear challenges to this premise).

Looking at payment channels as a way of increasing throughput, I am trying to understand how in real life scenarios these help much.

So for example:
Day 1: Cardholder receives a physical card associated with an ERC20 balance of say $100 (1:1 tokens for example). This amount is held in escrow for the payment channel. For the sake of this example, the payment channel is with a single merchant, not an aggregating provider or merchant  network.

Day 2: Cardholder goes to merchant and buys some shopping. This event is not likely to happen at a rate higher than say once per day on average. The payment channel is updated offchain with signed messages (details reserved)

Day 3: Cardholder repeats, shopping...

Day N: The card balance is used or the cardholder wishes to top up the balance, closing the payment channel. The Ethereum blockchain is updated with the net balance.

So, in this kind of scenario, in order to get only 20 or 30 times the throughput, the payment channel has to be open for one month. There would be a number of challenges with how to batch the payment channel closures, as a merchant (eg: Walmart) with say one million cardholders could result in delays closing and reopening channels.

Browsing the net, I may have seen claims of greatly increased throughput via Raiden/Lightning network for point of sale processing, but I am at a bit of a loss as to how this could work in practice.  The way I see it, is that a payment channel, like a side-chain, is in general a way of batching transactions so that the Ethereum blockchain can a) act as a settlement engine b) process a smaller number of transactions.


texts: Can I add a modifier in a function inheriting from the interface?

texts:
Let's consider this situation:

interface ITest
{
    function check()
        external;
}

contract Test is ITest
{
    address private admin;

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

    modifier onlyAdmin
    {
        assert(msg.sender == admin);
        _;
    }

    function check()
        external onlyAdmin
    {
        // work only with admin
    }
}

contract OtherTest
{
    ITest private test;

    constructor(
        address testAddress
    )
        public
    {
        test = ITest(testAddress);
        test.check();
    }
}

It doesn't give any error. Is this safe and is it working as expected? Will this function work only for admin? Interestingly, it seems to work on VM.


texts: I am trying to build a distributed application using pyethapp.But I am facing difficulty in setting up pyethapp.


texts: I want a list of coin holders for a coin

texts:
I am looking for a command in Solidity (or other API) that allows me to see the wallets with balances in excess of x coins.

Anyone know how do do this?

Thanks


texts: How to store token number with their holders?

texts:
I am actually looking towards cost reasonable design idea where I can know that which token number belongs to which wallet address. let's say addressA bought first five tokens, so token no 1,2,3,4,5 belongs to wallet addressA and so on.

If some one come and ask to which token holder does token no 3 belongs then in gas cost effective way, it can tell addressA.

Is this possible? I am open to discussions, ideas, or if someone have already done this?

Feel free to share your thoughts.

I have tried this code snippet:

pragma solidity 0.5.12;
contract A{
    struct Info {
        uint index;
        address owner;
    }

    Info[] public list;

    mapping(address => uint) public balanceOf;
    uint totalSupply;

    function buy(uint amount) public {
        totalSupply += amount;
        balanceOf[msg.sender] += amount;
        list.push(Info(totalSupply, msg.sender));

    }

    function call(uint index) public view returns (address){
        return getOwnerOfToken(index);

    }

    function getOwnerOfToken(uint index) public view returns(address) {
        uint256 lo = 0;
        uint256 hi = list.length;

        while (lo + 1 < hi) {
            uint256 mid = (lo + hi) / 2;
            if (list[mid].index >= index)
                lo = mid;
            else
                hi = mid;
        }

        if (list[hi].index >= index)
            return list[hi].owner;
        if (list[lo].index >= index)
            return list[lo].owner;

        revert("not found");
    }
}

It is currently working ok when getOwnerOfToken() is directly called but fails when call() is called, my need is to call a function which shall inside call this getOwnerOfToken().


texts: Best way to deploy a ERC20Token to the mainnet

texts:
I'm planning on deploy a ERC20 Token Contract to eh Main-net. I've tested it on both Rinkeby and Ropsten, deploying from different platforms. Parity,Ethereum Wallet, Remix with metamask. I wanted to ask based on previous experience, what platform/mean do you guys recommend to deploy the token.

Thank you!


texts:
I am currently analyzing ethereum data from google big query and and some transactions are dated as being from 1970-01-01. I assume that has to do with how date is stored since it is in seconds from 1970. Was wondering if anyone has come across this?

Currently work around would be to replace to when ETH was launched. However, there are a number of these transactions so not sure this is the best way to deal with the issue.


texts:
pragma solidity ^0.4.17;

contract Transport {
   address public manager;
   Car[] public carArray;
   Bike[] public bikeArray;

   struct Car {
      uint carId;
      address carOwner;
   }

   struct Bike {
      uint bikeId;
      address bikeOwner;
   }

   function Transport(address creator) public {
        manager = creator;
   }

   function carCreate(uint carId, address carOwner) public {

        Car memory newCar = Car ({
            carId: carId,
            carOwner: carOwner
        });

        //push this number into array
        carArray.push(newCar);
   }

   function bikeCreate(uint bikeId, address bikeOwner) public {

        Bike memory newBike = Bike ({
            bikeId: bikeId,
            bikeOwner: bikeOwner
        });

        //push this number into array
        bikeArray.push(newBike);
   }

   function createNewBatch(uint batchId, uint carId, uint bikeId) public {

        // check the existence of carId and bikeId before proceeding
        // require(carArray.carId.exists);
        // require(bikeArray.bikeId.exists);
        ...
        ...
   }
}

I am trying to write a contract of supply chain of transport, where cars and bikes are created and are required to be put in batches before being transported.

I got stuck in createNewBatch function since before putting everything into one batch (to be shipped later), I want to check whether the inputed carId and bikeId actually exist.

My logic is that I have to go back to the array of all the cars and bikes and check whether the supplied carId and bikeId matches any carId and bikeId in carArray and bikeArray. However, it does not work in terms of code. Would appreciate your help


texts: Changing current address to another address

texts:
I'm writing in Solidity using testrpc and truffle.

I wish to test my functions by altering my current address imitate other addresses.

This is what I have tried so far:

function getCurrAddress() constant returns(address currAddr){
    currAddr = msg.sender;
    return currAddr;
}

var accounts = web3.eth.accounts
contract.getCurrAddress() results in  = '0x53a1962e8844b2c9f1eed6e85e4d2026126ade0e'

web3.eth.defaultAccount = accounts[1]
      == '0xab6fa1d299e3b7d67fffd0829341534684d46560'

contract.getCurrAddress() results in  = '0x53a1962e8844b2c9f1eed6e85e4d2026126ade0e'

Is there a way I can change my current address as defaultAccount doesn't seem to be doing the job?


texts: How does it the geth ethereum platform to automatically connect to the nodes that are in the main network of Ethereum?

texts: I have tried to make connection between several nodes in my private network, but I do it with a enode direction, but Ethereum network does it without knowing my enode, I want to know what kind of p2p communication protocols used, so that all nodes are communicate with each other, and if that code is free.


texts: Does Geth have more transaction signers than EIP155Signer, FrontierSigner, and HomesteadSigner?

texts:
I'm trying to write code (in Scala) to verify transactions on the main net and I've go it to where it works on about 50% of transactions.  The steps I'm following are:

Download the transaction using the JSON RPC
RLP encode it using both EIP155Signer and FrontierSigner and hash it
Recover the public keys using both hashes, giving four possible Ethereum addresses
See if one of the four possible addresses matches the sender

I'm confident that the RLP encoding is correct because I've compared the results against the Geth RLP encoding functions for a lot of test cases.  I also saw that there's a HomesteadSigner in the Geth code, but it looks like it just inherits its hashing method from FrontierSigner.

func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
    return rlpHash([]interface{}{
        tx.data.AccountNonce,
        tx.data.Price,
        tx.data.GasLimit,
        tx.data.Recipient,
        tx.data.Amount,
        tx.data.Payload,
        s.chainId, uint(0), uint(0),
    })
}
func (fs FrontierSigner) Hash(tx *Transaction) common.Hash {
    return rlpHash([]interface{}{
        tx.data.AccountNonce,
        tx.data.Price,
        tx.data.GasLimit,
        tx.data.Recipient,
        tx.data.Amount,
        tx.data.Payload,
    })
}

I have a few questions related to this.  Is there another type of signer that I'm missing?  For EIP155Signer, I've been always using 1 for the chainId.  Are there cases on the main net where it can be something other than 1?  Is there something else I'm missing completely?  I know I'm on the right track because it successfully verifies about 50% of the transactions I've been testing it on, which is of course a whole lot better than random chance.  Thanks!


texts: Invalid genesis file:cannot unmarshal number into Go struct field Genesis.alloc of type *math.HexOrDecimal256

texts:
Here is my genesis.json file

{
    "config": {
    "chainId": 15,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
    },
    "gasLimit": "21000000",
    "difficulty": "20000",
    "alloc": {
      "6e8f98fa53bbb9ab8dad40af34b767172206099f":{"balance":500000000}
     }
}

But I got the following error while init command in the genesis file

  Fatal: invalid genesis file: json: cannot unmarshal number into Go
  struct field Genesis.alloc of type *math.HexOrDecimal256


texts: how to switch a bytes32 number to an integer

texts: I use the sha256 function in my contract, the result of this hash function is a bytes32 number so that many functions can not fit, I wonder how to transfer the bytes32 number to a corresponding integer?


texts: Truffle Migrate doesn't work: Error: No network specified. Cannot determine current network

texts:
When I try to run my migration with truffle migrate the following error message appears:

Error: No network specified. Cannot determine current network.
    at Object.detect (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43157:23)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:200497:19
    at finished (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:43085:9)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:198408:14
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:68162:7
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:163793:9
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:160353:16
    at replenish (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:160873:25)
    at iterateeCallback (/usr/local/lib/node_modules/truffle/build/cli.bundled.js:160863:17)
    at /usr/local/lib/node_modules/truffle/build/cli.bundled.js:160838:16

This is on an OSX machine and I am using truffle version 4.0.0, solidity version 0.4.18. TestRPC v4.1.3 is running in the background.


texts: Accessing custom JavaScript functions via RPC API on Geth

texts:
Geth allows me to define & load my own custom JavaScript functions with --preload flag or require() on Geth console.

But is there way to access my functions via RPC interface?

Like :

curl -H "Content-Type: application/json" \
--data '{"jsonrpc":"2.0","method":"mycustom_function()","params":[],"id":123}'

I've seen i can open access to more management APIs with --rpcapi eth,web3,admin,eth,miner but it doesnt work for my custom functions.


texts: Problem with log filters in java (web3j). Maybe proble with geth parameters?

texts:
I'm having trouble trying to create a simple contract that "just log" to the blockchain what is being sent from a java client. The transaction executing the log looks to be correct (how can I be sure about it?) but I find no way to retrieve the logs from the java client:

The smart-contract looks similar to:

pragma solidity ^0.4.2;

contract MyLogContract {
    event genericLog(
        uint256 indexed _index1, uint256 indexed _index2,  uint256 indexed _index3, string _log);

    function writeGenericLog01(
        uint256 _index1, uint256 _index2,  uint256 _index3,
        string _log)
    returns (bool success) {
        genericLog(_index1, _index2, _index3, _log);
        return true;
    }
}

The java code looks similar to (userWrapper4Logs => use java wrapper, otherwise use hand-made transaction):

TransactionReceipt receipt;
if (!userWrapper4Logs){
     String encodedFunction = FunctionEncoder.encode(
         new Function("writeGenericLog01",
             Arrays.asList(Uint256.DEFAULT,
                 Uint256.DEFAULT, Uint256.DEFAULT,
                 new Utf8String("Best log in Town!")) ,
              Arrays.asList(new TypeReference<Uint256>() {} )
          )
     );
     String from = ownerAddress;
     BigInteger gasPrice = BigInteger.valueOf(1),
                gasLimit = BigInteger.valueOf(1000000L);
                nonce = null; // <- Ummm?
     String to = bc.listenerAPI_contractAddress;
     Transaction transaction = Transaction.
         createFunctionCallTransaction(
             from, nonce, gasPrice, gasLimit, to, encodedFunction);

     Optional<TransactionReceipt> transactionResponse =
          auxExecuteTransaction(transaction);

     receipt =  transactionResponse.get();
}
if (userWrapper4Logs) {
    MyLogContract wrapper = getContract(contractAddress, owner);
    receipt =  wrapper.writeGenericLog01(
             Uint256.DEFAULT,
             Uint256.DEFAULT,
             Uint256.DEFAULT,
             new Utf8String("Best log in the wild wild West!")
         ).get();

}
System.out.println( ""
       + "\n BlockNumber()        : " + receipt.getBlockNumber()
       + "\n Cumulativ eGasUsed() : " + receipt.getCumulativeGasUsed()
       + "\n Log size             : " + receipt.getLogs().size() );

The transaction looks to execute properly and after mining 5 blocks the receipt is returned. Nothingness the log size is always zero. The STDOUT output looks similar to:

BlockNumber()        : 2528
Cumulativ eGasUsed() : 22872
Log size             : 0

I have some doubts about whether testrpc is able to handle log transactions or maybe they are just discarded by this sort of javascript node simulator, so I also tested with a real geth using next parameters (maybe something else is also needed):

$ geth --verbosity 4 --dev --maxpeers 0 --nodiscover --rpc --rpcaddr 0.0.0.0 --networkid 1500 --mine --fakepow --minerthreads=1 --etherbase=0x......

(I also tried without the --dev option but then transaction looks to be never confirmed).

Thanks in advance for any help/hint or link!

Update 201-05-09: I tested the same contract with Truffle/web3js and logs are detected properly by the client, even using testrpc (only restricted to setup the event listener before submitting the transaction).


texts: Can I control the time for confirmation?

texts: I will use ethereum as private blockchain. Then I'd like to change the confirmation time from 15 seconds to 1 second. Can I change it?  Could you tell me if you know that?


texts: How much time does it take to withdraw from Optimistic Rollup?

texts:
I am reading An Incomplete Guide to Rollups and Vitalik says the withdraw time of Optimistic Rollup takes

~1 week (withdrawals need to be delayed to give time for someone to
publish a fraud proof and cancel the withdrawal if it is fraudulent)

My questions:

I assume withdraw means any withdraws between eth addresses. Correct? Any exceptions? If I want to withdraw from an app deployed on the l2 and deposit to uniswap(on the l2), does it take 1 week?
What about deposits? I assume they are the same as withdraw. Correct?


texts: While importing web3.py getting following error: TypeError: 'ellipsis' object is not iterable

texts:
Python version : 3.5.2.
web3 version : 4.9.2.
Ubuntu : 16.04.
Also tried previous version of web3: 4.0.0


texts: Why using assert, since it would consume all gas

texts:
Since assert would consume all gas and require would return all gas,
Is there any reason to use assert not require? Use require to refund gas seems always a better choice than consuming them?

I saw some explanation in Difference between require and assert and the difference between revert and throw
but I still don't get it, why choosing a command that consuming all gas, any benefit?


texts:
How can I get the current time in Solidity. I don't need the current block's time given by now and block.timestamp, but rather the actual current time.

Thank you for your help!


texts: How does the network / EVM handle same contract call within same block with same gas?

texts:
As an example take the following test contract:

pragma solidity ^0.4.24;

contract DoubleCall {
    address public superHero;
    uint256 public price = 1 ether;

    function becomeSuperHero() public payable{
        require(msg.value >= price);
        superHero = msg.sender;
        price = price * 2;
    }
}

What will superHero be if two accounts send a transaction calling the contract's becomeSuperHero() - both sending 1Eth and the same amount of gas. Both transactions should be included within the same block.

What is the outcome?


texts: What is the accepted methodology for verifying the integrity of pulled chain data?

texts:
What is the accepted methodology of checking the integrity of a chain?

If I poll my Geth/Parity node for block data using web3.js how can I confirm that the data returned is not going to be subject to a later reorganisation?

Is it simply a case of implementing some self-checking. I.E. fetching the block data again x hours in the future, and confirming the hashes etc match. If so, what are considered 'safe' parameters for stating that a block is definitely part of the chain?

Tools such as block explorers need to be fetching new data 'as close to as it happens' as possible so that they can present useful and insightful data, yet it is completely plausible that the data at the head of the chain could change.

Thanks


texts: How to check uncle block when listening to new block?

texts:
I was reading the fantastic https://goethereumbook.org book and found this example to listen to new blocks from Ethereum.

Could I ask in this case, how is uncle blocks handled? To put it in another way, how do I be certain that the new block I get here is not an uncle block?

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("wss://ropsten.infura.io/ws")
    if err != nil {
        log.Fatal(err)
    }

    headers := make(chan *types.Header)
    sub, err := client.SubscribeNewHead(context.Background(), headers)
    if err != nil {
        log.Fatal(err)
    }

    for {
        select {
        case err := <-sub.Err():
            log.Fatal(err)
        case header := <-headers:
            fmt.Println(header.Hash().Hex()) // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f

            block, err := client.BlockByHash(context.Background(), header.Hash())
            if err != nil {
                log.Fatal(err)
            }

            fmt.Println(block.Hash().Hex())        // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f
            fmt.Println(block.Number().Uint64())   // 3477413
            fmt.Println(block.Time().Uint64())     // 1529525947
            fmt.Println(block.Nonce())             // 130524141876765836
            fmt.Println(len(block.Transactions())) // 7
        }
    }
}


texts: Is Ethereum blockchain really temper proof or immutable?

texts:
Suppose there is a user A which transfers some ethers to user B through a proper transaction.
So is it possible to alter the transaction. Something like going back to the block which contains the transaction and creating another chain with a new transaction in which ethers are not sent to User B. So, will the second transaction override the first one.
In short, I want to know what will happen to both of the transaction and how the blockchain will discard one and will keep the other?


texts:
Let us say that we create 3 bitcoin address and 4 ethereum address. This means that we have 3 public private key for bitcoin and 4 public private key for ether.

After recovery using the 24 word seed, How the new ledger nano s knows that I have used 3 address in bitcoin and 4 address in ethereum.

I wonder how this happens. Could you please help me to understand ?


texts: ganache-cli doesn't have enough funds to send tx – number increases proportionally to however much I initialize a wallet with

texts:
I'm trying to write a simple function to send a transaction using web3 and ethereumjs-tx that empties the wallet of an account (call this account A) into another account (account B). However, no matter what I initialize the balance of account A at using ganache-cli, ie with ganache-cli --account="0x4482be4e4e36d5521d70dafa57818eed38a4d0c69562bffebf24901c3199b271, 222222222222222222222", I get the error:

Error: Returned error: sender doesn't have enough funds to send tx. The upfront cost is: 73361650815041401384341826897131069221944849241050 and the sender's account only has: 222222222222222222222

Furthermore, if I increase the amount I initialize the wallet at, the 'upfront cost' increase proportionally:

Error: Returned error: sender doesn't have enough funds to send tx. The upfront cost is: 22704331223003175573249212746801550559464702875615796870481879467237868556850 and the sender's account only has: 22222222222222222222222222222222

Can anyone tell me what I'm doing wrong? Here's my code:

var Web3 = require('web3');
var web3 = new Web3(new
Web3.providers.WebsocketProvider("ws://localhost:8545/"));
const Tx = require('ethereumjs-tx');

  addr = account..address;
  key = account.key;
  key = key.slice(2);
  web3.eth.getBalance(addr).then( (result) => {
    evmBalance += parseInt(result, 10);

    web3.eth.getGasPrice()
    .then((gasPrice) => {
      var gasLimit = 25000;
      web3.eth.getTransactionCount(addr).then( (nonce) => {
        var nonce = nonce.toString();
        var rawTransaction = {
          "from": addr,
          "nonce": web3.utils.toHex(nonce),
          "gasPrice": web3.utils.toHex(gasPrice * 1e9),
          "gasLimit": web3.utils.toHex(gasLimit),
          "to": destinationAddr,
          "value": result,

        };

        var privKey = Buffer.from(key, 'hex');

        var tx = new Tx(rawTransaction);

        tx.sign(privKey);
        var serializedTx = tx.serialize();

        var transaction = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
        transaction.on('receipt', console.log);
        transaction.on('error', console.log);


texts:
When I go to the key store folder via Mist I find a .json-file (doesn't have a .json extension, but I believe this is still a .json file) that corresponds with my ether address (UTC blablabla). If I'm correct this file is the encrypted (or password protected) version of my private key.

Now I've got two questions:

Does a (password protected .json file) private key ever change? Is the key the same when it is freshly created as it is after 100 transactions?  Meaning: will it suffice if I just back it up after creation?
If I write down the name of the file in the key folder, can I later restore my wallet? Like a cold/paper wallet. Somehow it seems to me this is too short/simple to be a complete private key. It's just UTC + a creation date+the address/public key, but other than that very little extra info.


texts: How can I get particular state of a contract through web3.js?

texts:
I deploy a simple token contract "MetaCoin through web3.js as follows:

var Web3 = require('web3');
var web3 = new Web3(Web3.givenProvider || 'http://localhost:8545');
const abi = [...];
var MetaCoin = new web3.eth.Contract(abi, "0x77e82a433403f2d3273f391414b1eafe7e792624");

I can call a function 'getBalance()' of the contract and get the result like this:

MetaCoin.methods.getBalance("0x77e82a433403f2d3273f391414b1eafe7e792624").call().then(function(result){ console.log(result); });

But how can I call a state like 'address public creator' defined in the contract?


texts: Transfer tokens among multiple accounts in single function

texts:
I want the user to transfer tokens to an wallet instead of smart contract.

function getTokens () public {

    require (token.transferFrom(msg.sender, address(this), amount));
    require (token.transfer(NewWalletAddress, amount));
}

Initial tokes in contract address and NewWalletAddress is 0.

Will the above code work correctly in Eth mainnet? Will the 2 transfers take place or will there be any issues. or do we have another approach? Please suggest ideas


texts: Can Truffle deployer send ether on construction?

texts: If a contract has a payable constructor and needs to be filled on construction, is this possible with the truffle migration workflow?


texts: How to know whether the my address received ERC20Tokens?


texts: What is the purpose of the Zinken Ethereum 2.0 testnet?

texts:
The Spadina testnet launched less than 2 days ago.
What is the purpose of the Zinken testnet? What is being covered that was not covered in Spadina?
Related:
What are the Ethereum 2.0 testnets?


texts: Is there a way to allow metamask to allow all transactions for a specific dapp

texts:
The metamask popup prompts me and ask me a confirmation each time i send a transaction from my dapp.
Is there a way to configure metamask in order to allow all transactions from my dapp, without having to confirm them ?
Thanks


texts: Best way for two contracts that know each other's address?

texts:
Example situation:

contract A calls a function from contract B
contract B only permits only contract A to call the function (no other address allowed)

I know I could do this:

deploy contract B
deploy contract A with contract B's address in the constructor to connect to it
pass through contract A's address to a function in contract B that sets it as the permitted address

Is there a better way to do this though? Perhaps some way to have them both in each other's constructor?


texts: Error when trying to create new Solidity contract using Geth

texts:
Very new to Geth and Ethereum, and I'm just trying to create my first contract and deploy it to my private blockchain using Geth.

Geth version 1.7.3

Below is my Solidity contract code:

pragma solidity ^0.4.8;

contract Test {
uint256 public value;

function Test() {
    value = 123;
}
}

I have compiled this contract with the browser compiler and Copying the Web3 deployment instructions from the Remix browser compiler into geth console, and I have also tried using the built in solidity compiler on my mac to compile and create a new contract.  i'll note I'm not compiling from inside geth console, as I know that doesn't work anymore, I keep getting the error when I call:

testContract.new(<ContractCode>)

Below is the output of the code I run with the compiled contract with the error:

var test = testContract.new({ from: eth.accounts[0], data: "0x" + testOutput.contracts["Test.sol:Test"].bin, gas: 18000000000},
function (e, contract) {
  console.log(e, contract);
  if (typeof contract.address !== 'undefined') {
  var test = testContract.new({ from: eth.accounts[0], data: "0x" +
  testOutput.contracts["Test.sol:Test"].bin, gas: 18000000000},
    function (e, contract) {
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
    console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
  }
});
Error: exceeds block gas limit undefined


texts: How do I know when I've run out of gas programmatically?

texts: This keeps coming up on the gitter forums so I thought I'd ask and answer this question:   How do you know when you've run out of gas?


texts:
Are Uncle rewards paid to the miner of the uncle?
These are my logs. I don't understand if I've been paid  after the block I mined is no longer in the canonical chain.
INFO [08-20|17:21:19.206] Commit new mining work                   number=10698385 sealhash="4803fb…42ee3d" uncles=1 txs=183  gas=12470845 fees=1.926527275   elapsed=86.735ms
INFO [08-20|17:21:24.207] Commit new mining work                   number=10698385 sealhash="13335e…a82c76" uncles=1 txs=187  gas=12468272 fees=1.939251505   elapsed=87.202ms
INFO [08-20|17:21:24.313] Successfully sealed new block            number=10698385 sealhash="4803fb…42ee3d" hash="2b6ad4…6ff956" elapsed=5.106s
INFO [08-20|17:21:24.313]  mined potential block                  number=10698385 hash="2b6ad4…6ff956"
INFO [08-20|17:21:24.314] Commit new mining work                   number=10698386 sealhash="b30adc…38570e" uncles=0 txs=0    gas=0        fees=0             elapsed=1.103ms
INFO [08-20|17:21:24.398] Commit new mining work                   number=10698386 sealhash="a160f7…a4d133" uncles=0 txs=145  gas=12465119 fees=1.667804444   elapsed=85.373ms
INFO [08-20|17:21:24.403] Imported new chain segment               blocks=1  txs=203  mgas=12.498  elapsed=89.680ms    mgasps=139.365  number=10698385 hash="e4647d…cd1850" dirty=2.00GiB
INFO [08-20|17:21:29.068] Deep froze chain segment                 blocks=5  elapsed=13.466ms    number=10608384 hash="c48027…1ec23d"
INFO [08-20|17:21:29.395] Commit new mining work                   number=10698386 sealhash="8683a5…321120" uncles=0 txs=135  gas=12473957 fees=1.744267335   elapsed=81.889ms
INFO [08-20|17:21:34.399] Commit new mining work                   number=10698386 sealhash="af0df6…1ce794" uncles=0 txs=149  gas=12458243 fees=1.809310246   elapsed=85.763ms
INFO [08-20|17:21:39.404] Commit new mining work                   number=10698386 sealhash="585b75…34befd" uncles=0 txs=169  gas=12454774 fees=1.836050483   elapsed=90.217ms
INFO [08-20|17:21:44.400] Commit new mining work                   number=10698386 sealhash="fae165…b25ce9" uncles=0 txs=168  gas=12457487 fees=1.868399904   elapsed=86.097ms
INFO [08-20|17:21:49.517] Commit new mining work                   number=10698386 sealhash="a5a85c…719e4b" uncles=0 txs=156  gas=12462725 fees=1.889301565   elapsed=191.608ms
INFO [08-20|17:21:49.535] Chain reorg detected                     number=10698383 hash="d35252…e339a5" drop=2 dropfrom="2b6ad4…6ff956" add=3 addfrom="5142c0…e4e94e"
INFO [08-20|17:21:49.543] Imported new chain segment               blocks=1  txs=147  mgas=12.509  elapsed=396.652ms   mgasps=31.536   number=10698386 hash="5142c0…e4e94e" dirty=2.00GiB
INFO [08-20|17:21:49.544] Commit new mining work                   number=10698387 sealhash="e6c015…ae12e8" uncles=0 txs=0    gas=0        fees=0             elapsed="535.313µs"
INFO [08-20|17:21:49.683] Commit new mining work                   number=10698387 sealhash="b2624f…1b18e1" uncles=0 txs=137  gas=12484353 fees=1.710992588   elapsed=140.234ms
INFO [08-20|17:21:54.610] Commit new mining work                   number=10698387 sealhash="1c82e2…affc07" uncles=0 txs=147  gas=12479437 fees=1.792299693   elapsed=66.528ms
INFO [08-20|17:21:59.633] Commit new mining work                   number=10698387 sealhash="9f4696…d7f0dd" uncles=0 txs=178  gas=12489107 fees=1.892902982   elapsed=89.140ms
INFO [08-20|17:22:04.143] Imported new chain segment               blocks=1  txs=187  mgas=12.488  elapsed=113.661ms   mgasps=109.867  number=10698387 hash="293f14…cc4a21" dirty=2.00GiB

As you can see, my node detected a 3 block reorg from 10698386 to 10698383 just after I mined block 1069838. I would like to know if in this conditions I've been paid or not.


texts: Can I filter through an array of structs?

texts:
I want a way to store an array of structs. And then I want the ability to filter through this array and pick out a subset of items where a certain struct parameter named foo == bar for example.

Is this possible in solidity? Are there any limitations on how large my original my array is and the number of returned items?

Lastly, because this would only read from the ledger, it should not cost any gas to execute correct?

Thank you.


texts: how can we convert variable value into days?

texts:
i want to convert a value of variable into number of days! I have tried as follows, but got compile error at days!

function any(uint timeInDays) public
{
uint256 TotalDays=timeInDays days;
}


texts: What is the cost of inter-contract calls?

texts:
I have a contract with methods to create items and add them to categories.
I want to create a wrapper contract that would combine several calls into one: create an item and add it to several categories in one call.
What is the approximate price of calling the wrapper instead of calling the base contract directly?
Help me to decide if it is worth to call the base contract rather than the wrapper one directly, if the number of categories to add the created item to is zero.
Case 1: Create item and add it to categories 11 an 17.
Case 2: Create item and not to add it to categories.


texts:
I am writing a smart contract for a token sale.

How can I endSale destroy contract and transfer remaining tokens and accumulated ethers from the sale  to admin wallet ( using truffle commands)?

I have two contracts:

StoriToken.sol
StoriTokenSale.sol

Code for contract 1

pragma solidity ^0.4.2;

contract StoriToken {
    string  public name = "STori Token";
    string  public symbol = "STOR";
    string  public standard = "STori Token v1.0";
    uint256 public totalSupply;

    event Transfer(
        address indexed _from,
        address indexed _to,
        uint256 _value
    );

    event Approval(
        address indexed _owner,
        address indexed _spender,
        uint256 _value
    );

    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    function StoriToken (uint256 _initialSupply) public {
        balanceOf[msg.sender] = _initialSupply;
        totalSupply = _initialSupply;
    }

    function transfer(address _to, uint256 _value) public returns (bool success) {
        require(balanceOf[msg.sender] >= _value);

        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;

        Transfer(msg.sender, _to, _value);

        return true;
    }

    function approve(address _spender, uint256 _value) public returns (bool success) {
        allowance[msg.sender][_spender] = _value;

        Approval(msg.sender, _spender, _value);

        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_value <= balanceOf[_from]);
        require(_value <= allowance[_from][msg.sender]);

        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;

        allowance[_from][msg.sender] -= _value;

        Transfer(_from, _to, _value);

        return true;
    }
}

Code for Contract 2

pragma solidity ^0.4.2;

import "./StoriToken.sol";

contract StoriTokenSale {
    address admin;
    StoriToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    function StoriTokenSale(StoriToken _tokenContract, uint256 _tokenPrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;
    }

    function multiply(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x);
    }

    function buyTokens(uint256 _numberOfTokens) public payable {
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        require(tokenContract.balanceOf(this) >= _numberOfTokens);
        require(tokenContract.transfer(msg.sender, _numberOfTokens));

        tokensSold += _numberOfTokens;

        Sell(msg.sender, _numberOfTokens);
    }

    function endSale() public {
        require(msg.sender == admin);
        require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));

        selfdestruct(admin);
    }
}

Thank You in Advance


texts: Is there a way to send coins to a contract without executing it?

texts: Is there a way in Ethereum to send coins to a smart contract without actually executing a smart contract? And also, as an extension to that question, is it possible to determine from Solidity that sending coins to a particular address will result in an external contract execution (ie, will it incur more gas than if you were simply sending the coins to a wallet address?).


texts:
I want to be able to create my own local network using Ethereum and then I want to be able create my own currency and then trade that currency on my own local network and be able to have miners verify these trades.

I have looked at tutorials to set up a local test network and create my own currency on the Ethereum network, but it seems that there is nothing else to explain how that block would work, how the blockchain updates, and the other parts of my app.

Could someone help me?


texts:
I'm developing a Dapp based on Ethereum and I'm facing a problem that I don't know how to properly solve.

I need to store a very big JSON array composed by more or less 10k object where each object contains different fields such as floating numbers representing x and y coordinates of a polygon.

I can't find a way that I can use in order to store all these data in a decentralized way, I've read file system based technology such as IPFS and some decentralized databases such as BigChainDB.

My problem is that I need to associate each smart contract to one of these object and I need a way to navigate thought them. I wish to represent all the polygons contained in the different object on a map using a JS library but I can't understand how could I store these data and then query them in order to get the coordinates of the items that needs to be represented.

I've just started studying the technology, so I apologize in advance for any absurdities that maybe I've written.
Thanks in advance.


texts: Why did this transaction, with many contract self destructs, include such a large (34ETH) transaction fee?

texts:
The transaction 0xd0820f45ddc180231076a9b28f73f8d124ab296ad7cc7c87c745e0d44a461595 in block #124627591 paid a ~34ETH transaction fee. Why? Does this have to do with the number of contract self destructs?
Furthermore, the entire block paid ~93ETH in transaction fees. A few other transactions (6ETH, 11ETH, 10ETH) also paid, what seems to be, exorbitantly high transaction fees. They all also seem to include multiple contract self destructs.


texts: What is preventing malicious miners stealing data to steal smart contract rewards?

texts:
The motivation for this question is roughly along the lines of a puzzle contract -- whoever submits the correct solution to the puzzle gets a reward from the contract.

I'm guessing that the 'thing' in a transaction that is actually signed is a hash of the from: and to: addresses (the sender and recipient addresses of the transaction in question), and value too.. This would prevent malicious miners from just changing all to: addresses to ones owned by themselves, and mining blocks transferring random people's money to them.

Is the data field included in the hash too? Is it also sent in the clear? Is there anything 'binding' the signature/original sender and the data together? If not, is there anything else preventing puzzle solutions submitted to the contract being intercepted and resubmitted by the lucky guy mining the block?


texts: I want to create a local exchange site how to add ethereum?

texts: like a said I want to build an exchange site how can I add ethereum on it?


texts: solidity - allowance delegation - what if the owner spent it already

texts:
So userA delegates his tokens to be spent by me to whoever I want. That's great.
let's say userA's balance was 200Token. and he delegated 150 Token to me..
Now, userA can still transfer 180Token to some other account. So after that userA has 20Token remaining.
Now,  i come in and want to use the delegated tokens that userA gave me, but it turns out I won't be able too.
So what happened is he first gave me a permission to spend ,  but then he spent those, so I can't spend them anymore.
Is this how it works and how it should be ?


texts: How to send tokens from an existing contract to multiple people (will reward with $20 in eth)

texts:
EDIT: This question is not a duplicate. I am asking for someone to walk me through the entire process of distributing my token to multiple individuals. I am entirely new to coding and as such have near-zero clue as to what I am doing. Those other questions/answers are of no help at all. I have read through them and got no where. Please someone help a guy out.

First and foremost I've been doing some digging to try and learn as much as I can and there are already a number of threads that address a similair question in part. But having no background in coding/solidity etc I have no clue what I'm doing. So if anyone of you guys would be willing to, I'd love it if someone could fill me in step by step exactly how I need to go about solving the problem.

As the title suggests I'm fairly new to solidity and coding in general and as such i seem to be having a ton of difficulty figuring this stuff out. But my question is how do I implement a smart contract or something of the like that would then allow me to send a fixed amount of tokens that I have already created to x people at once.

Please help a brotha out lol.


texts: Check division is integer or float solidity

texts:
Suppose i have a contract with decimals and total Supply as follow.
How can i check if tokenAmountInWei pass in is integer value in form of ether.

decimals = 18
totalSupply = 1000000

function someFunction(uint tokenAmountInWei) {
    // check if tokenAmountInWei convert to ether is integer value
}


texts: ethereumjs-wallet/hdkey is no more in npm

texts:
how to generate multiple addresses from single mnemonic?

var hdkey = require("ethereumjs-wallet/hdkey")
var bip39 = require("bip39");

// You can generate a mnemonic seed with bip39 library
var mnemonic = "seed sock milk ";
var path = "m/44'/60'/0'/0/0";

var hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(mnemonic));
var wallet = hdwallet.derivePath(path).getWallet();
var address = "0x" + wallet.getAddress().toString("hex");
console.log(address)


texts: How is a contract settled when multiple wallets make the same transaction?

texts:
I'll use the DApp, CryptoKitties as an example:

Let's say some sweet digital cat is released with a "buy now" button for 1 Ethereum and 3 people make the transaction via MetaMask. All 3 transactions start pending.

Person A sends the transaction at 09:04:01 with gas price of 2 Gwei
Person B sends the transaction at 09:04:21 with gas price of 20 Gwei
Person C sends the transaction at 09:04:51 with gas price of 100 Gwei

If Person A's transaction takes 5 minutes to be verified, Person B's takes 40 seconds, and Person C's takes 10 seconds, then:

Whose transaction gets priority and is added to the block? (Only one will go through while the others are refunded minus the gas for the computation)
Does the timestamp of the initiated transaction have any effect on priority?

A detailed/technical answer would be very much appreciated. Thanks!


texts:
I've made the follwoing contract on my private node.

> contract
{
  address: "0x27f8df7f80ff48431594ef062ba80b2ad491d27b",
  transactionHash: "0x85303402ad0203f41efbc35abb9188e271ec17755664a9df6ec17b287825a058",
  Execution: function(),
  allEvents: function(),
  capital: function(),
  fixed_rate: function(),
  fixed_side: function(),
  floated_side: function(),
  spread: function()
}
> eth.getBalance("0x27f8df7f80ff48431594ef062ba80b2ad491d27b")
100000000000000000000
> eth.getBalance(eth.accounts[3])
1.39998e+21

Then I tried to send ether from a account to contract, then mined.

eth.sendTransaction({from: eth.accounts[3], to: "0x27f8df7f80ff48431594ef062ba80b2ad491d27b", value: web3.toWei(100,"ether"), gas:1000000})

However, it seemed that it cannot send ether. The balance of the contract does not increase. Could you tell me what is the problem?

> eth.getBalance("0x27f8df7f80ff48431594ef062ba80b2ad491d27b")
100000000000000000000
> eth.getBalance(eth.accounts[3])
1.39996e+21


texts:
I'm currently writing the "Trade" smart contract which is similar to "Crowdsale" smart contract. The only function that I want to add is "sell" function. In general Crowdsale smart contract is used for making people buy their token. There is no problem to implement "buy" function because of the payable. Not only it can make the Smart Contract can receive the ether but also it is able to make the transaction of particular payable function (i.e. function buy() payable public {}).

I need the Token Fallback function as ether does so I found the ERC223 which is improved based on ERC20. I'm wondering if I can use a Token Fallback Function in another Smart Contract. I mean another deployed contract. For instance, let's assume that someone transfer/send my erc20 custom tokens to "Trade" Smart Contract because he/she wants to sell some amount of tokens and get the proportional amount of ether back (using Web3 like this myContract.methods.transfer()). After the "Trade" Smart Contract received the token, Token Fallback Function in "Trade" Smart Contract is called and executed the "Sell" function in that Contract. Is that make sense?

The problem is how can I implement this?

function transfer(address _to, uint _value, bytes _data) public {
    require(_value > 0 );
    if(isContract(_to)) {
        ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
        receiver.tokenFallback(msg.sender, _value, _data);
    }
    balances[msg.sender] = balances[msg.sender].sub(_value);
    balances[_to] = balances[_to].add(_value);
    Transfer(msg.sender, _to, _value, _data);
}

(Refer to https://gist.github.com/anonymous/eb7be71f34911b013552960cc4ac0f45)

This is the ERC223 Token transfer function and the ERC223ReceivingContract is imported import 'browser/ERC223ReceivingContract.sol'; like this. I don't want to import the Contract because for the case when I have to update my Contract later. I want to remain my Token contract has only a few required functions.

I also found another function called TransferAndCall(). I can't find the detailed explanation how to use it. It seems like similar to Fallback function.

Anyway, do you guys have any solution to do this? Why I want to divide the "Trade" Smart Contract and "Token" Smart Contract is because for the case when I have to update my "Trade" Contract later like I mentioned.
Please help me smart solidity experts!


texts:
Every time I try to run the getPairPrice function in the contract bellow I get an out of gas error. My contract always has a balance before I call the function, 2 ethers to be exact, but I still get the out of gas error. Why is that?

pragma solidity ^0.4.3;
import "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";

contract BinaryTrading is usingOraclize {
  // ********* //
  // VARIABLES //
  // ********* //
  address minter;

  uint balance;

  string public ethusd;

  function BinaryTrading() {
    minter = msg.sender;
    oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
  }

  // This function is the fallback function
  function () payable {
    balance += msg.value;
  }

  function updatePrice(string newPrice) {
      ethusd = newPrice;
  }

  // This function is called when the oraclized request results are ready
  function __callback(bytes32 myid, string result, bytes proof) {
    if (msg.sender != oraclize_cbAddress()) throw;
    ethusd = result;
  }

  // IMPORTANT: Add private when in production, so that I can only call what will not give an error
  function getPairPrice() {
    bytes32 myid = oraclize_query("URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD");
  }

}

I have also tried running the code changing the gas value to 2000000.

By changing this line:

bytes32 myid = oraclize_query("URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD");

to

bytes32 myid = oraclize_query("URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD", 2000000);

Is 2000000 gas not enough to cover updating a variable?

Please let me know what might be causing this. I am testing it using the online solidity compiler. When I create the contract using MetaMask it says "Transaction Error. Exception thrown in contract code." That same message appears when I call the getPairPrice function but not the others.

Here is one of those test contracts I created using the code above:
https://testnet.etherscan.io/address/0x2831899baa68f655764d17e7a65c8e526e4ac53c


texts: How do I write test assertions for ethereum specific events?

texts:
For example, testing for a transaction that reverted or an out of gas error etc.
What is the best practice for writing such tests? Specifically, I am using truffle test framework (mocha/chai).


texts: Geth on Windows: Does my keystore need to be in blockchain directory?

texts:
I've noticed some weird behavior using Geth. My setup is that I am running Geth 1.7.3 with this command:

geth.exe --cache=1024 --rpc --datadir "C:\data\ethereum_blockchain"

Then, I start Mist and it connects to Geth just fine. But it does not load my account. My %appdata%/Ethereum directory is present with my Keystore inside it.

When I copied the keystore directory to C:\data\ethereum_blockchain\keystore, then Mist loaoded my wallet.

Is this expected? Have I been misunderstanding what --datadir is suppoosed to do?


texts: Why is there a Maximum bytecode to permit for a contract?

texts:
Why is there a Maximum bytecode to permit for a contract in Quorum?

i.e., MaxCodeSize = 24576 // Maximum bytecode to permit for a contract.

One should be allowed to deploy a smart contract of any size in a permissioned/private blockchain such as Quorum.


texts:
I think this has been answered somewhere in the internet once before, but I can't find the answer anymore.
If I own DOMAIN.ETH ENS and I create Subdomain.DOMAIN.ETH and transfer the ownership of subdomain to someone else and resolve the address to someone else's address, will I still be able to modify it's settings as the owner of DOMAIN.ETH?


texts: Exit process after sending multiple tx asynchronously

texts:
I have written a function that allows me to send an arbitrary amount of transactions, asynchronously, to my smart contract. However the process stays open even after the last transaction has finished. Currently, I have to manually press CTRL+C to exit. I would like for my program to automatically exit once the last transaction has finished. How would I go about doing this?

async function multipleTx(n) {
  accounts = await web3.eth.getAccounts()
  let totalGasUsed = 0
  for (let i = 0; i < n; i++) {
    instance.methods
      .addSubmission(i, i, i, i)
      .send({
        from: accounts[0],
        gasPrice: 10000000000,
      })
      .then((receipt) => {
        console.log(receipt)
        totalGasUsed += receipt.gasUsed
        console.log(totalGasUsed)
      })
  }
}


texts:
I have a custom ERC20 token project and I would like to cover the token behaviour with tests. As the ERC20 interface is standardized I wonder whether there are some libraries to test ERC20 functionality or to help me with it?

I use truffle in my project so I prefer tests specifically for this framework but it is not required.