texts: Solidity ^0.6.10 returnBalance() returns "VM Exception while processing transaction: invalid opcode"

texts:
I am using Ganache and Truffle console. I compile and migrate the following contract:
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;

contract EthReceiver {
    address payable private owner;

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

    receive() external payable {
        require(msg.value > 0, "No ETH sent.");
    }

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

I want the contract to be able to receive Ether and to be able to return its Ether balance through the returnBalance() method.
I run the following code in the Truffle console:
EthReceiver.deployed().then(instance => {return instance.returnBalance()}).then(value => console.log(value))

This is code I looked up here: https://stackoverflow.com/questions/46496845/how-to-use-truffle-console
My console output is:
{ Error: Returned error: VM Exception while processing transaction: invalid opcode
    at EthReceiver.deployed.then.instance (evalmachine.<anonymous>:0:58)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  hijackedStack:
   'Error: Returned error: VM Exception while processing transaction: invalid opcode\n    at Object.ErrorResponse (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/web3-core-helpers/src/errors.js:29:1)\n    at /Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/web3-core-requestmanager/src/index.js:140:1\n    at /Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/packages/provider/wrapper.js:112:1\n    at XMLHttpRequest.request.onreadystatechange (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/web3-providers-http/src/index.js:96:1)\n    at XMLHttpRequestEventTarget.dispatchEvent (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:1)\n    at XMLHttpRequest._setReadyState (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:208:1)\n    at XMLHttpRequest._onHttpResponseEnd (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:318:1)\n    at IncomingMessage.<anonymous> (/Users/cex/.npm-packages/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:289:47)\n    at IncomingMessage.emit (events.js:194:15)\n    at IncomingMessage.EventEmitter.emit (domain.js:459:23)\n    at endReadableNT (_stream_readable.js:1125:12)\n    at process._tickCallback (internal/process/next_tick.js:63:19)' }

My exact versions are:
Truffle v5.1.32 (core: 5.1.32)
Solidity - 0.6.10 (solc-js)

Why am I getting this result? What should I do in order to fix this issue?


texts: What happened if a Ethereum client do not have one event?

texts:
Reading this question, I understand that as long as you have the blockchain then you have all the events/logs.

But if a dapp is reading data from a light Ethereum client, how will this light client answer?

a) The light Ethereum client will answer only the events that the light Ethereum client has

b) The light Ethereum client will seek for more information in a full node and will answer with all events

c) The light Ethereum client will return an error

d) There is no specification to that and no good practice

e) N.A.


texts: How do you approve allowance for ether spending (not erc20 token)?

texts:
With a token you can do token.approve(...)
But how can we do it for ether?

Same question for checking the allowance. It's normally token.allowance(...) for erc20.


texts:
I have a contract that implements the following function:

    function getVehicles(address _addr) public view returns(Vehicle [] memory) {
        return addres_vehicles_map[_addr];
    }

I have activated the experimental pragma ABIEncoderV2.
The struct Vehicle is:

    struct Vehicle {
        string registration_ID;
        string brand;
        string model;
        string vehicle_docs_id;
        uint256 price;
        address seller;
    }

When obtaining the price everything works correctly with remix IDE, but when obtaining it with web3 the price number is not correct:

Whit remix IDE0: tuple(string,string,string,string,uint256,address)[]: CNP 1212,Tesla,Model Y,787856FGHJ,100000000000000000,0x88bFe284B409730Cd5bE6f02f37C682790DAE7C5
But with Web3: 0: "rt"
1: "rt"
2: "rt"
3: "rtg"
4: "100000000000"
5: "0x03d8dBAFFc736c5Ef644a01107988F31F2e414bc"

That is directly what the transaction returns, without converting any data or doing anything with them

As you can see the price parameter does not match.

I am stuck on this problem and can't find a solution.
Please help me. Thanks


texts:
I can't see underflow happening in latest Remix compiler. I have used the following code:

pragma solidity ^0.5.1;

    contract test {
    event testV(uint indexed value1);
    uint val= 0;

     function testf() public {

                  val--;

        emit testV(val);
    }
}

Can somebody please guide me how to show underflow in Remix because this is an important smart contract vulnerability?

Zulfi.


texts: How does web3.eth.estimateGas does its estimation?

texts:
I looked at https://github.com/ethereum/web3.js/blob/develop/dist/web3.js but can not find the method which it uses to estimate the amount of gas a transaction is going to consume.

Does anybody know how this works or can point to a reference?


texts: Is it possible to give custom mining rewards or provide custom transaction fees for mining in a private chain? I am looking to create a contract which will reward the miners with data instead of / in addition to ether as an incentive to keep the network running


texts:
Are logs a reliable place to store data long-term?

From the documentation:

"These logs are associated with the address of the contract and will be incorporated into the blockchain and stay there as long as a block is accessible (forever as of Frontier and Homestead, but this might change with Serenity)"

Edit

Logs work now- I understand. But are they future-proof ways of storing app-critical information? What information beyond the "this might change with Serenity" is available? Will they still linger for a long time after that? Further insights appreciated.


texts: How to allocate some ether to ethereum testnet accounts?

texts:
Question: How can I get some ether in Ethereum testnet/dev or even private blockchain?

I'm totally confused. If I use a customized genesis block like this:

{
"config": {
    "chainId":123 ,
    "homesteadBlock": 0,
    "eip155Block": 0,
    "eip158Block": 0
  },

"nonce": "0x0000000000000042",     "timestamp": "0x0",
"parentHash":
"0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x00",     "gasLimit": "0x8000000",     "difficulty":
 "0x400",
 "mixhash":
 "0x0000000000000000000000000000000000000000000000000000000000000000",
 "coinbase": "0x3333333333333333333333333333333333333333",
 "alloc":{"0x17e6672b3a917b7543d44e07846358aaa22a4379":{
 "balance":"8000000000000000000"

 }}

 }

Then  if I do

geth --datadir ~/.ethereum_private init ~/CustomGenesis.json

this error appears:

   Fatal: Failed to write genesis block: database already contains an
   incompatible genesis block (have 6650a0ac6c5e8054, new
   644f9b97e5f57df7)

If I leave the "alloc" field empty the error would not show up anymore (but I don't have any ether).

The other option to get some ether is to mine:

 miner.start(1)

But if I do that, null appears. So, I cannot get any ether again.

We don't have this kind of problems when we're using truffle + testrpc. As it allocates ether to all the accounts we create.

So I don't know how I can get some ether in Ethereum testnet/dev or even private blockchain.


texts: How does the tx pool handle txs from same address with consecutive nonce?

texts:
I have two questions here.

First one is about the txs from same address with consecutive nonce. When we use promoteExecutables to move txs from future queue to pending list, it compares the balance of all the txs with consecutive nonce with the current state balance(with filter function), but when you process one tx and the following tx should be compared with the balance of pending state. For example, if the current balance is 100, account nonce is 5. I have two txs in future queue, first total cost is 80 with nonce 6,and the second is also 80 with nonce 7, then, it seems both txs can be promoted to the pending list because both is less than 100. How can we avoid such situation happening when package blocks? I can not find any function handle this kind of check in tx-pool.

Second one is about the contract validation. It seems tx pool do not run the contract and make sure it is process-able before adding it to pending list. What if one contract transaction is not process-able and some miner package it in block?

I found obscuren and karalabe once talked about it in this issue, however it became stale afterwards.


texts: Why is the nonce uint64 and not big.Int in Geth?

texts:
Anyone knows why the nonce in geth is uint64 and not big.int?
My main (and perhaps only) problem with this is that then the test-case "TransactionWithHihghNonce256" from:

https://github.com/ethereum/tests/blob/develop/TransactionTests/ttTransactionTest.json

is kinda problematic.


texts: Used transfer function for minimal investement - still not working

texts:
uint256 public max_contribution = 50 ether;
uint256 public min_contribution = 0.1 ether;

function transfer(address to, uint tokens) public payable returns (bool success) {
    require(msg.value >= min_contribution);
    require(msg.value <= max_contribution);
    balances[msg.sender] = safeSub(balances[msg.sender], tokens);
    balances[to] = safeAdd(balances[to], tokens);
    emit Transfer(msg.sender, to, tokens);
    return true;
}

So i used this to set the minimal investement, still had no luck, transaction succeed even if i send less than 0.1 ether. Can you guys check what is wrong with it? Also is it possible to set a return if someone sents less than a min.contribution?


texts: I have created a ERC20 token in ethereum blockchain with token name as TestToken and Symbol as TTT. Now how can I ensure that others cant create a token with the same name and same symbol? Is there is any way to ensure the redundancy in token name?


texts: Parity synced at not existing block 4839212

texts:
I have problem with parity, cant get synchronization in archive mode to end,
anything, changing arguments, max-, min-, snapshot-peers, parity verisions do not help.
I have blockchain in archive mode synced to block: 4839212
with hash:
0xf418b3b2fbadccab0a6e7009792906006f66e17356c7640e874def344933e847

This block does not exist according etherscan.io, how can i get synchronization to end???


texts: Coins/tokens that use Ethereum blockchain

texts:
Trying to wrap my head around coins/tokens that uses the Ethereum blockchain.

Let's take for example Refereum that utilizes Ethereum smart contracts and is based off the Ethereum blockchain. Does this imply that they have joined the blockchain of Ethereum so that every transaction that's made on Refereum gets validated and stored on the Ethereum ledger?

If yes, does that also mean that the computers that are mining Ether is at the same time mining the coins of all the other ERC-20 tokens?

Or does Ethereum consist of one blockchain per coin, where the coin-creator themselves have to use PoW or PoS to validate the transactions? If this is the case, can they use another method to validate the transactions or are they bound by PoW as long as Ether is?


texts: Sent Ether to an ICO from a non ERC-20 compatible wallet

texts: So, I transferred some ether from my Koinex Wallet(non ERC-20 compatible) to Bloom ICO which clearly expects an ERC-20 compatible wallet. At the time of transaction I had no idea about ERC-20 wallets since I am new to this. After making the transaction I realized the blunder I had made. What should I do next?


texts:
I've followed instruction to build solidity. But when it finished, i've got develop version:

Version: 0.4.16-develop.2017.8.31+commit.d7661dd9.mod.Linux.g++

I've tried to run make with argument CMAKE_BUILD_TYPE=Release - the same result.
Code was checked out from tagged version v0.4.16.
Without release version I cannot compile sol files with version 0.4.16 because of error:

Error: Source file requires different compiler version (current compiler is 0.4.16-develop.2017.8.31+commit.d7661dd9.mod.Linux.g++ - note that nightly builds are considered to be strictly less than the released version


texts:
I have implemented improved token at: https://ethereum.org/token#full-coin-code

I use truffle to test and use migrations to deploy contract.

When I want to deploy a new version of MyAdvancedToken, I don't want to lose the values of 'balanceOf' in the token contract.

But when i create a new contract like MyAdvancesToken1 it compiles token and deploy to new address. Is there anyway to deploy a new contract without losing balance database?


texts: How to stop mining unwanted blocks on private net on geth ethrereum

texts:
I have started a geth client using the below client(I had already created two accounts.:

geth --datadir datadir --networkid 123 --rpc --rpcaddr="localhost" --rpccorsdomain="*" --unlock <my account> --minerthreads="1" --maxpeers=0 --mine console

I opened the the ethereum wallet and deployed the smart contract from there. The transactionId and the contract address is received on my geth console.

Then I started my Dapp and created the instances of the contract and I am calling the contract invoking a contract function through web3 API. The contract function gets invoked but the transaction does not get submitted in the block unless I start mining. Hence I started miner.start() This started mining numerous blocks.

My question is where are these blocks coming from if I have my own private net and have submitted only one transaction. This is adding too many blocks and my blocksize is increasing unnecessarily. How to mine only the transaction I have submitted?


texts:
I know there are dynamically sized arrays, but I need a data structure that can remove elements from the middle cheaply. Using pop() with a dynamically sized array should require a shift of every element coming after by one, which would be way too expensive. Is there an industry standard way of doing this?

Alternatively I can switch the element I want to delete with the last element in a dynamic array and then pop() the last element, because the order of my list doesn't matter.


texts: Error! Unable to generate Contract ByteCode and ABI in eth scan

texts:
i have compiler my code through remix… but when i try to verify it on eth scan it gives me following errors
Error! Unable to generate Contract ByteCode and ABI
here is my code
pragma solidity ^0.5.0;

contract IBEP20 {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);

event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

 contract SafeMath {
 function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
  return 0;
}
c = a * b;
assert(c / a == b);
return c;

}

 function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;

}

 function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;

}

 function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;

}
}

