texts: Ledger still shows that I have a balance of ETH, but I sent the entire amount twice to Bittrex

texts: My Ledger is still showing my entire "balance" of ETH when I open the wallet, but it also shows the twice attempted transfer of the entire amount to Bittrex underneath it. Both times I tried to transfer it said confirmed, but I have yet to see it on Bittrex and am still seeing the full balance on the Ledger. Are my ETH still secure on my Ledger or did I F**k up


texts: Truffle test to verify events can be queried by the address of the signing user?

texts:
I'm trying to write a test which verifies I can query a given type of events by the user/address which sign them.

I would like to apply TDD (relevant to say I haven't made the implementation for this particular case yet).

I was expecting something like:

  describe('get user history', () => {
    it ('returns the events signed by the user', async () => {

      # create account for user 'john' with generated private key

      # submit transaction 'buyGroceries' with 'john' signature which should emit an event

      # submit transaction 'buyNewspaper' with random account which should emit an event

      # assert the first and only the first transaction is returned when query for the event type signed by 'john'

    });
  });

The problem with this is that I don't find any utils which allow me through truffle tests to create an account with a private key on its clean-room environment.

What am I missing?


texts:
What is the cost of deploying contracts on Ethereum?

What is the cost of deploying contracts on Ethereum? Intuitively, the cost should to be proportional to the size of the contract.

How is the cost computed? And how can I check the size of my contract before deploying it, so that I know the cost of deployment?


texts: How to fix gas-related errors in sending a transaction

texts:
I tried to make my first transaction but kept failing.
I searched here and there but still could not find a solution.
And came here to write a question.
I am trying to send some from account[0] to other.
I started geth as below with my account[0] (real address):
Geth --syncmode full --miner.etherbase 'account[0] address' --nodiscover --cache 8192 console
Then, typed the line below:
eth.sendTransaction({ from:eth.accounts[0], to: _other account address_, value: web3.toWei(0.0015, "ether"), gas: 21000 } )
Geth said:

Error: exceeds block gas limit
at web3.js:6347:37(47)
at web3.js:5081:62(37)
at < eval>:1:20(20)

So I kept changing gas number and met this error with 5051:

Error: intrinsic gas too low
at web3.js:6347:37(47)
at web3.js:5081:62(37)
at < eval>:1:20(20)

So it looks like the gas limit is set as 5051 but this is TOO LOW to start (or asking) my transaction.
Where can I change the gas limit?


texts:
I have deployed a smart contract in Remix IDE using MetaMask and test rpc. I got the below error:

Error: Error: [ethjs-rpc] rpc error with payload {"id":6223335088050,"jsonrpc":"2.0","params":["0xf9061.......f2b"],"method":"eth_sendRawTransaction"} Error: transaction underpriced

So, please give me solution to resolve this issue.


texts: Truffle Pet Shop Tutorial App.js - Send Multiple Form Values to Function

texts:
Working through a little project using the Truffle Pet Shop as the starting point and hit a wall. It looks like this is the piece in App.js that fires the handleAdopt function:

bindEvents: function() {
$(document).on('click', '.btn-adopt', App.handleAdopt);
},

My question is how would I modify this to send multiple values from my form to a function?

I have this createWarrior function set up in the App.js file:

createWarrior: function(event) {
var WarriorFactoryInstance;

web3.eth.getAccounts(function(error, accounts) {
if (error) {
console.log(error);
}

var account = accounts[0];

App.contracts.WarriorFactory.deployed().then(function(instance) {
WarriorFactoryInstance = instance;

// Execute adopt as a transaction by sending account
return WarriorFactoryInstance.createWarrior(warName, level, attack, defend,
strategy, winCount, lossCount, tokenURI, to);
}).catch(function(err) {
console.log(err.message);
});
});
}

I have a form in my html file that has an input element for each of the variables that the function needs so I'm assuming that I need to set up that bindEvents piece to get those values and pass them to the function?

Any help/advice would be greatly appreciated. I'm a major novice so feel free to explain anything like you're talking to a 5 year old...

https://github.com/KevinMXRT/TribesOfWar

Thanks,
Kevin


texts: Is it possible to get a list of all active auctions on ENS?

texts:
On testnet, there is currently a registrar running for first-in-first-served (FIFS) .test domains, which can be directly claimed for 30 days, and the auction registrar for .eth domains, which require a 7-day public auction to claim a domain.

Is it possible to get a list of all active auctions on .eth domains from the ENS?


texts: unable to veriify a signed message in solidity

texts:
behaviour of web3py and solidity.
Samples:
## First in web3py

sig = Web3.soliditySha3( [uint256], [tokens] ) ## used below also
output: HexBytes('0x3efb3cf4e41109f6f1f998401d02dbe894719a8806f45e79a5fab7d4799f00bb')

from eth_account.messages import encode_defunct
msg = sig.hex()
message = encode_defunct(text=msg)
signed_message = w3.eth.account.sign_message(message, private_key=private_key)
signed_message

SignedMessage(messageHash=HexBytes('0x4c0c7077f770069785167e8b7451d63fad1e858ef5251b239eb0781c314000d2'), r=5665764915496639843348851536709769469640799172147461427941649091688603148258, s=48121517563314450138554207713326165180739298862566159641495137088718857193470, v=27, signature=HexBytes('0x0c86b594baa5bb06a0f4054ffdf3896377cfb757d42dcaeacf0241d96a4d5fe26a63d0514338ec600c89ee808dc088e7b3aadc55b9f5d86685d3ff212e2e47fe1b'))

Then I tried
w3.eth.account.recoverHash(signed_message.messagehash,signature=signed_message.signature)#gives correct contract address as output

But when I use:
w3.eth.account.recoverHash(sig,signature=signed_message.signature) ## gives incorrect address

But it gives the same address which solidity is giving...
then I checked what is the output of keccak256(abi.encodePacked(..)).
I found It is same as sig value
and then the ecrecover output of solidity gives the same address given by the above function..
How can I validate properly the tokens that I owe.
Please help..


texts: Security flaws in a simple smart contract

texts:
I developed a simple smart contract to store two privacy preferences for a user. I am testing and evaluating this contract on a private blockchain via Ganache.

I am currently validating the security of it but I have some doubts. In my research I identified three flaws that could affect this contract: Reentrancy, Front-Running and DoS with Block Stuffing (Details of the attacks can be seen here).

My main question is:

How to evaluate these issues in the developed contract?

1) To evaluate Reentrancy I thought of invoking one of the contract's functions several times at the same time. Would this idea be valid? How can I do to invoke this function several times at the same time?

2) For Front-Running I thought of monitoring the mempool and checking if I can observe the transaction before it is executed. The question is: how to do this via ganache?

3) For DoS, I thought again about calling a function repeatedly until the gas limit of the block is reached. Would this idea be valid?

Below is the contract code:

pragma solidity ^0.5.0;

