texts: Web3j doesn't observe new blocks/transactions

texts:
I'm using Web3j 3.2.0 and Infura to get information about new blocks and transactions in Ethereum.

    val web3j = Web3j.build(HttpService("https://mainnet.infura.io/<mytoken>"))
    log.info("Connected to Ethereum client version: ${web3j.web3ClientVersion().send().getWeb3ClientVersion()})

    val startingBlock = DefaultBlockParameter.valueOf(BigInteger.valueOf(4866661))

    web3j.catchUpToLatestAndSubscribeToNewTransactionsObservable(startingBlock)
        .filter { !it.value.equals(BigInteger.ZERO) }
        .subscribe {
            println("Block #${it.blockNumber}: ${it.blockHash.substring(2..8)}.. -- Transaction Index: ${it.transactionIndex} -- From ${it.from} To ${it.to} -- Value ${it.value}")
        }

My code does the scan and shows all the blocks but doesn't continue scanning for future blocks. How can I fix this?


texts:
I'm confused about the cost of the sha256 function, because my understanding of the cost from the yellow paper ( https://ethereum.github.io/yellowpaper/paper.pdf (Appendix E. Precompiled Contracts) ) doesn't match my experiments of executing the sha256 hash function in Remix.

Here's my understanding of how much sha256 should cost for a 'word' (a 256-bit input):

From the yellow paper:

  We define Ξ_{SHA256} as a precompiled contract implementing the SHA2-256 hash function. Its gas usage is dependent on the input data size, a factor rounded up to the nearest number of words.

The gas requirement (g_r) is stated as:

  g_r = 60 + ( 12 * ( |I_d| / 32) )

(where I've edited the notation to look nicer in markdown without latex).

Elsewhere in the paper, it defines I_d as:

  I_d, the byte array that is the input data to this execution; if the execution agent is a transaction, this would be the transaction data.

So my interpretation of gas cost for a word of 256-bits (32-bytes) is:

g_r = 60 + ( 12 * 32 / 32 ) = 60 + 12 = 72 gas

However:

I've explored the gas costs of the following simple function in Remix:

function hash() public pure returns (uint256 a) {
    a = 1234;
    a = uint256(sha256(abi.encodePacked(a)));
}

This has a transaction cost of 22789 gas of which the execution cost is 1517 gas.

Now, some of this will be extraneous storage costs to store a on the stack (and other stuff).

'Commenting out' the hashing line (// a = uint256(sha256(abi.encodePacked(a)));), for a very rough comparison, gives a transaction cost of 21486 gas of which the execution cost is 214 gas.

So a very approx. experimental cost of sha256 appears to be 1517 - 214 = 1303 gas. I'm surprised at how high this cost is (given my understanding that sha256 should be just 72 gas).

Any help would be appreciated in understanding the actual cost of sha256 :)


texts: Trying to send a token with web3.py, why is the receiver's balance not going up?

texts:
When I use web3.py to send some coins from account1 to account2, account2 does not see a balance increase.

from web3 import Web3 ,HTTPProvider, IPCProvider
from solc import compile_source

addr = 'http://127.0.0.1:8545'
web3 = Web3(HTTPProvider(addr))

source_code = ' contract token { mapping (address => uint) public coinBalanceOf; event CoinTransfer(address sender, address receiver, uint amount);  function token(uint supply) { coinBalanceOf[msg.sender] = supply; } function sendCoin(address receiver, uint amount) returns(bool sufficient) { if (coinBalanceOf[msg.sender] < amount) return false; coinBalanceOf[msg.sender] -= amount; coinBalanceOf[receiver] += amount; CoinTransfer(msg.sender, receiver, amount); return true; } }'

web3.personal.unlockAccount('<insert account 1 here>','password!')

compile_sol = compile_source(source_code)
contract_address = '0xC7c1F1129726df4148B756c356Dc64cb27d763AC' #test-net

Mycontract = web3.eth.contract(abi=compile_sol['<stdin>:token']['abi'], bytecode = compile_sol['<stdin>:token']['bin'],bytecode_runtime = compile_sol['<stdin>:token']['bin-runtime'])
my_contract = Mycontract(contract_address)

print my_contract.call().coinBalanceOf(Account1)
hashs = my_contract.transact({
    'from': web3.eth.coinbase,
    'to': '<insert account 2 here>',
    'value': 231,
    'gas': 702438
}).sendCoin('<insert account 2 here>', 231)

print web3.eth.getTransaction(hashs)
print "----------------------------------\n"
print web3.eth.getTransactionReceipt(hashs)
print  hashs+"\n"
print web3.eth.getTransactionCount(web3.eth.coinbase)

print my_contract.call().coinBalanceOf('<insert account 2 here>')

Account2 doesn't have any tokens. What do I have wrong?


texts:
My transaction failed due to running out of gas. Can I recoup this money?

I was trying to send to my Bittrex wallet via my Jaxx wallet. Below is the transaction id. Could someone please help me out, as i am clueless as to what to do.

TxHash:

0xe03302a5aeb552e97bb93dd05857b50f8741fa1bc0c478c556c9c7766d1978e7


texts: Where should I put the estimate gas produced by the remix IDE in my code?

texts:
I'm creating the ERC20 smartcontract transfer with web3.
I just want to use gas optimally so that users want to do token transfer.
From the Remix IDE I got the GASESTIMATES.
But I don't know where to put this. Should I put on gas, gas price or gas limit?
I got an estimate for tokentransfer from Remix IDE is 46877.
So, where do I put this in the code?
// transfer params are _address and _amount
var parameterValues = [toAddress,transferAmount];

// I use this to get data for raw tx
var encodeAbi = web3.eth.abi.encodeFunctionCall(oneAbiFunctionHere, parameterValues);

web3.eth.getTransactionCount(addressFrom).then(function(txCount){

  var theNonce  = web3.utils.toHex(txCount);

  var theTx = {
    to: qEnv.smartcontract_address,
    value: '0x0',
    gas: web3.utils.toHex(84000),               // should I put over here?
    gasLimit: web3.utils.toHex(60000),          // or here?
    gasPrice: web3.utils.toHex(168000000000),   // or here?
    nonce: theNonce,
    chainId: qEnv.web3ChainId,
    data: encodeAbi
  };

  var tx = new EthereumTx(theTx, {chain: qEnv.web3ChainName});

  tx.sign(privateKey);

  var raw = '0x' + tx.serialize().toString('hex');

  web3.eth.sendSignedTransaction(raw, function (err, transactionHash) {
    if(transactionHash) {
      callback('success', transactionHash)
    }
    else {
      callback('fail', 'Error transfer')
    }
  });
})

Please help.


texts: Does Ethereum use Ethash or KECCAK-256 (an alias to SHA3) as hash function?

texts: Ethdoccs says that the PoW algorithm Ethereum is using is Ethash. While I was searching around for information about Ethash, I ran across this post, which indicates KECCAK is the one. So what is Ethereum actually using?


texts:
I have an event as below:

event orderResult(string status, uint32 indexed orderId);

Calling the event as below:

orderResult(status, orderId);

Using web3.js to get event data on callback as below (which is working when transaction in which above specified event involved is mined):

event.watch(function(error, result){
    if (!error)
        console.log(result);
});

After the event is stored, I want to retrieve it on button click. How can I achieve this using web3.js.

The statement below did not retrieve any stored events:

var event1 = MyContract.orderResult(function(error, result) {
    if (!error) {
        var msg = "args: " + result.args + " (block:" + result.blockNumber + ")";
        console.log(msg);
    }
});

Please suggest how can I retrieve my stored events.


texts: The value returned by command in peer_id is not unique. (ipfs name resolve peer_id)

texts:
The value returned by the command in peer_id is not unique.
For example, if you do "ipfs daemon" and the peer id listed in "ipfs swarm peers" as a list of connections, the id of your own peer is exactly the same in name resolve. Why is this?


texts: How to know the reason of transaction's reversion in parity?

texts:
I am testing ERC20 USDT contract locally with parity. I imported contract to my private testnet and manually generated raw transaction that calls "transfer" method of contract. I send it to the node using eth_sendTransaction, but it's got reverted. I want to understand the reason of it. I tried to call trace_replayTransaction rpc method, here is the result:

curl
    --data '{
        "jsonrpc":"2.0",
        "method":"trace_replayTransaction",
        "params":[
            "0x9a6df75ffa10e229b5620cb1f2079da29b7a8cbe65535bf2e8a34ed1739f1d93",
            ["stateDiff"]
        ],
        "id":1
    }'
    -H "Content-Type: application/json"
    -X POST ip:port

The result:

{
    "jsonrpc":"2.0",
    "result":{
        "output":"0x",
        "stateDiff":{
            "0x56507ba059a09b2cb64f6ec5c2aaf402184858da":{
                "balance":{
                    "*":{
                        "from":"0x42ae0",
                        "to":"0x3cf50"
                    }
                },
                "code":"=",
                "nonce":{
                    "*":{
                        "from":"0x2",
                        "to":"0x3"
                    }
                },
                "storage":{}
            },
            "0x5ed8cee6b63b1c6afce3ad7c92f4fd7e1b8fad9f":{
                "balance":{
                    "*":{
                        "from":"0x1314fb370629b3c366",
                        "to":"0x1314fb370629b41ef6"
                    }
                },
                "code":"=",
                "nonce":"=",
                "storage":{}
            }
        },
        "trace":[],
        "vmTrace":null
    },
    "id":1
}

As I can see, the output field is empty. I would be very gratefull if someone could tell me how to find out the reason for the tx reversion in parity.

EDITED:

trace_replayTransaction takes a hash of the transaction, not it's actual body. But I can also provide the exact tx too. Here it is:

{
  "jsonrpc": "2.0",
  "result": {
    "blockHash": "0x161d801c113352414c409ac35883739c41d910acefbcff52fa14e4afdf047eed",
    "blockNumber": "0xb1",
    "chainId": "0x21",
    "condition": null,
    "creates": null,
    "from": "0x56507ba059a09b2cb64f6ec5c2aaf402184858da",
    "gas": "0x13880",
    "gasPrice": "0x1",
    "hash": "0x9a6df75ffa10e229b5620cb1f2079da29b7a8cbe65535bf2e8a34ed1739f1d93",
    "input": "0xa9059cbb000000000000000000000000807e09f9b439eeb7c7b3e2cfd52fc6775f33352c00000000000000000000000000000000000000000000000000000000000000fa",
    "nonce": "0x2",
    "publicKey": "0x497104220bd7241711ca8173314894414b7d4bbd5689f8642812f2a4d55e78ec1257eeff5ed7a001115a22a1f73ac04ea974966854d79dbdb52b0875f1d14388",
    "r": "0x3999c6dfcd91c70ebeedb844585851384ddc8e259b2b059cda5cdfc7faf51dd5",
    "raw": "0xf8a50201830138809475aa3ac9799770edd6db780302fcd55e5b2cdbb201b844a9059cbb000000000000000000000000807e09f9b439eeb7c7b3e2cfd52fc6775f33352c00000000000000000000000000000000000000000000000000000000000000fa65a03999c6dfcd91c70ebeedb844585851384ddc8e259b2b059cda5cdfc7faf51dd5a0011dcf406a22c916d63f01d4359c1869524f110732b1257a708261f14383258c",
    "s": "0x11dcf406a22c916d63f01d4359c1869524f110732b1257a708261f14383258c",
    "standardV": "0x0",
    "to": "0x75aa3ac9799770edd6db780302fcd55e5b2cdbb2",
    "transactionIndex": "0x1",
    "v": "0x65",
    "value": "0x1"
  },
  "id": 1
}

The arguments of USDT transfer are in input field.

a9059cbb — hash of a trasnsfer method
000000000000000000000000807e09f9b439eeb7c7b3e2cfd52fc6775f33352c — padded destination address
00000000000000000000000000000000000000000000000000000000000000fa — padded amount that I want to transfer

Also, 0x75aa3ac9799770edd6db780302fcd55e5b2cdbb2 — addres of my local USDT contract


texts: Trying to run contract function returns error "invalid opcode"

texts:
Looks like there are a couple of unanswered threads about this already, though mine is a more simple setup so maybe it will be easier to debug.

Running through testrpc I have a deployed contract, it deploys ok. I can access a contract function displayMessage in the callback of deployed contract ok.

However, I wish run the function on another page:

const contract = web3.eth.contract(abi);
const existingContract = contract.at(contractAddress);
existingContract.displayMessage(function(response){
  console.log('displaymsg')
  console.log(response)
})

The callback function in the response var returns: Error: VM Exception while processing transaction: invalid opcode.

Running console.log(existingContract.displayMessage()) returns the same error.

I have tried manually writing out my abi variable as an array:

const abi = [{
  type: 'function',
  name: 'displayMessage',
  inputs: [],
  outputs: [],
  constant: true,
  payable: false
}]

as well as using the dynamic approach (getting from the file) just incase something was wrong there:
const abi = JSON.parse(compiledContract.contracts[':contractName'].interface)

Can anyone advise on why I would be receiving this error & how to proceed?

Edit:

As requested, here is my contract:

pragma solidity ^0.4.0;

contract contractName {
  function displayMessage() constant returns (string){
    return ("{var}");
  }
}

To give a bit more insight, when creating the initial contract, I am replacing {var} with dynamic data:

fs.readFile(__dirname+'/../solc/contract.sol', 'utf8', function(err, data){
  const source = data.replace('\{var\}', data);
  const compiled = solc.compile(source);
  ...


texts: Current Disk Space requirements for a pruned parity node?

texts:
I want to keep the disk usage to under 30GB, is it possible with --pruned fast ? Or any other config.

If its not possible, what is the smallest disk requirements as of recently


texts: Why Ethereum sets user balance to MaxBig256 whenever a contract query is performed?

texts:
There is a strange behaviour on user wallet balances when performing a contract call (that is supposed to have no cost). Balance is right (expected value) until a free call is requested to a contract. By debugging wallet balances it is found that wallet balances always turn into maximum value at this very moment.

Ethereum code has a suspicious line where this strange behaviuor seems to come from:

eth\api_backend.go(135):
    state.SetBalance(msg.From(), math.MaxBig256)

It belongs to GetEVM() function:

func (b *EthAPIBackend) GetEVM(ctx context.Context, msg core.Message, state *state.StateDB, header *types.Header) (*vm.EVM, func() error, error) {
    ======> state.SetBalance(msg.From(), math.MaxBig256)
        vmError := func() error { return nil }

        context := core.NewEVMContext(msg, header, b.eth.BlockChain(), nil)
        return vm.NewEVM(context, state, b.eth.blockchain.Config(), *b.eth.blockchain.GetVMConfig()), vmError, nil
    }

Is it there any explanation for this balance setting? Is it part of the protocol? Any hint? Thx a lot!

I read at Why does function GetEVM set the balance of from address to MaxBig256?

that this is a temporary balance setting, but I still don't get the logic behind this weird behaviour. It seems to me a messy code to avoid a lack of funds problem when calling a contract, right?


texts: MetaMask verification on a server with web3.personal.sign

texts:
How to verify MetaMask account holder is the real owner of the address?

I recently saw this post and tried it immediately, unfortunately, I am not getting the right result from the server. I think it has something to do with the hashing algorithm sha3, but I am not sure. Could anyone please update the solution? Thank you!


texts: How to collect addresses with balance more then 1 ether using dump/snapshot

texts:
I need to get addresses from some latest block.
I tried geth but is very slow. With parity I got some problems.
Do you have any suggestions?


texts: I am trying to call a third party REST API that I developed using spring boot, and I want to call a function(param1,param2) in the API from the oracle using the oraclize_query() (POST request), but I kind of don't know how to pass the parameters in oraclize_query()!!


texts:
Could somebody help me out please? I'm really stuck creating a Private Ethereum Network and undestadning what the nodes are mining.

SO : Windows

Ethereum Client : Go-Ethereum

Here is my genesis.json:

{
"config": {
    "chainId": 9354,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
},
"alloc": {
    "8ef3b17dfd837ba9db963cb4aec03385cb58d366" : {"balance" : "1000000000000000000"}
},
"difficulty" : "0x20000",
"gasLimit"   : "0x8880000"}

I initialized the blockchain with following command in a terminal (T1):

geth --datadir pblkchain init genesis.json

Then started geth :

geth --port 3000 --networkid 9354 --nodiscover --datadir=./pblkchain --maxpeers=0 --unlock 8ef3b17dfd837ba9db963cb4aec03385cb58d366 --rpc --rpcport 8543 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner"

After that, I open a new terminal (T2) and attached via rpc :

geth attach http://127.0.0.1:8543

Finally I deployed my Truffle project to that private network in third terminal (T3) :

    truffle compile
    truffle migrate --reset

With all that steps the smart contracts are deployed at the private network, but actually there is nobody mining. So in T2, we'll init a miner:

miner.start()

After init the miner, the smart contracts are really introduced into the blockchain.

At the terminal it's able to see the smart contract address which are being deployed. After the smart contract is deployed, in my terminal appear messages that keep importing blocks, but I'm not generating more transactions, what is it?.

PS C:\Users\xmaltas\Desktop\PrivateNetwork\network> geth --port 3000 --networkid 9354 --nodiscover --datadir=./pblkchain --maxpeers=0 --rpc --rpcport 8543 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner" --unlock 8ef3b17dfd837ba9db963cb4aec03385cb58d366
INFO [03-08|13:16:41.833] Maximum peer count ETH=0 LES=0 total=0
INFO [03-08|13:16:41.905] Starting peer-to-peer node instance=Geth/v1.8.21-stable-9dc5d1a9/windows-amd64/go1.11.4
INFO [03-08|13:16:41.911] Allocated cache and file handles database=C:\\Users\\xmaltas\\Desktop\\PrivateNetwork\\network\\pblkchain\\geth\\chaindata cache=512 handles=8192
INFO [03-08|13:16:41.986] Initialised chain configuration config="{ChainID: 143 Homestead: 0 DAO: <nil> DAOSupport: false EIP150: <nil> EIP155: 0 EIP158: 0 Byzantium: <nil> Constantinople: <nil> Engine: unknown}"
INFO [03-08|13:16:41.995] Disk storage enabled for ethash caches dir=C:\\Users\\xmaltas\\Desktop\\PrivateNetwork\\network\\pblkchain\\geth\\ethash count=3
INFO [03-08|13:16:42.002] Disk storage enabled for ethash DAGs dir=C:\\Users\\xmaltas\\AppData\\Ethash count=2
INFO [03-08|13:16:42.012] Initialising Ethereum protocol versions="[63 62]" network=9354
INFO [03-08|13:16:42.109] Loaded most recent local header number=562 hash=d2e805…b5590e td=84636417 age=1h15m58s
INFO [03-08|13:16:42.115] Loaded most recent local full block number=562 hash=d2e805…b5590e td=84636417 age=1h15m58s
INFO [03-08|13:16:42.120] Loaded most recent local fast block number=562 hash=d2e805…b5590e td=84636417 age=1h15m58s
INFO [03-08|13:16:42.129] Loaded local transaction journal transactions=4 dropped=4
INFO [03-08|13:16:42.135] Regenerated local transaction journal transactions=0 accounts=0
WARN [03-08|13:16:42.140] Blockchain not empty, fast sync disabled
INFO [03-08|13:16:42.191] New local node record


texts: Geth light keeps showing "Looking for peers"

texts:
My Geth server in light mode was running without any issue up to yesterday. But after that, I only receive these messages continuously!

INFO [04-19|12:59:22.181] Looking for peers                        peercount=0 tried=9  static=29
INFO [04-19|12:59:35.670] Looking for peers                        peercount=0 tried=3  static=29
INFO [04-19|12:59:46.432] Looking for peers                        peercount=0 tried=17 static=29
INFO [04-19|12:59:57.181] Looking for peers                        peercount=0 tried=9  static=29
INFO [04-19|13:00:10.671] Looking for peers                        peercount=0 tried=3  static=29
INFO [04-19|13:00:21.408] Looking for peers                        peercount=0 tried=17 static=29
INFO [04-19|13:00:32.182] Looking for peers                        peercount=0 tried=9  static=29
INFO [04-19|13:00:45.671] Looking for peers                        peercount=0 tried=3  static=29
INFO [04-19|13:00:56.416] Looking for peers                        peercount=0 tried=17 static=29
INFO [04-19|13:01:07.182] Looking for peers                        peercount=0 tried=9  static=29
INFO [04-19|13:01:20.672] Looking for peers                        peercount=0 tried=3  static=29

And this does not finish!

May you help me to solve this issue please?


texts: How do geth and parity handle notifying clients of events after reorgs?

texts:
If you set up an event listener with Geth (I assume also with Parity) you get notifications when a particular event shows up in the event logs.

Sometimes a reorg will happen, and the block where that event happened will be orphaned and disappear from the main history. The same transaction may cause an event to be raised in a different block.

Is the following correct?

An event will always be fired when a block generating that event gets into what the node considers the main chain
If there's a big reorg events several blocks deep will be sent out almost simultaneously
An event will still be sent out again even if its content (aside from block hash etc) is the same, so for example if you listen for a contract that raises an event when it's paid, you may get the same event twice even though you'll ultimately only end up getting paid once

Are there any traps for the unwary or interesting implementation-specific wrinkles?


texts: I'm making a mobile wallet to send and receive ERC20 tokens, I finished with the code to Send and Receive, but I don't know what to do if a Token Contract Address changes, what happen if somebody have BAT (for example) and they change de address, do I need to do something? thanks.


texts: Retrieve specific account in truffle 5 console

texts:
I am following a truffle tutorial where the individual users web3.eth.accounts to retrieve all the accounts from Ganash. However that seemed depreciated and to duplicate his results I used web3.eth.getAccounts() as you can see below.

However a next command is ran in truffle console web3.eth.accounts[0] which presents account at position 1 (well the first account).

Ultimately, this is my problem as I cannot yet figure out how to accomplish the same in truffle 5.I have tried web3.eth.getAccounts([0]) and web3.eth.getAccounts().then(e => let firstAcc=e[0]; console.log(firstAcc)); which was suggested but neither works. Appreciate any help or guidance I could receive to assist me with this small issue.

Regards


texts: Endowing Contract Created via Factory with Specific Arguments

texts:
I'm trying to make a factory contract that accomplishes two things:

Create contracts and endow them at creation with specific parameters
Maintain a mapping of structs with info of all created contracts

Here is my code, then I will explain my question.

pragma solidity ^0.4.18;
import "SimplePurchase.sol"; //this is the child contract being created

contract PurchaseCreator {
    struct PurchaseData {
        address seller;
        uint txnValue;
    }

    //Creates new child contract & stores info in mapping
    function newSimplePurchaseContract(address seller, uint txnValue) isActive public payable returns (SimplePurchase newPurch, uint PurchaseId) {
        PurchaseId = nextPurchaseId++;
        seller = msg.sender;
        txnValue = msg.value;
        purchases[PurchaseId] = PurchaseData(seller, txnValue);

        newPurch = (new SimplePurchase).value(txnValue)();

        return(newPurch, PurchaseId);
    }
}

Here are my two questions:

When I create the child contract, is it possible to pass through the seller, txnValue, and PurchaseId from the function newSimplePurchaseContract? I'm currently passing the txnValue, but I'm just not sure if it's possible to pass through anything besides value based on reading the solidity docs.
Can the child contract pass information back to this contract to be added to the mapping? I'd like to hold a "buyer" address in the mapping struct as well, but with the way my user flow is set up, I won't know the buyer until the child contract is created.

Let me know if I'm unclear with my question. I've scoured stack exchange and the solidity docs to try to figure this out and haven't found answers, so I apologize if this is a duplicate.

Thanks for your help!


texts: Updated geth, now I am re-syncing the whole blockchain

texts:
This is the first time I have updated geth.

I was at a build of geth from several weeks ago, and this morning I updated to 1.4.12.  I downloaded the pre-built binary to a new location on disk, started it up, then ran geth attach and was surprised that my ether account balance was 0.  I then realized that the whole blockchain was re-syncing by running web3.eth.syncing.

I am assuming that when the sync is complete, I will be back to normal, but I am guessing there is a better way to do this?  How does one update to a new version of geth without having to go get the whole blockchain again?  Or have I misunderstood what is happening?


texts: I want to connect Ballot Dapp to Metamask but it Shows "rpc error with payload" and "ALERT: Trying to call a function on a non-contract address".


texts: Yellow Paper Section 4:1 (6) and (7) explanation help needed:

texts: Can anyone please explain this (6) and (7) and what does "element-wise transformation means"?


texts: Untitleded.sol:5:27: TypeError: Data location must be "memory" for parameter in function, but none was given

texts:
Im using solidity version 0.5.1(Ik they are vulnabilities in that version).
Im getting this erorr saying
"Untitleded.sol:5:49: TypeError: Data location must be "memory" for return parameter in function, but none was given. function chatfunction() view public returns(string){ ^----^"
This is the code
pragma solidity 0.5.1;

contract chat{
   event sendmessage(string mesg);
   function chatfunction() view public returns(string){
       emit sendmessage(message);
       return message;
   }
}

I dont see the erorr.


texts:
I am using truffle to write smart contracts , my code and deployments work well on local ethereum rpc.

Now i added another environment in "truffle.js" file with url to my azure "Ethereum Consortium Leader" rpc .

When I first tried to deploy, i got Locked account error. Then I unlocked my account using provided credentials during setup, using powershell and ssh address also taken from azure deployment.

However now the locked account error goes away.. but my deployment is stuck "Deploying initial_migration.." for few hours now..

Is there anywhere I can find what's wrong? it works perfect locally.


texts: How to avoid an error caused by wrong determining of gas consumption

texts:
I have a function that is being called by multiple users (say 3). That value is set by owner earlier as a constant. Inside this function there's a check whether it's the last user (3) or not. If yes then another function executes. It means that the last user pays more gas (figured it out suddenly).
So, if the transaction of the second user has not been completed yet and the third user starts a transaction, he pays the same amount of gas as the second user because contract still doesn't know if it's the last transaction (user).
Let's say the second transaction has been completed while the third is executing. And the error occurs because the third user became the last one and needed more gas to pay now. Maybe is there any way to avoid that behavior?
Example of that function:

function pay() payable external {
    cur += 1;
    require(cur <= max);
    players[msg.sender] = true;
    playerKeys.push(msg.sender);
    if (cur == max){
        anotherFunction();
    }
}


texts: I send from my MIST unnamed wallet 25 ETH to Yobit. Are my coins lost?

texts:
I send from my unnamed Contract wallet 25 ETH to Yobit. In the etherchain it sayed and shown as Internal Transactions.

So does discriminate between unnamed and base-wallets? The 25 ETHER It never reacted my Yobit Wallet :-(
A second dipost of 20 Ether from my mist base-wallet did come true.
What happened to the 25 Ether?  Why di9d my stupt wallet let me send Ether if its not possible to yobit.
See:  http://etherscan.io/tx/0xcbb81a6aaa5687fbc1ae53a1a86f79b0e2fa982019964db3fe93f841174f104f

Are my coins lost? Can youbit still get my coins?


texts: No network fee for internal ERC20 token transfer on the exchange

texts:
I came across scenario where there is no network fee (gas) charged for transferring utility token from one wallet to another wallet on the same exchange. It means the token was transferred internally.

Is that correct that there is no gas required to transfer token in internal network?


texts: getting contract address on remix compiler

texts:
When a contract is deployed on remix online web compiler, it displays the deployment by  showing:

browser/thecontract.sol:TheContract at 0xb9b...3de18 (blockchain)

How can we copy/paste the full contract address on remix ?  It is only showing
a part of it  0xb9b...3de18.

Remix is providing copy buttons for account addresses, but i cannot see any copy button for deployed contracts.


texts:
I use pragma 0.6.2. I am trying copile in truffle code which contain this lines:
fallback() external payable{}
I an getting error:
The payable fallback function is defined here.
fallback() external payable{}
^---------------------------^


texts: Transactions and smart contracts during reorganization

texts:
I learned from this question that transactions will be reverted and rollback after chain reorganization. But after a transaction is reverted, will the sender needs to resend this transaction? Or this transaction will automatically go into transactions pool and wait to be included in a new block?

When it comes to smart contracts, how smart contracts deal with this kind of revert/rollback problems due to chain reorganization?


texts: Proper way to design a descentralized game

texts:
Let's say I'm designing a multiplayer game, where players can fight each other in different battles. As a result of each battle, players get a punctuation. Suppose I'm using a sidechain. Which should be the a property way to decentralize the game?

a) battles are computed in servers, and only the final punctuation for each player is stored in the smart contract of the sidechain

b) battles are computed in smart contracts, and all the other change in parameters of the game are computed also in smart contracts (in sidechain)

Finally, following plasma protocol, I persist compressed data to the ethereum mainnet with some regularity...


texts: How to deploy smart contract so that average user can interact with its public functions?

texts:
I sucesfully wrote and deployed smart contract using Remix and Metask to generate hashes used as keys. This contract has few payable public functions that set or get some numbers. After deploying using Remix on mainnet, I can see "buttons"  and "text input box" in left bottom corner that can be used for interaction with contract public function.

But I need that my customer is able to interact with contract (using "buttons"  and "text input box" ).

I tried https://www.myetherwallet.com without success. After inserting ABI and bytecode, deploying contract  there was no "buttons" or "text input box" for user interaction.

After, I tried to use https://justsmartcontracts.dev. After inserting ABI and contract address, in window "Cals" or "operations"  there was no "buttons" or "text input box" for user interaction. I was onlz able to see public variables, but no public functions. Also there was problems with metamask connection.

Which software/wallet/webpage can provide "buttons" or "text input box" so that average ethererum user can interact with this smart contract?

Thank you for help


texts: go-ethereum: SimulateBackend AdjustTime is not adjusting time at all, or either in unexpected ways

texts:
While using SimulateBackend I attempted to roll forward the time of the simulated blockchain using AdjustTime(604800 *time.Second) which should roll forward time by a week. Checking the returned error value shows that it is nil, however from all my testing it appears that time does not actually roll forward, and local system time is used. Attempting to call functions which should work after time is rolled forward, do not work.

go version: go1.10.11 linux/amd64

Using the lates go-ethereum version.


texts: `deployments.get` not allowing me to call functions

texts:
I have a contract that is deployed when I run a hardhat deploy.
pragma solidity >=0.7.0 <0.9.0;
contract SampleCode {
    uint256 public variable;

    constructor() public {
        variable = 5;
    }

    function getVariable() public view returns(uint256){
        return variable;
    }
}

And I deploy it with :
deployments.deploy('SampleCode', {...})

But when I try to call my function, I am unable to:
sampleCode = await deployments.get("SampleCode")
sampleCode.getVariable()

With:
Uncaught TypeError: sampleCode.getVariable is not a function

What gives?


texts: Uncaught Exception: Unknown error when sending transaction

texts:
I am trying to deploy a Smart contract using truffle / web3js.  The script has been deploying smart contracts for months and I am suddenly facing this error:
error: uncaughtException: Unknown error when sending transaction.
2021-03-22T03:19:36.912282+00:00 app[web.2]: Error(Ethkey(InvalidSignature), State { next_error: None, backtrace: InternalBacktrace { backtrace: None } })
2021-03-22T03:19:36.912283+00:00 app[web.2]: Error: Unknown error when sending transaction.
2021-03-22T03:19:36.912283+00:00 app[web.2]: Error(Ethkey(InvalidSignature), State { next_error: None, backtrace: InternalBacktrace { backtrace: None } })
2021-03-22T03:19:36.912283+00:00 app[web.2]: at Object._fireError (/cache/node_modules/web3-utils/lib/index.js:50:17)
2021-03-22T03:19:36.912284+00:00 app[web.2]: at sendTxCallback (/cache/node_modules/web3-core-method/lib/index.js:540:30)
2021-03-22T03:19:36.912284+00:00 app[web.2]: at /cache/node_modules/web3-core-requestmanager/lib/index.js:300:20
2021-03-22T03:19:36.912285+00:00 app[web.2]: at /cache/node_modules/@trufflesuite/web3-provider-engine/index.js:238:9
2021-03-22T03:19:36.912285+00:00 app[web.2]: at /cache/node_modules/async/internal/once.js:12:16
2021-03-22T03:19:36.912286+00:00 app[web.2]: at replenish (/cache/node_modules/async/internal/eachOfLimit.js:61:25)
2021-03-22T03:19:36.912286+00:00 app[web.2]: at /cache/node_modules/async/internal/eachOfLimit.js:71:9
2021-03-22T03:19:36.912286+00:00 app[web.2]: at eachLimit (/cache/node_modules/async/eachLimit.js:43:36)
2021-03-22T03:19:36.912287+00:00 app[web.2]: at /cache/node_modules/async/internal/doLimit.js:9:16
2021-03-22T03:19:36.912287+00:00 app[web.2]: at end (/cache/node_modules/@trufflesuite/web3-provider-engine/index.js:217:5)
2021-03-22T03:19:36.912288+00:00 app[web.2]: at /cache/node_modules/async/internal/once.js:12:16
2021-03-22T03:19:36.912288+00:00 app[web.2]: at next (/cache/node_modules/async/waterfall.js:21:29)
2021-03-22T03:19:36.912288+00:00 app[web.2]: at /cache/node_modules/async/internal/onlyOnce.js:12:16
2021-03-22T03:19:36.912289+00:00 app[web.2]: at /cache/node_modules/async/internal/once.js:12:16
2021-03-22T03:19:36.912289+00:00 app[web.2]: at next (/cache/node_modules/async/waterfall.js:21:29)
2021-03-22T03:19:36.912299+00:00 app[web.2]: at /cache/node_modules/async/internal/onlyOnce.js:12:16

The funny part is that I am facing this issue only when deploying from my heroku server.  When deploying from local (using docker) there is no issue.
I have checked that al the env are properly stored in heroku.
I have cleared the node_modules cache on heroku and confirmed that the web3js version is 1.3.4.
Cannot seem to figure out what the error is and why.


texts: How to get privateKey from Metamask by code?

texts: Try to create ether wallet by privateKey from Metamask account


texts: Creating Custom Wallet for my ERC20 Token

texts:
I am currently working on a project for school, I just finished writing my smart contract.
A buddy of mine is going to make a custom wallet for me since it will help for his class project.
We are reading that when you have ERC20 Tokens you are required to hold ETH as well for the gas fee's for transacting across the ETH block chain to target my smart contract.
NOW this is where I find little research.
How do you make it so Token holders DO NOT NEED to hold ETH as well?
Where the contract takes it from the custom tokens total amount.
Say your wallet has 200 of example token.
You want to send 150 of example token.
It then takes the required amount of Example token from their total amount or transaction amount and pays for the transaction fee's allowing for simplistic trading and conversion.
Is there a line of code I need for this perform?


texts: Refund some ethers from smart contract and send the rest to an account

texts: Let's say we want to make a transaction of x ether and if (x>20) refund 5% to sender and send rest to the original initial receiver.How can I implement it in smart contract code, and invoke it from console ? should I send ether to contract and receiver's address in data or something like that...


texts: Can we extend ethereum client or smart contract to use external libraries?

texts: Basically the question is to extend the ethereum clients to bring some capabilities of external libraries on the blockchain either by extending the ethereum client or by using inside smart contracts and solidity


texts: Who/what makes up the nodes of the testnet?

texts: Is the testnet centralized?  Like is there a foundation that maintains the testnet nodes?  Or is it just a lot of people who want to support testing?


texts: ethereum makes extra space for no reason in memory

texts:
pragma solidity ^0.6.8;

contract C {
    function test3(uint f) external  returns(uint256[3] memory) {
        uint256[3] memory arr;
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        return arr;
    }
}

contract A {

    function test(C addr) external returns(uint) {
        uint256[3] memory  z =addr.test3(31);
        return z[0] + z[1] + z[2];
    }

}

I have the following code. I looked at memory before and after the call opcode is used. Here is the difference..
https://www.diffchecker.com/NZtopQv4
If you see on this link , it's very strange. The second snippet in the link is after the call code is executed, meaning that returned value is put in the caller's contract's memory, but from 0x80 to 0xd0, the bytes are still zero and the array got stored from 0xe0 to 0x130.
So, why did it create 0x80 to 0xd0 for no reason ?  I see that it might have created it for z variable before it would call call opcode, but then, it then put the returned value in different memory space. Is Solidity Stupid ?


texts: Call a smart contract function when condition met

texts:
I am currently developing a smart contract with several states:

enum State {created, accepted, over}

Depending on the state, users are allowed to perform different action. What I would like to do, is to automatically trigger a function when "accepted" has been set, without calling the function. The reason for that is that I want users to proceed step by step: I want the user to see that the "accepted state" is the current one, and that another function was called to transition to the "over" state.

Let's imagine the following code: I want the "close" function to be triggered when currentState becomes "accepted" but I still want the function accept() to return a value after currentState has been set.

function accept() public onlyState(State.created) payable returns (bool) {
    player2 = msg.sender;
    currentState = State.accepted;
    return true;
}

function close() internal onlyState(GameState.accepted) returns (bool) {
        currentState = State.over;
        return true;
}


texts: Uncaught ReferenceError: Web3 is not defined Solidity

texts:
I've been working with this project and I downloaded all dependencies and Web3 already but when I test my code it shows me this:

Uncaught ReferenceError: Web3 is not defined

in line 120.

This is my code:

<script>
if(typeof web3 !== 'undefined'){
    web3 = new Web3(web3.currentProvider); -this is where it errors
}else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

web3.eth.defaultAccount = web3.eth.accounts[0];

var SuffrageContract = web3.eth.contract('example');
var Suffrage = SuffrageContract.at('example');
console.log(Suffrage);

I have already tried several methods like declaring

web3 = required('web3');

but it is still not working.


texts: where to host my react fornt end and express endpoint that interact with smart contract to be fully decentralised?

texts: where to host my react fornt end and express endpoint that interact with smart contract to be fully decentralised. Are there any option to host it decentralised any cloud provider other than traditional centralised options like aws,gcp,azure. IPFS and Storj are file storage i want to run my reactjs fornt end app.


texts: ROPSTEN: Duplicate Blocks adding transactions using Geth Real-Time Event API

texts:
I'm using the Geth Real-Time Event to get the new blocks via web-socket and there's a subscription called "newHeads" for that propose.
The thing is sometimes the socket returns a duplicate block with different content. Why?
I'm using "Simple Websocket Client" extension for the socket.
Look at the attached picture and check block number "0x9073d7"

This is a diff of the content of both blocks: https://www.diffchecker.com/2UUt8n6H


texts: GetPastEvents From Web3 - Return Zero . instead Number of transactions?

texts:
I tried This Code With The GetPastEvents to get Transactions from a smart contract. but the console return 0 . and the error is Null.

Check the code below . Help me fix this please!!

const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/v3/......')

const abi = [ABI_CODE_FROM_SMARTCONTRACT]
const address = '0x95dAaaB98046846bF4B2853e23cba236fa394A31'

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

contract.getPastEvents('allEvents', {fromBlock: 9851116, toBlock:'latest'}, (err, events) => {
    console.log(events.length)
})


texts: Can't get deployed contract address through web3 API

texts:
I am trying to deploy a contract in Ethereum testnet, with the web3 API via my geth node. The contract is deployed correctly and I can see the address in geth and verify it exists on etherscan. However I can't get the contract address working in my javascript. My code is:

var myContractReturned = web3.eth.contract(abi).new({data: code,gas:500000}, function (err, contract) {
  if(err) {
    console.error(err);
    return;
  } else if(contract.address){
    console.log('ContractAddress: ' + contract.address);
    document.getElementById('status').innerText = 'Mined!';
  }else{
    console.log('ContractAddress: ' + contract.address);
  }
});

In the If statement the only part that is executed is the "else" and contract.address returns undefined.


texts: Solidity PRNG with future block hashes: reasonable secure?

texts:
I would like someone to tell me if I am neglecting serious security concerns here. I Am trying to create a Solidity slot machine where hash puzzles (leading zeros) are used to get various jackpots. However, I can't just use a nonce as someone could test nonces offchain and submit the winning one first try. So I've been looking into PRNGs. And I found future blockhashes to be a solid idea as it's very unlikely a miner will be the creator of each and every block in a sequence. The code bellow is a quick simple example of logic for a lottery contract where users submit guesses that must "vest" a number of blocks before they can be checked for a win.
    contract Lottery{

    uint128 difficulty;
    uint128 immutable public BLOCK_VEST_PERIOD;
    mapping(address => guess) entry;

    struct guess{
        bytes32 guess;
        uint256 vestEnd;
    }

    constructor(uint128 _vestPeriod, uint128 _difficulty){
        BLOCK_VEST_PERIOD = _vestPeriod;
        difficulty = _difficulty;
    }

    function submitEntry(uint128 _x)external{
        entry[msg.sender] = guess(
            keccak256(abi.encodePacked(_x)),           //guess is stored as the hash of the number entry
            block.number + BLOCK_VEST_PERIOD
        );
    }

    /// @dev returns true if entry is a winner
    function claimEntry()external returns(bool){
        require(block.number - entry[msg.sender].vestEnd < 256, "cannot claimEntry if more than 255 blocks have passed");
        require(block.number >= entry[msg.sender].vestEnd, "must wait a few more blocks for vesting to end. For security reasons");
        bytes32 hash = entry[msg.sender].guess;
        for(uint128 i = 0; i < BLOCK_VEST_PERIOD; i++){
            hash = keccak256(abi.encodePacked(
                hash,
                blockhash(i)
                ));
        }
        return hashPuzzle(hash);
    }

    function hashPuzzle(bytes32 _entry) public returns(bool){
        /// @dev will return true if hash's leading 0s >= difficulty
    }

}

As far as I can tell the only way to cheat this system would be to have control of every block or at least the last block as a miner could discard it if unfavorable to get a second chance. However, this seems to be a negligible advantage in practice, especially if a hash puzzle is sufficiently difficult. Please let me know if I am wrong about this.


texts: Error while I am compiling the contract using node

texts:
saitejas-MacBook-Air:Inbox saitejakuruva$ sudo node compile.js assert.js:340
throw err;
^

  AssertionError [ERR_ASSERTION]: Invalid callback specified.
      at wrapCallback (/Users/saitejakuruva/node_modules/solc/wrapper.js:16:5)
      at runWithReadCallback (/Users/saitejakuruva/node_modules/solc/wrapper.js:42:26)
      at compileStandard (/Users/saitejakuruva/node_modules/solc/wrapper.js:83:14)
      at Object.compileStandardWrapper (/Users/saitejakuruva/node_modules/solc/wrapper.js:90:14)
      at Object. (/Users/saitejakuruva/Documents/Inbox/compile.js:6:18)
      at Module._compile (internal/modules/cjs/loader.js:799:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:810:10)
      at Module.load (internal/modules/cjs/loader.js:666:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:606:12)
      at Function.Module._load (internal/modules/cjs/loader.js:598:3)

I have faced the above error when I am trying to compile a simple solidity contract.I am also providing the link of the code that I have written for compiling the contract.

https://i.imgur.com/aQ8ntUW.png
Please help me out asap.


texts:
Can't really use the transfer function as it is written. It assumes the owner uses it. So made a new function for the "minting" function for the faucet to use. Not sure why the compiler message is so cryptic.

totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);

Trying to create a Faucet for my ERC-20 Token, and getting a "Gas Estimation Failed" when running my dripToken function which looks like this (UPDATED):

function dripToken() public {
  require(faucetStatus);
  if(!checkStatus(msg.sender)) revert();
  tokenInstance.updateSupply(oneToken);
  updateStatus(msg.sender, oneMinute);
  tokenInstance.transfer(msg.sender, oneToken);
}

I have narrowed it down to the line with the transfer call which causes the error. I now deploy my ERC-20 Token and pass that into the faucet contract on the following way:

constructor(string _fname, address _tokenInstance) public {
  tokenInstance = MyToken(_tokenInstance);
  faucetName = _fname;
  faucetStatus = true;

  emit FaucetOn(faucetStatus);
}

My Token transfer function is from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/StandardToken.sol
I just noticed I get a compiler warning on the transfer function which hints at the problem, but I don't understand why (yet).
Here is the warning:

  Gas requirement of function StandardToken.transfer(address,uint256) high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)