contract MONK is IBEP20, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it

uint256 public _totalSupply;

mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;

/**
 * Constrctor function
 *
 * Initializes contract with initial supply tokens to the creator of the contract
 */
constructor() public {
    name = "MONK";
    symbol = "My";
    decimals = 18;
    _totalSupply = 1000000000;

    balances[msg.sender] = _totalSupply;
    emit Transfer(address(0), msg.sender, _totalSupply);
}

function totalSupply() public view returns (uint) {
    return _totalSupply  - balances[address(0)];
}

function balanceOf(address tokenOwner) public view returns (uint balance) {
    return balances[tokenOwner];
}

function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
    return allowed[tokenOwner][spender];
}

function approve(address spender, uint tokens) public returns (bool success) {
    allowed[msg.sender][spender] = tokens;
    emit Approval(msg.sender, spender, tokens);
    return true;
}

function transfer(address to, uint tokens) public returns (bool success) {
    balances[msg.sender] = sub(balances[msg.sender], tokens);
    balances[to] = add(balances[to], tokens);
    emit Transfer(msg.sender, to, tokens);
    return true;
}

function transferFrom(address from, address to, uint tokens) public returns (bool success) {
    balances[from] = sub(balances[from], tokens);
    allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
    balances[to] = add(balances[to], tokens);
    emit Transfer(from, to, tokens);
    return true;
}

function _mint(address account, uint256 amount) public returns (uint256) {
  require(amount != 0);
  balances[account] = add(balances[account], amount);
  emit Transfer(address(0), account, amount);
}

 function burn(uint256 amount) external {
_burn(msg.sender, amount);

}

 function _burn(address account, uint256 amount) internal {
require(amount != 0);
require(amount <= balances[account]);
_totalSupply = sub(_totalSupply, amount);
balances[account] = sub(balances[account], amount);
emit Transfer(account, address(0), amount);

}

 function burnFrom(address account, uint256 amount) external {
require(amount <= allowed[account][msg.sender]);
allowed[account][msg.sender] = sub(allowed[account][msg.sender], amount);
_burn(account, amount);

}
}


texts: How to install geth disasm and other dev tools

texts:
The geth disassembler seems like a really nice tool, if it can do stuff like this:

To disassemble, run echo 6005600401 | disasm, which produces:

0      PUSH1  => 05
2      PUSH1  => 04
4      ADD

However I couldn't find it, tried the solution here, and ran into this error:

How can we install the dev tools such as disasm?


texts:
I need to run a full node of ETH and its bound tokens for an experimental exchange site.

How will I do to differentiate ETH from others tokens ?

Is there a way to download the ETH blockchain excluding its tokens?

Thanks.


texts: Function not marked as View and Pure but read only

texts:
I have a function:

function test(uint value) {
    if (balances[msg.sender] < value)
        return;

    balances[msg.sender] -= value;
}

*note: the above is for illustrative purposes only. Security and safe maths is not a concern.

I understand that reading from the blockchain only consume 0 gas, for View and Pure function.

So my question is: For the function above will I have to pay for gas if I have insufficient balance and return early (no transaction made).


texts: Keep getting error 'Invalid number of arguments to Solidity function web3.js

texts:
I keep getting the same error saying

Uncaught Error: Invalid number of arguments to Solidity function
    at Object.InvalidNumberOfSolidityArgs (inpage.js:1)
    at u.validateArgs (inpage.js:1)
    at u.toPayload (inpage.js:1)
    at u.call (inpage.js:1)
    at u.execute (inpage.js:1)
    at gitter.js:21

this is the javascript code, it seems like the contract is not being loaded correctly, because also when I console log myAccount it returns undefined..

This is the javascript

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/<token>"));
}

web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/<token>"));
// web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

var tokenContract = web3.eth.contract(human_standard_token_abi);
var tokenRunning = tokenContract.at('0x5780a5928becc986edd597991a1a1af6357fdf05');

var myAccount = web3.eth.accounts[0];

if(!web3.isConnected()) {

  alert ('not connected');

} else {

  console.log('Balance of ' + myAccount + ' is equal to ' + tokenRunning.balanceOf(myAccount).toNumber() + ' tokens');
  // console.log(myAccount);

}


texts: Hi In my contract I send ether from my contract to other address like address.transfer(winnerAmount);. It transfer ether successfully if my array have one address. If I have more than one address it throws 'VM Exception while processing transaction: revert'. All other lines of code inside for loop works good if I comment transfer. I want to know what is the reason for this? I tried also adjusted gas limit, but it always fail. What is the better way to transfer the ether inside for loop? Thank you.


texts: Sent ETH to ETC address within Ledger Nano S. Confirmed on Etherscan, but not appearing in Wallet?

texts:
Sent ETH to ETC within Ledger Nano S (send/recieve)
Tx Confirmed (Success) on Etherscan, but not showing up in Ledger.
Is there any way to recover?
Many thanks


texts: Easy way to test contract code compiled with (Solidity) solc?

texts:
When compiling my contract code with solc, I get EVM bytecode (.bin).

How can I test this bytecode, i.e., call the functions etc.?

The Remix online compiler is not an option, since it also accepts Solidity source code.


texts:
Is there a way to do basic decryption in Solidity?

For example:

Given 3 actors and message:

Server
Client
Solidity contract

The flow:

Server generates message and signs with private key
Client uses the message as parameter to call contract
Contract uses server's public key to decrypt the message (make sure it came from server)

Is there a way in Solidity to do "decrypt" a string using a pubkey?


texts:
Strange thing happens with .toNumber function. It works well for account balance, but not for rate / endTime. I can't understand why, because balance is BigNumber and rate property is BigNumber (you can see screenshot). Has anyone similar issue and how it needs to be solved?
I use Truffle 4 + VS Code.


texts: Can anyone see transactions from a contract?

texts:
Can anyone see all outgoing Ether transactions from a contract?

If no, is it possible somehow to make the transactions visible? (maybe, using events?)


texts: how to write a test case for msg.sender==0?

texts:
In my contract I am use the below mapping.
    mapping(address => uint)Drivers