contractPrivacyPreferences {

bool preference = false;
bool monitoringType = false;

mapping (address => bool) addresses;

contructor () public {
    adresses [address(0x00281055afc982d96fab65b3a49cac8b878184cb16)] = true;
}

function changePreferences() public {
     if (addresses [msg.sender])
           preference = true;
}

function changeMonitoringType () public {
   if (addresses [msg.sender]) {
      monitoringType = true;
}

function preferenceStatus() public view returns (bool) {
    return preference;
}

function monitoringStatus() public view returns (bool) {
    return monitoringType;
}
}


texts: How can I set up callbacks in my UI after user has submitted tx via Metamask?

texts:
I have a webapp that calls a smart contract via web3js/Metamask and I want to reload certain elements once the user has submitted the tx.

How can I set up the callbacks for those reload actions?


texts: Issue trying to mine solo with Geth and ethminer

texts:
I am trying to use ethminer in combination with Geth to solo mine with GPU, but ethminer fails to get work.

Here is how I do. Geth is running in full sync mode and seems to be properly synchronized as I can check recent balances and the last block indicated by geth follows closely the one given by https://ethstats.net/. The geth command is:

geth --syncmode full --rpc

In addition, when launching geth, the log indicates it runs a server at http://127.0.0.1:8545/.

Then, I start ethminer (version 0.16.1) with:

ethminer -U -P http://127.0.0.1:8545

This does not work as shown by what ethminer displays:

 m 17:31:21 ethminer ethminer 0.16.1
 m 17:31:21 ethminer Build: linux/release
cu 17:31:21 ethminer Using grid size: 8,192, block size: 128
 i 17:31:21 ethminer Configured pool 127.0.0.1:8545
 i 17:31:21 main     Selected pool 127.0.0.1:8545
 i 17:31:21 main     Established connection with 127.0.0.1:8545 at
 i 17:31:21 main     Spinning up miners...
 i 17:31:21 cuda-0   No work. Pause for 3 s.
 X 17:31:21 getwork  Failed getting work!
 i 17:31:21 main     Disconnected from 127.0.0.1
 i 17:31:22 main     Selected pool 127.0.0.1:8545
 i 17:31:22 main     Established connection with 127.0.0.1:8545 at
 X 17:31:22 main     Failed getting work!
 i 17:31:22 main     Disconnected from 127.0.0.1
 i 17:31:23 main     Selected pool 127.0.0.1:8545
 i 17:31:23 main     Established connection with 127.0.0.1:8545 at
 X 17:31:23 main     Failed getting work!
 i 17:31:23 main     Disconnected from 127.0.0.1
 i 17:31:24 cuda-0   No work. Pause for 3 s.
 i 17:31:24 main     Suspend mining due connection change...
 i 17:31:24 main     Selected pool 127.0.0.1:8545
 i 17:31:24 main     Established connection with 127.0.0.1:8545 at
 X 17:31:24 main     Failed getting work!
 i 17:31:24 main     Disconnected from 127.0.0.1
 i 17:31:25 main     Selected pool 127.0.0.1:8545
 i 17:31:25 main     Established connection with 127.0.0.1:8545 at
 X 17:31:25 main     Failed getting work!
 i 17:31:25 main     Disconnected from 127.0.0.1

Any idea of what I am doing wrong?


texts: Tendermint vs Algorand - Similarities and Differences

texts:
The core of Algorand uses a Byzantine agreement protocol called BA⋆ that scales to many users while Tendermint is based on a modified version of
the DLS protocol which is resilient up to 1/3 of Byzantine participants.

Am trying to decide between both -- any inputs?


texts: How exactly are block rewards calculated in ethereum?

texts:
On some websites the block reward looks like this:2 + 0.9126 + 0.00257 + 0.06867 ETH
Etherescan shows it like this:2 + txfees
So, I think the block reward is a fix amount (2 in 2021) and tx fees.
Or is there any special calculation for the tx fees shown above ?
Cheers


texts: Contract created by another contract and exceptions

texts:
I have two questions regarding contract creation and exceptions:

If contract A creates contract B and then throws in the same function, is B also deleted?
If contract A creates contract B, and B throws in its constructor, does the exception bubble up to A?


texts: Is there "auto-drop" or "auto-cancel" for a transaction that's not been processed for a long time?

texts:
I sent a transaction with relatively low gas and during several days it was pending. Eventually I managed to have it to get through by increasing a gas fee.
Other time I send a transaction with a low gas fee as well, from some web-service or site where I have an account, and that one failed after around 12 hours, somehow. Although, I don't know, maybe a web service marked it as "canceled" by sending another one with same nonce and bigger gas fee, to cancel it.
Does Ethereum have mechanism for dropping or cancelling a transaction automatically, whether it be one sent to an ordinary account or smart contract, that's been pending for a long time? If yes, how long is long time?


texts:
Now I am getting trouble on checking the USDC balance in my wallet address using web3.

USDC is also said that it is ERC20 token, but when I checked the token contract

0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48

This doesn't contain the erc20 standard.
So I guess I can't use the traditional token balance checking way in this coin.
Also I tried in traditional way, but it never work.
How can I check the USDC balance / and create transfer transaction from one address to another using Web3?


texts: Unable to install geth on my Azure Ubuntu 12.4

texts:
Somehow, I am unable to install from this location:

bash <(curl -L https://install-geth.ethereum.org)

getting the error below:

error unable to install geth

screenshot:


texts: How do I allow the current owner an NFT to append 8 bytes to the token?

texts:
How would I allow the current owner of an NFT to append a fixed number of metadata bytes to their token on chain. Is this something that can be done with ERC-1155 or ERC-721. Or is this a whole new beast?
I would expect the owner would be paying the gas cost to accomplish this append operation. In my usecase there would not be any non technical reason to restrict how often an owner can append these bytes.
What is a rough estimate of the gas cost to perform and store such an append?


texts: Signed transaction vanishing from testnet (Kovan & Rinkeby)

texts:
I've been attempting to broadcast transactions to both Kovan & Rinkeby, I'm building and signing them offline and using the Etherscan API to broadcast the signed transactions. I see them in the explorer labelled as:

Pending This TxHash was found in our secondary node and should be picked up by our indexer in a short while.

They sit there for between 4-8 hours then just vanish. I've tried increasing the gas price and gas limit a few times. And I'm assuming because they get accepted by the API at all I've correctly signed them (I'm using an external method to sign the hash and stitch together the transactions). I'm not sure if there's a way to validate the transaction to see if the one I've created is valid and properly signed.

The most recent one I've tried to broadcast to Kovan is:

f86d01850ba43b7400830186a0944d6bb4ed029b33cf25d0810b029bd8b1a6bcab7b88015181ff25a980008077a060023895819271c2b033820c913c9c6326325dbea272b09429d886833d5a900ca04ccf4a6a3710806b2d137f4460551a8a2ef6627b1da81fbd971c4a18aba8a880

I've tried to decode it with https://flightwallet.org/decode-eth-tx/ and it seems to look good.

{
  "nonce": 1,
  "gasPrice": 50000000000,
  "gasLimit": 100000,
  "to": "0x4d6bb4ed029b33cf25d0810b029bd8b1a6bcab7b",
  "value": 95000000000000000,
  "data": "",
  "from": "0xe6652ca72b030b1c426b3e9654bd02e466943d54",
  "r": "60023895819271c2b033820c913c9c6326325dbea272b09429d886833d5a900c",
  "v": "77",
  "s": "4ccf4a6a3710806b2d137f4460551a8a2ef6627b1da81fbd971c4a18aba8a880"
}

I'd really appreciate if anyone had some advice or tools I could use to debug this, or sees something incorrect in my encoding. Thanks.


texts: Why can't I browse the internet while Parity is running?

texts:
I am using Parity/v1.5.0-unstable-a7037f8-20161126/x86_64-macos/rustc1.13.0
After I start the node, every page request in the browser fails with a "Server not found" error. As soon as I turn the Parity node my internet connection works again as expected.

These are the differences between netstat with parity running and parity off. Maybe this can help to detect if this is a port collision?

< tcp4       0      0  localhost.30303        localhost.62536        ESTABLISHED
< tcp4       0      0  localhost.62536        localhost.30303        ESTABLISHED
< tcp4       0      0  davids-mbp.local.62315 128.199.55.137.30303   ESTABLISHED
< tcp4       0      0  localhost.http-alt     localhost.61962        ESTABLISHED
< tcp4       0      0  localhost.61962        localhost.http-alt     ESTABLISHED
< tcp4       0      0  localhost.8180         *.*                    LISTEN
< tcp4       0      0  localhost.http-alt     *.*                    LISTEN
< tcp4       0      0  localhost.8545         *.*                    LISTEN
< tcp4       0      0  *.30303                *.*                    LISTEN
---
> tcp4       0      0  davids-mbp.local.63153 52.222.157.6.https     ESTABLISHED
> tcp4       0      0  davids-mbp.local.62942 fra16s18-in-f14..https ESTABLISHED
59,61d51
< udp6       0      0  *.62792                *.*
< udp4       0      0  *.62792                *.*
< udp4       0      0  *.30303                *.*
134,138c124,127
< 90d5bc5341b2c3b5 stream      0      0                0 90d5bc5341b2c60d                0                0 /Library/Application Support/OpenVPN/sock/cliapi.sock
< 90d5bc5341b2c60d stream      0      0                0 90d5bc5341b2c3b5                0                0
< 90d5bc533cd467fd stream      0      0                0 90d5bc5341b2cf6d                0                0 /var/run/mDNSResponder
< 90d5bc5341b2cf6d stream      0      0                0 90d5bc533cd467fd                0                0
< 90d5bc5341b2d0fd stream      0      0 90d5bc5349c5d01d                0                0                0 /Users/uscreen/.parity/jsonrpc.ipc
---
> 90d5bc533cd467fd stream      0      0                0 90d5bc5341b2c60d                0                0 /var/run/mDNSResponder
> 90d5bc5341b2c60d stream      0      0                0 90d5bc533cd467fd                0                0
> 90d5bc5341b2d0fd stream      0      0                0 90d5bc5341b2cf6d                0                0 /Library/Application Support/OpenVPN/sock/cliapi.sock
> 90d5bc5341b2cf6d stream      0      0                0 90d5bc5341b2d0fd                0                0


texts: Are assertions removed in release build?

texts:
Are assert() removed in release build?
Please show an authoritative document documenting that they are removed or no removed.


texts:
When a contract triggers a throw, the Solidity document states:

  Solidity will trigger an "invalid jump" and thus cause the EVM to revert all changes made to the state.

In this case, what happens to the ether value (not the gas) that was sent along with the transaction? Is it returned to the sender, or is it still stored in the contract?


texts:
I want to use parity as a multisig wallet, but I want to make sure they've already fixed the recent exploit.
Most articles online just talk about the exploit.


texts: what types of graph data are produced by the ethereum network?

texts:
I'm curious, what sort of node-link graph data is produced by the Ethereum network?  I imagine there there is a graph of all transactions, and a higher level graph of miners and the blocks they mined.  Are there similar emergent network datasets from other activities on the Ethereum network?

I build data visualizations, and would really like to create a force-layout network vis from some Ethereum data.

This bitcoin network vis or this citation network vis are examples of the sort of thing I'd like to create for Ethereum.


texts: Whats the cheapest/most gas efficient way of converting bytes32 to uint24?

texts:
I have an array of bytes32 with various pieces of information at various byte positions in it, and 2nd 3 bytes are a number, which I convert to uint24 like so (where currentData is of type bytes32):

uint24 convertedNumber = uint24(bytes3(currentData << 24));

However the operation happens in a loop, so the cost of shifting, then creating a bytes3, then converting to uint24 can add up as the size of the input array grows. Is there a more gas-efficient way to convert 3 bytes at a position inside a bytes32 into uint24?


texts: How can I transfer half mining award to an address?

texts:
Creating a dapp, which requires half allocated mining fee should go to an address.

I managed to cut down the mining as well as the block reward:

consensus.go

    // Accumulate the rewards for the miner and any included uncles
    reward := new(big.Int).Set(blockReward)
    rew := new(big.Int).Set(blockReward)
    r := new(big.Int)
    for _, uncle := range uncles {
        r.Add(uncle.Number, big8)
        r.Sub(r, header.Number)
        r.Mul(r, blockReward)
        r.Div(r, big8)
        state.AddBalance(uncle.Coinbase, r)

        r.Div(blockReward, big32)
        reward.Add(reward, r)
    }

    changedRew := new(big.Int).Set(rew) // half reward
    changedRew.Div(changedRew, big.NewInt(2))
    log.Warn("Mining block reward status .. ", "CHANGED", changedRew )
    state.AddBalance(header.Coinbase, changedRew)
}

state_transition.go

        if vmerr == vm.ErrInsufficientBalance {
            return nil, 0, false, vmerr
        }
    }
    st.refundGas()
    log.Warn("Half fee taken away ")
    // change price
    st.state.AddBalance(st.evm.Coinbase, changedRew.Div(new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice), big.NewInt(2)))

    return ret, st.gasUsed(), vmerr != nil, err
}

How can I now transfer the other half to an address? If I specify an account/address to be transferred , that can be easily changed without effecting the block rules. How can I do it securely ?

P.S : Just one account constant account for every node to transfer half mining fee.


texts: Using Ganache UI: Is there a way to find the names of the smart contracts?

texts: I realize this might be a limitation of Ethereum blockchain itself, but I thought that once I migrated a contract to Ganache I would be able to see the names, methods and method arguments of the contract using the Ganache UI. Is that wrong?


texts: returning a fixed size 2D array to web3.js

texts:
I would like to return a 2D array from solidity code and look at it with web3.js

this is the solidity function:

uint8 [10][10][100][100] public blocks;
function getBlock(uint x, uint y) returns (uint8[10][10]) {
    if (x < blockStoreSide && y < blockStoreSide) {
        return blocks[x][y];
    }
}

but what I get back from getBlock in web3.js is this number:

0xf5027db1aeac4c95acf2c3c32651cfd3f5561906399e19bd14818a6c7cc2d9cb

My assumption is this is an address?

I tried web3.eth.getStorageAt for that address but I just get zeros, not what I actually set the value to.

the ABI looks okay to me:

{ constant: false,
  inputs:
   [ { name: 'x', type: 'uint256' },
     { name: 'y', type: 'uint256' } ],
  name: 'getBlock',
  outputs: [ { name: '', type: 'uint8[10][10]' } ],
  type: 'function' }

So how do I actually read the storage?   More general question, how can I efficiently read large amounts of storage?