function transfer(address _to, uint256 _value) public returns (bool) {
  require(_value <= balances[msg.sender]);
  require(_to != address(0));

  balances[msg.sender] = balances[msg.sender].sub(_value);
  balances[_to] = balances[_to].add(_value);
  emit Transfer(msg.sender, _to, _value);
  return true;
}

I create my Token in the following way. I now initialize it with a small supply.

contract MyToken is StandardToken {
  string public name;
  uint8 public decimals;
  string public symbol;

  constructor() public {
    StandardToken.balances[msg.sender] = 1000000000000000000;
    StandardToken.totalSupply_ = 1000000000000000000;
    name = "My Token";
    decimals = 18;
    symbol = "MY";
  }
}

Posted my code on google drive:
https://drive.google.com/open?id=1EvKEVhD8bR2oKS2W1XNRQpTqVbieUcmC


texts: Drizzle React Component ContractData for array returns empty

texts:
<ContractData
  contract="TheContract"
  method="getData"
  methodArgs={[accounts[0], "0", { from: accounts[0] }]}
/>

and a contract view function

function getData() public view returns (string, string, uint) {
  return (
    "x",
    "y",
    0
  );
}

The React component renders the  that you would expect for the return of an array but none of the list items.

I can confirm that the function does return the items in Remix.