In the function

    function registerDriver(uint _perkm) public payable returns(string memory) {
           require(Drivers[msg.sender] == 0,"You are already registered as
    Driver.");
            driverCount++;
            driverList.push(Driver({
                driverID : driverCount,
            driverAddr : msg.sender,
            rideID : 0,
            perkm : _perkm,
            currentStatus : available,
            bids: 0

        }));
        Drivers[msg.sender] = driverCount;
        return "You are registered as Driver.";
    }

Can someone help me write test case for the above function? i.e - test case for my require statement. Thank you very much!


texts: Any idea why geth --fast is taking so much CPU *AFTER* sync is done

texts:
I'm running geth 1.4.17-stable. Also running Mist 0.8.6. While geth finished fast syncing up a few hours ago, it's still eating away at my laptop's CPU. Note I'm not trying to mine.

Is that normal for geth or is there anything I can do to reduce its CPU usage?

Thanks!


texts: Should I use new() or deployed() in Truffle unit tests?

texts:
What's the difference in using new() or deployed() when creating a contract instance to use in Truffle unit tests? Should I use

// VERSION A
it("should work", async () => {
  let instance = await MyContract.deployed();
  :
});

or

// VERSION B
it("should work", async () => {
  let instance = await MyContract.new();
  :
});


texts: Integrating Ethereum with other systems (permissioned/permissionless)

texts:
If I would like to integrate Ethereum with other systems - permissioned or permissionless, how does one do that?
for example, if I would like Ethereum to talk to Hyperledger or R3 Cordo as an example, how does it work?


texts:
after sending Ether to my contract address, why is balance returning zero?

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

Testing on Ropsten, and have also tried in the Remix Javascript VM.

This is the deposit function:

function deposit(uint referenceNumber) public payable {
    //add to completed deposits array
}

The tx when depositing:
https://ropsten.etherscan.io/tx/0x5d0cb3e66f565eecc52ab9f4322613dc2d4c43aacf30f3cf52e1dee8e4cd454f

Then when I call contractBalance (now called daoBalance):


texts:
I try to make GraphQL work on Geth (version 1.10.1-stable) without any success.
I try to run this query, but I only get 404.
curl -H "Content-Type: application/json" -d '{ "query": "{syncing{startingBlock currentBlock highestBlock}}"}' http://localhost:8545/graphql

...also tried port 8547 and without /graphql but no success. Am I missing something?
I run Geth using the following config:
# config.toml
...
[Node]
IPCPath = "geth.ipc"
HTTPHost = "127.0.0.1"
HTTPPort = 8545
HTTPCors = ["*"]
HTTPVirtualHosts = ["localhost"]
HTTPModules = ["web3", "eth"]
WSHost = "127.0.0.1"
WSPort = 8546
WSOrigins = ["*"]
WSPathPrefix = "/ws"
WSModules = ["web3", "eth"]
GraphQLVirtualHosts = ["localhost"]
GraphQLCors = ["*"]
...


texts: Returning a value from an external function

texts:
I have in a contract:

    function createCourt() external returns (uint256) {
        uint256 _id = ++nonce;
        courtOwners[_id] = msg.sender;
        return _id;
    }

Now, when I try to call this function from web3.js I stumble an impossibility to return values.

I was recommened to use events instead to return a value. But if I and another user calls createCourt():

    function createCourt() external {
        uint256 _id = ++nonce;
        courtOwners[_id] = msg.sender;
        emit CourtCreated(_id);
    }

how can I determine which of several events returned my court, not another one?

Or any other way to get the court number after I create it?


texts: 0 ETH Airdrop function with ICO contract

texts:
I see many airdrops that have been done by sending 0 ETH to the ICO contract address

my question is: how to add this function to the ICO contract with the ability to start and stop at any time?
and if there an ready contract with ICO functions and the function that I mentioned above, please insert it


texts: How to deploy contract with bytecode from etherscan?

texts: For example, I want to deploy a contract to my local testnet. But I only have its opcode from etherscan. How to deploy the contract with just those runtime bytecode?


texts: Increasing the difficulty/cost of manipulating an on-chain PRNG?

texts:
well, from what I understand since everything on-chain is deterministic so theoretically there's no way of having a real cryptograhically secure random number generator that cannot be manipulated by the miners. However, aside from using off-chain random data sources from Oracles, I wonder if there are some ways to surely increase the difficulty/cost of manipulating an on-chain PRNG?

For example, the most basic and naive on-chain PRNG is to use blockhash of a past block (I'm not talking about knowing the result of the PRNG beforehand, but to really manipulate the result, so I'm not using future blockhash as example here)

rand = uint256(blockhash(block.number - 1))

So the miner who mined the previous block will be able to manipulate the value of rand.

Now if someone do something like

rand = uint256(blockhash(block.number - 1)) ^ uint256(blockhash(block.number - 2))

From what I understand it actually doesn't increase the difficulty of manipulating the value of rand, as the miner of the previous block already knows the blockhash before it, so it still only takes the miner to mine the previous block to manipulate the result.

So doing things like

rand = uint256(blockhash(block.number - 1)) ^ uint256(blockhash(block.number - 2)) ^ uint256(blockhash(block.number - 3)) ^ ...

are practically useless since it still only takes the miner to mine the previous block to manipulate the result.

And as such, using future blockhashes are also useless in this case since it still only takes one miner to mine a deciding block to manipulate the result.

So is there anyway to actually increase the difficulty for a miner to manipulate an on-chain PRNG (for example, a miner has to mine two or three specific blocks to manipuate the result instead of just one block), or is it actually impossible by theory (ie. it always only takes a miner to mine one block to be able to manipulate the result of a purely on-chain PRNG without off-chain data input)?


texts: What is the best way to verify the comments in the contract code?

texts:
I have a contract that I want to be legally binding in traditional courts. It assigns rights, and for this I need legalese in the comments to describe the process. What is the best way to make sure that these comments are verifiable?

Solutions that I think might work:

1) Upload the contract to Etherscan for verification. If Etherscan keeps track of the hash of the pasted contract, then great, we can verify.

2) Get a swarm hash of the text with comments, and then after deployment, update the contract with the swarm hash, and then link to it on swarm in the frontend.

Why would one want to put legalese in a smart contract?

While a smart contract guarantees across borders that the terms of the code are enforced, what it does not do is give users legal protection in their jurisdiction if the contract assigns rights. If you assign rights of a copyright to someone for example, there has to be a scope acceptable in law, not just code. Adding an explicit conveyance in text of what a specific function transfers to the user is important for them to have proof that they are legally protected.


texts: Can I safely interrupt and restart fast sync in geth?

texts:
I am new to Ethereum and trying to get set up a new node with geth (using 1.6.5-stable).

I am running geth --fast --cache=1024 and so far have been syncing for around 3 days (Win 7, 6GB RAM). I see lots warnings in the log and a few errors, but the process always seems to continue.

However, when things seem to be moving slowly I have periodically stopped syncing with Ctrl+C. This seems to lead to a clean shutdown of geth. I then restarted again with geth --fast --cache=1024 and syncing appears to pick up again from the same point. Status so far via eth.syncing in the javascript console:

{
  currentBlock: 3294258,
  highestBlock: 3899534,
  knownStates: 47242,
  pulledStates: 3041,
  startingBlock: 3293182
}

Is this OK? Specifically my questions are:

Will it work? Will syncing finish correctly giving a usable node if I continue to follow this practice?
Is it safe to restart with the --fast flag after interrupting? I have read elsewhere that the flag should not be used with a partial download of the blockchain, but I'm not sure whether this refers to a historical "full sync" or any type of partial sync.


texts: Is Ethereum gong to crash now? Is it worthy to keep investing?

texts: With the last news that was found a vulnerability in the Ethereum DAO the coin lost almost 50% of its value in 2 days. Do you think is still worthy buy Ethererum?


texts: MyAdvancedToken Automating Selling and Buying function not working

texts:
I attempt to create a token with the "automatic and selling" function as describe here. After having copy/paste the code (footpage)and deployed the contract no error message appears. But when I execute the functions "sell" or "buy" nothing happens. When trying to execute the function "buy" no field appears, which seems very odd to me because one should enter the amount they want buy/sell ...
Have any idea how to fix this ?

My expectations are that the sender account receive an amount of the new token equal to the amount of ether sent * conversion rate specified, is this the purpose of this code ?

Thanks in advance !


texts: Transaction wont commit to a block if I send transaction that is signed by private key that is generated by ethereumjs-wallet

texts:
Problem

So basically what I am trying to do is to send Transactions that were signed by an account that was generated by ethereumjs-wallet so my node don't keep UTC file and therefore I don't have an issue if someone stealing accounts UTC file. But my contract doesn't execute if there is no UTC file, on a node, for an address that signed my transaction.

This is part of a code that I used for sending Tx.

utils.askForInput('Owner address: ')
  .then((ownerAddr) => {
    Tx.ownerAddr = ownerAddr;
    return utils.askForInput('New wallet address: ');
  }).then(async (newAddr) => {
    const data = await utils.prepareData('addWallet', newAddr);
    const nonce = await utils.getAccountNonce(Tx.ownerAddr);

    console.log('Data: ' + data);
    console.log('Nonce: ' + nonce);

    return utils.askForInput('Signed Transaction: ');
  }).then(async (signedTx) => {
    await utils.sendRawTransaction(signedTx);

    utils.closeReadLine();
  }).catch((err) => {
    console.log(err);

    utils.closeReadLine();
  });

Possible solution

I can just create UTC file and call contract and after I am done with everything I can just delete UTC file. But I think it is a hack. My Q is why this is the case and is it necessary to solve it like this.

Just to point out my code works, if UTC file is created for that account.


texts: Remix IDE + Ganache vs Truffle + Ganache

texts:
I have an issue migrating a smart contract from Truffle into Ganache. However, when I run the same smart contract from Remix IDE via MetaMask into Ganache, everything works fine.

To bypass the migrating error, I was thinking of using the Remix IDE ABI.js file instead of the Contract.json file that Truffle compiles. However, I am getting an error:

  Contract has not been deployed to the detected network
  (network/artifact) mismatch.

I can't understand why does the contract work when deploying form Remix and interacting with it in Remix, and it doesn't when I use the ABI generated by Remix in my Web3js functions?

UPD: This is the React Component (based on Truffle React boilerplate) that I'm trying to work with. Here, ContractOne.json is the one that is generated by truffle compile. Had the truffle migration worked correctly, this would have worked.

import React, { Component } from "react";
import ContractOne from "../../../build/contracts/ContractOne.json";
import getWeb3 from "../../utils/getWeb3";

export class Main extends Component {
  constructor(props) {
    super(props);

    this.state = {
      web3: null,
      account: ""
    };
  }

  componentWillMount() {
    getWeb3
      .then(results => {
        this.setState({
          web3: results.web3
        });
        this.getAccount();
      })
      .catch(() => {
        console.log("Error finding web3.");
      });
  }

  async getAccount() {
    const contract = require("truffle-contract");
    const contractone = contract(ContractOne);

    powerether.setProvider(this.state.web3.currentProvider);
    let instance = await contractone.at(
      "CONTRACT ADDRESS"
    );
    this.state.web3.eth.getAccounts((error, accounts) => {
      instance => {
      return this.setState({ account: accounts[0] });
      };
   });
    });
  }

  render() {
    return (

{this.state.account}

    );
  }
}

truffle.js

module.exports = {
  // See
  // for more about customizing your Truffle configuration!
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*" // Match any network id
    }
  }
};


texts: mistakenly sent ETC to ETH address on Cryptopia

texts: I have mistakenly sent ETC from Cryptopia To an ETH address.How can i recover my ETC back.


texts:
How can I append some (extra) data to a transaction that calls a contract method (with given parameters)? The transaction has only one 'data' field which is used to serialize the method call.

If I would simply append more data at the end of the method call (expecting it to be ignored by the EVM, but useful for off-chain purposes), would that work or would it result in the transaction being rejected by the EVM?

This would be useful, for instance, in assigning an invoice-id to an ERC-20 transfer.


texts: Broadcast error rlp: non-canonical integer (leading zero bytes) for uint64

texts:
Here's a transaction to broadcast:

  f86c008504a817c80082520894e0defb92145fef3c3a945637705fafd3aa74a241880de0b6b3a7640000001ba009ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9ca0440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428