texts:
Does anyone know where truffle keeps logs?

I am unable to perform a migration.  It gives me no error message; it just hangs on:

Running migration: 1_initial_migration.js
  Deploying Migrations...

Yes, I have the account unlocked.  Yes, that account has lots of ether.


texts: Is it necessary to import all headers when making private Ethereum blockchain?

texts: I am trying to make private block chain. I am following this link


texts: How to convert smallest unit of ERC20 with less than 18 decimals to full coins without rounding errors?

texts:
I can just use web3's fromWei function for all token that have 18 decimal places but I'm not sure how to convert token to full token without having to worry about rounding errors.

For example convert a token with 15 decimals:

convert 12345 to 0.000000000012345 and so on.

Any help is appreciated


texts: How can I get a geth node to download the blockchain quickly?

texts: I'm running a geth node on slow hardware. At the current rate of progress it could be several days before I can download all the blockchain. Is there a way to get it to synchronise more quickly?


texts: Swap ether to tokens on Uniswap V2 Router 02 fails

texts:
I am trying to buy DAI tokens from my smart contract using IUniswapV2Router02
 contract BuyExample{

    IUniswapV2Router02 usi = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

        /**
         * @param amountOfEther The amount of ether the user has to buy the tokens.
         */
    function buyDai(uint256 amountOfEther) public payable returns(uint256){

    address cryptoToken = 0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735;

          uint deadline = now + 15; // I am only using 'now' for convenience, for mainnet I will pass deadline from frontend
            usi.swapETHForExactTokens.value(amountOfEther)(0, getPathForETHToToken(cryptoToken), address(this), deadline);

            // refund leftover ETH to user
            msg.sender.call.value(address(this).balance)("");

           return 1000;// a random value for now

        }

  function getPathForETHToToken(address crypto) private view returns (address[] memory) {
    address[] memory path = new address[](2);
    path[0] = usi.WETH();
    path[1] = crypto;

    return path;
  }

    }

The contract deploys successfully.
I try to use it by calling:
c.buyDai(web3.utils.toWei('0.02'))

...from truffle console.
But it reverts with a long error message.
On kovan.etherscan.io, its status says Fail
What am I doing wrong please?
A running instance of the contract is here


texts: What are the design targets which the light client is being developed against?

texts:
For example:

persistent storage?
volatile storage?
connectivity?

The closest I could get to a definition for the above is the following: "1KB of data per 2 minutes". However the following remains unclear:

is the light client required to store this 1KB every 2 minutes?
what happens if the client runs out of capacity?
what if the client looses connectivity for an hour... a day.. or perhaps longer?
does the connectivity have to be synchronous or can it be asynchronous? i.e. can the client "wake up" at any time, or is it expected to synchronize at some specific points in time?


texts:
We are trying to build a platform where a user can buy any coin with USD/BTC. The functionality is similar to that of Polonix (Deposit/Withdrawal). So, I was not sure on how to manage users' account.

I have expertise in ethereum. So, I know how to implement such functionality with ethereum based erc-20 standard token. I have created an ethereum node where each user will have an ethereum address. Once a user buys a coin we will add(transfer) the requested coin to that ethereum address.

But I am not sure on how to manage other coins like Ripple, Synereo AMP, Litecoin etc.  Do we need to have a node of all such coins which have different blockchain than ethereum?

How does polonix does this? Currently, if I want to deposit Ripple, Polonix gives me an account where I can deposit XRP, does polonix has a ripple node too? Where does these address, private and public key of these addresses reside? Another such platform is Token Market

Do these guys have nodes/wallets for every coin they support?

Is there any better way to implement such functionality?

PS: This is more a type of development idea and not exactly an issue. But I think our community is the best platform to get positive inputs.


texts: Access deployed contract's constructor's parameters from address

texts:
I'm using ethers.js but any answer will be okay !

I'm trying to access a contract's constructor's parameters that was used when deployed to make sure the contract has not been modified before being deployed by a user.

I'm able to get the code from the contract with ethers.js function provider.getCode(_address) but it doesn't include the parameters passed in the constructor of the contract.

Anyone know how this could be done ?


texts: Gas cost when calling multiple contracts

texts: If contract a was to call one or more contracts when running it, would the gas cost be the sum of both contract's gas cost?


texts: What is BlackList and why it is used in Tether Token Smart Contract? And what is the use of Pause and Unpause in Tether?

texts:
contract BlackList is Ownable, BasicToken {

function getBlackListStatus(address _maker) external constant returns (bool) {
    return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
    return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
    isBlackListed[_evilUser] = true;
    emit AddedBlackList(_evilUser); //event emmiting
}
function removeBlackList (address _clearedUser) public onlyOwner {
    isBlackListed[_clearedUser] = false;
    emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
    require(isBlackListed[_blackListedUser]);
    uint dirtyFunds = balanceOf(_blackListedUser);
    balances[_blackListedUser] = 0;
    _totalSupply -= dirtyFunds;
    emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);

}

contract Pausable is Ownable {

event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;

}
  modifier whenPaused() {
    require(paused);
    _;
}

function pause() onlyOwner whenNotPaused public {
    paused = true;
    emit Pause();
  }
 function unpause() onlyOwner whenPaused public {
    paused = false;
    emit Unpause();
  }
}


texts: How can I get delegatecall to return data?

texts:
I'm having trouble getting delegatecall to return the output of the executed function.

Here is a simplified version that shows my problem.

I have this contract deployed on kovan at: 0x850ec47a0f40e3605a7ba21f1c99b04410090134

pragma solidity ^0.4.8;
contract Tester {
    function getBytes() returns (bytes32) {
        return bytes32(0x1);
    }
}

I want to make a delegatecall to this contract and get the return 0x0000000000000000000000000000000000000000000000000000000000000001

Here is my caller contract:

pragma solidity ^0.4.8;
contract foo {
    function bar() returns (bytes32 response) {
        address dest = 0x850ec47a0f40e3605a7ba21f1c99b04410090134;
        bytes memory calldata = hex"0bcd3b33";
        assembly {
            let status := delegatecall(sub(gas,5000), dest, add(calldata, 0x20), mload(calldata), response, 32)
            jumpi(invalidJumpLabel, iszero(status))
        }
        return response;
    }
}

Now I can call the function bar either via a JSON-RPC call or via a transaction from another contract. The response is always 0x0. I can check on etherscan the transaction is not failing in any way. Should the code being imported getBytes() throw, then status should be false and the jumpi should throw bar().

This does not happen. I considered that the return parameter bytes32 response was in calldata and not memory (despite documentation stating it was in memory), and thus could not be written to. I checked this by getting the free memory pointer through mload(0x40), having delegatecall write to that location, and then copying the output to a state variable in storage. Then I could query the state variable to see if delegatecall had returned a value. Still nothing. I'm not sure what I am doing wrong here.


texts:
I sent some ether to Poloniex
https://etherscan.io/address/0x2b85d38c4c3d9422f75156ea36f479ab26a98faa
As you can see in etherscan.io, there are 2 income transfers for this address.
This is for my Polonix account. After that, I tried to do withdraw some ether and checked the transaction.
https://etherscan.io/tx/0x5f32f8ca905f975cf8c2977b3f3cefcf5f0ad6b3f7c704d8b761e2671f1034d8
This is my withdraw transaction. But from address is "Poloniex Wallet".
What is "Poloniex Wallet"?
Polonix has their pool address?
If they have pool address, how can they have my ether?

I also checked this Poloniex Wallet in Etherscan.
https://etherscan.io/address/0x32be343b94f860124dc4fee278fdcbd38c102d88
But there is no any income transfers?
It is weird.

Such this problem is also showing in Okex. I did withdraw to    0xf4A3D01Dc620687301b678b437913d57CA511bf9.
But from address is not my account. It says from address is 0x236F9F97e0E62388479bf9E5BA4889e46B0273C3 but my Okex address is 0x9CdAEFeE6fAe05B98A4a1492E2596b96712fB8A5.

How can I understand this problem?
Please let me be clear about this problem.


texts:
I'm currently reviewing the code of RANDAO and there is a function that does not return on all codepaths. Is this legal? Is the return value well defined in the case that the if statement does not hold?

  function returnRandom(Campaign storage c) bountyPhase(c.bnum) internal returns (uint256) {
      if (c.revealsNum == c.commitNum) {
          c.settled = true;
          return c.random;
      }
  }


texts: How to get back the ownership from crowdsale?

texts:
When I started crowdsale, I transferred token ownership to the crowdsale contract. When the sale finished, I'd like to send back the ownership to token so that the next crowdsale will start. How can I do that? I guess I can use FinalizableCrowdsale for defining those functions, but I have no idea how to get the token address in the contract and how to define the finalize() function... help me..

Actually, the contract was working well, but after finishing the crowdsale, the finalize() that I defined in the contract didn't work which means the ownership was not transferred. Should I call the function manually?

Crowdsale.sol

pragma solidity 0.4.24;

import "./DappToken.sol";

import "../node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol";
import "../node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol";
// import "../node_modules/openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol";

contract DappTokenCrowdsale is Crowdsale, MintedCrowdsale, CappedCrowdsale, TimedCrowdsale, FinalizableCrowdsale {
    DappToken private token;
    address tokenAddress;
    address crowdsaleOwner;

    bool public isFinalized = false;

    constructor(
      uint256 _rate,
      address _wallet,
      DappToken _token,
      uint256 _cap,
      uint256 _openingTime,
      uint256 _closingTime
    )
    Crowdsale(_rate, _wallet, _token)
    CappedCrowdsale(_cap)
    TimedCrowdsale(_openingTime, _closingTime)
    public
    {
      token = _token;
      crowdsaleOwner = msg.sender;
    }

    function transferOwnership(address _newOwner) public onlyOwner {
        require(msg.sender == crowdsaleOwner); // Only the owner of the crowdsale contract should be able to call this function.
        // I assume the crowdsale contract holds a reference to the token contract.
        token.transferOwnership(_newOwner);
    }

    function finalize() onlyOwner public {
      require(!isFinalized);
      require(hasClosed());

      transferOwnership(token);

      finalization();
      emit Finalized();

      isFinalized = true;
    }
 }


texts: geth account list returns accounts but eth.accounts does not

texts:
I had my ethereum node on one server. I needed to migrate the accounts and all to another server (due to the huge size of blockchain). I started new ethereum node on another server. To copy my accounts, I copied the keystore folder from one server to other.

Now my node on new server is fully synced but when in geth console I type eth.accounts, it returns an empty array. However, if I check by geth account list, it displays me list of all accounts. Also on eth.coinbase returns me one of my accounts. What's going wrong?

I have etheres as well as custom token in my account. Am I missing anything?


texts: How to generate a DAG for the given epoch with geth?

