texts: Deploy smart contract with web3 and ganache-cli

texts:
I've been trying to get a simple contract deployed on ganache with web3.js.
Here is my test code :

const ganache = require('ganache-cli');
const Web3 = require('web3');
const provider = ganache.provider()
const web3 = new Web3(provider);
const { abi, evm } = require('../compile');

let accounts;
let myContract;

before(async function() {

    accounts = await web3.eth.getAccounts()

    myContract = await new web3.eth.Contract(abi)
        .deploy({data: "0x" + evm.bytecode.object, arguments: []})
        .send({from: accounts[0], gas: 5000000});

    console.log("finished")

});
// describe and it part....

The error is : Callback was already called :
at ....../ganache-cli/build/lib.node.js:22953:36

Anybody got any idea?
Thanks a lot


texts: VM Exception: invalid JUMP when I call a second function

texts:
I'm experimenting with
Solidity Browser

Here is my  contract code:

contract Test {

    mapping (address => uint256) weismap;

    function bet(uint vote) payable returns (uint256 weis) {
        if (msg.value==0) throw;
        weismap[msg.sender]= msg.value;
        return  weismap[msg.sender];
    }

    function test()  returns (uint myVote)  {
           return 1;
    }
}

If I set as transaction value 1

,create the contract and call the function bet with 1 as parameter

the function is run successfully.

If after that,  I call the test() function I get

  VM Exception: invalid JUMP

Any idea, about what's wrong?


texts: Vyper fundraising smart contract: 'Attribute' object has no attribute 'func'

texts:
[SOLVED]: See below.

I am taking a blockchain and security class and we are working with vyper. We have been tasked with rewriting a fundraising smart contract. However, the compilers do not seem to give much information about errors within your code. I started on remix, which only told me that my code failed to compile but not why. I switch to vyper.online and got this error message:

vyper.online:
'Name' object has no attribute 'func'

Since the line number is not given nor is the applicable function I am at a loss for what I should be looking for. In two other compilers I get the following error messages:

Etherscan:
IsADirectoryError: [Errno 21] Is a directory: 'vyper-in-NPSnEgc1jPs2mP9.vy'

jacqueswww.github:

Can anyone give some insight into where I have gone wrong? I have looked at some other similar questions and they have answered about having a function name and a model name being the same, but I don't think that is the case here.

Fundraiser.vy

struct Contributor:
    userAddress: address
    contribution: wei_value

contributors: map(int128, Contributor)
nextContributorsIndex: int128
owner: address
target: public(wei_value)
endTime: public(timestamp)

@public
@payable
def __init__(_target: uint256, _duration: uint256):
    self.owner = msg.sender
    self.target = _target
    self.endTime = block.timestamp + _duration

@public
@payable
def contribute():
    assert block.timestamp < self.endTime
    nci: int128 = self.nextContributorsIndex
    self.contributors[nci] = Contributor({userAddress: msg.sender, contribution: msg.value})
    self.nextContributorsIndex = nci + 1

@public
def collect():
    assert self.balance >= self.target
    assert msg.sender == self.owner
    selfdestruct(self.owner)

@public
def refund():
    assert block.timestamp > self.endTime
    assert self.balance < self.target
    for i in self.nextContributorsIndex:
        send(self.contributors[i].userAddress, self.contributors[i].contribution)
        clear(self.contributors[i])

@public
@constant
def retBalance() -> wei_value:
    return self.balance

[Answer]: I found pretty much the exact contract as an example on this website:

https://vyper.readthedocs.io/en/v0.1.0-beta.6/vyper-by-example.html

The key point is found in the following image.

As I understand vyper does not like the gas expenditure that comes with potentially large loops so the creator of the example has the contributors to the fundraiser refunded in groups of 30. I still do not fully understand how this works but its the best answer that I have.


texts: How would I create a function where 3% of transactions gets sent to an address I assign?

texts: I am creating an erc20 token that will serve as the currency between online communities, and I want to have an ethereum address that accumulates a 3% fee from all the transactions.


texts:
I want to test off chain data input in truffle testing.  So basically I kick off a test and then need to wait for another program to do something.  In the old web3, this worked great:

function promisifyLogWatch(_event) {
  return new Promise((resolve, reject) => {
    _event.watch((error, log) => {
      _event.stopWatching();
      if (error !== null)
        reject(error);
      resolve(log);
    });
    });
}

And I test it in my js file like this:

await promisifyLogWatch(oracle.NewValue({ fromBlock: 'latest' }));

But now I get that _event.watch is not a function.  How do I update this for web3 v1?


texts: "gas required exceeds allowance" with eth.sendTransaction on geth CLI

texts:
I am trying to follow these instructions.

I do not want to sync so I run