The error message is:

  Error: rlp: non-canonical integer (leading zero bytes) for uint64, decoding into (types.Transaction)(types.txdata).AccountNonce

Decoding the transaction the result is:

  {"nonce":0,"gasPrice":{"_bn":"4a817c800"},"gasLimit":{"_bn":"5208"},"to":"0xe0defb92145fef3c3a945637705fafd3aa74a241","value":{"_bn":"de0b6b3a7640000"},"data":"0x00","v":28,"r":"0x09ebb6ca057a0535d6186462bc0b465b561c94a295bdb0621fc19208ab149a9c","s":"0x440ffd775ce91a833ab410777204d5341a6f9fa91216a6f3ee2c051fea6a0428"}

What is wrong with the transaction?  Why does it have an error when it is broadcasted?


texts: I am a beginner and got confused. According to some online tutorial, I need to install "ethereum" and "geth" package in my linux (ubuntu) first before I run any mining program such as cgminer. However, it seems without the two packages the mining program runs fine (I already have a public address). So what exactly are the "ethereum" and "geth" packages for? Do I need them?


texts: Gas estimation error in functions with external calls

texts:
My front + smart contract is working on localhost. Now, I deployed at Rinkeby and all functions that has external calls are not working. Metamask says there will an exception even before the submission

  "Transaction Error. Exception thrown in contract code."

So, I tried to execute any of these functions on Remix. I also could not execute them. Remix says that there is an error during gas estimation:

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

In fact, Remix is warning about gas estimation during compilation:

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

There is an example of such a function below. Does anyone has a clue?

function makeUntrustedWithdrawalOfTokens (address tokenAddr, uint256 value) public onlyOwner returns (bool) {

    bool b = IERC20Token(tokenAddr).transfer(owner,value);

    emit WithdrawTokensEvent(tokenAddr, owner, value, b);

    return b;

}

I am using web3 1.0 in the front end, but this error seems to be not related to that, since it also happens on Remix.


texts:
I want to create a contract that would produce a hash from a file and have it signed.

Can i put a file through the sha3 using the solidity to get a hash? Or do i have to do it through js?


texts: Is it possible to have unique constraint on parameters of an event? I will have a number of users using my Dapp, and I have provided functionality to delete the users. So while reading from the transaction log, I will get a list of all the users created to date. I want only the users that are active on my Dapp.


texts: Need Solidity software for smart contract, for Multiple Token dispatch

texts:
Please I need to distribute tokens to at least 1,500 wallets and can't go through the stress of sending them one by one.

What I need is a smart contract to enable multiple dispatches to several wallets simultaneously.

I would appreciate it if I can get the code for the above issue.

FYI: I dont know too much about coding.

Thanks in anticipation.


texts: Geth POA network: How to create and approve a fake transaction using 100% authority on sealer nodes?

texts:
Assume a 2-node local POA network. Having full authority on both nodes, is it possible to execute a 51% attack by approving a fake transaction without the sender's private key?
For example, let's say Alice has 50 ETH in her wallet. Is it possible to broadcast and approve a transaction where Alice sends 50 ETH to Bob without knowing Alice's Private Key and making use of the 51% attack or voting? If so, how?
Thanks.


texts: Contract transfer between two address, pay gas from third address

texts:
The scenario is to transfer from Address B to Address C, deducting the transaction fee from Address.

Here A will have some ether amount, which should be used to deduct the gas.

The ERC20 Token Standard, has a method transferFrom, which takes from, to and amount as input.