texts: I need to run some integration tests that include block sealing. I would like to separate the process of DAG generation from the tests themselves. Is it possible to pregenerate the given DAG with geth?


texts: Calling a contract from another contract - nothing happens

texts:
I'm trying to call a contract from another contract. When I use a simple example, like below, it just works fine, no problem, the counter in contract A adds up when I trigger function in contract B:

pragma solidity ^0.4.13;

contract A {
    uint public counter ;
    function increment(uint add) {
       counter = counter + add;
    }
}

contract B {
    function delegateIncrement(uint add) {
        A(addressA).increment(add) ;
    }
}

But when I want to incorporate a transfer function, like below, nothing happens. I don't get why. Increased gas etc already.:

pragma solidity ^0.4.13;

contract Betaal{
    address public bedrijf = addresBedrijf;

    function UitBetalen(){
        bedrijf.transfer(this.balance);
    }

    function ()payable{
    }
}

contract Trigger{
    function TriggerBetaling() payable{
        Betaal(addressBetaal).UitBetalen;
    }
}

When I the "uitbetalen" function directly in the "Betaal"contract, it works just fine, but when I want to trigger it using the "TriggerBetaling" function in the "Trigger" contract, the transaction reaches the Trigger contract just fine and then nothing happens, the uitbetalen function is not triggered. Anyone any idea?

I'm using remix and metamask, but they seem to work just fine.


texts: How to store 32 input parameters in a single solidity function with data types being string and bytes32?

texts:
When I try to exceute a solidity smart conract function to store 32 input parameters, I am getting a stack too deep error.

To resolve that, at the middleware we have consolidated and created an array of bytes32 for 24 input parameters and the rest of the 8 parameters are of string datatype. But again we get the same stack too deep error.

How can I possibly exceute a function to store the 32 input parameters?

We are making use of solidity compiler version 0.4.25.

This is the basic skeletal of code

struct Sample {
    bytes32 key;
    string str1;
    .
    .
    .
    .
    .
    string str8;
    byts32[] someArray; //23 elements
}

mapping(bytes32 => Sample) sampleMap;

function set(bytes32 key,string str1,string str2,......,string str8,bytes32[] array) public returns(bool) {
    //set the values using sampleMap mapping;
    return true;
}

function get(bytes32 key) returns(bytes32 key,string str1,string str2,......,string str8,bytes32[] array) {
    //retrieve values from struct using sampleMap mapping
}


texts: Do verifiers apply a gas limit to the blocks they receive?

texts: I know that there is a gas limit for each transaction, set by the sender. Also there is a gas limit for each block set by the miner. So I want to know does an additional gas limit applied to the mined blocks when being verified by other nodes before insertion to the chain, or they just rely on the gas limit set by the miner in the block header?


texts: How can I easily parse a raw transaction?

texts:
In the Bitcoin ecosystem, there are tools like https://blockchain.info/decode-tx to decode a raw transaction. Is there a site that offers the equivalent for Ethereum?

I'm looking for an easy way to parse a raw transaction and make it human readable, without installing a library or broadcasting the transaction.


texts:
Are pending transactions processed sequentially in IBFT?

In a networks based on PoW you would usually pay higher gas price in order to get your transaction mined first. Is there a way to manipulate pending transactions ordering in IBFT?


texts: How to calculate gas for calling a function without deploying to mainnet?

texts:
What is the best way to check the cost (gas) price for any given function call in a smart contract, before deployment to mainnet?

Thanks


texts:
How do I create a constructor in solidity?

My goal is to have values initialized when the smart contract is deployed. As a java programmer, I default to a constructor to handle this.

contract NimGamev3 {

...

constructor(NimGamev3) internal {

...

}

...

}

I've read that you should use the constructor keyword to create a constructor to initialize values. This doesn't raise any errors when using remix. When I copy the code to Ethereum Wallet I get an error, "Could not compile source code. Expected identifier, got 'eth_compileSolidty' constructor(NimGamev3) internal {"

When I use a function to initialize variables, it is not called on when the contract is deployed, and if I make it public, it can be initialized multiple times which is not the intended function of the constructor.

Note: I am currently using 0.4.21


texts: call contract from another contract internal transaction

texts:
I'd like to call a function on another contract from my own contract but do not want to sign the transaction as a user but rather let the contract sign the transaction itself.

contract A

contract EtheremonLite {
    function initMonster(string _monsterName) public;
    function battle() public returns(uint256);
    function getName(address _monsterAddress) public view returns(string);
    function getNumWins(address _monsterAddress) public view returns(uint);
    function getNumLosses(address _monsterAddress) public view returns(uint);
}

contract B

contract Monster {
    string name;
    uint win;
    uint loss;
    event EmitName(string name);

    address constant public ethermonster = 0xf3259eec5b4a46748a1f608ec3d74b89058bb3ad;
    EtheremonLite monsters_contract;

    constructor() public {
        monsters_contract = EtheremonLite(ethermonster);
    }

    function create_moster(string monster_name) public returns (bool) {
        monsters_contract.initMonster(monster_name);
    }

    function get_monster_name() public {
        name = monsters_contract.getName(address(this));
        emit EmitName(name);
    }

    function get_last_block_hash() public view returns(uint) {
        return uint(blockhash(block.number -1));
    }

    function get_game_stats() public view returns(string) {
        win = monsters_contract.getNumWins(address(this));
        loss = monsters_contract.getNumLosses(address(this));
        return string(abi.encodePacked("win: ", win, " loss: ", loss));

    }

    function check_attack() public view returns(uint) {
        uint result;
        uint _dice = get_last_block_hash();
        uint dice = _dice / 85;
        return dice % 3;
    }

    function attack() public returns(uint256) {
        return monsters_contract.battle();
    }
}

I want to call the attack function internally without needing to confirm the transaction using metamask.

My goal is to win everytime I call battle. To do that I need to wait until the last blockhash is divisible by 3. So need to create a function that continuously checks for the previous block and if it is divisible by 3 then call battle and win the game.

Here is the battle function on that other smart contract:

   function battle() public returns(uint256){
       address challenger = msg.sender;
       require(monsters[challenger].created  && monsters[Ogre].created);
       bool challengerWins = false;

       uint battleRatio = monsters[Ogre].weight / monsters[challenger].weight;

       uint dice = uint(blockhash(block.number - 1));

       dice = dice / 85; // Divide the dice by 85 to add obfuscation
       if (dice % battleRatio == 0) {
           monsters[challenger].wins += 1;
           monsters[Ogre].losses += 1;
           challengerWins = true;
       }
       else {
           monsters[challenger].losses += 1;
           monsters[Ogre].wins += 1;
       }
       emit battleOutcome(challenger, challengerWins);
   }


texts: How are transfer and send protecting against reentrancy if the gas is taken from the EOA (msg.sender)?

texts:
I guess transfer and send simply allow 2300 gas but no gas is taken from the contract? In other words if a wallet calls this function with say one million wei gas:

function sending() public payable
{
contract.transfer(1 ether);
balance[someone] = 0;
}

This is enough to stop reentrancy? Since the 2300 gas will prevent callback even if EOA sends it with million gas?

However this will NOT stop it since the allowed will be 30,000+?

function sending() public payable
{
contract.call.value(1 ether)();
balance[someone] = 0;
}


texts: Cannot access functions contract myetherwallet

texts: No functions show up when adding this contract to https://www.myetherwallet.com/interface/interact-with-contract. Anyone know why?


texts: My Ethereum smart contract is always returning an empty array when using web3 with metamask

texts:
import Web3 from 'web3';

window.ethereum.enable();
const web3 = new Web3(window.ethereum);

const address = "0x977b5A39B6E95A7688570BF1b77e8FAb150791af";
const abi = [
  {
    inputs: [],
    stateMutability: 'nonpayable',
    type: 'constructor',
    constant: undefined,
    payable: undefined,
    signature: 'constructor'
  },
  {
    inputs: [],
    name: 'enter',
    outputs: [],
    stateMutability: 'payable',
    type: 'function',
    constant: undefined,
    payable: true,
    signature: '0xe97dcb62'
  },
  {
    inputs: [],
    name: 'getPlayers',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x8b5b9ccc'
  },
  {
    inputs: [],
    name: 'manager',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x481c6a75'
  },
  {
    inputs: [],
    name: 'pickWinner',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
    constant: undefined,
    payable: undefined,
    signature: '0x5d495aea'
  },
  {
    inputs: [ [Object] ],
    name: 'players',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0xf71d96cb'
  },
  {
    inputs: [],
    name: 'test',
    outputs: [[Object]],
    stateMutability: 'pure',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0xf8a8fd6d'
  }
];

const contract = new web3.eth.Contract(abi, address);

const testMyContract = async () => {
  const manager = await contract.methods.manager().call();
  console.log("manager", manager); // return empty []
  const helloWorld = await contract.methods.test().call();
  console.log("Hello world", helloWorld); // return empty []
}

testMyContract();

The address is of the contract deployed to Rinkeby. Whenever I call any method, it always returns an empty array. Even pure functions. I am using Metamask as a provider for web3.


texts: Is it possible to change back to previous metamask acct?

texts:
I want to craete the following flow with web3 or etherjs
1- I change to wallet B
2- With the ui trigger the change to another wallet
3- It is changed on metamask but FROM the UI
is it possible? im not able to find something similar


texts: How can I return an array of struct from a function?

texts:
I know that it's possible to return a struct through argument destructing:

contract Test {
    struct Point {
        int x;
        int y;
    }

    Point point;

    function getPoint() returns (int x, int y) {
        x = point.x;
        y = point.y;
    }
}

The problem is that I need to return an array of structs:

contract Test {
    struct Point {
        int x;
        int y;
    }

    Point[] allPoints;

    function getPoints() returns (???) {
        ???
    }
}

Is it possible?


texts: Is there multiple chains of block in ethereum network?

texts:
Since blockchain is a chain of blocks,

In ethereum,

1. is there only one chain of blocks

2. are there multiple chains of blocks.


texts: What is the best way to find out the type of a variable in Solidity? (something like typeof in JS)


texts: Give some examples of documentation that talks about reentrancy attacks / recursive call vulnerabilities

texts:
The DAO, a smart-contract on Ethereum, was vulnerable to reentrancy attacks and 3 million ETH worth $50 million was stolen from it.

What are some examples of content that mentions reentrancy attacks? Specifically, older content, as the content from June 2016 and forward is easily found through Google.

Does the whitepaper or the yellowpaper or other developer documentations mention reentrancy attacks ?


texts: Optional Multi-Parameter Call to External Contract

texts:
I would like to half implement ERC223 for business reasons. This means being able to notify other contracts when they receive tokens, but not revert if the recipient is a contract that doesn't implement the tokenFallback function. So the following situations should work:

User transfers token to an address. No call to tokenFallback (as it's just an address), transfer succeeds.
User transfers token to a contract that doesn't implement tokenFallback. No call, transfer succeeds.
User transfers token to a contract that does implement tokenFallback. Function is called, transfer succeeds.

Here are my findings thus far:

I can call by doing TokenRecipient(address).tokenFallback(msg.sender, value, 0) and this works for 1 and 3, but not 2 because I can't find a way to check if the contract conforms with the ERC223 interface.
I can call by doing to.call(<parameters>), and this works if I omit the bytes parameter. But the problem is the ERC223 call includes this bytes parameter, and even their reference implementation doesn't seem to actually work this way: https://github.com/Dexaran/ERC223-token-standard/issues/51 The behaviour I'm seeing is that as soon as there's a bytes parameter at all, call() starts just returning false and not doing anything.
I could theoretically use inline assembly to do the call, but I can't find any documentation on how I should correctly encode the bytes parameter. I know it's possible because the first option here works cross-contract, I just need to know how to actually do the assembly call.

Can anyone provide any guidance on the best way to go here? Is there a fix for call(), or a way to stop the normal call from reverting if the function doesn't exist? Or alternatively can someone point me to some docs on how to prepare the call from inline assembly?

EDIT: Here's what I've tried for the assembly. Doesn't seem to work as the function isn't called when it exists:

function _internalNoThrowTokenFallback(address contractRecipient, address from, uint value, bytes data)
    internal
{
    // We need to do this in assembly because:
    //   1. Calling the function as normal would result in a revert if the destination contract doesn't
    //      implement tokenFallback. We want this case to be ignored.
    //   2. We could use contractRecipient.call() but that doesn't work with bytes parameters:
    //      https://github.com/ethereum/solidity/issues/2884
    //   3. So we need to do the call the same way
    assembly {
        // Get some free memory to copy our params over to.
        let free_ptr := mload(0x40)

        // Tee up the function selector in the memory we've gotten
        mstore(free_ptr, 0xc0ee0b8a)

        // Load our calldata across to the new call, except for
        //  - The function selector (4 bytes)
        //  - The first address parameter (64 bytes when padded)
        //
        // Thus making a total of 68 bytes we want to ignore, and we want to copy the
        // data to our free_ptr after our function selector
        calldatacopy(add(free_ptr, 4), 68, sub(calldatasize, 68))

        // Ok, call the function without allowing the other contract to alter our state
        let result := staticcall(
            30000,                  // Give the other contract 30k gas to work with
            contractRecipient,      // The other contract's address
            free_ptr,               // We've prepared the inputs at free_ptr.
            sub(calldatasize, 64),  // They're the same length as our inputs were minus the address parameter.
            0,                      // There's no return from the function
            0
        )

        // Don't check the result or revert if the call failed. We want to proceed regardless.
    }
}


texts:
Hi i deployed a token contract in ethereum and managed to interact with it. solidity code :

contract Token {
  mapping (address => uint) public balances;
  event TokenSent(address sender, address receiver, uint amount);
  function Token(uint supply) {
    if (supply == 0) supply = 10000;
    balances[msg.sender] = supply;
  }
  function send(address receiver, uint amount) returns (bool ok) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    TokenSent(msg.sender, receiver, amount);
    return true;
  }
}

now im trying to send tokens to an account and i keep getting the following error:

new BigNumber() not a number: [object Object]10[object Object]
    at raise (web3.js:14426:29)
    at web3.js:14414:33
    at BigNumber (web3.js:13442:67)
    at BigNumber (web3.js:13452:29)
    at web3.js:2241:16
    at web3.js:2252:21
    at web3.js:950:32
    at web3.js:1598:12
    at web3.js:707:16
    at web3.js:706:20
    at web3.js:3991:46

I'm sending the following:

myContractInstance.send([{"receiver": "ed7a39b8cd4c217f99af29b5e5d7cbfd3c53030d"},{"amount": "100"}]),

if anyone could point me in the right direction that would be awesome!


texts: Private testnet + Smart Contract testing

texts:
is it possible to test a smart contract on a private net with two or more nodes? With nodes I mean two different machines, either virtual or physical, doesn't really matter.

I tried running geth with the usual commands however, the two nodes didn't seem to find each other, as netstat did not show a connection between the two.

All running on the same local network.

What can I do to debug this?


texts: How to write a simple token contract which token can only be transferred within the specific geographical region?

texts:
In my use case, I want to build a local currency system with solidity. The core concept of local currency is that the currency can only be used in the specific region. It aims to encourage spending within a local community, especially with locally owned businesses.
So my question is that how can I restrict the token only be transferred within the region. It means that the function 'transfer(address, amount)' will be reverted when the user calls the function outside the region.


texts: When do transactions on an exchange appear on etherscan?

texts: Hopefully my question is self-explanatory. For example, I purchased some ether on Poloniex today. Within what time frame is that transaction likely to appear on etherscan?


texts: Get ERC20 balance of token holder as of block number with C# Nethereum and Infura

texts:
When this code runs, it throws an error "RpcResponseException: header not found", and I don't understand why or how to fix it. Any advice?
Notes: I am using Nethereum in C#.net and using Infura API
[Function("balanceOf", "uint256")]
public class BalanceOfFunction : FunctionMessage
{
    [Parameter("address", "_owner", 1)]
    public string Owner { get; set; }
}

public void QueryingForBalanceAtBlockNumberWorksAsExpected()
{
    HexBigInteger blockNumber = new HexBigInteger("10933333");
    var web3 = new Nethereum.Web3.Web3("https://mainnet.infura.io/v3/" + _InfuraAPIKey);

    string contractAddress = "0x514910771af9ca656af840dff83e8264ecf986ca"; //chainlink

    string accountAddress = "0x56d065849ef9c59c1bc5ba54b9f96caba5c88812";

    var balanceOfFunctionMessage = new BalanceOfFunction()
    {
        Owner = accountAddress,
    };

    var balanceHandler = web3.Eth.GetContractQueryHandler<BalanceOfFunction>();

    //THIS WILL THROW AN ERROR "RpcResponseException: header not found":
    var balanceInBaseUnits = balanceHandler.QueryAsync<BigInteger>(contractAddress, balanceOfFunctionMessage, new Nethereum.RPC.Eth.DTOs.BlockParameter(blockNumber)).Result;
}


texts: How to search for event in when an input should be the 5th topic in event

texts: I want to query an ERC1155 token event where I know the token Id, there only can be 4 topics and tokenId would be the fifth,which means it's not an indexed input and goes to the data part. How can I query that way? I'm using alchemy for querying but I guess it's the same with one contract in web3.js too. any ideas?


texts: How to specify custom directory with c++ client

texts:
With the Go client, one can use the following command to create new accounts/keystore in a specified data dir:

geth --datadir ./data account new

While using the C++ client, there is no such option:

eth --db-path ./data account new

It doesn't work. Any pointers please?


texts: Can I estimate the total gas limit of several dependent transactions?

texts:
Assume two dependent transactions A and B. Transaction B depends on transaction A and will fail if transaction A has failed.

I would like to estimate the gas limit required for the success of both transactions if executed sequentially.
Estimating gas for each transaction separately does not work.
While there is no problem with estimating gas for transaction A, estimating gas for transaction B without actually executing transaction A might return a wrong result.
Transaction A has not yet happened and the state not changed.

In other words, how to estimate the gas limit for transaction B, given transaction A has completed successfully.


texts:
How are the various 0x network order trackers sourcing on-chain settlement data?

My first assumption was that they were utilising the Etherscan API, however Etherscan have their own tracker, found at https://etherscan.io/dextracker , which appears to have more complete transactional data than others such as https://0xtracker.com/ and http://0xtrades.info/ .

All three of the above have inconsistent data, which leads me to believe that there is no current best practice.

From a given list of relayers, I'm trying to obtain the order JSON for each transaction as following:

{
  "maker": {
    "token": {
      "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
      "name": "Wrapped Ether",
      "symbol": "WETH",
      "decimals": 18
    },
    "address": "0xa793f13c7c7d38b2ffb27c5273edbd0245adbe76",
    "amount": "334823067048678893",
    "feeAmount": "0"
  },
  "taker": {
    "token": {
      "address": "0x107c4504cd79c5d2696ea0030a8dd4e92601b82e",
      "name": "Bloom Token",
      "symbol": "BLT",
      "decimals": 18
    },
    "address": "",
    "amount": "418006325903469279650",
    "feeAmount": "0"
  },
  "signature": {
    "v": 27,
    "r": "0x48a7e06a617bd10ea3684d4f40a9e2b1167d3fd003245dd096adbad53e11195a",
    "s": "0x6c3c9df27ffd23371a35f7b6f0928031df1ace65f04de1023da4e05ffd31adb2",
    "hash": "0x52c77348c40f58fcd1e48b5fa91322ca515a7824b834dc9fcdb25a65ac76e96b"
  },
  "expiration": "1520170848",
  "feeRecipient": "0xa258b39954cef5cb142fd567a46cddb31a670124",
  "salt": "72248519509688682556724797082899905741793832544995882654354657068693442284506",
  "exchangeContract": "0x12459c951127e0c374ff9105dda097662a027093",
  "networkId": 1
}


texts: UnimplementedFeatureError: Encoding type "struct BiddingContract.Bidder memory" not yet implemented

texts:
The code is broken with the new upgrade v0.5,
 using
  Truffle v5.0.1 (core: 5.0.1)

struct Bidder {
    address bidders_address;
    uint productId;
    uint bidValue;
}

struct Product {
    uint productId;
    uint bidStartPrice;
    uint32 bidStartTime;
    Bidder latestBid;
    string productName;
    bool isAvailable;
    uint32 bidSession;

}

And mapping as

mapping(uint => Product)  product;

removed the public getter venerability but still, the error is coming.

This is my full code :

    pragma solidity >=0.4.21 <0.6.0;

    import "./AucSters.sol";
    import "../libraries/SafeMath.sol";

    contract BiddingContract {

    using SafeMath for uint;

    address admin;
    AucSters public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    //structs
    struct Seller {
        uint256 sellerId;
        string sellerName;
        bool isValidSeller;
    }
    struct Bidder {
        address bidders_address;
        uint productId;
        uint bidValue;
    }
    struct Product {
        uint productId;
        uint bidStartPrice;
        uint32 bidStartTime;
        Bidder latestBid;
        string productName;
        bool isAvailable;
        uint32 bidSession;

    }

    mapping(address => Seller) registeredSeller;
    mapping(uint => address) public productIdToOwner;
    mapping(address => uint) public productCount;
    mapping(uint => Product) product;
    mapping(address => mapping(uint => uint)) public latestBidStore;

    //ARRAYS
    address[] public regSellers;
    Product[] public productsForSale;
    address[] public bidders;

    constructor(AucSters _tokenContract, uint _tokenPrice) public {
        //Assign an admin
        admin = msg.sender;

        // token Contract
        tokenContract = _tokenContract;

        //Token price
        tokenPrice = _tokenPrice;
   }

}