texts: To transfer ERC20 tokens (using Web3js), is it necessary to implement web.eth.Contract?

texts:
I'm kind of new to Ethereum network. I used to implement Stellar before.
I have successfully implemented my JavaScript app to transfer Eth already.
Therefore, I want to expand my above app to accept/transfer ERC20 tokens on the markets, by still using web3js, I wonder

Do I have to implement web3.eth.Contract for my app wallet to achieve ERC20 tokens compatible ?
If not, is there any other easy ways to implement this ?
What is the SOME_ERC20_FILE.json file as shown in code below (that is related to ABI) ? Where can I get an example of this JSON file ?

const fs = require('fs');
const parsedFile = JSON.parse(fs.readFileSync(SOME_ERC20_FILE.json));
const abi = parsedFile.abi;
const myContract = new web3.eth.Contract(abi, 0x012345678912345678012345678012345678012);

Thank you in advance.


texts: What does "Time" in the Geth VM Trace Transaction refer to?


texts: How to use erc20 transfer in another contract in remix ethereum using metamask?

texts:
I read a lot of documentation in here and another web pages, I have a question and I so tried to solved but nothing works for me.

I am using this example.

It works fine with truffle, but I don't know what I need to do to make this work fine using metamask.

The problem is the next:

Create a ERC20 Token // works
Import the IRC20 Token Contract to Another Contract Named "TokenReceiver" // I think I do correctly, I only copy and paste to test in remix ethereum.
Deploy, Use doStuff function into the new Contract "TokenReceiver" // Error here