What is the point of from here, does it always has to be the person signing the transaction (if so, then what's the reason behind having two method transfer and transferFrom)? Or it can be a different address?


texts: Are most ICOs based on Ethereum's Smart Contracts or other technology?

texts:
where can I find an overview of the technologies that blockchain startups use?

Are most ICOs based on Ethereum's Solidity Smart Contracts, creating a simple ERC20-compatible token?

Why are the alternatives like Hyperledger, Chain, Bitstake not so common?


texts:
I wonder what would happen in following hyphotwtical scenario.

Transaction is being sent with blockchain state A. In this state transaction consume 100_000 gas and sender has enough funds to pay for it.
Local GETH receive tx and broadcast it.
Blockchain fork happens and now blockchain is in state B. In this state same transaction consume 1_000_000 gas and sender does not have this much ETH to pay for it.
After some time I request transaction details with eth_transactionByHash api call or similar web3 call.

What would be response then? Will ETH report that tax is not found or it return response with some indication that tax actually failed?


texts: How to export mnemonics for a specific account in MetaMask

texts:
How can I get the mnemonics from a specific account in Metamask?

I found the reveal seed words in the settings-dialog, but this seems to be something global.

Instead of this I want to export the 12 words mnemonics from a specific account, to make it available on other machines also. There is the option "export private key", which just give me the private key consisting of several hexa decimal characters. I would expect different options here like the private key and mnemonics also.

My questions:

how can I get the mnemonics from a specific account?
what is the reveal seed words in global settings dialog for? which account is affected with that?

Update

I have found out, that the seed words from settings-dialog stands for the very first account.

I installed MetaMask on another machine, recovered the account with these seeds and imported the very first account of my meta mask accounts from the origin machine.

However, while I can export private key for all other accounts and import them into my second machine this way, I'm curious why metaMask doesn't offer to generate seed words for a specific account instead of only the first account?


texts: What is the difference between IBFT(Istanbul BFT) and PBFT?

texts: I recently got to know about IBFT and Quorum and started studying on their consensus protocols. And what is the difference on IBFT and PBFT? Are they pretty much like the same and, when considering Quorum IBFT is doing something more with respect to PBFT in other solutions like Hyperledger? Or are they completely different no matter it is Quorum or Hyperledger? Any answer would be highly appreciated.


texts: What is the access-level of Solidity's implicit getters?

texts:
I have a "real" contract and an interface contract.

In the interface contract, I want only to expose the 'getter' functions of the "real" contract.

Those functions are implicitly generated by the Solidity compiler (solc).

The options, I suppose, are:

external constant
public constant
external view
public view

But no matter how I try it, the binary of my "real" contract comes out with no contents.

The only way I am able to work-around it is by explicitly implementing the 'getter' functions (in the "real" contract).

Since those functions can also be generated implicitly, I was hoping to avoid it, so I would like to know if by any chance I'm doing anything wrong in the way that I declare these functions in the interface contract.

Here is the interface contract ('ITest.sol'):

pragma solidity ^0.4.18;

contract ITest {
    function x() external constant returns (uint256);
}

And here is the "real" contract ('Test.sol'):

pragma solidity ^0.4.18;
import './ITest.sol';

contract Test is ITest {
    uint256 public x;

    function Test(uint256 _x) public {
        x  = _x;
    }
}

Thank you!!!


texts:
How to get the current selected account in Metamask?
I've seen things like this as the answer to this..
const accounts = await web3.eth.getAccounts();
const account = accounts[0];

But doesn't this just select the first account? Not the current selected account?


texts: should we create a contract instance every time we interact with the contract?

texts:
I am following a tutorial.

  contract

contract Auction {
  event AuctionClosed (uint highestBid);  //declare eventto be triggered when Auction closes
  address public creator;
  function Auction () { //Auction Constructor to register the creator of the contract
    creator = msg.sender;
  }
  function closeAuction (uint someRandomBid) {
    if (msg.sender == creator) {  //make sure that auction is being ended by the creator themselves
      AuctionClosed (someRandomBid);  //trigger the event to notify the listeneres that the auction has ended
      return;
    }
    throw;
  }
}

  js

window.onload = function () {
  let accounts = web3.eth.accounts; //create local variable for easy access
  let maxBid = Math.ceil (Math.random () * 1000); //the maximum bid placed by the end of the auction
  let status = document.getElementById ('status');
  Auction.new ({from: accounts [0]}) //create new contract object
    .then ( (contract) => {
      contract.AuctionClosed ().watch ( (err, response) => {  //set up listener for the AuctionClosed Event
        //once the event has been detected, take actions as desired
        status.innerHTML = 'The auction has ended! Highest Bid is ' + response.args.highestBid;
      });
      setTimeout ( () => {  //simulate an auction for 3 seconds, after which the creator closes the auction
        contract.closeAuction (maxBid, {from: accounts [0]});
      }, 3000);
    })
    .catch ( (err) => {
      status.innerHTML = 'Some error occured. I guess shit happens =(';
    });
};

My question is on the JS app, every time the user is using the app, should we use
Auction.new
to generate a new contract object?

or using new web3.eth.Contract(jsonInterface[, address][, options]) to load a existing contract? is this code a form of creating a contract instance?


texts: checking the transferFrom method from the Openzeppelin vanilla ERC20

texts:
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

why transfer first and then check that msgSender is allowed to transfer? Should we not first check that and then transfer in order to save time and gas?


texts:
I am running private ethereum blockchain using geth and I am using web3j to send transactions. Since yesterday I am not able to deploy my contract, In my java console I am getting "transaction receipt was not generated after 600 seconds for transaction" while I can see using block explorer that the contract is created in my blockchain.
String contractAddress = myContract.deploy(web3j, credentials, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT, BigInteger.valueOf(campaign.getId()),
                        campaign.getName(), startDateTime, endDateTime).send().getContractAddress();

Here is my genesis file code
{
"config": {
        "chainId": 987,
        "homesteadBlock": 0,
        "eip150Block": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
    "nonce": "0x0000000000000042",
    "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",
    "gasLimit": "0x8000000",
    "difficulty": "0x400",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x3333333333333333333333333333333333333333",
    "alloc": {
    }
}

I am using following command to run blockchain
geth --datadir ~/chaindata/ --networkid 12345 --verbosity 3 --rpc --port 30304 --rpcport 8545 --rpcaddr "<private IP>" --rpccorsdomain "http://<private IP>:8080,  http://<private IP>:8000" --rpcapi "web3,eth,personal,net"  --preload "/home/ubuntu/scripts/mineWhenNeeded.js" --nodiscover  --gcmode archive  --allow-insecure-unlock > ~/myLogs/bcLogs.out 2>&1 &

Also, my miner was creating so many blank blocks so I have used following script to mine the blocks when only needed

var minimum_confirmations = 3;
var mining_threads = 1
var txBlock = 0
function checkWork() {
    if (eth.getBlock("pending").transactions.length > 0) {
        txBlock = eth.getBlock("pending").number
        if (eth.mining) return;
        console.log("  Transactions pending. Mining...");
        miner.start(mining_threads)
        interval = setInterval(function () {
            if (eth.getBlock("latest").number < txBlock + minimum_confirmations) {
                if (eth.getBlock("pending").transactions.length > 0) txBlock = eth.getBlock("pending").number;
            } else {
                console.log(minimum_confirmations + " confirmations achieved; mining stopped.");
                miner.stop()
                clearInterval(interval);
            }
        }, 600)
    }
}

eth.filter("latest", function (err, block) { checkWork(); });
eth.filter("pending", function (err, block) { checkWork(); });

checkWork();

Also, my average blocktime is getting too higher its 38.9 minute now. How to reduce the average blocktime?


texts: What would happen to transfers to a contract address before creation?

texts:
If someone transfers funds to a contract address before I create the contract, what will happen to the funds when I create the contract?

For example:

Get address of future contract.
Transfer funds.
Create contract.

Does the new contract get created with a positive balance? Or do the funds get cleared out?


texts:
I want to sign my contract offline (I have ABI and Bytecode) and then broadcast it to the network.
I found this code that is quite good :
https://gist.github.com/cicorias/ae88a6012fa6153ed58c5d9c53d7edf0
But I have a this raw transaction :
const rawTx = {
    nonce: nonceHex,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: contractData,  // <==== this is Bytecode only, no need ABI ?
    from: web3.eth.coinbase
};

I did a contract deploy on Ropsten :
https://ropsten.etherscan.io/tx/0x4faf12cd1c7f1a63a23e31dfb1efcdb380a377dbd88e27984f00d56b29059141
In this transaction, you have only "0x + BYTECODE" on data. But the "to" transaction is computed by EVM network.
Can I construct the transaction like that ? Directly with :
const rawTx = {
    nonce: nonce,
    gasPrice: gasPriceHex,
    gasLimit: gasLimitHex,
    data: ByteCode,
    from: myaddress
};


texts: How would a miner cope with a huge block time?

texts:
Given that:

According to the white and yellow paper a block's timestamp must be bigger than the parent's.
According to the white paper a block's timestamp can be within 15 min of the parent blocktime.

Would that imply that if a differential block time of 14 min occurs,

the next winning miner has to either fake a timestamp, and this potentially could lead to the blockchain running faster and faster into the future,
or wait until his Unix time catches up.

Is this true? Is there a reason why empirically it never happened?


texts: Building a mobile DApp without a full node?

texts:
I'm new to blockchain and Ethereum and have a few questions:

Does Apple's App Store allow mobile DApps other than wallets and browsers?
Is it possible to build a mobile DApp that runs on your mobile device without downloading the full ethereum node, but still make full use of things like smart contracts and the IPFS technology?
Is it possible to develop mobile DApps in native languages like Swift or Kotlin, not web apps or hybrid apps?
Are there big differences in terms of technical challenges between developing mobile DApps that use private blockchain vs public blockchain?


texts: How to read partial values from a tuple?

texts:
I haven't seen this question asked and answered, so I decided to post it myself.
How to read only some variables from a tuple returned by a function in Solidity?


texts: How to use ConsenSys/Tokens to create new token

texts:
As per ConsenSys/Tokens copy/paste is highly discouraged. So what modification is required in Step:2 of this article to create an EIP20
compatible token?

Should I just clone/download the repo and create new contract with my token name ( or even simply rename EIP20 to my token name) and use it as my new token?

I'm wondering, is there a recommended way to use [ConsenSys/Tokens] implementation?


texts: I am a software engineer with blockchain background and I am new to the exciting Ethereum project. One thing I am not quite sure about is how Ethereum solves the trust problem between involved parties. Specifically, who can execute the contract? What if the owner of the contract does not execute it? Even if the contract will be executed as it is programmed, it does not matter if it is never called.


texts: How can I split a 56 character input and store them in two Bytes32?

texts:
I want a function to accept, store and output 56 characters.  My other question (How to return bytes array in Solidity Contract) shows that I tried to return bytes[], but it gives me an error:

  Internal type is not allowed for public or external functions

I haven't been able to get past this error.

So now, I would like to see if I can split the 56 character input into two bytes32, so that I can return bytes32.  How do I do this?

I modified the code from this question (How can I split a Bytes32 source into two halfs and store them in Bytes16?) and created this:

  event trace(bytes x, bytes32 a, bytes32 b);

    function foo(bytes source) {
        bytes32[2] memory y = [bytes32(0), 0];
        assembly {
            mstore(y, source)
            mstore(add(y, 32), source)
        }
        trace(source, y[0], y[1]);
    }

  function cut(bytes sha) constant returns (bytes32 half1, bytes32 half2) {
    assembly {
      let freemem_pointer := mload(0x40)
      mstore(add(freemem_pointer,0x00), sha)
      half1 := mload(add(freemem_pointer,0x00))
      half2 := mload(add(freemem_pointer,0x10))
    }
  }

But I wasn't able to get them to work.

EDIT on 2017-08-22 for benjaminion:

Ideally, I want to return bytes[].  See my code and the error with bytes[] at How to return bytes array in Solidity Contract .  Benjaminion's first block of code worked with a little bit of modification.  I changed my "iterator" function to the following:

  function iterator() constant returns (address[],uint256[],uint256[],bytes32[],bytes32[]){
      uint256 len = ledger.keys.length;
      address[] memory keys = new address[](len);
      uint256[] memory values = new uint256[](len);
      uint256[] memory values2 = new uint256[](len);
      bytes32[] memory newKeys1 = new bytes32[](len);
      bytes32[] memory newKeys2 = new bytes32[](len);
      for (uint256 i = 0 ; i <  len ; i++) {
         address key = ledger.keys[i];
         keys[i] = key;
         values[i] = ledger.maps[key];
         values2[i] = token.balanceOf(key);

         bytes memory sha = ledger.newKeys[i];
         bytes32 half1;
         bytes32 half2;

         assembly {
            half1 := mload(add(sha,0x20))
            half2 := mload(add(sha,0x40))
         }
         newKeys1[i] = half1;
         newKeys2[i] = half2;
      }
      return (keys,values,values2,newKeys1,newKeys2);
  }


texts: Options for executing an arbitrary function from my wallet

texts:
What are my options if I want to call an arbitrary function at an arbitrary address, from my wallet (Metamask)?
To be more precise, I want to be able to call a function from a web wallet, when I have the following ingredients:

I know the contract address

I know the function signature and know what parameters I want to use

I don't have the full ABI

The contract isn't verified in Etherscan, or something like that

Is my best option to write an interface, create a dumb website and connect my Metamask to it? Or to figure out the payload data and execute directly in Metamask? Aren't there some easier ways?


texts: The confirmation speed of the transaction is related to the number of nodes

texts: The transaction confirmation speed is proportional to the number of nodes.？


texts: Why does compiled solidity code do this check on the argument with which it was called?

texts:
I have compiled the following Solidity code:

pragma solidity ^0.4.9;
import "./Callee.sol";

contract Caller{
  function call(address callee_address){
    Callee callee = Callee(callee_address);
    callee.callee_function();
  }
}

This becomes the following EVM:
http://pastebin.com/BeUPghsT

I do not understand the following code snippet. Only the code after address 0x1c is copied into the bytearray of the contract upon execution. So all addresses should be 0x1c lower than what is stated here.

Address 0x1c
  PUSH1 0x60
  PUSH1 0x40
  MSTORE
  PUSH1 0x00
  CALLDATALOAD
Address 0x24
  PUSH29 0x0100000000000000000000000000000000000000000000000000000000
Address 0x42
  SWAP1
  DIV
  PUSH4 0xf55332ab
  EQ
  PUSH1 0x3a
  JUMPI
  JUMPDEST
  UNKNOWN OPCODE "0xFE"

Does the CALLDATALOAD put the address argument (callee_address) onto the stack? If so, it seems that the unknown opcode FE (a way of stopping all execution?) is called if the address does not have 0xf55332ab as its first four bytes. Is that correctly understood?

Why should the address start with 0xf55332ab? There are no checksums in Ethereum addresses, right?

Am I correct to understand that this is where a call to function lands or is this dead code?


texts: Can anyone tell what might had gone wrong with the transaction below?

texts:
May I know what does this transaction mean? I am running this inside my private node. Running the same transaction repeatedly none stop. Sending on average 10 transactions / sec. So I had to keep track of the nonce.

But suddenly the transaction below just stopped and refused to process. Query transaction receipt just return null.

May I know what might had gone wrong?

Did I skipped one nonce? How can I tell if I had really skipped one nonce?

> eth.getTransaction("0xb992cfa1e25268de903d54196c1efa1908fcaf900a304db2bde14c1315461dca")
{
  blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",
  blockNumber: null,
  from: "0xc8caa71c16299b40b8579742a27ee53162886040",
  gas: 160000,
  gasPrice: 2600000000,
  hash: "0xb992cfa1e25268de903d54196c1efa1908fcaf900a304db2bde14c1315461dca",
  input: "0x2a281eb70000000000000000000000000000000000000000000000000000000000000011",
  nonce: 2049,
  r: "0x88741393e597de552cf28563c7a601fd7c4f43111144f010d29011aac82756e9",
  s: "0x6becf956d4d622ca4cbe68381dfd6f614aa75fe6ffc6c2081dc725b79ee51819",
  to: "0x9ee0ff1b31fb2587d55f3a6726cb6d653d4b6615",
  transactionIndex: 0,
  v: "0x47",
  value: 0
}


texts: How can I only allow transactions before a certain block?

texts:
I'm writing a token contract now and I'm trying to only allow a user to purchase tokens before a certain block N. What I thought of doing is checking if block.number >= n and if so you either throw and error or issue a refund.

I'm not entirely sure which one I should do (or if this is even the correct approach).

     if(block.number >= 4370000){
      msg.sender.transfer(msg.value);
     }


texts: How to encrypt a string with a smart-contract private-key and decrypt that offline

texts:
Say I want to make a smart contract that is able to save secret messages (strings). The messages should be stored only in encrypted form so no one can read them, but should be decrypt-able by a couple of users.

I can write basic Solidity, but I need some help on how to do this design wise.

I know it's possible to encrypt/decrypt strings offline and only send the encrypted data to the blockchain. But in the case there must be multiple users who need to be able to decrypting the same strings, how can this best be done?

Would this be possible with creating a multi-sig wallet contract comprised out of a few users? Will they all need to have the private key on their computers in order to use it? Isn't that dangerous?

Any advice much appreciated.


texts: what is the role of merkle tree in ethereum?

texts: I know the functionality of merkle tree, it makes a root hash from a group of data.My question is how merkle tree is act in ethereum blockchain,precisesly in the place of transaction hash,block hash,how and where the root hash is used in the ethereum blockchain?


texts: how does commit/reveal solve front-running?

texts:
I am trying to make sure I understand something correctly, so I will pose a problem with a solution.
Problem:
Let's say commit has been called. After this, we call the reveal. attacker listens to commit transactions, and calls the commit was a front-run by himself. Then, attacker listens to reveal transactions. What attacker does now is as soon as he figures out there's a new reveal transaction in the pool, he grabs the arguments(these are the arguments how the hash was derived from), hashes them and if it matches the one already stored on his own address when he called commit , then attacker will also front-run the reveal transaction.
Solution:
I think the only solution to the above problem is that we include msg.sender while getting the commitment hash. This way, even if attacker listens to reveal transactions, and front-runs it, it won't be enough, because msg.sender of attacker will be different and it won't produce the same hash as commitment.
Question 1: What do you think ? Am I right about Solution above ?
Question 2: I've seen some implementations that msg.sender is not included while deriving a commitment hash. This means that front-run still exists, which means attacker front-runs commit , and then front-runs reveal.  If there're lots of transactions happening, sure, this front-run doesn't make any sense to the attacker, but I don't think commit-reveal scheme solves front-run if we use it for quiz smart contract where user submits the solution and gets the reward, because attacker can listen to commit again and it's highly likely that whoever commits, is most likely the winner, so attacker will also wait for the reveal from the same user who called commit and front-runs again. What do you think about this ? For me, for quiz systems, commit/reveal doesn't seem a good solution to solve front-running. Could you put some examples where it would really be useful ? NOTE: I know commit/reveal is a good scheme, but I need examples where it solves the front-running problem and doesn't use msg.sender in the hash too.


texts: How do I dynamically set in my Web3.js file the deployed smart contract's ABI & address?

texts: I'm using Truffle, Solidity, Web3.js, and Ganache. Whenever I deploy a smart contract, I have to copy and paste the new ABI & address of the contract. How can I dynamically change the value so that every time a new smart contract is deployed it saves me from having to copy and paste these new values into my .js file?


texts:
I am using the MyAdvancedToken code from: https://www.ethereum.org/token

I transferred tokens from owner account into the contract, to fund any buy().  Now, I want those tokens back.  Is there any way to transfer them, except for sell()? Because of decimals issue, I could never buy that many tokens back.

I have seen similar questions, but I thought I could use transferFrom(), and enter the contract address in the _from field.  However, that seems to fail:

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_value <= allowance[_from][msg.sender]);     // Check allowance
        allowance[_from][msg.sender] -= _value;
        _transfer(_from, _to, _value);
        return true;
    }