texts: How many new nodes join the Ethereum Network per month? How many leave?

texts:
I'm researching the cost of serving old blocks to new nodes that need to synchronize and download the whole blockchain. I can indirectly estimate the bandwidth consumed to serve old blocks, if I know how many new nodes join/leave the network per month. For simplicity, I will can assume that each of the new nodes needs to download the full blockchain, and each node that leaves will not come back.
The more direct way is to instrument a geth node to measure the bandwidth dedicated to serving old block requests, but nobody seems to have done it while publishing this information.


texts: For production dApps, what kind of sync should be done on server node?

texts:
I plan to use web3 server side using NodeJs with geth. For production usage, should I do a full sync or fast sync is enough?

Also, how much space do I need to store the blockchain data for each of these sync types as on today?


texts: How to decode error response from contact


texts: Reflect Base contract's update in another contract

texts:
I have wanted to know what concept is it called when we want two contracts which are deployed on the Network, reflect the transaction and updates in another contract.
for example:
contract Base{
  mapping(address => bool) addressTrue; //mapping true some addresses, as per our requirement(s)

  function setTrue(address _address) public {
    addressTrue[_address] = true;
  }
}

contract FromBase{ //Maybe without inheritance/ interface.

   function seeStatusAndDoSomething(_address) public returns(bool) {
        //Return: the mapped value of _address is true or false
   }
}

If Alice deploys Base contract and sets the addresses of Bob as true. Later Daves want to see the status of Bob's address, which should return true. But in future if Alice decides to change status of Bob's address to false. Dave, when he checks the by calling seeStatusAndDoSomething should now get false.
What I want to understand is that whenever a function setTrue in contract A is called, where some _address is getting true. How should I see those changed in contract B, without redeploying it?
Is such presented above scenario possible in Solidity?
I am familiar with solidity concepts, just want to know which one to use and what should be the workflow.
Thank you.
Edit:
Added details in question


texts: Tried using splitter contract, not getting ETC

texts:
Hi I followed Vitalik's instructions for using the splitter contract.

I used Wallet 8.1, on the fork chain to send ETH from my etherbase account to the splitter contract targeting a fresh ETC wallet on the non-fork chain (also etherbase), and refunding a 2nd etherbase account on my ETH wallet.

etherbaseYesFork A -- >  Splitter Contract \ --- etherbaseYesFork B
                                            \ -----  etherebaseNoFork A

This transaction for 1 ETH went through, and split correctly into both ETH and ETC accounts.

However I followed with 2 more transactions and over 1 hour later they don't appear in the ETC Chain, they are correctly being moved in the ETH chain to the account.

Here is the first and successful transaction:
http://etherscan.io/tx/0xd74b6861c47dffe68393593b13320269c49336f2342ad9b5ff8147d745c9b00f

Here is the follow up, that still has not appeared in my ETC Wallet (No Fork Chain).
http://etherscan.io/tx/0x73b3ef8fc2f4b544e36617cfb20f3edbc61db3b01dfbee4c1af034845dc1c4f5

Any ideas what went wrong?

**  Corrected the links -

Wallet Address:
ETH : 0x0d1af24b05015fa6ef57493bb3697e75c28ef0bc1
ETC : 0x0fdde2c8255e661ecece17b0ac431d5f7caf6a2e


texts: Transaction not going through in Mist 0.8.6

texts:
I have update Mist-wallet to latest 0.8.6 version and I was trying to execute a contract on my Test-network before working on Public net with this version. When I execute contract with fee suggested by Mist, it says

  It seems your transaction will fail. If you submit it, it may consume all the gas you send.

I even provided the max available fee in Mist i.e 1.0541272 ether, And on confirmation page I see provide max fee as 0.02550988 ether (121000 gas). But still getting hit by same error message on confirmation page.


texts:
I want to write a function let user deposit 1 eth to a specific address for registering purpose.

pragma solidity ^0.5.0;

contract Election {
    mapping(uint => UserRequest) public userRequest;
    // chairman account, let airline deposit to become a member
    address payable chairman;

    // Constructor
    constructor () public payable {
        chairman = msg.sender;
    }

    function register() public payable{
        chairman.transfer(1 ether);
    }
}

While I test the register() on the remix, the following error threw out.

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

Some solution I found said I need to deploy it with a certain value, but what does that mean?


texts: Unable to use Truffle Migrate with Kovan

texts:
I'm trying to use Truffle for the first time to deploy and test my new Smart Contract.  I can deploy and test it in Remix just fine, but the truffle migrate command fails with the following error:
Error:  *** Deployment Failed ***
"Migrations" -- Invalid chain id..
This is using my Kovan node on QuikNode, which is also working fine from my node js app.  Here is the truffle-config.js settings related to the wallet:
const HDWalletProvider = require('@truffle/hdwallet-provider');
const mnemonic = "twelve word seed phrase that im not dumb enough to put here"

networks: {
    kovan: {
      provider: function() { return new HDWalletProvider(mnemonic, "https://my.node_url.here/") },
      network_id: 42       // Kovans's id
   }
}


texts: Why is my Contract interaction cost so high?

texts:
When interacting with the UI of my application, it says the cost of doing this interaction through metamask is 400 ether. I am using Ganache for testing which only allows you to have 100 ether. I am confused how come the cost is so high, and where in the truffle pet shop directory, would the files be located that affect this price, so I can bring it down for testing.

// Attempt to sign up user.
      rideshareInstance.joinRide(ride_number, {value: parseInt(payment * Math.pow(10,18)), from: coinbase})
      .then(function(result) {
        // If no error, login user.
        return browserHistory.push('/dashboard')
      })
      .catch(function(result) {
        // If error...
      })
    })
  })
}

When i change the values inside the Math.pow function, the contract code throws an exception. I believe that the values inside the Math.pow function are making the cost so high, but dont know how to change it.


texts:
Using the online Solidity compiler I get this error:

browser/TokenSales.sol:18:10: Error: Member "value" not found or not visible after argument-dependent lookup in function (address) external returns (bool) - did you forget the "payable" modifier?
    if (!TokenSalesInterface(tokenSales).proxyPurchase.value(msg.value).gas(106000)(payout)) throw;
         ^-------------------------------------------------^

For this code:

contract ProxyPayment {

  address payout;
  address tokenSales;
  address owner;

  function ProxyPayment(address _payout, address _tokenSales) {
    payout = _payout;
    tokenSales = _tokenSales;
    owner = _payout;
  }

  function () {
    if (!TokenSalesInterface(tokenSales).proxyPurchase.value(msg.value).gas(106000)(payout)) throw;
  }

}

This is my repo.

How can I fix this issue?


texts: Speaking of Ethereum blockchain, Is it possible to perform homomorphic secret sharing algorithmic calculations like SSS/pVSS/VSS on-chain? or should this be calculations performed off-chain


texts: How to obtain the implementation address from an upgradeable proxy smart contract?

texts:
Is there any way to externally obtain the current implementation address of a proxy that doesn't involve interacting actively with it (e.g. calling a transfer or approve function, i.e. without using gas)?
Let's use for example the USDC ERC-20 token, which its upgradeable proxy smart contract's address is: 0xA0b8...eB48 and it's current contract implementation to which it delegates to with the fallback function is 0xb727...78a2.
Is it possible?


texts: web3.eth.compile.solidity(source) throws me Invalid JSON RPC response

texts:
I am relatively new to Blockchains and when I execute the following command I am getting an error.

contract mortal {
    address owner;

    function mortal() {
        owner = msg.sender;
    }
    function kill() {
        if(msg.sender == owner) suicide(owner);
    }
}

contract greeter is mortal {
    string greeting;

    function greeter(string _greeting) public {
        greeting = _greeting;
    }
    function greet() constant returns (string) {
        return greeting;
    }
}

web3.eth.compile.solidity(greeterSource)

  Invalid JSON RPC response: undefined
      at InvalidResponse (:-81076:-41)
      at send (:-154580:-41)
      at solidity (:-131712:-41)
      at :1:1**

What is going wrong?


texts: Is there a way to test an onlyOwner function from a Truffle/Solidity unit test?

texts:
I have a contract with a function marked as onlyOwner (from OpenZeppelin, so only the address that deployed the contract can call it).

pragma solidity ^0.4.17;

import "./Ownable.sol";

contract MyContract {

    function myFunction() public onlyOwner {
        dummy();
    }
}

I have created a Truffle/Solidity unit test for that contract but when I call the function I get an error, as the calling address is different than the address that deployed the contract.

pragma solidity ^0.4.17;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";

contract TestMyContract {
    MyContract contract = MyContract(DeployedAddresses.MyContract());

    function testCanCallFunction() public {
        myContract.myFunction();
    }
}

Is there a way to use the same address? And to do tests from different addresses? For example if I want to test with an owner and with another one. I know it can be done with Javascript tests.

Thanks!


texts: How to access already deployed Smart Contract using Java?

texts:
I would like to get information about token. For example total supply and so on. For this I need the contract. However what is the way to actually load it/access it from Java?
Checking examples in languages such as python, it seems trivial:
contract_address = 'CONTRACT_ADDRESS'

abi = json.loads(abiJson)

contract = web3.eth.contract(address=contract_address, abi=abi)

totalSupply = contract.functions.totalSupply().call()

However how to actually do this using Java? Do I need to generate .abi file and then compile it to java? This way, wouldn't I need to recompile the project everytime I wanted to find info about another contract?
Thanks for help!


texts: Issue in ERC721 token transfer to contract address

texts:
I am using ERC721 implementation for NFT tokens.

I am testing the transfer functionalities in ERC721.

 `transferFrom(address _from, address _to, uint256 _tokenId)`
 `safeTransferFrom(address _from, address _to, uint256 _tokenId)`
 `safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)`

I have tried the token transfer scenario with _to address as account address.

I am trying to do the token transfer scenarios with _to address as contract address.

I have written a receiver contract for testing the functionality.

  pragma solidity ^0.4.22;

  import "./standard/ERC721TokenReceiver.sol";

  contract ValidReceiver is ERC721TokenReceiver {

      event  LOGTokenFallBack(address from,bytes4 value);

      function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4 value) {
            emit LOGTokenFallBack(_from, bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")));
            return 0x150b7a02;

     }
}