The error says:

  Gas estimation errored with the following message (see below). The
  transaction execution will likely fail. Do you want to force sending?
  gas required exceeds allowance (10000000) or always failing
  transaction

The code is the same:

pragma solidity ^0.5.0;

import "./IERC20.sol";

/**
 * @title TokenReceiver
 * @dev Very simple example of a contract receiving ERC20 tokens.
 */
contract TokenReceiver {

    IERC20 private _token;

    event DoneStuff(address from);

    /**
     * @dev Constructor sets token that can be received
     */
    constructor (IERC20 token) public {
        _token = token;
    }

    /**
     * @dev Do stuff, requires tokens
     */
    function doStuff() external {

        address from = msg.sender;

        _token.transferFrom(from, address(this), 1000);

        emit DoneStuff(from);

    }
}

I read a lot but I really know I am doing something wrong but I don't know what it is, reading I see that I need to approve the function before using transfer, but nothing works for me, I am trying do this and the error is the same and I don't see the approve window with metamask:

function doStuff() external {

    address from = msg.sender;

    _token.approve(from,1000); // i trying adding this line

    _token.transferFrom(from, address(this), 1000);

    emit DoneStuff(from);

}

Somebody help me please, it is hard for me to understand what's happening but I really want to know what I am doing wrong.