Is there a way to do an allowance to get this to work?  And why can't the contract address send the tokens using transferFrom?  Thanks.


texts: Initializing array of structs inside a mapping of structs - "UnimplementedFeatureError

texts:
I have two structs

struct Vote {
  address from;
  uint256 rep;
  bool vote;
}

struct Pool {
  address from;
  string tokenSymbol;
  string name;
  uint256 timeout;
  string evidence;
  Vote[] votes;
}

mapping(uint256 => Pool) validationPool;

How do I initialize an empty array of votes while creating a new Pool Struct?

    validationPool[proposalIndex] = Pool({
        from: msg.sender, tokenSymbol:_tokenSymbol,
        name:_name,
        timeout: now + 180,
        evidence:_evidence,
        votes: new Vote[](0) });

I see the compilation error :

UnimplementedFeatureError: Copying of type struct DemoContract.Vote memory[] memory to storage not yet supported.
What does it mean and how do I initialize an array of structs inside another struct?


texts: how would you test if the smart contract from github is the deployed smart contract on the blockchain ERC20

texts:
The scenario is that scammers could give a .sol on an open github repo and deploy another contract on the ethereum blockchain.
One reason to do that is to give a github smart contract with a vesting coded and deployed a smart contract without vesting coded on to the blockchain.

The reason I'm asking this is that I can't always check on etherscan.io the source code of some contracts Sometime they do release a github smart contract but how to make sure that the one deployed on github is the one deployed on the blockchain ?

bytecode ?


texts: Why do almost all of the ERC20 tokens have even number of decimals?

texts:
I'm thinking of creating a token with a decimal point of odd number.
However I'm kind of worried if there is any issue that can be caused by using an odd number for the decimal point.
Is there any reason that why do almost all of the ERC20 tokens have even number of decimals?


texts: is not contract address during truffle test

texts:
I have a stupid smart contract like this:

pragma solidity ^0.4.24;

contract ProdottoFactory  {

    function foo() view returns(string nome){
        return "foo";
    }
}

And I want to test it with chai

var Prodotto = artifacts.require("ProdottoFactory");
expect = require("chai").expect;

contract("descrizione primo test", function () {
    describe("test 2", function () {
        it("blablabla", function () {
            return Prodotto.new().then(
                istance => {
                    prodottoContract = istance;
                }
            )
        })
    })
})

contract("descrizione primo test2", function () {
    describe("test 2 2", function () {
        it("blablabla2",function () {
            return prodottoContract.foo().then(function (res) {
                expect(res.toString()).to.be.equal("foo")
            })
        })
    })
})

When I run the command
truffle test
I have this error

  Error: Attempting to run transaction which calls a contract function, but recipient address 0xe8f29e5c4ca41c5b40ed989439ddeae4d9384984 is not a contract address


texts:
I was going through the solidity doc and this contract example.

Check the contract Ballot.

http://solidity.readthedocs.io/en/v0.4.24/solidity-by-example.html

I seem to get most part. However the below code confuses me. What do we mean by address(0) here?


texts: To be absolutely sure: start gas and gas limit are the same thing in the context of a transaction, correct?


texts: how to decompile smart contract bytecode?

texts:
I don't want the whole bytecode to solidity.
I just want that bytecode have fallback function and it's content.
is feature in the bytecode about fallback function?

about external contract call, external contract's address is existed in bytecode?


texts:
I'm trying to make a transfer function require X or Y dependent on time relative to the contract creation.
So far this is what I have:
uint256 public createTime;

function Time() public {
    createTime = block.timestamp;
}

 function _transfer(blabla)
 if(createTime < 7 days * 1 days)
    {
        require(this and that);
    }

    if(createTime > 7 days * 1 days)
    {
        require(this and that);
    }

The first function Time shows as 0 in the testnet. I'm not sure if this is correct? I was under the impression that function would display the timestamp the contract was transacted (deployed), so that I could calculate certain time requirements relative to that starting time.
Is this in any way correct or am I off the ballpark here?
Thanks!


texts: Is it possible to calculate gas needed for a transaction to run within a certain amount of time?

texts:
I'm trying to find out how much gas is required for a transaction to complete in about 5-10 seconds. Is there any way to do that, or is my understanding of this wrong?

Thanks in advance!


texts: Solidity msg.sender.send security problem?

texts:
As far as I understand msg.sender.send just gives enough gas to the call to do one simple logging and not more, so the contracts which does:

msg.sender.send(winnings)
balances[msg.sender] -= winnings

are safe, or not? Sorry I couldn't find a simple answer to this. I have an old contract and I am not sure if I should update it or if it's okay. Better option would be:

balances[msg.sender] -= winnings
if(!msg.sender.send(winnings)){
    balances[msg.sender] += winnings
}

but is the first one still good?


texts: Proof of inclusion inside a Block Header - State Root

texts:
I'd like to verify the inclusion of a certain data within the state of a smart contract supposing that I've already have the right block header.

What is the depth of the State Root?
When I've reached the right node, how depth is again the Storage Root?

Essentially if I am given a value of a variable inside a smart contract, how long is the Merkle Patricia Proof so that it is possible to re-construct the State Root?

Thanks for your time :)


texts:
This is not a duplicate question. The other one doesn't answer the problem in any way. Can anyone explain to me why do I get No Events where emmited when running truffle test? Ganache is listening in 7545 and my truffle config file points to that port.
I can see more blocks being produced in Ganache each time I run truffle test.

I am starting to think it has nothing to do with the contract code or the truffle test, but here they are:

Contract code

function addExam(string memory hash) public returns (string memory examProfessorHash) {
    // save the exam hash and link it with the professors address
    professorsExam[msg.sender] = hash;

    return professorsExam[msg.sender];
}

Test code