./geth-1.9.0 --maxpeers 0 console`

and do this:

FROM="0x..."
TO="0x..."
ETH_AMOUNT=0.1
NONCE=1

VALUE=web3.toWei(ETH_AMOUNT,"ether")

TX={ from: FROM, to: TO, value: VALUE, nonce: NONCE }

personal.unlockAccount(FROM)
eth.sendTransaction(TX)

I get this error

WARN [06-30|20:58:39.016] Served eth_sendTransaction               reqid=36 t=5.238384ms   err="gas required exceeds allowance (5003) or always failing transaction"
Error: gas required exceeds allowance (5003) or always failing transaction
    at web3.js:3143:20
    at web3.js:6347:15
    at web3.js:5081:36
    at <anonymous>:1:1

How do I figure out if the error is "gas required exceeds allowance" or "always failing transaction"?

How do I figure out what the required gas amount and allowance amounts are?

What went wrong?


texts: getting --> Fatal: invalid genesis file: invalid character '/' looking for beginning of object key string

texts:
I'm just getting started with this.  I started by reading this collection of articles:

https://medium.com/m/global-identity?redirectUrl=https://hackernoon.com/heres-how-i-built-a-private-blockchain-network-and-you-can-too-62ca7db556c0

The syntax they suggested for creating a private blockchain didn't work so I tried every combination I could think of.  Eventually I tried the following:

geth init CustomGenesis.json --datadir .ACPrivateChain

Here's how I configured my install:

I installed geth in c:\program files\geth.
I created a genesis.json file and put it in this folder.
I created a subfolder named 'ACPrivateChain'.

When I run the command, I get:

"Fatal: invalid genesis file: invalid character '/' looking for beginning of object key string"

Can someone help with the right syntax for Windows?

thanks,
clem


texts:
How can I invalidate a smart contract that has already been deployed? I might want to do so because of business reasons, and maybe beneficial network effects.

Is it possible to invalidate a smart contract?


texts: Solidity: Is there any way to store the start time of solidity code? now() function returns block.timestamp only

texts:
I wanted to get a start time of solidity code, so I used now() previous which only returns block.timestamp whenever the solidity got started.
Is there any way to store or know the start time of solidity code which is typically elapsed time in other programming language. In case of Javascipt, it is simple to calculate the elapsed time of code as below.

var start;
var end;
var elapsed;

function startTime() {
   start = new Date();
};

function endTime() {
   end = new Date();
   elapsed = end - start;
}

I have tried to calculate the time difference in solidity like that, but it has shown only block time stamp for the now function. Is there any way to find the start time in solidity?


texts: I am following Ethereum Book, but I am getting errors in the Terminal

texts:
I am learning Ethereum Development from the Ethereum Book by Andreas. I have stumbled on the first error trying to do $ cargo install . I will post the instructions as an image and the errors I got.

When I try $ cargo install it first gave me a warning which is will also display below

The command does some compiling and then gives me the following error

I cant really proceed since all the other commands that follow are nolonger working. Please assist if there is anything I did wrong. I am really new to this. I am not a pro-developer but working towards becoming a solidity dev.

I will really appreciate your help


texts:
is possible to make a function to recall a certain amount from a token Holder?

What I meant is:

The Token Owner make a transaction with 10 tokens to a client, this client do not pay for the tokens. Is possible to make a function to get back the 10 tokens?


texts:
I am trying to find the transaction count of an address using ethGetTransactionCount method but it's returning 0 value. What the issue over here. I'm using infura mainnet and web3j in maven

/Find the current transaction count/
EthGetTransactionCount txnCount = web3j.ethGetTransactionCount("0xa9e4E3b1DA2462752AeA980698c335E70E9AB26C"
,DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = txnCount.getTransactionCount();
System.out.println("Transaction Count "+ nonce);


texts:
My geth node (v1.4.18 on testnet) has unexpectedly go down throwing an error like this:

I1028 04:46:29.305710 ethash.go:259] Generating DAG for epoch 44 (size 1442839168) (0016bedd7bd1a4976b855daf38926317ac50d2ff306182c9c1f0c61fddfff77b)
I1028 04:46:37.202844 core/blockchain.go:1001] imported 195 block(s) (0 queued 0 ignored) including 95 txs in 8.0030203s. #1323724 [d3e89d0e / 248089b1]
fatal error: unexpected signal during runtime execution
[signal SIGBUS: bus error code=0x2 addr=0x7fcce9996000 pc=0xb38b76]

runtime stack:
runtime.throw(0xd3ba06, 0x2a)
        /usr/lib/go-1.7/src/runtime/panic.go:566 +0x95
runtime.sigpanic()
        /usr/lib/go-1.7/src/runtime/sigpanic_unix.go:12 +0x2cc

goroutine 70 [syscall, locked to thread]:
runtime.cgocall(0xb36760, 0xc42300bab8, 0xc400000000)
        /usr/lib/go-1.7/src/runtime/cgocall.go:131 +0x110 fp=0xc42300ba50 sp=0xc42300ba10
github.com/ethereum/ethash._Cfunc_ethash_full_new_internal(0x7fd8f8000900, 0x97a4d17bddbe1600, 0x17639238af5d856b, 0xc9826130ffd250ac, 0x7bf7ffdd1fc6f0c1, 0x55fffa80, 0x7fd8f8000940, 0xb39c40, 0x0)
        ??:0 +0x51 fp=0xc42300bab8 sp=0xc42300ba50
...

Any idea about it? Is it a go-Ethereum bug? How can I fix it? Thx!


texts: Replacing A Stuck MetaMask Transaction With Something Other Than 0ETH To Yourself

texts:
I tried to send ETH from one of my wallets to another, but I set the gas too low & it's been stuck (pending) for days. I understand that the typical way to 'un-stick' such a transaction is to replace it by sending a 0 ETH transaction to yourself, with higher gas, and setting the nonce to same as the 'stuck' transaction - like this: https://www.youtube.com/watch?v=ivCPlz2P2mE.
Every example I've seen about "un-sticking" ETH transactions always does so by sending 0ETH back to yourself. Would this work just as well with a different type of ETH transaction? For example, could I just replace it with a transaction sending some ETH from my wallet1 to wallet2, as I was originally trying to do? Or it should only be replaced with 0eth sent back to myself?


texts:
I am trying to calculate the price of an ERC20 token. My approach is to determine the total value of the token pool and divide that by the total number of tokens. However, the values I am getting for the balanceOf method are not even close to the values in etherscan. The values of totalSupply do match etherscan. I am using web3.js with node.
const web3 = new Web3('wss://') // my connection address
const contractInstance = new web3.eth.Contract(TOKEN_ABI, TOKEN_CONTRACT_ADDRESS)

contractInstance.methods.decimals().call().then(function (bal) {
    decimals = bal; // number of decimals
});

contractInstance.methods.totalSupply().call().then(function (bal) {
    console.log("Total Supply: "+bal/(10**Number.parseFloat(decimals).toFixed())); // total supply
});

contractInstance.methods.balanceOf(TOKEN_CONTRACT_ADDRESS).call().then(function (bal) {
    console.log("Balance of: "+new BigNumber(bal).toFixed()); //
});

Is this the correct approach?


texts:
I want to reuse on type DateRange in two contracts. However, I fail with multiple errors. Currently I have one error:

G21FE98E9  Member "endTicks" not found or not visible after argument-dependent lookup in tuple(uint64,uint64)

I didn't find any related info that could help solve this issue.

Here is complete contract code:

pragma solidity ^0.4.21;

contract SeasonFactory {
    address public owner;
    address[] public seasons;

    event SeasonCreated(uint64 indexed beginTicks, uint64 indexed endTicks, address season);

    function SeasonFactory() public {
        owner = msg.sender;
    }

    function newSeason(uint64 beginTicks, uint64 endTicks) public restricted {
        require(beginTicks < endTicks);
        require(seasons.length == 0 || Season(seasons[seasons.length - 1]).period().endTicks() < beginTicks);

        Season season = new Season(owner, beginTicks, endTicks);
        seasons.push(season);
        emit SeasonCreated(beginTicks, endTicks, season);
    }

    function getSeasonsCount() public view returns(uint) {
        return seasons.length;
    }

    function getSeasonForDate(uint64 ticks) public view returns(address) {
        for (uint i = seasons.length - 1; i >= 0; i--) {
            Season season = Season(seasons[i]);
            if (ticks >= season.period.beginTicks() && ticks <= season.period.endTicks())
                return season;
        }
        return 0;
    }

    modifier restricted {
        require(owner == msg.sender);
        _;
    }
}

contract Season {
    address public owner;
    SharedTypes.DateRange public period;

    function Season(address owner_, uint64 beginTicks, uint64 endTicks) public {
        owner = owner_;
        period = SharedTypes.DateRange(beginTicks, endTicks);
    }
}

library SharedTypes {
    struct DateRange {
        uint64 beginTicks;
        uint64 endTicks;
    }
}

What could be wrong here?


texts: What does decrypt the key mean? in parity wallet transfere

texts: I just created a Wallet in Parity 1.8.0 and transfered there some ether from main account using a passphrase in Parity signer. Now as I'm trying to send a sum from the Wallet to yet another account, the Parity signer asks to "decrypt the key"/ who knows what that could be? I was never asked to create any key, nor encrypt it. Seems locked in my wallet & I am not able to use it. Thanks!


texts:
Let's say we have a function such as:

function tokenFallback(address sender, uint tokenAmount)

And some other contract decides to call it with:

contract.tokenFallback(sender, tokenAmount, data)

There are only two arguments in the tokenFallback, but the call includes three arguments. The tokenFallback function doesn't include the _data. What happens? Can the tokenFallback still execute like normal and ignore the _data variable that it received?


texts:
I'm new to the Ethereum ecosystem and I was hoping to get something clarified. I have an idea for Dapp that I wish to build. I am now trying to understand whether I should be creating a new ERC20 token or if I should just be accepting payments in ether.

I've encountered several articles such as this one that say that not all applications should need their own token.

To my knowledge ICOs seem like a neat way to raise capital and define the economic model for a token that will fuel your platform. But, what exactly constitutes a platform? Is something like SALT Lending that just requires users to hold the token for membership or for paying for services a platform? To me, SALT sounds like a product rather than a platform. Thus, I feel like they could easily accept payments in Ether and call it a day.

However, I do also see the upside towards ICOs. I see it mainly in the form of monetary incentives. Early investors and founders have the potential to cash out big if they invest in tokens that end up creating huge demand. But, at the cost that you need a new token for every product/platform. I've also noticed from this question that staking tokens like Omisego should be their own token, but don't quite understand what why that is the case.

So, my question is - If I am creating a Dapp that I could potentially see being as an established live application with millions of users, should I be creating an ERC20 token or should I be accepting payments in Ether? When is it recommended to create your own token?


texts: Good iptables rulesets for IPv4 and IPv6 in Geth Ethereum Node

texts:
Currently I'm using the following iptables rules for my remote (server) geth node:

V4

*filter

# Allow all loopback (lo0) traffic and reject traffic
# to localhost that does not originate from lo0.
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT

# Allow ping.
-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT

# Allow SSH connections.
-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

# Allow TCP and UDP connections from anywhere
-A INPUT -p tcp --dport 30303 -m state --state NEW -j ACCEPT
-A INPUT -p udp --dport 30303 -m state --state NEW -j ACCEPT
-A INPUT -p udp --dport 30301 -m state --state NEW -j ACCEPT

# Allow inbound traffic from established connections.
# This includes ICMP error returns.
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Log what was incoming but denied.
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables_INPUT_denied: " --log-level 7

# Reject all other inbound.
-A INPUT -j REJECT

# Log any traffic that was sent to you
# for forwarding.
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables_FORWARD_denied: " --log-level 7

# Reject all traffic forwarding.
-A FORWARD -j REJECT

COMMIT

V6

*filter

# Allow all loopback (lo0) traffic and reject traffic
# to localhost that does not originate from lo0.
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -s ::1/128 -j REJECT

# Allow ping.
-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT

# Allow SSH connections.
-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

# Allow TCP and UDP connections from anywhere
-A INPUT -p tcp --dport 30303 -m state --state NEW -j ACCEPT
-A INPUT -p udp --dport 30303 -m state --state NEW -j ACCEPT
-A INPUT -p udp --dport 30301 -m state --state NEW -j ACCEPT

# Allow inbound traffic from established connections.
# This includes ICMP error returns.
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Log what was incoming but denied.
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "ip6tables_INPUT_denied: " --log-level 7

# Reject all other inbound.
-A INPUT -j REJECT

# Log any traffic that was sent to you
# for forwarding.
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "ip6tables_FORWARD_denied: " --log-level 7

# Reject all traffic forwarding.
-A FORWARD -j REJECT

COMMIT

Is there any way I can make the rules more secure. Also I would like to know if the same are good enough for a parity node.


texts:
I tried to read a list of posts using the code below

struct posts {

  bytes32 postTag;
  string post;
  address[] acceptedBy;
  uint8[] voteCount;

}

mapping(address => posts) totaluserPosts;

I tried to read all the posts in different ways but couldn't find a way to do.

Is it possible to read all the posts through one request?


texts: throw new error"could not find artifacts from "+import_path" from any sources

texts:
pragma solidity ^0.4.18;

import "./ConvertLib.sol";

contract SimpleAuction{
    event HiggestBidIncreased(address binder,uint amount);
    function bid()payable{
        HiggestBidIncreased(msg.sender,msg.value);
    }
}


texts: web3.eth.getBlock('pending') returns latest block, not pending block, is that expected?

texts:
I am trying to use web3 or JSON-RPC to get a list of pending transactions.

The web3 API docs say that a call to web3.eth.getBlock('pending') will return a structure showing the block number and hash to be null. The answer to this question agrees and says that block.transactions will have pending transactions. But I see non-null values for the number and hash fields that match the latest block and a list of transactions that were included in that block. In fact, web3.eth.getBlock('pending') and web3.eth.getBlock('latest') return the same result. For example, when running a local parity node (Parity/v1.4.7-beta-f2058bd-20161227):

> let Web3 = require('web3');
> let web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
> blockL = web3.eth.getBlock('latest');
> blockP = web3.eth.getBlock('pending');
> [blockL.number, blockL.hash]
[ 2971275, '0x2187511e60d49a5ed081ccc31ee4f76365727254e9001f4b563c47cee457ed3f' ]
> [blockP.number, blockP.hash]
[ 2971275, '0x2187511e60d49a5ed081ccc31ee4f76365727254e9001f4b563c47cee457ed3f' ]

I tried making the JSON-RPC call directly and also got the latest block, not information about the pending one:

$ curl -s -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["pending",false],"id":0}' localhost:8545
  { "result" : {
       ... ,
       "number" : "0x2d4c56",
       ...
       "hash" : "0xb0d47255dbeae836384321b1141ae221254fa7ee4ded07f3d49afb875f05a44e"
       ... }
  }

I also tried using an Infura RPC node and got similar results.

Do I misunderstand what pending is supposed to mean? Is there another way I should use web3 or JSON-RPC to get the list of pending transactions?

(When I use web3.eth.filter('pending') I do see pending transactions as they arrive at my node, but that is different from asking for the current pending set.)


texts:
I'm using web3 1.0 beta, and I'd like to get TxId before it's mine

I find a lot answer with sendTransaction, but If I use it I get sendTransaction is not a function

My code is like this:

c.istanza.methods.registraTicket(matricola).send({
   from: c.defaultAccount
}).then(
(valore) => {....},
(err) => {....})

In this way, from my client, I can call my function in my Smart contract.
c.istanza is istanza = new web3.eth.Contract(data.abi, data.address);

If i Use something like this

c.istanza.methods.registraTicket(matricola).sendTransaction({
            from: c.defaultAccount
        }).then(
            (valore) => {

            },
            (err) => {
                console.dir(err);
            }
        )

I have a problem sendTransaction is not a function.

How can I get TxId before it mined?
I want to have this id, because I store it in Database and I can check when it's mined (it's correct to check this ?)

thanks


texts: Get ERC20 Tokens Transferred Information from Transaction Hash

texts:
I am building very simple Golang program to get transaction details from HASH.
I am able to get the information of any transaction but I am unable to get information what ERC20 token was transferred and how many.

 Transfer 700 ERC20 (GLOBALALTCOIN) TOKEN From 0xaacc58c7c85f7ea78f36ea700edf6a15f9b74aac to  0x01e574ab996f8fbd6adbd92c82ffd9b293bc6349

Can someone please advise me how to get it?

I am getting this information

{
nonce: "0x7",
gasPrice: "0x14b8d03a00",
gas: "0x134cb",
to: "0xb3c8826e2c5bc48415c1618384e1aa544d32f69b",
value: "0x0",
input: "0xa9059cbb00000000000000000000000001e574ab996f8fbd6adbd92c82ffd9b293bc634900000000000000000000000000000000000000000000000000000000000002bc",
v: "0x29",
r: "0x2712c5a09046d61c809865c6a716c34c4bde3c8d1b84f2a18c60b7d77d52d402",
s: "0x6d1a322fa417ffa8c21c746616fab0036830772c597156981e761ff66e44ebd0",
hash: "0xcbf739a96f23b7bb5a62802e0389257f5f872aebbd03cbeeee023dfee2c7e3dc"
}

My code is very simple from example:

conn, err := ethclient.Dial("https://ropsten.infura.io/")
if err != nil {
    ApiUtility.Log("GetTransactionStatus: Unable to connect to ETH Client. "+ err.Error())
    return nil, false, err
}

ctx := context.Background()
txt, pending, err := conn.TransactionByHash(ctx, common.HexToHash(id))

if err != nil {
    ApiUtility.Log("GetTransactionStatus: Unable to get Transaction hash. "+ err.Error())
    return nil, false, err
}

return txt, pending, nil

I have searched a lot. In Web3, they mentioned that Event logs must be used but there is nothing about go library.

Please help.

Thanks


texts: How to update the Ethereum Wallet Solidity Compiler

texts:
I'm using the latest Ethereum Wallet version which is 0.9.0 and I want to update my latest Solidity compiler since it seems that the wallet is using this version

0.4.13+commit.0fb4cb1a.Emscripten.clang

I wanted to update the compiler in order to execute the Shareholders Association code in ethereum.org without error. The error I've been having is this:

Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.

I've read a previous post about how to know the Solidity Compiler version which is this link:

How do I find out the solidity compiler version I am using?

However, the answers are not necessarily giving instructions on how to update the compiler.


texts: Converting tokens with different decimal places

texts:
Hi let's say I have a smart-contract that converts one erc20 for another erc20.

erc20A is set up with 18 decimals

erc20B is set up with 6 decimals

i want to convert 10 erc20A tokens to 10 erc20B tokens, and keep them in their respected format.


texts: Can I reduce the space chaindata takes up?

texts:
So the size of my chaindata folder has snowballed to close to 80GB. Is there a way to reduce it or is the only way to delete it and resync geth with --syncmode fast?

Thanks!


texts: Avoiding congestion in large scale contracts

texts:
I have a contract that will implement a client/server-like functionality through the use of of events (peers have event listeners and make method calls depending on the events they are listening to).

If each peer listens to a an event bound to a method that all remaining peers call then the respective peer will get flooded with log data. I was thinking about writing multiple method with different names but same argument list and functionality and use a scheduler to select one based on a seed provided by the caller. Are there any large scale contracts with thousands of interacting peers? If yes, how is complexity managed?


texts: STOP after RETURN in bytecode generated by solidity

texts:
I am currently analyzing the code generated by the solidity compiler. Let's take this simple example:

pragma solidity^0.4.24;
contract test {
    constructor() public { }
}

The code generated with REMIX IDE (with compiler
(version:0.4.25+commit.59dbf8f1.Emscripten.clang) (after removing the 43 bytes of SWARM hash) is the following one:

PUSH1 0x80
PUSH1 0x40
MSTORE
CALLVALUE
DUP1
ISZERO
PUSH1 0xF
JUMPI
PUSH1 0x0
DUP1
REVERT
JUMPDEST
POP
PUSH1 0x35
DUP1
PUSH1 0x1D
PUSH1 0x0
CODECOPY
PUSH1 0x0
**RETURN**
**STOP**
PUSH1 0x80
PUSH1 0x40
MSTORE
PUSH1 0x0
DUP1
**REVERT**
**STOP**

In the yellow paper it is specified that return opcode halts the execution. Why would one also call stop after return?


texts: How would I return a nested array of string in this situation?

texts:
I am trying to create a function where if you call getDeployedCampaigns, it will output both the address and the string. I want the array of title strings to return with the array of addresses but nested dynamic arrays is not implemented in solidity. Is there a way I can work around this issue so I can return both the arrays of addresses and arrays of string?
pragma solidity ^0.4.17;

contract ContractFactory {
    address[] public deployedCampaigns;
    string[] public title;

    function getDeployedCampaigns() public view returns (address[], string[]) {
        return (deployedCampaigns, title);
    }

    function createCampaign(uint min, string name) public {
        address newCampaign = new Campaign(min, name, msg.sender);
        title.push(name);
        deployedCampaigns.push(newCampaign);
    }
}

contract Campaign {

    address public organizer;
    uint public minContribution;
    string public title;

    function Campaign(uint min, string name, address creator) public {
        organizer = creator;
        minContribution = min;
        title = name;
    }
}

What I'm trying to do is when I make the webpage using react, the campaign address and name will show up for every campaigns created.

Right now, 0 and 1 is there in place of the title because I couldn't figure out how to get this to work.
static async getInitialProps() {
        const campaigns = await factory.methods.getDeployedCampaigns().call()

        return { campaigns: campaigns }
}

renderCampaigns() {
        const items = this.props.campaigns.map((address, title) => {
          return {
            header: title,
            description: (
                <Link route={`/campaigns/${address}`}>
                    View Campaign
                </Link>
            ),
            meta: address,
            fluid: true
          };
        });

        return <Card.Group items={items} />;
    }


texts: Error "no key for given address or file" when unlocking coinbase account

texts:
Using json-rpc eth_unlockAccount() method I can unlock everyone of my node accounts except coinbase. When trying to unlock coinbase account, geth responds with the message:

  no key for given address or file.

I've bee reading Ethereum Wallet: error of no key for given address or file but I am not using Ethereum Wallet, but just json-rpc calls to geth node. Nevertheless I have restarted geth node, as recommended in the answer, but still the same error.

How can I unlock coinbase account? Why the error:

  no key for given address or file.

P.S.: Trying to unlock the coinbase account directly with command line, same result:

$ geth --testnet --unlock 0x47978a69f410d0f61850c92acdb0d4c464d70937

  Fatal: Failed to unlock account 0x47978a69f410d0f61850c92acdb0d4c464d70937 (no key for given address or file)


texts:
I would like to set array contents using data present in another one. I'm tring to use the function below but got opcode error. Can anyone explain me why?
function getfreecars() public returns(uint) {
      for (uint i=0;i<car.length; i++){
          if(car[i].status == 0){
              freecars.push(Car({
                        car_name:car[i].car_name,
                        plate:car[i].plate,
                        status:car[i].status
              }));
          }
          else{}
      }
      return freecars.length;

  }

I leave also complete code:
pragma solidity ^0.6.0;

contract new_client {
    enum carstatus {free, rented, maintenance}
    enum isclient {client, not_client}
    uint clientstatus;
    uint public refclient;

    struct Car {
        string car_name;
        string plate;
        uint status;
    }

    mapping(address => Car) booking;
    Car[] public car;
    Car[] public freecars;
     uint c=0;

    struct Client {
        string name;
        string surname;
        uint age;
        bool license;
        address id;

    }

    uint total_client;

    Client[] public client;
    uint numberofclient;

    function innewclient(string memory name_, string memory surname_, uint  age_, bool  license_, address id_) public  {
        require(age_ >= 18, "must be 18 at least");
        require(age_ <= 75, "can't be over 75");

        client.push(Client({
            name: name_,
            surname: surname_,
            age: age_,
            license: license_,
            id: id_

        }));

        numberofclient = client.length;

    }

   function gettotalclient() public view  returns(uint) {

       return numberofclient;
   }

    function gettotalclient2() public view  returns(uint) {

       return client.length;
   }
    function checkifclient(address _id) public view returns(string memory,string memory,uint ,bool ,address) {
        for (uint i=0; i<client.length;i++ ) {
            if (client[i].id ==_id){
                return (client[i].name,client[i].surname,client[i].age,client[i].license,client[i].id);
            }
            else {}
        }

       // return refclient;

    }

  function insertnewcar(string memory model, string memory plate_, uint  status_) public  {

     car.push(Car({
         car_name:model,
         plate:plate_,
         status: status_
     }));

  }

  function gettotalcar() public view returns(uint) {
      return car.length;
  }

  function carlist() public view returns(string memory,string memory,uint) {

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

          return (car[i].car_name,car[i].plate,car[i].status);
      }
  }

  function getfreecars() public returns(uint) {
      for (uint i=0;i<car.length; i++){
          if(car[i].status == 0){
              freecars.push(Car({
                        car_name:car[i].car_name,
                        plate:car[i].plate,
                        status:car[i].status
              }));
          }
          else{}
      }
      return freecars.length;

  }

}


texts:
I have this contract with this functions, why each use different gas amount?

pragma solidity 0.4.24;

contract Foo {
  //transaction cost: 21471 gas
  //execution cost: 199 gas
  //total cost: 21670 gas
  function withoutNewS() external {
    uint256[3] storage data;
  }
  //transaction cost: 21427 gas
  //execution cost: 155 gas
  //total cost: 21582 gas
  function withoutNew() external {
    uint256[3] data;
  }
  //transaction cost: 21533 gas
  //execution cost: 261 gas
  //total cost: 21794 gas
  function withoutNewM() external {
    uint256[3] memory data;
  }
  //transaction cost: 21607 gas
  //execution cost: 335 gas
  //total cost: 21942 gas
  function withNewM() external {
    uint256[] memory data = new uint256;
  }
}


texts: To run a dapp is it required to download the full blockchain?

texts:
In this article
https://medium.com/@mvmurthy/ethereum-for-web-developers-890be23d1d0c
the author writes that

  This means, every person who wants to interact with a dapp
  (Decentralized Application) will need a full copy of the blockchain
  running on their computer/phone etc. That means, before you can use an
  application, you have to download the entire blockchain and then start
  using the application.

Some comments point out that's not correct. What is now true?


texts: How should one approach the signing of ERC20 token transactions with an offline device?

texts:
I use an offline PC as a cold wallet. It works in combination with 2 USB drives: the 1st has Tails OS; the 2nd has my key files, a copy of MyCrypto desktop, and my encrypted account info. I can sign an offline transaction for later broadcasting on a separate connected PC using this set-up. Problem is, I can only do ETH transactions. I'd like to perform similar transactions with ERC20s (specifically, Dai) with this type of solution, but without having to buy a hardware wallet or smartphone.

For example, suppose I transfer some ETH from my cold wallet to a hot wallet, use the hot wallet to purchase some Dai off a DEX, and then finally deposit this Dai back into my cold wallet. What is the best approach to then transfer the Dai from the cold wallet back into a hot wallet using my set-up?


texts: What are IBEP20 _lp and address _wbnb parameter in BnbStaking.sol

texts: I am trying to deploy bnbstaking.sol for my own project by cloning pancakeswap-farm repository. The farm repository has other contracts of MasterChef, Souschef, CakeToken and SyrupBar. For farming all these contracts need to be deployed. I have deployed successfully the remaining smart contracts. If anyone has cloned pancakeswap can they guide me a bit. I do not understand what these two parameters (IBEP20 _lp and address _wbnb ) are and what to assign them . This is the github link.


texts:
I'am trying to create a modifier that allows certain accounts to execute functions.

 address[] authorized;
       function verify (address adrs) internal view returns (bool)
{
    bool exist;
    uint  j=authorized.length;
    uint i =0;
    exist = false;
    address[] memory adrss;
    while (i<j){
        uint x =0;
        if (adrss ==address[i]){
            bool = true;
        }
        i++;
    }
    return exist;
}

  modifie allowed (address adrs){
        require  (  verify(adrs)==true);
                    _; }

anyone how has an idea?


texts: Solidity: accessing a library constant in a contract that imports the library

texts:
Is it possible to access a library constant in a contract that imports the library?

I am using solidity 0.4.11

For instance:

library Lib {

    bytes1 constant flag = 0x01
    ...
}

separate file

import Lib
contract A {
    bytes1 x = (I have tried Lib.flag, and flag, neither works)
}

Trying to use Lib.flag, I get Member "flag" not found or not visible after argument-dependent lookup in type(library Lib).

Trying to use flag, I get Undeclared identifier.


texts:
So I recently withdrew funds from binance to my wallet, unfortunately I input a digit wrong in the address and it’s gone elsewhere.
Is it possible to recover these funds or the funds are completely lost?
Sorry I have very little knowledge of the technical side of crypto but I have no idea where else to get advise on this.
Thank you
L


texts: Truffle compile command stuck at "Compiling your contracts..."

texts: I developed a dapp using my PC (OS: Pop_OS!) and it was running fine. Then I had to format PC and installed new OS (Ubuntu 18.04 LTS), due to some issues in compatibility and performance.After that, I cloned the project from git and installed all dependencies using yarn and tried to compile the contracts. I was using truffle framework 5.0.7 and solidity ^0.5.0. I have done this few times in previous OS, it works fine. But, this time, when I tried to compile the contracts using "truffle compile" command, it stuck at "Compiling your contracts..." and simply exits after some time showing no error. Truffle simply not compiling the contracts.


texts:
What is current payout of ether mining compared by bitcoin mining in terms of usd per unit of electricity/time?
Can hardware designed for bitcoin can be used for ether with same efficiency?

I ask this in particular due to bitcoin halfing of 25 USD per block which as I understand is due to happen in nearest future to estimate if significant mining resources will be moved from bitcoin to ether mining.


texts:
I have variable: TokenPriceWei = 2000 , that means I set 1 token price for 2000 Wei.

When I get msg.value , is it correct tokensAmount = (msg.value / TokenPriceWei) to get correct token Amount?

I'm wondering because i've seen some examples and none of them do that when calculating token /wei rate.


texts: It is possible to run out of gas when calling bytes32[]?

texts: Is possible to run out of gas when calling bytes32[], even when count e.g. 1k entries?


texts:
I have events (fired some time ago by the contract) containing numbers.
I need to load them all, and then to draw a chart.

What I do:

contract.getInitBlock(function(error, value)
{
    var init_block = value.toNumber();
    var prevTransactions = contract.updateHistory({_from: web3.eth.coinbase},
        {fromBlock: init_block, toBlock: 'latest'});
    prevTransactions.watch(function(err, result)
    {
        if(err)
        {
            return;
        }

        add_info_to_history(result);

    });
});

window.setTimeout(function()
{
    chart();
}, 3000);

But this is a bad style.

Question: how can I find out that I got ALL events iterated and it is time to draw chart?


texts: Time locked wallet contract withdraw revert

texts:
I have a time locked wallet code which withdraws the fund after some period:
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

contract TimeLockedWallet {

    address public creator;
    address public owner;
    uint256 public unlockDate;
    uint256 public createdAt;

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    event Received(address from, uint256 amount);
    event Withdrew(address to, uint256 amount);
    event WithdrewTokens(address tokenContract, address to, uint256 amount);

    constructor(
        address _creator,
        address _owner,
        uint256 _unlockDate
    ) public {
        creator = _creator;
        owner = _owner;
        unlockDate = _unlockDate;
        createdAt = block.timestamp;
    }

    // keep all the ether sent to this address
    receive() external payable {
        Received(msg.sender, msg.value);
    }

    // callable by owner only, after specified time
    function withdraw() onlyOwner public {
       require(block.timestamp >= unlockDate, "reverted here");
       //now send all the balance
       payable(msg.sender).transfer(address(this).balance);
       emit Withdrew(msg.sender, address(this).balance);
    }

    // callable by owner only, after specified time, only for Tokens implementing ERC20
    function withdrawTokens(address _tokenContract) onlyOwner public {
       require(block.timestamp >= unlockDate);
       ERC20 token = ERC20(_tokenContract);
       //now send all the token balance
       uint256 tokenBalance = token.balanceOf(address(this));
       token.transfer(owner, tokenBalance);
       emit WithdrewTokens(_tokenContract, msg.sender, tokenBalance);
    }

    function info() public view returns(address, address, uint256, uint256, uint256) {
        return (creator, owner, unlockDate, createdAt, address(this).balance);
    }

}

When I try to test the code above in JavaScript, it reverts:
let timelockWallet = new TimeLockedWallet(ownerWallet[0]);
await timelockWallet.send(ethToSend, {from: owner});
await timelockWallet.withdraw();

Does anyone know what's wrong with my code? Thanks!


texts:
Is this always necessary?

If for example you are increasing the supply from an external contract, and the supply is already at max, the function will fail and hence revert. There's no need for a return bool to return false as the tx will fail either way.

Why do we include the return bool? Isn't it just wasting gas?


texts: Can I create own public blockchain in Ethereum?

texts:
Is it possible to create own ethereum public network, and use it for my token, created on Solidity?

I want to have cryptocurrency without mining option, which can be traded on markets.


texts: How can I call a library method from a contract?

texts:
I'm currently looking at this contract (https://bscscan.com/address/0x05ff2b0db69458a0750badebc4f9e13add608c7f#code) (yes, I'm aware it's bsc and not eth, but functionally, they're the same).
Inside of it, there's a library called PancakeLibrary with a method called pairOf. I'm trying to call this method but I couldn't find anything for calling a library method in a contract using web3 or ethers in nodejs.
I've tried manually rewriting the contract and I've gotten this so far:
let factory = '0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F';
let address1 = '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82';
let address2 = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c';
console.log(ethers.utils.solidityKeccak256(['uint32', 'string', 'bytes32', 'uint32'], ['0xff', factory, ethers.utils.solidityKeccak256(['string','string'], [address1, address2]), '0xd0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66']));

It's not working and I assume it's because the types I have aren't correct because changing them yields different results.
How can I either call the contract library method directly or rewrite it using ethers? Any help is greatly appreciated.


texts:
The test contract is

pragma solidity ^0.5.0;

contract Test{
    event Here(uint256 indexed a);
    uint256 public a;

    function add() public returns (uint256){
        a += 1;
        emit Here(a);
        return a;
    }
}

So I use this below method to listen event according to https://web3py.readthedocs.io/en/stable/filters.html#asynchronous-filter-polling

from web3 import Web3
import asyncio

provider = Web3.HTTPProvider([A INFURA URL])
web3 = Web3(provider)

# this contract has been deployed on the rinkeby net
contract_address = '0x6c0827Aa560Bff3D316C9BfC700E7806e11e0a7F'
contract_abi = '[{"constant":true,"inputs":[],"name":"a","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"add","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"a","type":"uint256"}],"name":"Here","type":"event"}]'

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

def handle_event(event):
    print(event)
    # and whatever

async def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
        await asyncio.sleep(poll_interval)

def main():
    block_filter = web3.eth.filter('latest')
    tx_filter = web3.eth.filter('pending')
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(
            asyncio.gather(
                log_loop(block_filter, 2),
                log_loop(tx_filter, 2)))
    finally:
        loop.close()

if __name__ == "__main__":
    main()

That is all, the question is that it does not work. please give any advice, thanks.


texts: Error: Invalid number of parameters (regular getter function). Got 0 expected 1!

texts:
Playing with drizzle, I am trying to use a getter for an uint variable campaignCounter, that gets incremented by 1 whenever a factory creates a new campaign.

Here is my component's code:

import React, { Component } from "react";

class ReadCounter extends Component {

  state = { dataKey: null};

  componentDidMount() {
    const { drizzle, drizzleState } = this.props;

    const contract = drizzle.contracts.CampaignFactory;

    const dataKey = contract.methods.campaignCounter.cacheCall({from: drizzleState.accounts[0], gas: 3000000});

    this.setState({ dataKey });
  }

  render() {
    const { CampaignFactory } = this.props.drizzleState.contracts;

    const campaignCounter = CampaignFactory.campaignCounter[this.state.dataKey];

    return <p> Number of campaigns {campaignCounter && campaignCounter.value}</p>;
  }
}

export default ReadCounter;

In the console i get the following error:

index.js:1375 uncaught at _callee at _callee
 at contractsSaga
 at takeEvery
 at callCallContractFn
 Error: Invalid number of parameters for "campaignCounter". Got 0 expected 1!

I have tried:

const dataKey = contract.methods.campaignCounter.cacheCall({from: drizzleState.accounts[0]});

and

const dataKey = contract.methods.campaignCounter.cacheCall();

For each case the same error is thrown.

My setup:

Truffle v5.0.18 (core: 5.0.18)
Solidity v0.5.0 (solc-js)
Node v10.16.0
Web3.js v1.0.0-beta.37

Why does it expect a parameter for a getter function that only returns an uint? And what would be the parameter?

Thanks

---EDIT

pragma solidity ^0.5.0;

contract CampaignFactory {

    address[] public deployedCampaigns;
    uint public campaignCounter;

    function createCampaign(uint minimum) public {

        address newCampaign = address (new Campaign(minimum, msg.sender));
        deployedCampaigns.push(newCampaign);
        campaignCounter++;
    }

    function getDeployedCampaigns() public view returns(address[] memory) {
        return deployedCampaigns;
    }
}


texts: Which version of web3 is more current, 1.0.0-beta2 or 1.0.0-beta.29

texts:
I just ran npm outdated on my project and it shows

Package       Current       Wanted         Latest
web3    1.0.0-beta.29  1.0.0-beta2  1.0.0-beta.29

However web3 has a rather dreadful history with respect to version naming and so forth.

Running npm view web3 versions gives a long list ending in

[...
'1.0.0-beta.28',
'1.0.0-beta.29',
'1.0.0-beta1',
'1.0.0-beta2' ]

But if I go to the 1.0 branch in Github, package.json shows the version as 1.0.0-beta.29

Is 1.0.0-beta2 truly more recent than 1.0.0-beta.29?


texts:
Is it bad practice to return dynamic arrays in case they grow beyond the block gas limit?
If the array grew too large you would no longer be allows to access this array?
The other alternative I see is to return the length of the array and then send many queries to retrieve each member in the list.


texts: Where can I find the snarkverify precompile (opcode) implementation in parity and the example coin mixing contract that utilizes it?

texts:
With the recent announcement of zkSNARKs support and the ZoE (ZeroCash over Ethereum) mixing contract (https://z.cash/blog/zksnarks-in-ethereum.html)

Where can I find the mentioned parity branch and any accompanying examples of the coin mixing contract?


texts: Does Ethereum Wallet not sync ERC-20 tokens in light mode?

texts:
As of 0.9.1 Ethereum Wallet rolled out a "sync with light client (beta)" functionality. However, on my machine it does not seem to update ERC-20 token values, only eth count.

Is that the actual case? Does this feature not yet support synchronization of tokens?


texts: Calling the fuction GetEthToTokenInputPrice

texts:
Please help since I'm getting furious over this problem.
I deployed a contract to the ropsten network, and am trying to call a function getEthToTokenInputPrice to see if it worked through solidity. I have no idea how this works.
This is what i currently have
pragma solidity ^0.5.11;

contract A { // This doesn't have to match the real contract name. Call it what you like.
   address addressB;
   function setAddresssB(address _addressB) public{ // No implementation, just the function signature. This is just so Solidity can work out how to call it.
       addressB = _addressB;
   }
}

contract B {
  function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought) ;
  }


texts: Accessing mapping inside object with web3.js

texts:
Good day.

I have a struct object called HomeWork

HomeWork[] public homeworks;

struct HomeWork{
    uint256 assignId;
    string description;
    mapping(address=>uint256)handedAt;
    mapping(address=>bool)passedOrFailed;

};

As you can see, this object contains nested mappings inside.

I'm trying to interact with this object using web3.

contract = web3.eth.contract([ABI]).at("0x0..");
var homeworks = contract.homeworks();

But when I'm examining specific instance, I can't get any information about the mappings:

  [>homeworks(2)]

  [>BigNumber, "this is description for item number 3"]  * there should be 2 mappings here *

That's it. the mappings aren't there at all.

Any idea what might be the problem?


texts: TypeError: LoginContract.LoginAttempt is not a function

texts:
Here is my Login.sol

pragma solidity ^0.4.2;

contract Login {
   event LoginAttempt(address sender, string challenge);

   function Login (string challenge) public {
       LoginAttempt(msg.sender, challenge);
   }

}

Here is my server.js

const LoginContract = new web3.eth.Contract(abiLogin);

// LoginAttempt is the name of the event that signals logins in the
// Login contract. This is specified in the login.sol file.

loginAttempt = LoginContract.LoginAttempt({});

challenges = {};
successfulLogins = {};

loginAttempt.watch({}, '', function(error, event) {
    if(error) {
        console.log(error);
        return;
    }

    console.log(event);

    const sender = event.args.sender.toLowerCase();

    // If the challenge sent through Ethereum matches the one we generated,
    // mark the login attempt as valid, otherwise ignore it.
    if(challenges[sender] === event.args.challenge) {
        successfulLogins[sender] = true;
    }
});

I don't know what is wrong with my code, I followed the instruction from https://auth0.com/blog/an-introduction-to-ethereum-and-smart-contracts-part-2/

But for some reason, my contract's event is unable to be watched. Can someone help me solve this issue?

EDIT 1
Since I need to deploy the contract, I changed my code above into these things below

let LoginContract = new web3.eth.Contract(abiLogin);

web3.eth.personal.unlockAccount('6ded1c5b448819a6cde4293e33fbe54583ef5c52', 'bank')
.then(result => {
    util.log(`>>>>> contractApi - Is bank account unlocked ? ${result}`);
    util.log('>>>>> contractApi - Ready to deploy Login contract');

    LoginContract.deploy({
        data: '0x'+binLogin,
        arguments: ['']
    })
    .send({
        from: '6ded1c5b448819a6cde4293e33fbe54583ef5c52',
        gas: gas
    })
    .on('receipt', receipt => {
        util.log(`>>>>> contractApi - Login Contract sucessfully deployed @ address: ${receipt.contractAddress}`);
        // LoginAttempt is the name of the event that signals logins in the
        // Login contract. This is specified in the login.sol file.

        const loginContract = LoginContract.at(`${receipt.contractAddress}`)

        loginAttempt = loginContract.LoginAttempt();

        challenges = {};
        successfulLogins = {};

        loginAttempt.watch((error, event) => {
            if(error) {
                console.log(error);
                return;
            }

            console.log(event);

            const sender = event.args.sender.toLowerCase();

            // If the challenge sent through Ethereum matches the one we generated,
            // mark the login attempt as valid, otherwise ignore it.
            if(challenges[sender] === event.args.challenge) {
                successfulLogins[sender] = true;
            }
        });

        secret = process.env.JWT_SECRET || "my super secret passcode";

        util.log('>>>>> setup - Completed !!!')
    });
}, error => {
    util.log(`***** contractApi - Bank account unlock error - ${error}`);
});

But a new error occurs, TypeError: LoginContract.at is not a function. What should I do in this case? Does this issue related with web3 module installation?


texts: How to use private blockchains in ethereumjs-tx@2.1.2?

texts:
I know this method
var transaction = new Tx(rawTransaction, {chain:'ropsten'});

I tried
var transaction = new Tx(rawTransaction, {chain:'192.168.XX.XX:8545'});

But get Error: Chain with name 192.168.XX.XX:8545 not supported
Any help with this is much appreciated, thank you!


texts: Cannot find module ethereumjs-tx even though it is there

texts:
I'm trying to send a signed transaction from a web interface using web3, web3 is loaded and I'm connected to an Infuro.io node. Ethereumjs-tx is installed and I've also included it as seperate JS, but whatever I do I keep getting the error message 'Cannot find module ethereumjs-tx'

Really a loss as to what to do, it's clearly in the node_modules folder as well as being loaded as a seperate script. How can the module not be found?

  web3 = new Web3(new Web3.providers.HttpProvider("<TOKEN>"));
          var tokenContract = web3.eth.contract(human_standard_token_abi);
          var tokenRunning = tokenContract.at('0x5780a5928becc986edd597991a1a1af6357fdf05');
          console.log('Balance is equal to ' + tokenRunning.balanceOf('" . $ETH_ADDRESS . "').toNumber() + ' tokens');

          var Tx = require('ethereumjs-tx');
          var privateKey = new Buffer.from('42d14f44661a68167622a3200f3a2555665b2f4f4d0e4f0e8ce878c0c3d6e6bf','hex')

          var rawTx = {
            nonce: '0x00',
            gasPrice: '0x09184e72a000',
            gasLimit: '0x2710',
            to: '0x0Cf9Dd61389Be41CD620C99579B6Ff1A8Be3B3fb',
            value: '20',
            data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
          }

          var tx = new Tx(rawTx);
          tx.sign(privateKey);

          var serializedTx = tx.serialize();

          //console.log(serializedTx.toString('hex'));

          web3.eth.sendRawTransaction(serializedTx.toString('hex'), function(err, hash) {
            if (!err)
              console.log(hash);
          });

Can it be the CDN of Web3 I'm using? Is there a CDN to include ethereumjs-tx?

The CDN I'm using is loaded like this

  <script src="https://cdn.jsdelivr.net/npm/web3@0.20.1/dist/web3.min.js"></script>


texts:
any one please help when show QR for receiving erc20 token can i enter amount like  "ethereum:ethaddress?address=contractaddress&uint256=token" not working
"ethereum:0x9610a371f94be34d4d0cb9c35d621d657133c0e5?value=2.014e18" likewise how to use for erc20


texts:
I wrote my erc20 token by solidity and the decimals of token is 18.
I'm testing the smart contract on truffle and one thing that I noticed was the octal number is returned when I called the balanceOf() function.
I want to check the balance of accounts as decimals which is fixed as 18.
For example, I want to transfer the 1.001 or 22.0000003  and then get the return value of balanceOf() as 23.0010003.
However, this is the result I got.

> cc.transfer(user1, 000000000000000100, {from: owner})
{ [String: '512'] s: 1, e: 2, c: [ 512 ] }

How can I transfer or check the balance as fixed 18 Decimals not the octal number? Please help!


texts: Make Smart Contract Only Accessible from a Web App

texts: I have got a Solidity smart contract which only interacts with a React front-end using web3. I want to restrict access to the smart contract so that only the React front-end can access the smart contract. This should prevent other contracts or dapps being able to call the contract. How can this be done?


texts: How does a smart contract hold funds without holding private keys?

texts:
I understand that smart contracts:

Don't have private keys
They can hold, receive and spend ether

How does the latter work ? Let's say I want to send 1 eth to a smart contract and leave it locked up in there until person B calls some function on the same contract. How does the smart contract hold my 1 eth and how does it get freed up again upon receiving the signed transaction from person B ?


texts: I accidentally deposited all my tokens and ETH with with Etherscan, how can I get back?

texts:
I screwed up the first time on site and I transferred 1 ETH to buy coins then rather than depositing coins into myetherwallet, I used the wrong address and sent to Etherscan. I've been able to see them move around a but dont know how to get back or even if I can. I have 990 coins and $400 worth of ETH just gone. I'm bummed. Can anyone help?

I need step by step instructions how to get my tokens back or my ETH so I can buy more.


texts: My wallet got hacked - I do not know what do to

texts:
Someone hacked my eth wallet and when ever I deposit ethereum to the wallet my deposited ethereum is sent directly to his wallet automatically.. Pls how can I stop this issue because my wallet has my useful coins which I want to withdraw. I need help guys please. Am not a programmer
But please guys help me am running mad


texts: What happens after selfdestruct is called?

texts:
https://ropsten.etherscan.io/address/0xf825d3b3d06a4b46379a3c276df7f26abd055463

After selfdestruct call was made, all the balance was transferred to the deployer of the contract. Why are withdraw requests still being processed?


texts: Transaction included in block whereas log not generated

texts:
When I sent a transaction continuously below 27 Transaction Per Second (TPS) then all transaction is included in a block and generated the log as expected.
Whereas When TPS increases above 27 then included transaction not generated the log (empty log) when I checked in the particular block using transaction hash.

Edit:
 Contract is a simple function with 12 arguments and which have to store in the state and finally emit the log after updating the state in each transaction without any validation.


texts: How to flush token to another contract from token holder's token balance from ERC-20 contract?

texts:
I have to implement the following scenario:
- One ERC-20 token contract.
- Another contract which will flush tokens of ERC-20 tokens.
- Add these tokens to one, defined Admin address.

Note: All procedure without using forwarder address.


texts:
I'm currently trying to get a deeper understanding of how transactions in the Ethereum Blockchain work. A not so trivial example seems to track token balance of an address.

I thought about the following example: Having nothing but an address and a full node, how can I get all the transactions made by this address, including token transfers and amount of transferred tokens?

I understand that tokens are not more than mapped addresses in a smart contract (correct me if I'm wrong) and so my first thought was to just read the balanceOf() method (assuming its ERC20 standard). But that would just give me the current amount, not all the past transactions.

So what gives me some headaches now is trying to "connect" (like wire the concept in my brain) addresses and smart contracts. How to determine if an address is a smart contract, figure out if the given address is holding (or held) tokens of that contract and if so, get the transaction history of the given address. Furthermore, is there some kind of identifier to transactions?

An example so you get what I mean:
I trade some tokens on Etherdelta (just an example, idk if it is a good one) and the I/O order to my address is not "First in, First out", how can I know which transaction belongs to which trade?

(all tokens are the same)

I send 10 tokens(A) to Etherdelta
I send 12 more tokens(B) to Etherdelta
I send 3 more tokens (C) to Etherdelta
I recieve 0.24 Eth from trade B
I recieve 0.10 Eth from trade A
I recieve 0.03 Eth from trade C

If you didn't already get what I was talking about, I guess you're getting it now. Even if I would be able to track all those transactions from the given address, is it possible to determine transaction pairs, like corresponding A, B and C in the example above?

Thanks for any help!


texts: Can we have an array of Ether in Solidity?

texts:
My ultimate goal is to have an array of token, e.g.

 mapping (address => x) token_balance;

where x is of type a float/double.

As far as I'm aware, Solidity does not support float/double values.

However, wie or ether etc supported and wie is a fraction of Ether. So, if we can have an array of Ether, then we might be able to handle float/double. Because, for instance, we can add one wei to token_balance["address"]+=wei;

Question 1: In Solidity, can we have any array of Ether, like:

  mapping (address => Ether) balances

Why do I need an array of float? Because, the token holders will be charged this amount: x= t.10/T, for doing certain actions; where t is total the token a token holder has, and T is the total number of token all token holders have. So x is a float value, even if t and T are integer values.


texts: what is the meaning of 0x0? say when variable gets assigned to it, example: keccak256(number) = 0x0;

texts:
Is 0x0 just zero? thanks

keccak256(number) = 0x0;

Or when not used as address I mean just to denote variable?


texts:
So I've been playing around with the following code which represents a simple leaderboard implementation - how do I make sure that the same user is not represented on the leaderboard twice and rather update his score if his already on the leaderboard?
pragma solidity 0.8.0;

contract Leaderboard {

  // person who deploys contract is the owner
  address owner;

  // lists top 10 users
  uint leaderboardLength = 10;

  // create an array of Users
  mapping (uint => User) public leaderboard;

  // each user has a username and score
  struct User {
    string user;
    uint score;
  }

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

  // allows owner only
  modifier onlyOwner(){
    require(owner == msg.sender, "Sender not authorized");
    _;
  }

  // owner calls to update leaderboard
  function addScore(string memory user, uint score) onlyOwner() public returns (bool) {
    // if the score is too low, don't update
    if (leaderboard[leaderboardLength-1].score >= score) return false;

    // loop through the leaderboard
    for (uint i=0; i<leaderboardLength; i++) {
      // find where to insert the new score
      if (leaderboard[i].score < score) {

        // shift leaderboard
        User memory currentUser = leaderboard[i];
        for (uint j=i+1; j<leaderboardLength+1; j++) {
          User memory nextUser = leaderboard[j];
          leaderboard[j] = currentUser;
          currentUser = nextUser;
        }

        // insert
        leaderboard[i] = User({
          user: user,
          score: score
        });

        // delete last from list
        delete leaderboard[leaderboardLength];

        return true;
      }
    }
  }
}


texts: Understanding Solidity Libraries using Solidity Docs code example

texts:
I was going through this code (see code below) about how to use libraries in solidity docs :
https://solidity.readthedocs.io/en/v0.4.24/contracts.html?highlight=library#libraries and there are some things I really don't understand.

pragma solidity ^0.4.16;

library BigInt {
    struct bigint {
        uint[] limbs;
    }

    function fromUint(uint x) internal pure returns (bigint r) {
        r.limbs = new uint[](1);
        r.limbs[0] = x;
    }

    function add(bigint _a, bigint _b) internal pure returns (bigint r) {
        r.limbs = new uint[](max(_a.limbs.length, _b.limbs.length));
    //I understand that in the line above we are tying to get the array with
    //the greatest length then initializing a new r.limbs array with that
    //length. Why is this being done?

        uint carry = 0;
    //What is the purpose of this "uint carry"?

        for (uint i = 0; i < r.limbs.length; ++i) {
            uint a = limb(_a, i);
            uint b = limb(_b, i);// why are we running this function?
            // What is the significance of the value we get from this
            // function? limb()
            r.limbs[i] = a + b + carry;
            if (a + b < a || (a + b == uint(-1) && carry > 0))
                carry = 1;
            else
                carry = 0;
        }//Why is Carry = 1 or zero what is the significance?
        if (carry > 0) {
            // too bad, we have to add a limb

            uint[] memory newLimbs = new uint[](r.limbs.length + 1);
            for (i = 0; i < r.limbs.length; ++i)
                newLimbs[i] = r.limbs[i];
            newLimbs[i] = carry;
            r.limbs = newLimbs;
        }// What exactly is a limb? Is it an empty array slot? Because from
    }// my understanding of the code above all that's happening is the
    //addition of the array length but no value is passed to the new slot.

    function limb(bigint _a, uint _limb) internal pure returns (uint) {
        return _limb < _a.limbs.length ? _a.limbs[_limb] : 0;
    }// What does the last line in this function mean?
     // What is the use of the question mark?
     // What is the use of the colon?

    function max(uint a, uint b) private pure returns (uint) {
        return a > b ? a : b;
    }
}

contract C {
    using BigInt for BigInt.bigint;

    function f() public pure {
        var x = BigInt.fromUint(7);
        var y = BigInt.fromUint(uint(-1));
        var z = x.add(y);
    }
}

Is it a method to store big integers using arrays in solidity? I am asking because the library name and the struct name are both BigInt and the array in the first function has a length of 1... I mean why not just make it an Unsigned Integer?
In the library a struct bigint is defined, then in the functions bigint is used as a value type. E.g in the first function when defining the returns parameter ***returns (bigint r). Why is it being done like this?
Then, in the second function, this is where I get totally lost. I have so many questions I have commented them in the code...

Thank you in advance.


texts: Geth message: Regenerated Local Transaction Journal

texts: When I'm running geth to sync the blockchain, sometimes the message "Regenerated local transaction journal" appears, what does it means?


texts: Ethereum: Which endpoint can I use for testing?

texts:
I am developing python project using web3.py.
Myetherwallet API is used.
I'm gonna test get_balance().
Here used endpoint is live net.
What is endpoint for testing? Can I use above descrived endpoint for testing?


texts:
While following this udemy tutorial I've managed to set up two nodes using with Clique and using puppeth. But the problem arises when I am about to launch the first node. This is the command

geth --networkid 1015 --datadir "./data" --bootnodes enode://876091d0a5577a006d458e5f8dc3eb7e46569969c3972f32a39e7cc92d35427ce7e03c11d336efa7b8d7e6b2563beb7c97b6a51ae9209b76a9b4f199b34a8787@127.0.0.1:30310  --port  30303 --ipcdisable --syncmode full --rpc --rpccorsdomain "*" --rpcport 8545 --unlock bc758cc69671f3bb2a4f0ab9aa3ca233d0074c0a --password password.txt --mine console

I have double checked the password.txt file and it exists in the specified directory. I am even running the command in the node1 directory which contains the file but I get the following error.

Fatal: Failed to unlock account bc758cc69671f3bb2a4f0ab9aa3ca233d0074c0a (no key for given address or file)

I have written the correct password in the file but somehow it is not getting it. What do I do?

EDIT:
I tried what was suggested in this question too but it did not help.

Full stacktrace

INFO [10-09|15:07:05.770] Maximum peer count                       ETH=25 LES=0 total=25
INFO [10-09|15:07:05.785] Starting peer-to-peer node               instance=Geth/v1.8.15-stable-89451f7c/windows-amd64/go1.10.3
INFO [10-09|15:07:05.790] Allocated cache and file handles         database="E:\\Blockchain first step\\Private Network2\\usingpoa\\node1\\data\\geth\\chaindata" cache=768 handles=1024
INFO [10-09|15:07:05.853] Initialised chain configuration          config="{ChainID: 1015 Homestead: 1 DAO: <nil> DAOSupport: false EIP150:
2 EIP155: 3 EIP158: 3 Byzantium: 4 Constantinople: <nil> Engine: clique}"
INFO [10-09|15:07:05.872] Initialising Ethereum protocol           versions="[63 62]" network=1015
INFO [10-09|15:07:05.878] Loaded most recent local header          number=0 hash=e4305d…8a9774 td=1
INFO [10-09|15:07:05.884] Loaded most recent local full block      number=0 hash=e4305d…8a9774 td=1
INFO [10-09|15:07:05.890] Loaded most recent local fast block      number=0 hash=e4305d…8a9774 td=1
INFO [10-09|15:07:05.896] Loaded local transaction journal         transactions=0 dropped=0
INFO [10-09|15:07:05.902] Regenerated local transaction journal    transactions=0 accounts=0
INFO [10-09|15:07:05.907] Starting P2P networking
INFO [10-09|15:07:08.060] UDP listener up                          self=enode://fe6c5b1aa37c182a0c466be231921c54a469a38163e081a85751b319ea351f385ede5ae20c6cfe4c6d742bbc592420bb5102b89d15c83eed330576951382129a@0.0.0.0:30303
INFO [10-09|15:07:08.079] HTTP endpoint opened                     url=http://127.0.0.1:8545 cors=* vhosts=localhost


texts:
I have below configuration laptop

  windows 7 64 bits

  AMD A4-3305M APU with Radeon HD Graphics,

  4 GB RAM

  AMD RADEON HD 6480G

"" CAN I MINE ETHEREUM ON MY LAPTOP ""

Thanks in advance.. Please guide..


texts: Getting error in Deposit function in smart contract : The constructor should be payable if you send value

texts:
I am getting the error while deposit the amount in remix.

Following is my code

 pragma solidity ^0.4.19;

 contract Savings {
 address owner;
 uint256 deadline;

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

function deposit(uint256 amount) public payable {
    require(msg.value == amount);
}

function Savings(uint256 numberOfDays) public payable {
    owner = msg.sender;
    deadline = now + (numberOfDays * 1 days);
}

function withdraw() public onlyOwner  {
    require(now >= deadline);

    msg.sender.transfer(address(this).balance);
  }
}


texts: Can blockchain technology can ever be useful if the currency conversion to fiat money is volatile?

texts:
From my limited understanding of blockchain technology in general and ethereum in particular, whatever the token, or ether that this technology uses, eventually it has to be related to fiat money. Eg: a gas has to be paid for in ether, which can be purchased from fiat money such as USD.

So whatever the benefits of blockchain promises, such as displacing much of the sector’s infrastructure, cutting out middlemen, speeding transactions and reducing costs for things like securities and payments processing, the usefulness of blockchain technology is very much limited by the stability of the currency conversion; if the price is volatile, then blockchain can't be widely adopted because no one would want their investment to drop 50% overnight.

Am I right on this? If yes, why banking and logistic sectors are still implementing the blockchain technology right now when the price is violatile?


texts: Is it ok to Use Javascript VM in remix IDE to know the Gas values?

texts: Just wanted to know that using the Gas values generated for a contract in Remix IDE when Javascript VM option, does the Gas values are useful when deploying contracts to testnet or live, does the Javascript VM generate accurate Gas values so that it can be used to know the required Gas for a contract or function?


texts: List all transactions to: and from: this.state.account in chronological order web3js

texts:
I'd like my Web3 wallet to list all transactions to: and from: this.state.account in chronological order, currently I am getting a split of transactions, from: listed first and then to: listed second, Is there a way to list to: and from: all in order so the results flow and are not split? If I exclude the filter: altogether, I get all transactions on the blockchain which is in the correct order! -But it lists all transactions from all wallets, I only need the to: and from: this.state.account.

My goal is to list all the transactions of this.state.account in the order they occurred, without listing the activity of other addresses on the blockchain.

Here's what the split results look like showing received (top three tx) and sent (bottom six tx):

Defining const:

    const transactions = (await Promise.all([
      Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { from: this.state.account } }),
      Token123.getPastEvents('Transfer', { fromBlock: 0, toBlock: 'latest', filter: { to: this.state.account } })])).flat()
    this.setState({ transactions: transactions })

Here is how I am viewing the results:

                { this.state.transactions.slice().reverse().map((tx, key) => {
                  return (

                      {tx.returnValues.to}
                      {window.web3.utils.fromWei(tx.returnValues.value.toString(), 'Ether')}

                  )
                }) }

Using: "web3": "1.0.0-beta.55"


texts:
I'm currently in the process of writing a game however a question has popped up in my head.

A while back I started writing my game in Solidity (i.e the characters, names, stats etc.) and I had completely forgotten. I was just going to use JavaScript to manipulate how the site/game looks etc.

I recently found my old .sol files whilst I was just planning on how to write the game in javascript (i.e the same thing, characters, names, stats etc.) but then came up with the question on, is there really a difference between Solidity and Javascript on how the game will handle, so should I carry on writing as much as my game as possible in Solidity and for those bits I cannot do, write in Javascript.

Or should I just use Solidity to handle the backend of the game (for example, the process of managing money, rewards, payment etc.)?
Any ideas?
Thanks,
Sam


texts: How to permission (disallow) smart contract deployment on private Ethereum network?

texts:
On a private Ethereum network, what is the best way to permission the deployment of who (and what) users can deploy?

One obvious way would be increasing the gas cost of CREATE opcode. Yet, I do not like sending a lot of ETH in order to allow the deployment of a SC.

Can this be controlled via another smart contract or would changes to the node software be needed?


texts:
do you have any cheat sheet in order how the variables should be ordered to achieve best possible packing and to be more gas efficient
For example I know bool takes 8 bits, address takes 20 bytes but what is the correct order for all do you have any idea? Thanks in advance!


texts: Do you need the fully synced node before sending a transaction to the network?

texts: I'm trying to create a wallet locally. I can create an externally owned account using geth that is connected to a local test chain. Now I would like to "push" that account to the real blockchain. Does my geth node need to be fully synced (either fast or regular) in order to send that Tx to the network?


texts: Sent Ether to ICO from my Jaxx wallet - How can I get token to show in my Etherwallet?

texts: I've participated in an ICO by sending Ether from my Jaxx wallet, how can I make the new token show in myetherwallet?


texts: Programming contracts and blockchain: Where do I start?

texts:
So I'm doing my academic practices in my university and I'm assigned to a company that has plans of doing blockchain projects. Neither of them has actually been defined so far, and I'll work alone.

I don't have previous experience in the blockchain field and the only formation I've been given is a bunch of video courses. The theory behind the technology is okay (pretty interesting, tbh), but for the application, most of them are outdated and I find it impossible to follow the course. Here's an example of what I'm talking about.

I've spent the previous days trying to follow tutorials, but there's always something that differs from what it is expected to happen and what actually happens when I follow the instructions. Version errors, this tool doesn't work, this one is discontinued... My tutor doesn't know much about the technology and I've simply been told to "learn" about Solidity and blockchains. I still haven't managed to find a way to apply and test what I have coded in Remix, and there's no way I can know what I'm going to be asked to do yet, since, as I mentioned, the project I'll work on hasn't been defined yet.

Is there any reliable tutorial which is up to date and won't mess with more versions, deprecated stuff and compatibility issues that I can stick with? I'm really lost and desperate at this point. I've tried pretty much everything (and ended up installing a lot of stuff in my computer - geth, parity, truffle, ganache...), but it seems that the easy, understandable documentation and guides are from a little bit ago, while things have changed to this date.

I'll truly appreciate any kind of help. Have a nice day.


texts:
I have a smart contract that uses require to validate the parameters inside some functions and I have noticed that geth 1.9.13 and 1.9.14 do not enforce the condition in require. I could reproduce the problem with this simple smart contract

 pragma solidity >=0.6.0 <0.7.0;

 contract NodeContract {

      // Define the struct with the data of a node
      struct Node {
        // UUID
        bytes32 nodeId;
      }

      uint numberOfNodes = 0;

      mapping (uint => Node) nodes;

      constructor() public {
      }

      function publishNewNode(bytes32 nodeId) external returns(uint256)
      {

        uint256 nodeIndex = numberOfNodes;

        nodes[nodeIndex] = Node({nodeId:nodeId});

        numberOfNodes += 1;

        return (nodeIndex);
       }

      function getNodeData(uint256 nodeIndex) external view returns(bytes32  nodeId)
      {
        require(nodeIndex < numberOfNodes, "The nodeIndex supplied is larger than the number of available nodes");

        return (nodes[nodeIndex].nodeId);
      }

      function nodesCount () external view returns(uint) {
       return (numberOfNodes);
      }
}

If I deploy it on https://remix.ethereum.org/ and I call getNodeData(0) then I get the expected error message Reason provided by the contract: "The nodeIndex supplied is larger than the number of available nodes".. If I deploy that contract in my private blockchain in geth and call myContractInstance.getNodeData.call(0); I get 0x which means that the whole function executes instead of stopping at the require line. Is there a way to fix this and get the expected behavior?


texts: What happens to the missing coins in this transaction? Copy paste this code into remix to reproduce my original bug. Thank you

texts:
pragma solidity ^0.4.24;

contract TheCaseOfTHeMissingCoins{

    string public name;
    string public symbol;
    uint8 public decimals = 18;
    address public owner;

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

    event Transfer(address indexed from, address indexed to, uint256 value);

    constructor(
        uint256 initialSupply,
        string tokenName,
        string tokenSymbol
    ) public {
       initialSupply = initialSupply * 10 ** uint256(decimals);
        balanceOf[msg.sender] = initialSupply;
        name = tokenName;
        symbol = tokenSymbol;
        owner = msg.sender;

    }

        //Using a different account than the one used to initialize the contract
    //please call this function with the value of 5.208333333333330000(ether) in remix
    //then check the account balance
    function TESTbuyCoins() public payable{
        uint amount = TESTcalculateAmountOfCoins(msg.value);
        _transfer(owner, msg.sender, amount);
        owner.transfer(msg.value);
    }
    //we should be getting 250000000000000000000 but instead when this
    //runs we get 249999999999999840000.
    //What happens to the missing coins?

    /**
     * Internal transfer, only can be called by this contract
     */
    function _transfer(address _from, address _to, uint _value) internal {
        // Prevent transfer to 0x0 address. Use burn() instead
        require(_to != 0x0);
        // Check if the sender has enough
        require(balanceOf[_from] >= _value);
        // Check for overflows
        require(balanceOf[_to] + _value > balanceOf[_to]);
        // Save this for an assertion in the future
        uint previousBalances = balanceOf[_from] + balanceOf[_to];
        // Subtract from the sender
        balanceOf[_from] -= _value;
        // Add the same to the recipient
        balanceOf[_to] += _value;
        emit Transfer(_from, _to, _value);
        // Asserts are used to use static analysis to find bugs in your code. They should never fail
        assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }

    /**
     * Transfer tokens
     *
     * Send `_value` tokens to `_to` from your account
     *
     * @param _to The address of the recipient
     * @param _value the amount to send
     */
    function transfer(address _to, uint256 _value) public returns (bool success) {
        _transfer(msg.sender, _to, _value);
        return true;
    }

    function TESTcalculateAmountOfCoins(uint coinsWanted) public returns(uint totalCoins){
            totalCoins = coinsWanted * 48;
        return(totalCoins);
    }
}


texts: Subscription stop after only a few blocks in Web3j

texts:
I am using the following code to catch and receive new transactions:

    DefaultBlockParameter startingBlock = DefaultBlockParameter.valueOf(lastActionedBlockNumber.add(BigInteger.ONE));

web3j.catchUpToLatestAndSubscribeToNewTransactionsObservable(startingBlock).subscribe(transaction -> {
        System.out.println("Processing transaction: " + transaction.getHash());

        //do processing
    });

When running this code against test geth it works totally fine.  However, when it is switched to the main block chain it will only execute one or two blocks then immediately unsubscribe itself.

These are my geth parameters:

Test:

geth --datadir node5 --network 1907 console --rpc --rpccorsdomain "*" --rpcapi "db,eth,net,web3,personal" --rpcaddr localhost --rpcport 8545

Main:

geth --cache 2048 --rpc --rpccorsdomain "*" --rpcapi "db,eth,net,web3,personal" --rpcaddr localhost --rpcport 8545


texts: Private Chain Self-Hosted Mist Wallet Build Issues

texts:
I'm currently trying to deploy a fork of the Meteor Wallet Dapp on a custom private chain and I'm a bit confused at the set up, there seems to be a bit of lacking documentation on how Mist, Meteor-Dapp-Wallet and Meteor-Build-Client work together and how the wallet.ethereum.org server is set up and it has been challenging to try and recreate it externally.

I've forked the Mist Client and did the full:

$ gulp

To build both distributions as well as:

$ meteor-build-client ../build --path ""

from within the interface folder to get my custom build folder with the index.html

Then based on the instructions here in the Meteor-Build-Client repo (https://github.com/frozeman/meteor-build-client) I've set up a server that has meteor installed, has the files from the build folder (such as index.html) in my Apache htdocs, added the required .htaccess modifications and is running a geth node with RPC enabled.

Then on my desktop I launch the Mist client that I tried to build with 'gulp' and I navigate in the browser to my site.

I think I'm missing at least one step here (in relation to connecting the html page to the meteor app on the server. It was pretty unclear where that code goes from the Meteor-Build-Client repo), and I could be missing a few other elements.

Can anyone provide some insights to the current set up of wallet.ethereum.org and the steps that would go into using these packages to recreate that setup?

Thanks for any insights!


texts: Openzeppelin ERC20/StandardToken.sol changes some state variable to private

texts:
I made token based on Openzeppelin ERC20.
Few days before, StandardToken.sol which I imported changed some of its state variables(total supply_, balances) from internal to private.
github history

After changing, my token does not work anymore.
Is there any other ways to import and using the StandardToken?

I use remix IDE.

Thanks.


texts: is Ethereum MIt licensed? Can we use it for business purpose?


texts:
Can we access the struct member using a variable as we access in JavaScript? For example:
struct Abc {
     uint256 a,
     uint256 b
}

Abc xyz;

string memName = 'a';

I want to do something like this:
xyz[memName]

as we can do in JavaScript.


texts: Crowdsale Contract, why I can't send ether to contract?

texts:
Ethereum wallet displays:

It seems this transaction will fail.

But why? Here is the code:

function () payable {
    uint amount = 0;
    amount += msg.value;
    balanceOf[msg.sender] += amount;
    amountRaised += amount;
    tokenReward.transfer(msg.sender, amount / price);
    FundTransfer(msg.sender, amount, true);
}

This code doesn't throw exception or smth... Please help me. I get Crowdsale contract code from ethereum website


texts: How Ethereum nodes are searching for each other?

texts:
I think it's a pretty silly question, but I'm stuck. If Ethereum (or probably any other *coin) is fully decentralized, how can I find any other nodes without scanning all the network?

I mean, if I know at least one address, I can ask: "Can you tell me any other addresses?". Probably it will send me a list of addresses and I'll ask the same question to each of them, etc. But how can I get the first address? Maybe it's hardcoded or something?


texts: Why is a proxy object created when you try to access the same web3 object outside of the scope where it was created?

texts:
I have two functions, called one after another. The first one called creates a new Web3 object and sets it to window.web3:
  async loadWeb3() {
    window.addEventListener('load', async () => {
      if (window.ethereum) {
        window.web3 = new Web3(window.ethereum);
        console.log(window.web3);
        await window.ethereum.enable();
       }
    });
  }

Next, my program calls another function, which tries to access the web3 object which is set to window.web3. Here it is:
  async loadBlockchainData() {
    console.log(window.web3);
  }

So to sum it up, I create a new Web3 object and set it to window.web3 in one function, log it to the console and then in a different function, I log this same object. Here's the catch, you can't do any of the typical things like window.web3.eth.getAccounts() within the loadBlockchainData() function. This is because in the loadBlockchainData() function, window.web3 becomes a proxy object, and is different from the same window.web3 that is defined in the loadWeb3() method. You can try it out yourself.
My question is, why does window.web3 become a proxy object, what makes it a proxy object (metamask? web3.js?), and how do we interact with this proxy object using the web3.js library?


texts: How to list transactions from account address?

texts:
I have a small service where people can exchange cryptocurrencies.
Every user has its own Bitcoin, Litecoin, etc address for balance deposit.
Now I want to add Ethereum. So I thought I will create account for every user and then check for incoming transactions.
But as I understood I can't get a list of transactions from account address.
This is weird. Even in the Mist wallet I don't see where ether comes from.
Only way to get transactions is to check some 3rd party blockchain explorer.

Also as I understood the proper way will be to create smart contract, because it has necessary API. But I can't create contact for each user.

Maybe I need to create only 1 contract that will "redirect" ether to my main account, but this is not very user friendly, because the user will be asked to add some extra data to the transaction so that I could understand who is who.

Any advise will be helpful.


texts: How to run my own full node pool? (error: unexpected identifier)

texts:
When I run this geth with the following parameters:

geth --rpc --rpcaddr "my ip" --rpcport 8545

I get an error like:

(anonymous): Line 1:13 Unexpected identifier (and 1 more errors)

Please help.


texts: Providing base contracts' constructor arguments

texts:
I'm a bit puzzled about multiple inheritance and providing arguments for different constructors. Solidity documentation has long explanations about this (http://solidity.readthedocs.io/en/develop/contracts.html#arguments-for-base-constructors) but (in my opinion) not enough information about base contracts' arguments. It states:

  If the base constructors have arguments, derived contracts need to specify all of them

How does this exactly work when there is a complicated inheritance chart? An example:

pragma solidity ^0.4.0;

contract A {
    constructor(uint paramA) public {

    }
}

contract B is A {
    constructor(address paramB) public {

    }
}

contract C is A {
    constructor(string paramC) public {

    }
}

contract D is B, C {
    constructor(uint paramForA, address paramForB, string paramForC) public // stuff here to call A, B and C constructors with non-static parameters
    {

    }
}

How should contract D specify its constructor arguments for contracts A B and C to provide all required parameters and in what order? Is there only one correct order?


texts:
Why Parity keys are named differently?

I have one in the following format:

UTC--2016-11-21T14-59-51Z--109a31067644516b04549bddcb473e51fd0cf835

And all the rest as:

UTC--2017-04-05T13-01-10Z--d4c80f9f-b59d-9c3e-d2ea-b20073690df8
UTC--2017-04-05T13-00-53Z--49516ba7-ba23-1bae-bcb0-55f315e4a190

My guess was that the unlocked account is renamed to include address, but it seems not to be the case either.

So how can I have all my key files named UTC--2016-11-21T14-59-51Z--address?


texts: Can I call the testnet contract's view from the main-net contract?

texts:
The question may be silly, but it is something I want to play around and experiment with.
I want to call the view function that exists on the test-net from the main-net contract.
Can we do this, and how ?


texts: How a smart contract retrieves information from signed message in solidity?

texts:
A dapp can sign a message with the web3.js:
// recipient is the address that should be paid.
// amount, in wei, specifies how much ether should be sent.
// nonce can be any unique number, used to prevent replay attacks.
// contractAddress is used to prevent cross-contract replay attacks.
function signPayment(recipient, amount, nonce, contractAddress, callback) {
  var hash = "0x" + ethereumjs.ABI.soliditySHA3(
    ["address", "uint256", "uint256", "address"],
    [recipient, amount, nonce, contractAddress]
  ).toString("hex");

  web3.personal.sign(hash, web3.eth.defaultAccount, callback);
}

The signed message can be sent when calling function in smart contract and there is built-in solidity function ecrecover which can recover the address used to sign the message. How does the smart contract recover other information such as recipient, amount, nonce, contractAddress in the signed message for further verification? For example, the smart contract can compare his own address with the contractAddress in signed message to make sure the message was indeed for him.


texts: metamask pending transaction cannot find at MEW

texts:
need your help.
While I was sending my eth to somewhere from metamask, it somehow made two different transactions. 1st one was 9.98 eth, and 2nd one was 9.97 eth.
Since my metamask wallet only had 10 eth, the 1st one (9.98 eth) finally made a transaction after few hours. But the 2nd one (9.97eth) is still pending in my metamask.
The problem arise from here is that, I can't do other transactions since that 2nd one is still in pending. So, I tried to find from the Internet how I can cancel the transactions and follow. I tried the method that go to the MyEtherWallet and paste the TX Hash. But it tells that the TRANSACTION cannot find.
TX HASH: 0x51dcd6319ed331a79630fdf766d59f9605e782b183428f82dbdca801e275e118

I don't know how to handle this. Please help.
Thank you.


texts: is it possible to get address and private key from mnemonic code?

texts:
I have question

Is it possible to get address and private key from mnemonic code??

For example)
I created address (0x12345) and I receive mnemonic code such as apple bed bad rice

If i know mnemonic code (apple bed bad rice),
Can i get 0x12345 address ??


texts: ERC20 tokens in Metamask suddenly not showing

texts:
I've been using Metamask in Chrome for a while and had a list of ERC20 tokens in Ropsten network already added in the Assets section through their contract addresses:

DAI address: 0xad6d458402f60fd3bd25163575031acdce07538d
UNI address: 0x1f9840a85d5af5bf1d1762f925bdaddc4201f984
WETH address: 0xc778417e063141139fce010982780140aa0cd5ab

In fact, when connected to Uniswap, I can see all balances with the right amounts.
However, all these tokens have suddenly disappeared from Metamask and now I can only see ETH. If I try to manually add those tokens again (Add Token -> Custom Token -> Token Contract Address), I receive the following message:

Token has already been added.

Even after reopening Chrome or changing networks, I can't see the tokens.
Any alternative before uninstalling Metamask and importing the accounts again?


texts: Fast access of any given transaction in the blockchain

texts:
That is a conceptual question that I am asking here. We are trying to developp an application to securely store the hashes of some files in the blockchain. Everything is automated (taking a file as input, computing the hash, connecting to the Parity Client and calling the notarize function of our contract).

However, we are struggling to answer the question of the accessibility to data: imagine you proceed about 300 transactions per day. If then, from a "proof" point of view, you are asked to retrieve the hash of a given file, how could it be fastly done?

1) We need the Tx hash of the transaction. Thus, we would have to parse every transaction, see the input data, convert to ascii and compare that to a local calculation of the file to be proved. And repeat every step till we find the good input data (if there is one) ---> that's very time consuming and therefore not feasable.

2) Store every detail of every transaction in a DB. But then, we cannot reach our goal, which is to securely store data: integrity of DB can be compromised.

Do you have any clue, about how to build such an access-application? Thank you a lot!


texts: Web3 - how to send transaction with some data and include Ether at the same time?

texts:
Using web3 0.20.3

I want to call function and send some Etherium at the same time.

JavaScript

Contract = web3.eth.contract(ABI);

Instance = Contract.at('0x162b74ea16da6ae9d7f7b349eaeab2fcadf4e835');

Instance.setData("name", "url", function(err, result) {
  console.log(err, result);
});

Solidity

  function setData(string name, string imageUrl) public payable {
    accounts[msg.sender].name = name;
    accounts[msg.sender].imageUrl = imageUrl;
    accounts[msg.sender].bid = accounts[msg.sender].bid + msg.value;
    emit Bid(msg.sender, accounts[msg.sender].bid);
  }

  function() public payable { // fallback function
    accounts[msg.sender].bid = accounts[msg.sender].bid + msg.value;
    emit Bid(msg.sender, accounts[msg.sender].bid);
  }

I know how to send Ether: https://github.com/ethereum/go-ethereum/wiki/Sending-ether
I know how to call function.
How do I call function and send Ether at the same time using simple syntax?

Ideally something like that:

Instance.setData("url", "name", {value: "1000000000000000000"}, function(err, result) {
  console.log(err, result);
});

(note adding extra value parameter)

More involved syntax I've observed in the wild, but they involve manually creating the whole transaction. I just want to add sending Ether to something that I have.

How to properly create a raw transaction and sign it using web3 in browser
https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsendtransaction


texts: What are contract Variables and how are they different from normal varables declaration

texts:
pragma solidity ^0.4.2;
   import DappToken;

    contract DappTokenSale {
       address admin;
       DappToken public tokenContract;

      function DappTokeSale(DappToken _tokenContract) public {

          admin = msg.sender;
}
    }

DappToken is my previous smartContract  why did we declare a varable type of contract how is it diffrent from other types why did we declared
DappToken public tokenContract;


texts:
I would like to start a Geth full node, and I have to see how much SSD to buy. How can I have an appropriate estimate on the full size of an ethereal full node?
Thanks


texts: How to set default gas limit for my custom private network?

texts:
I've connected to my custom private ethereum network in remix with web3 provider. Everything was fine, account balance, and address was retrieved successfully.
But I don't know why, but I could not set gas limit for my transaction (e.g. contract deploy). The remix has gas limit issue. Here

Is there any way to increase default gas limit for my custome private network? Because I cannot send any transactions (i.e. contract deploy, call function, etc.) except normal ETH send transaction because of the gas limit is too low.