texts: What is the ethereum account abstraction?

texts: This is coming up in Metropolis, but I'm having a real hard time finding an understandable explanation.


texts:
I tried launching a private POW etherium blockchain. Following is what I observed.
Attempt 1
2 node network. Node1 is a miner, node2 doesnt not sync
Attempt 2
2 nodes network. Node1  is a miner, send 1 eth transfer, node 2 doesnt sync
Attempt 3
3 node network. node1 is miner. node2 and node3 dont sync
Attempt 4
3 network. node1 is miner, sent eth transfer. Syncing works properly.
Are there any docs that explain this behaviour? I know that 2 nodes in a blockchain network makes no sense, but was wondering is there are some docs that explains this.


texts:
problem with retrieving decimal value.
Example:
ufixed8x2 profit = 0;
uint256 amount = 5000000; //msg.value;
 uint256 constant private PERCENT_DIVIDER = 1;

profit= ufixed8x2(amount.div(24).div(60).div(60).mul(PERCENT_DIVIDER).div(100));

Output is 0 - wrong must be 0.57
Please help


texts: Hi is it possible to send token XYZQ to two addresses in one transaction. here is example. 100 XYZQ ===> 99.9999 to XYZQ 1 address and 0.0001 XYZQ to second XYZQ address? For same amount of gas


texts: In Ethereum, a smart contract can get external datafeed via oracle services. Does Eris also support such oracle services?


texts: Setup Etherum private blocjchain on server?

texts:
I have an issue of connecting Ethereum private node on that particular Ip server in which I setup the ethereum node.I create a gui of server enbale json rpc client on 127.0.0.1:8545.When I connect this address with web3 on my server gui I open browser and hit my address "3.10.9.248/index.php" It shows connected with this "127.0.0.1:8545" and I am getting my ethereum node address and balance.When I hit this address outside the GUI of server 3.10.9.248/index.php then its shows nothing.

Its shows private node is running only in node GUI browser not in any other browser.I want to create an API for ethereum node and provide access to another website to use that API.

Thanks


texts:
Does it save gas to link to the bytecode of an interface? I tested this is solidity remix and using the interface to link bytecode instead of the full contract, didn't seem to reduce any gas costs for deployment.
Am I mistaken that the bytecode of an interface is smaller than the full contract?


texts: Warning! Error encountered during contract execution [Bad jump destination] / missing ETH

texts:
Can some one please advise if I understand this correctly.

This evening, I received the above error warning with a transaction.

The relevant ETH is currently missing from my wallet.

Do I understand correctly that the missing ETH will automatically find its way back to my wallet in due course or is there a process or procedure I need to follow to recover my missing ETH.

Many thanks in advance.

Lance


texts: Oraclize Ethereum Bridge incompatible with current node

texts:
I am trying Oraclize with a private ethereum blockchain.
I downloaded the current version of ethereum-bridge and tried the active mode
node bridge -H localhost:8042 -a 1

I get the error

Not compatible with v8.0.0 of nodejs, please use v6.9.1 or a lower
version
exiting...

Is there a workaround for this?
BTW: I tried commenting out the checkVersion function, it crashes with an error