Updated the safeTranferFrom functionality also as follows:-

   function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public  {
    transferFrom(_from, _to, _tokenId);

    //Get size of "_to" address, if 0 it's a wallet
    uint32 size;
    assembly {
        size := extcodesize(_to)
    }
    if(size > 0){
       ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
       require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")));

    }

It seems to be that the transfer gets reverted.

I have updated the ERC721TokenReceiver by removing the return type as follows.

   function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external ;

And updated ValidReceiver as follows.

contract ValidReceiver is ERC721TokenReceiver {

      event  LOGTokenFallBack(address from,bytes4 value);

      function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external  {
            emit LOGTokenFallBack(_from, bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")));

     }
}

And it seems to be a successful transfer by emitting the LOGTokenFallBack event.

I have tried various ways to do the transfer by return type in receiver contract.

Did anyone face the issue similar to the one mentioned?

Any help is appreciated.


texts: How can I locally store my Ether from Coinbase?

texts:
Right now, I'm in the process of creating a Coinbase account. As I'm typing this question, Coinbase is verifying my ID. Once the registration process is over I'd like to buy Ether. Once I buy Ether it will be stored on the databases of Coinbase, right? This seems like a liability to me, so I'd like to store it locally. However, I don't know how to do that. I read online that I need a wallet, so I downloaded Mist. But Mist requires me to download the whole blockchain (which is currently more than 30GB?). I don't wanna do that, because I think it is a waste of space.

Can someone tell me what I should do? I'm a beginner to Ethereum.


texts: How to get node to notify of transactions?

texts:
I just finished syncing my Ethereum node. I'd like to set up a way my node can run a bash script or trigger something to run a PHP script every time someone interacts with a contract.

Node Detects transaction involving contract -> data sent to PHP script / recorded on my database -> website displays to users

How can I achieve something like this? Can someone give some pointers on where to start? Ethereum nodes are different than bitcoin nodes.


texts: How can i read transation data from ethereum to file or database?

texts: I want read transations data "input" field from ethereum to file.How can i do it?thanks.


texts:
Which blockchains use the same addressing as Ethereum?
I find this blockchains:

Smart chain BNB
ETC
VeChain VET
GoChain GO
POA Network
Callisto
Wanchain
TomoChain
Thunder
Theta
Minter (without MX)

Any else?
Thanks.


texts: Sending ERC20 token to the constructor of a contract

texts:
I want to send an erc20 token to the constructor of a contract. I can't manually use the approve(spender, amount)  function before deploying the contract as the spender address needs to be the address of the contract. If I use token.approve or token.transfer methods in the contract it returns transfer amount exceeds balance, though I have sufficient balance in my account. I assume that it's trying to approve or transfer tokens from the contract.
Note: This question is different from this. Using token.approve inside the contract approves from the contract and not from msg.sender.


texts: fast syncing has completed, yet eth.blockNumber still returns 0

texts:
I've ran a fast sync via

  geth --syncmode "fast" --cache 1024

After running for about 12 hours (didn't think fast sync should take that long!) "eth.syncing" finally returns

  false

which I'm led to believe means that the syncing has completed successfully.

Correct?

Yet, when I issue a "eth.blockNumber" it continues to return "0"

Why is this?
How can I truly know when syncing has completed successfully?

I'm running geth 1.8.0 on Windows 10, and I'm fast losing confidence that running a local node is achievable

HELP!


texts: Truffle deploy via Infura : does it work?

texts:
I've read mixed things.  In the docs for Truffle Framework there are instructions for deploying contracts via Infura's APIs.

But, elsewhere, I've read that Infura doesn't allow one to send transactions and hence deploying via Infura is not possible.

Which is it?

Has anyone managed to deploy via Infura?


texts: How Ethereum consensus validates same transaction from different miners?

texts:
In an Ethereum node, my brief understanding regarding transaction flow is below.

When a client initiates a transaction, all mining nodes receives this request. Based on gas price, miner choose to process the request. after processing they keep the transaction in their own tx pool. Once it becomes a block (Block has collection of transactions) ,this block get's added into ledger.
Here it is possible that multiple miner accept to process this request and put it in their own tx pool before storing into blockchain and each block can have own set of transaction pool.

My query is,
when multiple miners solve the puzzle and keep the transaction in their own pool and when each one has their block ready , how Ethereum consensus decide which one to accept. If it is on First Come First Serve Basis then what happens to other blocks, whole block gets rejected or only transaction which was already processed gets rejected.

Question may not be well phrased but hope you got my question. Looking for answer.


texts:
I have some JavaScript that's connecting to a private ethereum network via JSON-RPC. I am trying to extract the transaction hash of the blocks but am unable to do so.

// BlockNumber
clientNodeOne.call({"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1},
        function(err, res) {
          if (err) console.log(err)
          console.log("MINER ONE block number: " + parseInt(res.result, 16) )
          miner_one_block_number = parseInt(res.result, 16);
        })

        // console.log("BLOCK NUMBER: " + miner_one_block_number);

// Block Hash
clientNodeOne.call({"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[miner_one_block_number, false],"id":1},
      function(err, res) {
        if (err) console.log(err)
        console.log("MINER ONE transaction hash: " + res.result)
      })

The first call to read the block number works great. I am saving the block number to another variable, miner_one_block_number. I am then passing that variable into the input parameters for the call to eth_getBlockByNumber. Instead of getting the transaction hash for that block, I am instead getting a value of undefined. Any help would be appreciated!


texts: Why does adding "public" to a mapping break my contract?

texts:
I have a contract that breaks after I add only the word "public" to a mapping. For reference, my contract is below:

contract VendingMachine {

event Unlocked(address machineID, address unlocker);
event MachinePayed(address machineID, uint amount);
event CustomerPayed(address customer, uint amount);

address admin;

struct Machine {
    bool exists;
    bool isFunded;
    address owner;
    address currentBuyer;
    uint minFunding;
    uint escrowBalance;
}

mapping(address => Machine) public machines;

modifier onlyMachines() {
    if (machines[msg.sender].exists)
    _
}

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

function () { throw; }

function VendingMachine() {

    admin=msg.sender;
}

function fundMachine(address _machineID) {
    if (msg.value < machines[_machineID].minFunding)
    throw;
    machines[_machineID].currentBuyer=msg.sender;
    machines[_machineID].isFunded = true;
    machines[_machineID].escrowBalance = msg.value;
    Unlocked(_machineID, msg.sender);
}

function executePayment(uint _price) onlyMachines {
    machines[msg.sender].escrowBalance -= _price;
    machines[msg.sender].currentBuyer.call.value(machines[msg.sender].escrowBalance)();
    CustomerPayed(machines[msg.sender].currentBuyer, machines[msg.sender].escrowBalance);
    msg.sender.call.value(_price)();
    MachinePayed(msg.sender, _price);

    //reset machine
    machines[msg.sender].escrowBalance = 0;
    machines[msg.sender].isFunded = false;

}

function registerMachine(address _machineID, address _owner, uint _minFunding) onlyAdmin {
    machines[_machineID].exists = true;
    machines[_machineID].owner = _owner;
    machines[_machineID].minFunding = _minFunding;
}

function checkAdmin() returns (address){
return admin;
}
}

After deploying and getting the contract address in context with:

var myContract = contract.at(<returned address>)

I first register a contract:

myContract.registerMachine(eth.accounts[1],eth.accounts[2],400000000000,{from:eth.coinbase,gas:4000000})

This should set machines[eth.accounts[1]].exists to true, and set some of the other struct values...but intsead nothing happens and the rest of my contract can't execute. When I take change the mapping to remove the "public" visibility, it works perfectly and I am able to execute the rest of the calls and move ether around as needed.

If anyone can help explain why adding public breaks my contract so badly I'd be very grateful. Thanks


texts: Efficiency of zkSNARKs as an Ethereum smart contract vs Zcash

texts:
How would the efficiency of zkSNARKs as an Ethereum smart contract compare to the same technology being used on its own blockchain (such as Zcash or Zclassic)?

By efficiency I mean 3 things:

Tranaction confirmation time
Transaction cost
Size of the transaction in kB


texts:
I'm new using ethereum and I have a problem trying to add liquidity to uniswap in a local network using ganache and forking from insura, this is my code:
from web3 import Web3
import json

def get_abi(file_name):
    with open("../build/Contracts/{}".format(file_name)) as f:
        info_json = json.load(f)
        abi = info_json["abi"]
        return abi

ADMIN_ADDRESS = "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"
FIRST_OWNER_ADDRESS = "0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0"
REGULATED_TOKEN_ADDRESS = "0x30407c231565675C80eDbE83995dc4FeEEF9f714"
UNISWAP_ROUTER_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"

def to_wei(value):
    return Web3.toWei(value, 'ether')

def from_wei(value):
    return Web3.fromWei(value, 'ether')

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
if w3.isConnected():
    print('Is connected')
    regulated_token_contract = w3.eth.contract(
        address=Web3.toChecksumAddress(REGULATED_TOKEN_ADDRESS),
        abi=get_abi('RegulatedToken.json')
    )
    uniswap_router_contract = w3.eth.contract(
        address=Web3.toChecksumAddress(UNISWAP_ROUTER_ADDRESS),
        abi=get_abi('UniswapV2Router02.json')
    )

    regulated_token_contract.functions.mint(FIRST_OWNER_ADDRESS, to_wei(100)).transact({"from": ADMIN_ADDRESS})

    regulated_token_contract.functions.approve(
        UNISWAP_ROUTER_ADDRESS,
        to_wei(2),
    ).transact({"from": FIRST_OWNER_ADDRESS})
    allowance = regulated_token_contract.functions.allowance(FIRST_OWNER_ADDRESS, UNISWAP_ROUTER_ADDRESS).call()
    print(from_wei(allowance))

    tx_add_liquidity_hash = uniswap_router_contract.functions.addLiquidityETH(
        REGULATED_TOKEN_ADDRESS,
        to_wei(1),
        to_wei(1),
        to_wei(1),
        FIRST_OWNER_ADDRESS,
        1618599786,
    ).transact({"from": FIRST_OWNER_ADDRESS})

else:
    print('Is no connected')

But the uniswap contract always return to me an error
revert TransferHelper: TRANSFER_FROM_FAILED

Can anyone help me with this problem?


texts: How to handle Ether and Token payment in same contract?

texts:
How do I have a single contract handle receiving payments in Ether in the constructor and receiving/transferring an ERC20 Standard Token in the same contract's methods?

constructor = receiving msg.value in Ether
contract method 1 = receiving msg.value as ERC20 Token
contract method 2 = transfer ERC20 Token to address

I understand and have implemented the receiving payment in Ether for the constructor, but I am kind of confused as to how to handle the ERC20 Standard Token in two other contract payable methods.

I understand I could keep track of the amounts of the ERC20 Token inside the contract, but I am wondering how to verify on receiving/transferring that it is that type of token?

Do I need to interface with the deployed ERC20 Token contract to hold all the values and process the transactions for this contract?


texts:
I got stuck in making two contracts interact. The code for two contracts is as follows:

Test1.sol

pragma solidity ^0.5.8;

contract Test1 {

   struct Car {
       string carCreationDate;
       string carOrigin;
       address carOwner;
   }

   mapping(uint => Car) public CarStruct;

   function setNewCar(string memory _carCreationDate, string memory _carOrigin, address _carOwner) public returns(uint) {
       uint carId = uint(keccak256(abi.encodePacked(msg.sender, now)));
       CarStruct[carId].carCreationDate = _carCreationDate;
       CarStruct[carId].carOrigin = _carOrigin;
       CarStruct[carId].carOwner = _carOwner;
       return carId;
   }
}

Test2.sol

pragma solidity ^0.5.8;
import "./Test1.sol";

contract Test2 {

    Test1 test1;
    function carAdd(string memory _carCreationDate, string memory _carOrigin, address _carOwner) public returns(uint) {
        uint carId = test1.setNewCar(_carCreationDate, _carOrigin, _carOwner);
        return (carId);
    }
}

There are no issues deploying the contracts, however when I try to implement carAdd function in Test2.sol, Remix gives me an error and I don't understand why.

Any help would be appreciated!
Thanks


texts: Can a smart contract show value in users wallet?

texts:
We want to make a smart contract that keeps track of wallets that invested and % ownership of the pool (total investments) for each wallet. Without selling tokens that represent shares of the pool, how can we show in the user wallet their value?
We want to avoid tokens because there is no open exchange involved, only investment in the pool. They should not have to use the dApp to see their ownership.
We are not opposed to tokens if we can make them non-exchangeable, mintable on purchase, and cancelable on our paying out.


texts: Is it worth to store Ether at the full precision in database?

texts:
Ether has precision of 10^18 which makes it impossible to use BIGINT type in database to store values in weis: DECIMAL type should be used instead.

Is it worth to store values in Gwei to stay with BIGINT at expenses of losing some precision? What may be negative side-effects?
What are the industry best practices for exchanges, custodian wallets? From API docs it seems Binance uses 8 digits after the decimal point.


texts: How to filter 2 indexed event fields, both fields array?

texts:
I have this event:
event onSubmissionBoth(bytes32[] indexed docHash, string[] indexed doc4DHash);

Now I log into the event like this:
function submitHash(bytes32[] calldata docHash,string[] calldata doc4DHash) external onlyOwner() {
       emit onSubmissionBoth(docHash,doc4DHash);
    }

But when I try to search it through web3.js I am a bit confused:

Can I search for docHash only? i.e only with one field.

Also trying this I get null:
contract.events.onSubmissionBoth({
filters: {docHash:["hashValue"],
doc4DHash:web3.utils.sha3(["stringValue"])}},(s,events)=>{
console.log(events)
})

Is there a way to filter the two array fields? Because I only get null everytime I do it in this way.


texts:
How do I install web3@1.0.-beta.26 on Windows 10? npm install --save web3@1.0.0-beta.26 does not work and creates a page of errors.

I've also tried --python=python2.7

Here is what I get.

C:\Users\user\inbox>npm install --save web3@1.0.0-beta.26 --python=python2.7
npm WARN deprecated fs-promise@2.0.3: Use mz or fs-extra^3.0 with Promise Support
npm WARN deprecated tar.gz@1.0.7: ⚠  WARNING ⚠ tar.gz module has been deprecated and your application is vulnerable. Please use tar module instead: https://npmjs.com/tar
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

> scrypt@6.0.3 preinstall C:\Users\user\inbox\node_modules\scrypt
> node node-scrypt-preinstall.js

> scrypt@6.0.3 install C:\Users\user\inbox\node_modules\scrypt
> node-gyp rebuild

C:\Users\user\inbox\node_modules\scrypt>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Traceback (most recent call last):
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\gyp_main.py", line 16, in <module>
    sys.exit(gyp.script_main())
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 545, in script_main
    return main(sys.argv[1:])
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 538, in main
    return gyp_main(args)
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 514, in gyp_main
    options.duplicate_basename_check)
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 98, in Load
    generator.CalculateVariables(default_variables, params)
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\generator\msvs.py", line 1916, in CalculateVariables
    generator_flags.get('msvs_version', 'auto'))
  File "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\MSVSVersion.py", line 434, in SelectVisualStudioVersion
    versions = _DetectVisualStudioVersions(version_map[version], 'e' in version)
KeyError: '2017'
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:336:16)
gyp ERR! stack     at emitTwo (events.js:126:13)
gyp ERR! stack     at ChildProcess.emit (events.js:214:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\user\inbox\node_modules\scrypt
gyp ERR! node -v v8.9.4
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
npm WARN inbox@1.0.0 No description
npm WARN inbox@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! scrypt@6.0.3 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the scrypt@6.0.3 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2018-01-17T22_41_28_270Z-debug.log


texts: where is authentication happening in web3js?

texts:
When using web3 js to connect to ethereum private network, I just configured the http provider of the web3 instance to connect to the node.

how is just info about RPC endpoint sufficient to be able to connect to a node.

shouldn't there be some user authentication in place? because with just a RPC endpoint we were able to do what ever we want with the blockchain?

Is it just like that ? or am I missing some thing here?


texts: Efficient way to save and retrieve hash in blockchain

texts:
I am learning Ethereum using Geth. I have a private blockchain and I am saving hashes through a REST API (python web service). I have readed I can save hash values using maps (mapping data type) and using logs. I am using the logs option and it works fine, but I want to know if it is the most efficient way, or if I should use a map or other kind of variable (like a string or byte array). I need to save millions of hashes (about 1 per second) so I am worried about the long-term scalability, mainly related to the search. By now I have a service saveHash(string hexHashValue) returning the transaction hash, and a service verifyHash(string hexHashValue, string transactionHash).

In python using web3.py I have this functions, I don't now if this can be improved, if using a map I can save millions of values in a better way or if I can find a specific string value in the contract using other methods. So my question is if the best way is logs, maps, strings or if the difference is trivial.

The contract:

pragma solidity ^0.5.0;

contract HashSave {
   event log_current_hash(bytes hashArg);

   constructor() public {
   }

   function set_hash(bytes memory objectHash) public {
       emit log_current_hash(objectHash);
   }
}

My current test methods using logs (event log_current_hash):

def save_new_hash(hash_bytes):
    tx_hash = contract_instance.functions.set_hash(hash_bytes).transact()
    log_test_file=open("hash_logs_simplified.txt","a")
    log_test_file.write("Hash: 0x%s Tx: %s\r\n" % (hash_bytes.hex(), tx_hash.hex()))
    log_test_file.close()
    return tx_hash.hex()

def check_transaction_exists(tx_hex_hash, obj_hash_bytes):
    try:
        tx_data = w3.eth.getTransaction(tx_hex_hash)
        if tx_data is not None:
            print("Transaction is in the blockchain")
            if find_obj_hash_in_transaction(tx_data.blockNumber, obj_hash_bytes) is True:
                return "Data validated ok"
            else:
                return "Data is not valid"
    except Exception:
        return "Transaction does't exists"

def find_obj_hash_in_transaction(block_num, obj_hash_bytes):
    hash_filter = contract_instance.events.log_current_hash.createFilter(fromBlock=block_num, toBlock=block_num,
                                                                       argument_filters={'hashArg': obj_hash_bytes})
    if hash_filter is None:
        return False
    hash_events = hash_filter.get_all_entries()
    if len(hash_events) > 0:
        return True
    else:
        return False


texts: How compatible are ICAP addresses with HD wallets?

texts:
A Hierarchical Deterministic (HD) wallet has some nice features such as easier backup (instead of needing to backup multiple keystore files and the passwords for each of them).

Since ICAP addresses  have features such as a checksum, that make them safer to use than regular hex addresses, how compatible are they with HD wallets?  Are there any implementations or roadmap for ICAP HD wallets?


texts: Mutating slot 0 of a storage array in Solidity assembly

texts:
Have been working on a function allow users to edit specific types of state using Solidity assembly, and ran into some unexpected behavior.

According to the documentation, for a storage array arr located at position p, the value at p (i.e. p + 0) is the length of the array (i.e. does not store data):

  For dynamic arrays, this slot stores the number of elements in the array.

And yet, when I attempt to mutate the value stored at position 0 (p + 0) using sstore, in fact it is the first element of the array arr[0] which is affected. I would have expected to need to add an additional offset (i.e. p + 1) to reach location arr[0].

Did I misunderstand the documentation? Does Solidity assembly know enough about the underlying storage structure to prevent me from mutating the array length directly?

Here is the function used to determine the location to be mutated. The idea is that you begin with a base storage location of a mapping, and then process a sequence of mapping keys or offsets to get the final storage location for your variable.

  bool constant MAPPING = false;
  bool constant OFFSET = true;

  function changeState(
    bytes32 baseSlot,
    bool[] memory mask,
    bytes32[] memory keys,
    bytes32 value
  )
    public
  {
    require(mask.length == keys.length, "bad-num-keys");
    bytes32 slot = baseSlot;

    for (uint256 i; i < keys.length; i++) {
      if (mask[i] == MAPPING) {
        slot = keccak256(abi.encode(keys[i], slot));
      }
      if (mask[i] == OFFSET) {
        slot = bytes32(add(uint256(keys[i]), uint256(slot)));
        if (i != keys.length - 1) { // If not last offset
          slot = keccak256(abi.encode(slot));
        }
      }

    assembly {
      sstore(slot, value)
    }
  }

And here is the storage structure I am working with:

struct MyStruct {
 address addr;
 uint256 val1;
 uint256 val2;
 uint256[] otherVals;
}

mapping(uint256 => MyStruct) myStructs;

Using this code, I was expecting to pass the following to edit the first value of the otherVals storage array, located in the myStructs mapping with a key of 0:

const baseSlot = myStructs_slot;
const mask = [F, T, T];
const keys = [0, 3, 1];

But  found that the following worked:

const baseSlot = myStructs_slot;
const mask = [F, T, T];
const keys = [0, 3, 0];


texts: Sending my first transaction, Help!... Unexpected string error

texts: I'm trying to send some ethers to another account, but I'm having some errors, please help me


texts: How can ethereum token use as payment gateway on ecommerce website

texts:
I have problem that if I created ethereum token and I want to use it in real project . especially in payment gateway . How can integrate ethereum token as payment in ecommerce website and how can develope as android wallet from ethereum token solidity codes.
plz guide me.


texts: I sent this transaction to an investment page online the name: Zinc7, but the Ethereum that i send never made it to my account.