it("should add an exam to the exams list", async () => {
    let hash_test = "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08";
    let instance = await Exam.deployed();
    let hash = await instance.addExam(hash_test, {from: accounts[0]});
    assert.equal(hash.valueOf(), hash_test, "Not returning the correct address");

Why do I get

  Contract: Exams
  ✓ should pass this test

  No events were emitted

  1) should add an exam to the exams list

  No events were emitted


texts: Unable to deposit ETH to simplest-possible contract

texts:
contract MyContract{

}

With Ethereum-wallet on the Morden testnet, if I try to send or deposit ETH, it gives an exception.

In browser-solidity, if I call the fallback function with msg.value = 10, it also throws an exception.


texts: Can't open ethereum wallet when blockchain is on my SSD

texts:
After a lot of searching I found how to set the datadir path to download the blockchain on my SSD instead of my :C/ drive since that's almost full

and now that it's downloading the blockchain i would normally be able to open the wallet without issue but It's giving me an error saying "Ethereum node cannot run. Is another instance running?"

I assume it's because on starting the ethereum wallet exe file from my computer while the blockchain data is on my SSD, but when i tried starting the exe file from my SSD is says "the progrom can't start because node.dll is missing from your computer"

anyone have an idea of what i should do?


texts: How to force one person to only vote once?

texts:
Using DAOs, today we have The DAO that aims to be an autonomous company management system. It's ruled by the fact that the more parts of the company you own, the more voting power you own. As this is not a problem for a company that has financial goals, this is absolutely not possible to rule a country with a democratic system. If we would like to rule a country with a DAO, each citizen would have to weight the same while voting in a democratic process.

So, how could we ensure that one account belongs to someone ? I know this is an open question, but I would like some more possibilities to explore this subject.
Thanks.


texts: How does Ethereum avoid inaccurate timestamps in blocks?

texts: A contract can reference the currently being mined contract's timestamp. This means that changing the timestamp of an in-progress to be mined block requires executing all contracts referencing that timestamp. How exactly does Ethereum avoid miners being incentivized to keep old (inaccurate) timestamps within their blocks due to this? Or am I misunderstanding how contracts and blocks tend to interact?


texts: Truffle migrate Could not connect to your Ethereum client

texts:
Issue:
I fail to migrate(connect) a ethereum private chain on cloud server.

Actual Results

Will:dragon zhuangweiming$ truffle migrate --network development
Using network 'development'.

Running migration: 1_initial_migration.js
Could not connect to your Ethereum client. Please check that your Ethereum client:
    - is running
    - is accepting RPC connections (i.e., "--rpc" option is used in geth)
    - is accessible over the network
    - is properly configured in your Truffle configuration file (truffle.js)

Environment

truffle.js

module.exports = {
    networks: {
        development: {
            host: "47.92.53.158",   //this is the IP of ethereum server running on cloud
            port: 8545,             //
            network_id: "15",       // test server.
            from: "0xbe2c0def75c0257f1a9968d2d373febf849d6603", // account created on ethereum 47.92.53.158.
            gas: 4712388,          //default 4712388
            gasPrice: 100000000000  //default 100000000000(100 Shannon)
        }
    }
};

1_initial_migration.js

var Migrations = artifacts.require("./Migrations.sol");
module.exports = function(deployer) {
    deployer.deploy(Migrations);
};

2_deploy_contracts.js

var Dragon = artifacts.require("./Dragon.sol");
module.exports = function(deployer) {
  deployer.deploy(Dragon);
};

I tried geth command as below:

geth --networkid 15 --datadir data --rpc --rpcapi 'web3,eth,net' --rpccorsdomain '*' --rpcaddr 0.0.0.0 --rpcport 8545 --port 30303 console


texts: How signed messages are sent when using Ethereum Payment Channels

texts:
So I've read Ethereum Payment Channel in 50 Lines of Code and have the general gist of how the contract works.  But I don't understand how the signed messages are transmitted between Alice and Bob.  Communication isn't done through the blockchain, so via what medium are messages passed?

I'm presuming there is a clever ethereum way to send messages, rather than having to fall back on sending signed messages via email.

Thanks in advance.


texts:
Hi I'm having this error when I try to set a variable in remix.

inpage.js:1 Uncaught Error: The MetaMask Web3 object does not support synchronous methods like eth_sendTransaction without a callback parameter. See https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#dizzy-all-async---think-of-metamask-as-a-light-client for details.
at MetamaskInpageProvider.send (inpage.js:1)
at s.send (inpage.js:1)
at n.e [as sendTransaction] (inpage.js:1)
at u.sendTransaction (inpage.js:1)
at u.execute (inpage.js:1)
at HTMLButtonElement.<anonymous> (index.html:93)
at HTMLButtonElement.dispatch (jquery-3.2.1.slim.min.js:3)
at HTMLButtonElement.q.handle (jquery-3.2.1.slim.min.js:3)

This is my code in script

  <script>
    if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    }
    web3.eth.defaultAccount = web3.eth.accounts[0];

    var CoursetroContract = web3.eth.contract([
{
    "constant": false,
    "inputs": [
        {
            "name": "_fName",
            "type": "string"
        },
        {
            "name": "_age",
            "type": "uint256"
        }
    ],
    "name": "setInstructor",
    "outputs": [],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
},
{
    "constant": true,
    "inputs": [],
    "name": "getInstructor",
    "outputs": [
        {
            "name": "",
            "type": "string"
        },
        {
            "name": "",
            "type": "uint256"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
}]);
    var Coursetro = CoursetroContract.at('0xdfae0c09d27d0614cc337b821be4370d9ec2d7c6');
    console.log(Coursetro);

      Coursetro.getInstructor(function(error, result){
        if(!error)
            {
                $("#instructor").html(result[0]+' ('+result[1]+' years old)');
                console.log(result);
            }
    });

    $("#button").click(function() {
        Coursetro.setInstructor($("#name").val(), $("#age").val());
    });
</script>

This is the first time I encounter this problem because I'm new in making dapps. Any answer will be accepted and appreciated. Thank you and sorry about my english. :)


texts:
so I have a contract deployed on Ropsten and now I'm trying to access the public variable using a JSON RPC call through Infura and Oraclize.

Here's my contract:
contract test_contract {
    uint public last_a;

function double(uint a) public returns(uint) {
  last_a = a;
  return 2*a;
 }

 function getLastA() public constant returns(uint){
     return last_a;
 }

 function getMethod() public constant returns(bytes4){
     return bytes4(keccak256("getLastA())"));
 }
}

Ok. So I get the method getLastA using the getMethod,  pad it to 32, get the contract address on Ropsten...and now this is my call:

url post - json(https://ropsten.infura.io/).result
 params -  {"jsonrpc":"2.0","id":3,"method":"eth_call","params":[{"to":"0x76a83b371ab7232706eac16edf2b726f3a2dbe82","data":"4b9a1598000000000000000000000000000000000000000000000000000000000000000"], "latest"}

You can see my oraclize query here

Just wondering if I'm doing something wrong or if this is even possible.  The value it should return is 17 if anyone else thinks they have an answer.


texts: Lets say events are invoked from all the methods of a contract. Each event is storing some data. The methods where only computation or data fetching logic is applied will it cost ether if any event is generated from these kind of methods?


texts: how to transfer token with timestamp to restrict token transfer

texts:
I am working on basic ERC20 token smart contract and i would like to add some conditions in token transfer

Suppose, I transfer 100 tokens to  receiver on 2018-03-01 then receiver can't sent that 100 tokens before 2018-03-15 and If i transfer another 100 tokens to same receiver on 2018-03-05 then another 100 tokens can't be sent before 2018-03-20

What would be the code for that scenario, Thanks.


texts: How does a miner determine the sequence of transactions?

texts:
Let's say I have a first-come-first-serve bounty contract. Whoever calls "getBounty()" first gets all balance owned by the contract.

Now if 10 people create transactions calling the getBounty() function - How does the blockchain/the miner determine who comes first and gets the ethers?


texts: Unable to change/read local variable in a smart contract on a local private geth blockchain

texts:
I trying to create and test an ERC-20 Token on a local geth blockchain.

I tried compiling and testing my contract on Remix's Javascript VM environment and it works fine.

Then, I wanted to try deploying the contract on my local chain so I changed the environment to Web3, set it to local host with the correct port of the miner process, and deployed it (the deployment transaction was successful and I can view the contract object on Remix).

I use a totalSupply variable which is given in the constructor and saved in a local variable.

However, when I try reading this variable it always returns 0 rather than the value that I have provided (this works as intended in the Javascript VM) and I even tried giving totalSupply a default value of 1 but the getter function still returns 0 so I reckon it is a reading problem rather than a writing one.

Here is my code but I don't think the code is the problem:

pragma solidity ^0.5.0;

import "./IERC20.sol";
import "./SafeMath.sol";

contract EnergyToken is IERC20{
using SafeMath for uint;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
uint256 totalSupply_;
address minter;

constructor(uint256 total) public{

totalSupply_ = total;
balances[msg.sender] = totalSupply_;
minter = msg.sender;

}

  modifier onlyMinter() {
    require(msg.sender == minter);
    _;
  }
function totalSupply() public view returns(uint256){
    return totalSupply_;
}
function balanceOf(address tokenOwner)  public view returns(uint256){
    return balances[tokenOwner];
}

function transfer(address receiver, uint numTokens) public returns (bool) {

  require(numTokens <= balances[msg.sender]);
  balances[msg.sender] = balances[msg.sender].sub(numTokens);
  balances[receiver] = balances[receiver].add(numTokens);
  emit Transfer(msg.sender, receiver, numTokens);
  return true;

}

function approve(address delegate, uint numTokens) public returns (bool){

    allowed[msg.sender][delegate] = numTokens;
    emit Approval(msg.sender, delegate, numTokens);
    return true;

}

function allowance(address owner, address delegate) public view returns (uint){

    return allowed[owner][delegate];

}

function increaseAllowance(address delegate, uint numTokens) public returns (bool){

    allowed[msg.sender][delegate] = allowed[msg.sender][delegate].add(numTokens);
    return true;
}

function decreaseAllowance(address delegate, uint numTokens) public returns (bool){

    allowed[msg.sender][delegate] = allowed[msg.sender][delegate].sub(numTokens);
    return true;

}

function transferFrom(address owner, address buyer, uint numTokens) public returns (bool)
 {

    require(balances[owner]>= numTokens);
    require(allowed[owner][msg.sender] >= numTokens);
    allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
  balances[owner] = balances[owner].sub(numTokens);
  balances[buyer] = balances[buyer].add(numTokens);
  emit Transfer(owner, buyer, numTokens);
  return true;

  }

function _mint(address account, uint256 amount) public  {

        require(account != address(0), "ERC20: mint to the zero address");
        require(msg.sender == minter, "ERC20: unauthorised mint!");
        totalSupply_ = totalSupply_.add(amount);
        balances[account] = balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    function _burn(address account, uint256 amount) public onlyMinter
{

        require(account != address(0), "ERC20: burn from the zero address");

        balances[account] = balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        totalSupply_ = totalSupply_.sub(amount);
        emit Transfer(account, address(0), amount);

    }
}


texts: Is it possible to buy Ethereum without any service fee using Debit/credit card?

texts:
I just installed the Coinbase app and when I select the add payment method it says 2.5% of service fee of visa and master card.

Is there any app where I can buy crypto-currencies without paying any fees to the middleman and buy directly?


texts: How can we lock an ERC20 token in a contract and generate another ERC20 token proportionally over the locked duration?

texts:
"Gnosis tokens (GNO) are the generator for Wisdom token (WIZ) creation. WIZ can only be created via activating the utility of the Gnosis (GNO) tokens. This is done via a smart contract system. The smart contract works as follows: GNO token holders agree to “lock” their tokens in a smart contract (30–365 days). A multiplier is added for longer lock durations. The smart contract determines the user selected lock duration and applies that duration to a formula that is designed to regulate the supply of WIZ tokens currently in use. Prior to locking their GNO tokens in the smart contract, users will be able to see exactly how much WIZ they will receive as a result of executing the smart contract. Once users execute the contract, 30% of their WIZ will be distributed for immediate use, and the remaining 70% will be distributed proportionally over the locked duration. Once the lock duration expires, the locked GNO ceases to generate WIZ and the GNO becomes freely transferable by the holder. There is no limit (other than duration) for how many times GNO tokens may be used to create WIZ."

How can we implement a token like WIZ (ERC20) which is generated by locking another GNO (ERC20)?

I couldn't find the official implementation of WIZ token on gnosis github page. Can anyone point to a similar implementation on these lines ?


texts:
I want to make a token on ERC20 and that would be staked, and other token would be rewarded as on interest earn. After certain time, that earned token being staked, and third token will came out as on interest.

Is this possible in Ethereum ?


texts: How use SSL between geth nodes communication?

texts: I have a poa network contains 4 nodes, I want to secure the communication between those nodes, is it possible using SSL and reverse proxy ?


texts:
This code works:

contract C {
  function Get() constant returns(bytes8[]) {
    bytes8[] stuff;
    return stuff;
  }
  function Copy() {
    bytes8[] memory stuff = Get();
  }
}

But when I try to call Get() in another way...

contract A {
  A other;
  function Get() constant returns(bytes8[]) {
    bytes8[] stuff;
    return stuff;
  }
  function Copy() {
    bytes8[] stuff = other.Get();
  }
}

I get this error:

DynamicType.sol:8:5: Error: Type inaccessible dynamic type is not implicitly convertible to expected type bytes8[] memory.
    bytes8[] memory stuff = other.Get();
    ^---------------------------------^

I come from the Javascript world where we don't have to worry about storage vs memory types. I have read the section in the Solidity docs on Data Location but it would be helpful to get an explanation particular to this example so that I can better connect the concepts.


texts: Best practices for handling payment in smart contracts

texts:
I am developing a Dapp in which users can buy and sell stamps.
I have two different smart contract with the following struct each (plus setter/getter functions):

 //Stamp.sol
 struct Stamp {
    bytes32 id;    //id generated by keccak
    bytes32 name;    //name of the stamp
    uint cost;     //cost in wei of buying the stamp
    address owner; //owner of the stamp
}

//Envelope.sol
struct Envelope {
    bytes32 id;    //id generated by keccak
    string color;  //color of the envelope
    uint cost;     //cost in wei of buying the envelope
    address owner; //owner of the envelope
}

A user can buy a stamp/envelope or sell a stamp/envelope that she owns.

I assume that each user stores her stamps/envelopes on a DB and in my frontend I read the DB and I create a new struct of the corresponding object in the contract.
This means that a stamp owner can be different from an envelope owner.

The users can view the available stamps/envelopes but they have to buy a pair (stamp/envelope) of the available items each time.

In order to handle the payment, my idea is to have a different contract that handles the payments, which has a function execPayment with the following arguments:

1) ID of the bought stamp

2) ID of the bought envelope

3) Address of the Envelope.sol

4) Address of the Stamp.sol

So when I call the execPayment method, the contract will retrieve the relevant information for each item based on the ID and find the cost and the owner, and then transfer the amount to the right address.

What is the best/efficient way to design the contract for payments?

I also don't know how to transfer the money from the seller since there is one buyer but 2 (possibly different) sellers who get different amount of money.


texts:
I use Solidity Remix IDE for develop purpose. And when I finish I copy in VisualStudio Code and i attach to my project folder. But visual is telling me that i have a problem with the version. I can compile, migrate and use this contract when I deploy at ganache but the warning still there.

Any idea?


texts: Why do miners not always "vote" to increase the block gas limit?

texts:
Miners can increase/decrease the block gas limit. I read that they can increase/decrease for about 0.01% per block.

Why do miners not always want to increase the block limit? This would lead in more gas spending. From an economic perspective you would want the gas price to stay the same or go higher so the block reward goes up too (in ETH).

During the current token spam transactions which have to do to get tokens listed on an exchange lots of high gwei transactions exist. So, for me it would be logical to keep increasing block gas limit so you can mine more of these high gas txns in a block. However, the block gas limit stays about the same (8 million). Why?


texts: Why does adding more external functions adds more cost to a smart contract?

texts:
Please let me know to delete the question if it's already been asked.

I was told (by a colleague of mine) that adding more external function to a smart contract increases its gas. I tested (on remix and metamask) and it's true, for example when my contract has only one external function and one internal function the total gas is: 89941.
But if I change the internal one to external function, (so two external functions) then the gas would be 99943.

Question: Why does a contract having more external function require more gas (when it's deployed)? Is it due to memory/storage allocation?


texts:
Is it possible to read any storage spot in a contract from another contract in EVM? I don't care if it is hackish or not.

My guts say that's not possible because it makes it possible to read internal or private variables like that, but I'd like to know for sure.


texts: how to setup a custom coin initial release so users can buy them using cash or card?

texts:
Is it even possible ?

I am sort of new around the Cryptocurrency arena and we are gearing up to launch our own coins to support our app eco system.

Initial release of a set of coins is slated to be based on a bid system with a lower cap ( say 0.01 USD ) and an upper cap (say 1 USD). We want people in the wild (outside ethereum eco system) to buy the coins using credit card or transfers. So in theory someone who wins the bid will make a transfer of x amount to our bank account. We intend to release his/her account a set of custom coins in return.

Is this possible ? How will we write the solidity contract for this ?


texts: Trying to sync the ropsten testnet to local server using geth


texts: Getting all ERC721 transactions by an account

texts:
My approach here was to listen for Transfer event for a contract (e.g. Cryptokitties) filtered by the indexed from account.

var contract = new web3.eth.Contract(kittyABI, kittyContractAddress,
{from: account});
contract.events.Transfer(
  {filter: {from: account}}, fromBlock: 0},
  function(error, event){ console.log(event); })

The provider was at first Metamask. But that threw the error:
The current provider doesn't support subscriptions

So, I switched over to Infura. Infura had a similar problem unless you use websockets. The error went away and instead I started battling with timeout issue. After much effort, it seems like Infura websocket approach is still not perfectly functioning. So, I am thinking of rolling out my own geth node that simply runs that query. But before I do that, is there anything that I am missing? The problem shouldn't be this hard. I have seen a lot of ERC20 wallets afterall.


texts: Step by step smartcontract debugging with truffle or brownie

texts:
I am writing smart-contracts with Vyper/Brownie or Solidity/Truffle.
In order to debug and test my smartcontracts, i want to execute them step by step.
Is there a way to do that exactly like we debug a c++ program with breakpoints for example.
Is there a way to see EVM instructions during this step by step debugging ?
Thanks a lot


texts: In interface does the function listed have to be exactly the same as they are in contract?

texts:
In solidity 0.7.x, I am creating an interface of contract A in contract B to allow contract B call functions in contract A.
contract A {
  function transfer(address recipient, uint256 amount) public override returns (bool) {
        //definition goes here
    }
}

in contract B, the interface is:
interface A {
    function transfer(address recipient, uint256 amount) external returns (bool) //changed public to external and removed override
 }

Is this definition of interface correct? I used to copy and paste the function definition to the interface. However there was some error asking to remove override and use external instead. I don't quite understand what causes error.


texts: In geth, `eth.syncing` gives `false` even when blocks are imported

texts:
I issue eth.syncing and get false even when at the same time blocks are imported. Is this correct behaviour?

Using geth version 1.4.6


texts:
Stumbled upon this piece of Solidity code which is an Ethereum payment channel :

https://github.com/mattdf/payment-channel

How am I to write a Python client that interacts with it over Web3 ?

What is my Python code supposed to do in order to transfer data over the channel ?

My aim is to eventually write "pings" from many clients to the state channel, after all clients pinged I want to move on to the next one and then, using Merkel Tree write to the blockchain once every X minutes.


texts: Simplest way to use a variable in an Oraclize query?

texts:
I have a variable number in my Solidity contract which changes and I need to incorporate this into an oraclize query. My oraclize query looks like the following:

oraclize_query(60, "URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", '\n{"jsonrpc":"2.0","method":"generateIntegers","params":{"apiKey":${[decrypt]BF8gEz7O4gvAdzdJK/FTWHheGo3TuV5VIFku1rAEG78AxzX6AFEbWJSLZ0sCdEwGzppPsPltUXvIvxNaV5Yvnh3qfmzndRy/nfGjlWESfvNL3S1Fl4y2zqGmGi9DA4D+UokY83Awrw6tZd918KtRAvKe2Bos},"n":1,"min":0,"max":10,"replacement":true,"base":10},"id":1}');

I want the value of max in the above oraclize_query to be number - 1 (instead of 10).

What is the simplest way to do this? I noticed this question How to put a variable inside a string in solidity but the answer is not at all clear to me (I get a lot of errors copy/pasting that code and am not sure how it is meant to be implemented).

I tried using the strConcat function in the Oraclize contract (line 601 at https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol) by converting my number uint into bytes32 and then a string, then putting it all together, like this:

    string string1 = '\n{"jsonrpc":"2.0","method":"generateIntegers","params":{"apiKey":${[decrypt]BF8gEz7O4gvAdzdJK/FTWHheGo3TuV5VIFku1rAEG78AxzX6AFEbWJSLZ0sCdEwGzppPsPltUXvIvxNaV5Yvnh3qfmzndRy/nfGjlWESfvNL3S1Fl4y2zqGmGi9DA4D+UokY83Awrw6tZd918KtRAvKe2Bos},"n":1,"min":0,"max":';

    string string3 = ',"replacement":true,"base":10},"id":1}';

    function update() payable {

         bytes32 data = bytes32(number - 1);

         strConcat(string1, bytes32ToString(data), string3);

        oraclize_query(60, "URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", strConcat(string1, bytes32ToString(data2), string3));

This doesn't work (oraclize doesn't get called at all then).


texts: What is json interface parameter in mycontract?

texts:
in web3.js , to define a new contract

new web3.eth.Contract(jsonInterface[, address][, options])

so what is jsonInterface and where can i find it?
Thank you for reading :)


texts:
Im doing an experiment and for some reason I keep mining 0 h/s?

output: https://pastebin.com/pCPrjUWa

Batch file: ethminer -G -F http://eth-eu.dwarfpool.com/0x618aE67290bDa7707B8fDd9b070E485970D1d3bf/gushoukoens@gmail.com

Anyone know how to fix this?