{"message":"Error: Account ","stack":"Error: Error: Account \n    at
deployOraclize
(/Users/abc/code/blockchain/ethereum-bridge/bridge.js:525:16)\n    at
/Users/abc/code/blockchain/ethereum-bridge/bridge.js:425:33\n    at
/Users/abc/code/blockchain/ethereum-bridge/bridge.js:506:14\n    at
Request._callback
(/Users/abc/code/blockchain/ethereum-bridge/lib/bridge-http.js:24:14)\n
at Request.self.callback
(/Users/abc/code/blockchain/ethereum-bridge/node_modules/request/request.js:188:22)\n
at emitTwo (events.js:125:13)\n    at Request.emit (events.js:213:7)\n
at Request.
(/Users/abc/code/blockchain/ethereum-bridge/node_modules/request/request.js:1171:10)\n
at emitOne (events.js:115:13)\n    at Request.emit (events.js:210:7)\n
at IncomingMessage.
(/Users/abc/code/blockchain/ethereum-bridge/node_modules/request/request.js:1091:12)\n
at Object.onceWrapper (events.js:312:19)\n    at emitNone
(events.js:110:20)\n    at IncomingMessage.emit (events.js:207:7)\n
at endReadableNT (_stream_readable.js:1045:12)\n    at
_combinedTickCallback (internal/process/next_tick.js:102:11)"}
Exiting...


texts:
I've just set up Swarm. It's amazing.

My domain names now serve swarm pages.

http://eth.ie/bzz:/75de632463a8ea86ce859945e74a502f4cea67e8cdf4c8ced5712621c38a7578/

http://ethereum.ie/bzz:/45238c8c4330b1d64068b0c795e653a3d99a5219b3b0e0437bafc3ef58b74668/

The purpose of my server is to be a gateway that serves pages and do nothing else.

So how can I prevent my server from eating up disk space? (i.e. run Swarm in a mode that it doesn't write anything)


texts: Is there a way to prove to a third party that you are the recipient of a transaction?

texts:
Let's say that someone sends me some ETH. How can I prove to a third party that I am the actual recipient of that transaction?
The third party is anyone with access to the blockchain. In other words, I want to send some data to this third party that allows it to verify that I am the recipient of a specific transaction on the blockchain.


texts:
Say I have a list of addresses whose transactions I want to monitor.

Detecting regular ethereum transactions is easy. Detecting internal contract transfers looks much more complex.

If my research is right, I'll need to essentially Debug all transactions to any contract in the blockchain via parity/get trace modules and see if its trace mentions an ethereum value transfer to my concerned addresses.
Again, in my understanding, I'll have to do this process for all transactions in every block.
I feel like there has to be a better way. The best I can think of is to trigger this process only if the balance of concerned addresses has changed.

This must be something every ethereum wallet must be doing right?


texts: Nethereum "WebException: The underlying connection was closed: The connection was closed unexpectedly."

texts:
I'm trying to call a contract function from asp.net backend, using a public node.

            var abi =
            @"[{""constant"":false,""inputs"":
[{""name"":""addr"",""type"":""address""},
{""name"":""amount"",""type"":""uint256""}],""name"":""test1"",""outputs"":
[{""name"":"""",""type"":""bool""}],
""payable"":false,""stateMutability"":""nonpayable"",""type"":""function""},
{""constant"":false,""inputs"":[{""name"":""addr"",""type"":""address""},
{""name"":""amount"",""type"":""uint256""}],""name"":""test2"",
""outputs"":[{""name"":"""",""type"":""bool""}],
""payable"":false,""stateMutability"":""nonpayable"",""type"":""function""},
{""anonymous"":false,""inputs"":
[{""indexed"":false,""name"":"""",""type"":""address""},
{""indexed"":false,""name"":"""",""type"":""uint256""}],
""name"":""Test1"",""type"":""event""},
{""anonymous"":false,""inputs"":
[{""indexed"":false,""name"":"""",""type"":""address""},
{""indexed"":false,""name"":"""",""type"":""uint256""}],
""name"":""Test2"",""type"":""event""}]";

        var account = new Nethereum.Web3.Accounts.Account("private-key-here");
        var web3 = new Nethereum.Geth.Web3Geth(acc, "http://104.236.182.85:30303");
        var contract = web3.Eth
.GetContract(abi, "0xcff863b8f953caf4418c50d56f2cc5afc839be01");
        var myFunction = contract.GetFunction("test1");
        var result = await myFunction
.CallAsync<bool>("d56F18bD24557E75E1b0082B66d6B9f5134Ed1da", 2);

And always I'm getting this WebException. Even when I'm just requesting my account's balance:

var balance = await web3.Eth.GetBalance
.SendRequestAsync("d56F18bD24557E75E1b0082B66d6B9f5134Ed1da");

Is there another ways to execute the contract function? Am I have to run my own node instead of public?

Node's port is opened.


texts:
If I am not mistaken, the following two assertions hold true for Ethereum PoS:

An entity becomes a validator in the upcoming PoS block validation scheme by first issuing a special transaction to lock its stake.
The rate of profit of a block validator in PoS scheme is proportional to its percentage share of the total stake being locked for block validation.

If my #2 assertion is correct then we can readily deduce that an entry of a new validator in the network decreases the rate of profit of all existing validators. This is obvious because for all existing validators, the percentage share of total validation stake decreases.

Now, if the above derivation is accurate then we find that it is rational for all existing validators to discourage a newcomer from entering the blockchain network's validators group.

Then if the mechanism for being a validator is indeed what I stated in my #1 assertion then the rational validators can censor a newcomer by refusing to validate the transaction that locks the stake. Since all of them will refuse that particular validation task, the transaction will never be mined into a block.

Then Ethereum PoS does have a censorship problem regarding the validator set. Right?

Note that one cannot say that the existing validators acted dishonestly by refusing to validate the stake-locking transaction. They only acted rational and the protocol for network entry led them to the sole profit maximizing action.


texts:
I have been reading in different papers and comments these two concepts and I would like to know the difference between them(if there is, sometimes it is a bit confusing).

I understand that the block time is the period for collecting transactions, the time that to mine a block takes, and the confirmation time is the time to put a transaction in a block. I am not sure if it is correct. If it is true, is it possible to get the confirmation time of a transaction? What do these times depend on?

I know that there are more open questions here talking about this, but I do not get the concept very well and I cannot comment on the threads, so I would appreciate the help.


texts: Metamask – Trying to call a function on a non-contract address

texts:
I am receiving the following alert from Metamask.

ALERT: Trying to call a function on a non-contract address.

The address is most certainly a contract address, I can interact with it perfectly through the geth console.


texts: Different proxy code to upgrade smart contract and reentrancy attacks

texts:
I am trying to upgrade smart contract in ethereum. I found that proxy pattern can help me with this. In the openzeppelin docs, I should add the following code in fallback function in my contract:
assembly {
  let ptr := mload(0x40)

  // (1) copy incoming call data
  calldatacopy(ptr, 0, calldatasize)

  // (2) forward call to logic contract
  let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
  let size := returndatasize

  // (3) retrieve return data
  returndatacopy(ptr, 0, size)

  // (4) forward return data back to caller
  switch result
  case 0 { revert(ptr, size) }
  default { return(ptr, size) }
}

It seems that I should forward call and retrieve the return data. However, in some contracts, they just upgrade the contract with code like this:
/**
     * Resolves asset implementation contract for the caller and forwards there transaction data,
     * along with the value. This allows for proxy interface growth.
     */
    function () payable {
        _getAsset().__process.value(msg.value)(msg.data, msg.sender);
    }

I have two questions:

Can the second code also upgrade the smart contract?
I think add the first code in fallback function in my contract can lead to reentrancy attack, is it true?
Thanks!


texts: A question related to Metamask and ERC20 token

texts:
Currently I am trying to send out my ERC20 token TRX to binance exchange, however any time I did that the metamask is pointing insufficient balance for transaction.
I did research and I am wondering now if I need to have eth in my ethereum balanace or I can pay the fee with trx. The eth account does not have any eth but a lot of trx and other erc20 tokens. Thanks in advance for the help!


texts: How to deploy a new version of the contract?

texts:
Probably this is not possible, but I still have to ask.

Let me follow the example created in truffle init. It contains a contract called MetaCoin.sol. Say,

I have deployed it on the network (the first version of it).
Then I have extended it with a foo() method.
Now I want to deploy a new modified version of the contract with the same name MetaCoin but the new code of it. Is there a way of doing it?

As the hint there is a contract called Migrations.sol which has a method called upgrade():

  function upgrade(address new_address) restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }

that sets a new address for the code of the contract. Is there a better way of doing versioning or upgrades (deploy rollouts) of the coins code?


texts:
I successfully setup a private blockchain and created the "hello world" contract according to tutorial from etherium web site.  One thing that I can't figure out is how to find the contract later.  I thought once the contract is mined, it becomes part of the blockchain forever.  The documentation seems to imply permanence because it's stressing how it's good etiquette to clean up unused contracts by committing suicide on them.  That's why after I got this message, I thought the contract was permanently part of the blockchain:

    Contract mined! address: ........

But after quiting geth and getting back in, I can't find the contract anywhere (I lost it's address).  It seemed to last only during the single instance of when geth was running.  What am I missing here?   Do I have to register the contract for it to become permanent?   Would I use the same technique on the real blockchain in order to get my code listed here?:

https://www.etherchain.org/contracts


texts: Solidity Transfer Token Test Case is not working fine.

texts:
I'm doing testing of smart contract when I try to transfer token using https://remix.ethereum.org. That was working fine. But now I want to write its test case but that is not working fine and not transferring the tokens.
Code:

 it('should properly [transfer] token', async function() {
    let recipient = "0xe0f5206bbd039e7b0592d8918820024e2a7437b9";
    let tokenWei = 1000000;
    let status = await contract.methods.transfer(recipient, tokenWei).call();
    console.log(status);

    let ownerBalance = await contract.methods.balanceOf(owner).call();
    let recipientBalance = await contract.methods.balanceOf("0xe0f5206bbd039e7b0592d8918820024e2a7437b9").call();
    console.log("Balance:"+ownerBalance +'----'+recipientBalance);
  });

Output is like this.

status = true
Balance:1705243055----100000000

These balaces are exactly same as before mean no deduction from owner account and no addition in recipient account.

Any guidance/help will be appreciated.

Thanks


texts:
I am using solidity 0.7.4, web3.py 5.12.2, and python 3.7.
I am working with Windows 10.
My goal is to emit an event inside a solidity function, in order to retrieve the log after the function is executed.
This is my event event logString(string arg);
And this is how I emit the event emit logString("example string");
On Remix it works, and I am able to retrieve the string I emit, in the log of the transaction.
When I try it on Python, it doesn't work.
This is my Python code:
web3_instance = Web3(HTTPProvider("http://"+host+":"+port, request_kwargs={'timeout': timeout}))
Platform_contract= web3_instance.eth.contract(address=contract_address, abi=abi, bytecode=bytecode)
coinbase= web3_instance.eth.coinbase
functions= Platform_contract.functions

tx_hash =functions.market_clearing(n_clearings,
t_clearing_first,supplier_bids,uniform_pricing,discriminative_pricing).transact({'from': coinbase})
tx_receipt = web3_instance.eth.getTransactionReceipt(tx_hash)

log_to_process = tx_receipt['logs'][0]
processed_log = Platform_contract.events.logString().processLog(log_to_process)
log = processed_log['args']['arg']

Unfortunately tx_receipt['logs'] is empty and I get an exception.
Do you know how can I retrieve the log of the event?


texts:
When I set more than eight values as function’s return , the following error occurred. ( When the num of values is less than seven, the  error didn’t  occur)

Could you tell me how can I get more than 8 return values by a function?

Code

struct  User{
    uint256 uuid;
    bytes32 first_name;
    bytes32 last_name;
    bytes32 sex;
    bytes32 age;
    bytes32 birth_day;
    bytes32 address;
    bytes32 mail_address;
    bytes32 phone_number;
 }

function getUser(uint256 uuid) constant returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
    return (
    users[uuid].first_name,
    users[uuid].last_name,
    users[uuid].sex,
    users[uuid].age,
    users[uuid].birth_day,
    users[uuid].address,
    users[uuid].mail_address,
    users[uuid].phone_number
    );
}

Error

Compiler error: Stack too deep, try removing local variables.
        users[uuid].phone_number


texts:
I am trying to deploy my contract using geth on my private network. When i use truffle mirate --reset  shows that is has been deployed but the metamask gives me an error( ALERT: Transaction Error. Exception thrown in contract code metamask). So i am using this command
eth.getTransactionReceipt with the transaction hash to see if it's ok but the transactionIndex = 0. I read that if  transactionIndex
= 0 the contract is not deployed. Right? Can you help? I tried to deployed in remix with the provider of my netowrk and it gives me this error (gas required exceeds allowance (8000000) or always failing transaction)

Below i have the contract code.

    pragma solidity ^0.5.8;

contract Creation  {

    struct hero  {
        string name;
        int life;
        int lvl;
        int xp;
        int attack;
        int winCount;
        int trophies;
        int lossCount;
    }
    hero[] public heroes;

    struct enemy {
        string name;
        int life;
        int lvl;
        int xp;
        int attack;
    }

    int basiclife=50;

    enemy[] public enemies;

  mapping (uint => address) public herotoowner;
  mapping (address => uint) public  heroCount;

  mapping (uint => address) public monstertoowner;
  uint public monsterCount;

    function createhero(string memory _name) payable public  {
     require(heroCount[msg.sender] == 0);
       uint id= heroes.push(hero(_name,basiclife,1,0,20,0,0,0))-1;
       herotoowner[id] = msg.sender;
       heroCount[msg.sender]++;

    }
     function enemyRage(int _herolvl) public  {
       uint id=enemies.push(enemy("Rage",20*_herolvl,_herolvl,7*_herolvl,5*_herolvl))-1;
       monstertoowner[id] = msg.sender;
       monsterCount++;

    }

    function enemyDerpina(int _herolvl) public  {
       uint id=enemies.push(enemy("Derpina",40*_herolvl,_herolvl,14*_herolvl,10*_herolvl))-1;
       monstertoowner[id] = msg.sender;
       monsterCount++;

    }

       function getHerosByOwner(address owner) external view returns( uint ) {
        uint result =3;
        for (uint i = 0; i < 3; i++) {
              if (herotoowner[i] == owner) {
                result = i;
                break;
          }
        }
        return result;
        }
        function getmonstersByOwner(address owner) external view returns( uint ) {
        uint result =0;
        for (uint i = enemies.length ; i > 0 ; i--) {
              if (monstertoowner[i] == owner) {
                result = i;
                break;
          }
        }
        return result;
        }

        uint nonce=0;

   function randNum(int _num) private   returns(int) {  //sinartisi gia tixaies times
    int randomnumber = int(keccak256(abi.encodePacked(now, msg.sender, nonce))) % _num;
    if (randomnumber <=0) {
        randomnumber=(-1)*randomnumber;
    }
    nonce++;
    return randomnumber;
    }

    function attack_hero(uint _heroid, uint _monsterid, int _num  ) external  {

      hero storage myhero = heroes[_heroid];
      enemy storage monster = enemies[_monsterid];
      int attackofhero=0;
      if(_num==0) {
       attackofhero=randNum(myhero.attack);
      }
      monster.life=monster.life - attackofhero;

      int attackofmonster=randNum(monster.attack);
      myhero.life=myhero.life - attackofmonster;

      if (monster.life <= 0 && myhero.life >0) {
        myhero.winCount++;
        myhero.xp+=monster.xp;

        if (randNum(100) > 50 ){
              myhero.trophies++;
          }

      }
      if (myhero.xp>=10+2*myhero.lvl){
          myhero.lvl++;
          myhero.xp=0; //reset you xp
          myhero.life=basiclife*myhero.lvl;
          myhero.attack=myhero.attack*myhero.lvl;
        }
      if (myhero.life <= 0 ) { //ita
          myhero.lossCount++;

      }

    }
    function resurrection(uint _heroid) public {
         hero storage myhero = heroes[_heroid];
         myhero.life=basiclife*myhero.lvl;
     }

}


texts: Casino / Ethereum - Withdraw from multiple addresses?

texts:
Hi I am in the middle of looking into creating an ETH casino for fun and to learn smart contracts and what not.

So say I have a website where you deposit 1 ETH and then you gamble it and you win, so now you have 2 ETH and you decide to withdraw.

How would the flow look like?

Like when a user registers they must be assigned an address to deposit to that is unique to that user.

Then the user has a balance of 1 ETH and he gambles it and it turns into 2 ETH.

How would the withdraw procedure look like for this? When he withdraws it would send from that deposit address and from the "main" address?

So my questions are:

Would this be possible to do through smart contracts?

How would you generate these deposit addresses and control them to withdraw and such?

Thank you very much.


texts: Code not returning when using websocket provider in web3

texts:
Below are two code snippets. I have created a 'ganache-testing.js' file and running it using node ganache-testing.js command

Web3 = require("web3");

provider = new Web3.providers.HttpProvider("http://localhost:8545");

web3 = new Web3(provider);

getAccounts = async () => {
  console.log("Started");
  const accounts = await web3.eth.getAccounts();
  for (const account of accounts) {
    const balance = await web3.eth.getBalance(account);
    console.log(account, web3.utils.fromWei(balance, "ether"));
  }
};

getAccounts();

//This is the second code
Web3 = require("web3");

provider = new Web3.providers.WebsocketProvider("ws://localhost:8545");

web3 = new Web3(provider);

getAccounts = async () => {
  console.log("Started");
  const accounts = await web3.eth.getAccounts();
  for (const account of accounts) {
    const balance = await web3.eth.getBalance(account);
    console.log(account, web3.utils.fromWei(balance, "ether"));
  }
  console.log("Completed");
};

getAccounts();

Both of the codes gives the same output:

Started
0x90e04CD9df771C31c6a81c406Bb73f871a3FBDD4 100
0x6ACabD5d20f34C19Aec6405c6956279E465FD6D8 100
0xb5068d22eb632da154A9eEC2c1940691b438F1a5 100
0x6252fe1c3e5a1B9A3eF0c0035d18FCa5b6c3f75B 100
0xafe1c27B9BAbc17BEad0F9326F03b36B4E4A2dB3 100
0x769ef23e6a1727469D75b1860E855F6708DD031a 100
0x33C35c3b96c7C3E27d0FFb38aE30ad868A08aB4A 100
0xa17493a84B10C8790A9Eb4E844BdE8154061eb03 100
0x753fa379E54D5f2DE256785F3b530f228C01b52F 100
0x22fd52A35D14AAd6552C540EE0C7663C622Df22a 100
Completed

However the second code does not return from execution back to the command line. Why would this be happening.


texts: DEVp2p Wire Protocol tutorial on geth or Web3.js/Web3.py

texts:
I was looking to develop an application using ÐΞVp2p Wire Protocol and I'm having trouble finding an example or tutorial. I was able to find only ÐΞVp2p Wire Protocol's wiki.

[Q] Does anybody has a working example or tutorial such as sending Hello World message between a receiver and sender for ÐΞVp2p Wire Protocol that works with the recent version of geth or Web3.js/Web3.py?


texts: Code Explanation of how to return an array of structs

texts:
I was reading a tutorial on a medium about how to return an array of structs. This is the code they have for doing it.

pragma solidity ^0.4.13;

contract Project
{
    struct Person {
        address addr;
        uint funds;
    }

    Person[] people;

    function getPeople(uint[] indexes)
        public
        returns (address[], uint[])
    {
        address[] memory addrs = new address[](indexes.length);
        uint[]    memory funds = new uint[](indexes.length);

        for (uint i = 0; i < indexes.length; i++) {
            Person storage person = people[indexes[i]];
            addrs[i] = person.addr;
            funds[i] = person.funds;
        }

        return (addrs, funds);
    }
}

The uint[] index argument however makes no sense to me. Can someone please explain what it is and what it does?


texts: How to run a multiline script in truffle console?

texts:
I'm following truffle tutorial to interact with a deployed contract and have a naive question. How do I run this block of multiline scripts in truffle(development)> without collapsing it into a single line?

var account_one = "0x1234..."; // an address
var account_two = "0xabcd..."; // another address

var meta;
MetaCoin.deployed().then(function(instance) {
  meta = instance;
  return meta.sendCoin(account_two, 10, {from: account_one});
}).then(function(result) {
  // If this callback is called, the transaction was successfully processed.
  alert("Transaction successful!")
}).catch(function(e) {
  // There was an error! Handle it.
})


texts: How can I handle computationally expensive operations on the blockchain?

texts: Sometimes a blockchain application needs to perform an operation, such as a scrypt verification, that is extremely computationally expensive.  Are there any techniques that can help me design around this problem so that my application doesn't have to pay enormous fees?


texts:
I am coding an app where users can deposit ether into their accounts and do stuff with it (Im using web3.js and geth). However I would like to have everyone deposit into one single account, and then have a database that knows how much of the total pool of ether in the single account belongs to each person.

I was wondering if there was a feature in Ethereum where users would be able to send a message along side their transactions? So that a specific code could be given to the user who is making a deposite, and once the serverside code of the app sees the code, it can know who sent the ether.

QUESTION: Does this functionality or a similar one exist?


texts:
Is the natural specification format a real standard, or a mostly unused tool?
I wonder if it is worth natspeccing my programs.


texts: What are the steps to compile and deploy a library in Solidity?

texts:
I have several pieces of documentation about libraries, but I am not yet able to infer what steps are needed to compile and deploy a library and then a contract that uses it. The behavior of the library within solidity is quite clear, but compiling and linking is not obvious to me.

Resources I have consulted:

http://solidity.readthedocs.io/en/latest/contracts.html#libraries
http://solidity.readthedocs.io/en/latest/miscellaneous.html#commandline-compiler
https://github.com/ethereum/wiki/wiki/Solidity-Features#libraries-without-inheritance
https://github.com/ethereum/solc-js
https://ethereum.stackexchange.com/questions/2916/finding-and-using-solidity-libraries-ie-math-functions/2933

Here is an example contract and library that I would like to get working:

MetaCoin.sol:

import "TestLib.sol";

contract MetaCoin {
  TestLib.Data data;
  address public owner;

  function MetaCoin() {
    owner = msg.sender;
    TestLib.Set(data, 2);
  }

  function GetData() constant returns(uint) {
    return TestLib.Get(data);
  }
}

TestLib.sol:

library TestLib {
  struct Data {
    uint n;
  }

  function Set(Data storage self, uint a) {
    self.n = a;
  }

  function Get(Data storage self) returns(uint) {
    return self.n;
  }
}

Thanks for your help!


texts: Programmatically unlock certain accounts with Parity?

texts:
Using geth it is easy to send transactions from multiple accounts but I do not know how to do this with Parity.

I do not want all accounts unlocked.

I do not want any account unlocked when it is not being used for a transaction.

How can I programmatically unlock (and then lock) an account in Parity?  Using json or web3?  I prefer web3?


texts: How to deploy a Smart Contract in Ethereum on Azure?

texts: Iam trying to deploy a smart contract in Azure's Ethereum on Azure. I have created a blockchain in that but now I need to deploy a smart contract and design a UI for the same. I want to use Remix to deploy the contract because I have connected it to the RPC end point of the blockchain I have created in Ethereum on Azure. Can anyone help me with this?


texts: Do I need a wallet to deploy a smart contract into Ethereum network?

texts:
I am new to Ethereum world and I would like to know if developers who desire to deploy their smart contract in the Ethereum mainnet or testnet, need to create previously a digital wallet with real or test Ether respectively. ???
In other words, is the following process from a developer's perspective correct?

Create digital wallet (is create account more correct ???)
Fund wallet with real or test ether (is fund account more correct ???)
Write Smart contract
Compile code
Deploy smart contract


texts:
My question pertains to my mist wallet and some presale tokens that I successfully imported into the wallet. Before importing the presale tokens, I successfully created the wallet, received and sent tokens from the main account.  My password and the software worked.

Then I imported the presale tokens and they ended up in an account called account 2.  I did not create the account, they just seemed to end up there as I remember... I've tried to send a token from that account but it asks for a password.  The only password I have is for the main account that was created when the wallet was first run from the downloaded from the Ethereum...cosx 0-7-3 download file.

Can you please help me figure out what is going on and gain access to my funds.


texts: Getting transaction history for a particular account

texts:
I want to get the list of all the transactions which have been performed by/on an account in my private blockchain. I tried using the function

getTransactionsByAccount(accountAddress, startBlockNumber, endBlockNumber)

given on this link.
The problem with this method is that for transactions which include transfer (of amount) from one account to another, it gives the correct address in "from" field, but incorrect one for "to" field.

So, I'd like to ask if there is some other method by which we can get the transaction history???


texts: Solidity events in libraries - not displaying correctly in Mist

texts:
Has anybody been successful in executing and viewing events (in Mist) generated from solidity libraries?

My contract can log and display events in the contract but events in the associated libraries are not being displayed correctly in Mist.

I am not sure if this is a solidity issue, node client issue (using Geth) or a Mist issue.

Screenshot attached of library event in Mist.

Added issue to Github - https://github.com/ethereum/mist/issues/1083


texts:
I'm trying to do the hello world app seen here https://www.ethereum.org/greeter#compiling-your-contract.

It says I should be able to do eth.getCompilers()

  The first you can get by using a compiler. You should have a solidity
  compiler built in on your geth console. To test it, use this command:

So I have geth installed, but how am I supposed to do eth.getCompilers()? I'm I missing some install? My geth version is Version: 1.6.5-stable.


texts: If Ethereum does a hard fork to return exploited funds from theDAO, does this cause a concern for immutability?

texts: I'm still torn on both sides with theDAO fiasco. I'd like to do a hard fork so I can get my coins back, as right now theDAO is pretty much dead moving forward. But does this cause a concern for immutability and would it destabilize Ethereum itself? Supposedly theDAO shouldn't be changed once its written into code. How does this affect the reputation of Ethereum if its immutable or not? Suggested best course of action?


texts: Understanding openzeppelin's crowdsale contract

texts:
I am new to solidity and am trying to understand this openzeppelin crowdsale contract.

I am currently stuck on the _deliverTokens function and unable to understand how this function works. As far as I understood, the token here is actually referring to the ERC20 token but when it calls token. transfer(), whose tokens its transferring? Does this mean that the crowdsale contract's address owns the tokens?


texts:
I need to check the balance of several addresses for the presence of erc20 tokens, if the balance is not empty, send eth there and forward this balance to the resulting address. But in the end, I get an error: private key should be a Buffer on the line transaction.sign (keys [k])

let foreth = ["addr1", "addr2"];
let keys = [Buffer.from('keyaddr1', 'hex'),Buffer.from('keyaddr2', 'hex')]

foreth.forEach(async function(recipient, i) {
    const balance = await contractInstance.methods.balanceOf(recipient).call(function(err, result) {

        if (result > 0) {

                web3.eth.getTransactionCount(fromAddress)
                    .then((count) => {
                        let rawTransaction = {
                            'from': fromAddress,
                            'gasPrice': web3.utils.toHex(20 * 1e9),
                            'gasLimit': web3.utils.toHex(21000),
                            'to': recipient,
                            'value': web3.utils.toHex(web3.utils.toWei("0.0002")),
                            'nonce': web3.utils.toHex(count + i)
                        }

                        let transaction = new Tx(rawTransaction)
                        transaction.sign(privateKey)
                        return new Promise((resolve, reject) => {
                            web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
                                .on('transactionHash', console.log)
                                .on('receipt', resolve)
                                .on('error', reject)
                        })
                    }).then(receipt => {
                        console.log("status success")
                        for (var k = 0; k < keys.length; k++) {
                         web3.eth.getTransactionCount(recipient)
                        .then((count) => {
                            let rawTransaction = {
                                'from': recipient,
                                'gasPrice': web3.utils.toHex(20 * 1e9),
                                'gasLimit': web3.utils.toHex(200000),
                                'to': tokenAddress,
                                'value': 0x0,
                                'data': contract.methods.transfer(fromAddress, web3.utils.toHex(result)).encodeABI(),
                                'nonce': web3.utils.toHex(count+i)
                            }
                            let transaction = new Tx(rawTransaction)
                            transaction.sign(keys[k])
                            web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
                                .on('transactionHash', console.log)

                            .on('error', console.log)

                        })
                    }
                    })

        }
    })
})


texts:
I stumbled across this interesting code on Reddit for generating Ethereum private keys with terminal:

cat /dev/urandom |LC_ALL=C tr -dc '0-9a-f' | fold -w 64 | head -n 1

Of course the randomness and everything would be sufficient but is it possible that this could generate an invalid key? Are all keys generating in this manner valid or does Ethereum have some weird exception rules?


texts:
I was thinking in add a function to my contract in order to avoid locking ethers there (for example, someone can transfer ether to the contract in a mistake)

It is important to note that this contract is not supposed to store any ether in normal conditions. However, there are some payable functions in the contract used to transfer money between parts.

What do you think? Is it a good idea?

function withdrawETH () public onlyOwner {

    owner.transfer((address(this)).balance);
}


texts: Where is the position of each paramter in a smart contract function when encoded as inputdata in a transaction

texts:
When I reviewed the BEC attack, I found the position of each parameters value in real transaction was not corresponding in to definition of function in smart contract.

The exploit transaction is at:

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

In transaction inputdata, the address[] value is put at the second, but in function definition, it's in the first. Another question is why the value of _value take three values.

So is there any rule for setting 'inputdata' value position in transaction?


texts: How to host my java web app onto decentrailsed network like ipfs as my web need a web server like tomcat to run and serve the dynamic content so how can i install tomcat on ipfs and push my war in it and start a server in ipfs node.  Thanks in advance


texts: What to do, if node sync doesn't work on MAC with Wallet 0-8-6?

texts: Working with latest ETH wallet on MAC. For days now trying to synch the node without any result, stuck at 2,287,960. any idea how to resolve this issue?


texts: Can i convert my HEX private key to RAW form?

texts: Sorry guys if this is a basic question but i am new to this. I have got my private key only in HEX format. converting to raw and then importing or directly making a wallet using HEX private key. Is it possible?


texts: Smart contract storage doen't work with ganache

texts:
I have this smart contract

contract Ballot {

    struct Prop {
        uint votes;
        bytes32 data;
        address[] validators;

    }

   mapping (bytes32 => Prop) props;
   function addProp(address [] validators, bytes32 data ) public returns(bytes32) {
       var pHash = keccak256(data);
       var newProp = props[pHash];
       newProp.data = data;
       newProp.validators = validators;

       return(pHash);

   }

   function getProp (bytes32 pHash) public constant returns (uint, bytes32, address[]){
       var newProp = props[pHash];
       return(newProp.votes, newProp.data, newProp.validators);
   }

   function voteTo(bytes32 pHash) public {
        var newProp = props[pHash];
        newProp.votes = newProp.votes+1;

   }
}

when I add prop and vote for it I can get it's updated data using javascript VM and ropsten, but it doesnt work using testrpc or ganache


texts: Remix: Gas estimation errored with the following message (see below). (...) execution reverted

texts:
I am trying to deploy a smart contract on remix written in VYPER.
The code for the simple open auction comes from the vyper documentation website. Remix compiles the code perfectly fine. However, when I want to deploy the contract with the following variables I get the gas estimation error: EXECUTION REVERTED.
_BENEFICIARY: a meta mask address
_AUCTION_START: 300
_BIDDING_TIME: 300
Here is the failed transaction in ETHERSCAN.
Can anybody help?


texts:
I'm wondering how much data a smart contract can store per block.

Ex: The gas limit is currently ~6,700,000, and it costs 20,000 gas to store 32-byte word. So the EVM can store a maximum of 335 bytes (6.7M / 20k) of data per block? Is this reasoning correct?


texts: Once a contract is no longer valid (eg after calling selfdestruct on it), one can still call functions on it although the contract won't behave as expected. In javascript, how can one check if the contract has been destructed before performing a transaction?


texts: How and from where i can learn about Ethereum Mining algorithm(including PoW)?


texts: Invalid number of arguments to Solidity function (trying to retrieve mapping)

texts:
The solidity contract has defined the following mapping

struct recordStruct {
    uint256 price;
    uint64 time;
}

mapping(address => recordStruct[]) public records;

Question: How can we use Web3.js to retrieve the entire mapping?

If this is not possible, how can we pass in the address and receive the object stored in the recordStruct array?

Attempt When using the following web3 code:

var record = await MyContractInstance.records.call('0xDbB7d1Ed07F8D1D0C5D5bB9b9e427E997f240F7d')

I get the following error

  (node:2452) UnhandledPromiseRejectionWarning: Error: Invalid number of arguments to Solidity function

I am using Web3.js 1.0.0-beta.34


texts: How can I decode getData from a contract method call

texts:
I'm using myContractInstance.myMethod.getData() to be able to serialize a transaction:

// Get the call data, so you can call the contract through some other means
var myCallData = myContractInstance.myMethod.getData(param1 [, param2, ...]);
// myCallData = '0x45ff3ff6000000000004545345345345..'

The transaction is later excuted later (by another person):

web3.eth.sendTransaction({"data": myCallData});

However, I want the other person, who will execute the transaction, to be able to decode myCallData, so they know that they're not transfering a huge amount. I can't find a way to do that in the documentation, however.

Is there a friendly way to decode myCallData, and make it readable again for the user (other than breaking up the data ABI pieces myself)?

Peter.


texts:
I'm trying to download the blockchain using geth. I started it around 10 days ago, without the --fast parameter. After about 7 days it got corrupted at block 1.800.000 or so. Then i tried starting over using the --fast prefix, it went a lot faster at first but now it is taking 5-10 minutes per block while previously it used to take 8 seconds per block. What causes this difference?

Not sure if i'm doing something wrong or if it's normal to take multiple weeks to download the whole blockchain?


texts: Storing hash on blockchain (hash of image stored on ipfs)

texts: I am creating a dapp using react to store image on ipfs and the corresponding hash on blockchain. The purpose of storing hash on blockchain is timestamping, proof of ownership wtc and i wish to retrieve the hash also at later stage. I need to know how can we store and retrieve hash on blockchain.


texts: Provided address is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can't be converted

texts:
Here is my transaction from ethereum.

transaction is shown as followed

{
    blockNumber:12,
    contractAddress:null,
    cumulativeGasUsed:22977,
    gasUsed:22977,
    status:1,
    transactionIndex:0,
tx:"0x92c1ec18a97bce88fca9649711280ec84241cd230ffa5dc51485a6637b238fc0"

}

Using the code below gives me a error,

var count = web3.eth.getTransactionCount(tx);

Error: Provided address "0x92c1ec18a97bce88fca9649711280ec84241cd230ffa5dc51485a6637b238fc0"
is invalid, the capitalization checksum test failed, or its an indrect
IBAN address which can't be converted.

update
I changed the transaction hash to the eth address, the call returns me

{
    _bitField:33554432
    _fulfillmentHandler0:undefined
    _promise0:undefined
    _receiver0:undefined
    _rejectionHandler0:155
}

instead of the count value

what is the problem?


texts: How upgradeable smart contracts work? Is it possible to deploy a contract at a self-chosen address?

texts:
Is it possible to deploy a contract on the blockchain at a self-chosen address?

When deploying a contract by sending contract code to the address null, the contract is created at a "random" address by hashing the transaction's contents (correct me if I'm wrong).

But suppose, I want to deploy my contract at address 0xFFFFFF. How will I accomplish this? This should be important for upgrading smart contract.


texts: Unable to deploy smart contract on testnet or by using testrpc stuck

texts:
I have completed writing a smart contract successfully and using Ethereum Wallet to deploy contract. After waiting for 3 days I have synced testnet Ropsten successfully but not able to mine ethers, faucets also don't work.

Another question is that when I deploy this in main network how much time does it take to to sync the main network?

Have also tried using testrpc with Ethereum Wallet but whenerver i try doing any transaction I get error "unable to estimate gas" and geth console shows gas{} null, none of the solutions on internet helped.


texts:
i did a sendrawTransaction on ropsten and got out of gas, despite contract is shown on etherscan. i sent again with enough gas and now contract address is 0x0.
What i did wrong ?
here is the link to etherscan
https://ropsten.etherscan.io/address/0x000ab857d04871672516292412e1e9ea887c652f
where transaction can be viewed