texts: How to decode txn_hash from contract function call via Python web3.py, w3.eth.sendRawTransaction

texts:
Hi I am running Python web3.py(Not web3.js) to run this:

 txn = ctrtInstance.functions.setzString(zString).buildTransaction()
 print('\ntxn: '+ str(txn))
 txn['nonce'] = 3643
 txn['chainId'] = 3
 print('\ntxn: '+ str(txn))

#So the txn looks this: {'value': 0, 'gas': 33504, 'gasPrice': 1000000000, 'chainId': 3, 'to': '0x5227D720d8eFDcB259c6c79C74f3Cfe04DC4D4fa', 'data': '0xb32e420700000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000007476f204d616e2100000000000000000000000000000000000000000000000000', 'nonce': 3643}

 signed = w3.eth.account.signTransaction(txn, privateKey)
 txn_hash = w3.eth.sendRawTransaction(signed.rawTransaction)

Then txn_hash looks very strange: b"\x83\xd4\t'\x9e\xec\xb7\xc0\xf5\xdd\xf9\xb9\x0fD\xdc\x81\xfb\x8d\x0e\xf7\xb5\xbc2e~\x81R\x8c]Ek|"

What is it?
How to decode this Transaction hash?

Why does it look different from other transaction hash I've seen online?

How can I decode it so I can enter it into EtherScan to check such transaction? Thank you

Reference: http://web3py.readthedocs.io/en/latest/web3.eth.html#web3.eth.Eth.sendRawTransaction


texts: Mist/EthereumWallet error: Method 'eth_sendTransaction' not allowed

texts:
I am trying to deploy a smart contract on a private ethereum blockchain and I get this error message "Method 'eth_sendTransaction' not allowed" whenever I try to submit a transaction for sending ether or even for creating the contract through the mist integrated Remix IDE.

Your help is much appreciated!


texts: Checking for no duplicate values in an array

texts:
I have an uint256[] array. I need to check that no value is repeated in the array more than once.

What is an efficient way to do this?


texts: What explains the "saw teeth" shape of the pending transactions graph?

texts:
The graph of pending Ethereum transaction does not seem to show a flat line, rather, it looks like "saw teeth" with the number of pending transactions rising slowly for an hour or so and then dropping off sharpy within a minute. What explains this phenomenon?
https://etherscan.io/chart/pendingtx
It is also visible here: https://txpool.zengo.com/#0,24h


texts: Get a large amount of blocks with web3 (nodejs)

texts:
I'm writing a nodejs program that gets a large amount of blocks (>100,000) and looks at each transaction inside to filter / analyse the data.

I'm currently using web3 (v1) getBlock function:

eth.getBlock(i, true, handleFunction)

However, even though the handleFunction is called asynchronously, my program (if not manually throttled) blasts out 100,000 requests, overheating the infura websocket I think...

I have manually made a throttle to make only 10 requests and wait 'till all of them are handled, then go to the next 10.

My question: I imagine that a lot of people face this same problem, so is there any method from web3 more appropriate to request multiple blocks? Or is there any design aspect I can improve on?


texts: Struct not being stored in mapping when it contains more than two 'string' properties. Bug?

texts:
I am playing around with Solidity, and have encountered an extremely bemusing issue. I want to have a mapping of Address instances (postal addresses NOT the address type)

Address is a custom defined struct as follows:

//Struct representing a postal address
struct Address {

    bool initialized;

    string identifier;

    string street;
    string city;
}

Now, I have a public function for building an address, defined as follows:

function buildAddress(string identifier, string street, string city) public returns(string){

    Address storage addressInstance = addresses[sha3(identifier)];

    addressInstance.initialized = true;
    addressInstance.identifier = identifier;
    addressInstance.street = street;
    addressInstance.city = city;

    return identifier;
}

and I have a getter defined as follows:

function getAddressStreet(string addressIdentifier) public constant returns(string) {

    Address storage addressInstance = addresses[sha3(addressIdentifier)];

    if (addressInstance.initialized == false) {
        // Unknown node, just return 0x0;
        return "No address";
    }

    return addressInstance.street;
}

My issue is that this does not work. 'Building' an address, mining the transaction, and then 'getting' the street name returns 'No address'.

What is bemusing however is that if I remove one string property from the address struct e.g city, it all works perfectly.. as expected.

That is to say that when there are more than 2 string properties in the struct, the Address is seemingly not persisted on the block chain.

I suspect this may be something to do with storage locations, but having read the appropriate documentation a number of times I cannot see anything that is obviously incorrect..

Could anyone provide any insight into this? This may well be a bug, but I imagine that it is more likely a simple oversight on my part. Any clarification would be appreciated !

Thomas


texts:
ENS is a deployed contract. Where is it?

Specification: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md

And why didn't they specify that in the EIP?


texts: Help me debug this delegatecall Serpent demo I'm working on?

texts:
https://gist.github.com/ChrisCalderon/2818e6ba0214c25962b16c02e761dc26

Whenever I try to run it, I get "Transaction Failed". What it's supposed to do is call it's own functions double and half using delegatecall from function foo and then return the result.

Here's the code from the link at the time the question was asked:

import serpent
from ethereum import tester as t

code = '''\
def foo(x, flag):
    with prefix = 0:
        if flag == "double":
            prefix = 0x6ffa1caa*2**248
        else:
            prefix = 0x70cd69ae*2**248
        delegate_calldata = alloc(36)
        out = alloc(32)
        mstore(ref(delegate_calldata), prefix / 2**248)
        prefix *= 2**8
        mstore8(ref(delegate_calldata) + 1, prefix / 2**248)
        prefix *= 2**8
        mstore8(ref(delegate_calldata) + 2, prefix / 2**248)
        prefix *= 2**8
        mstore8(ref(delegate_calldata) + 3, prefix / 2**248)
        mstore(ref(delegate_calldata) + 4, x)
        delegatecall(msg.gas, self, 128, 36, 128 + 36, 32)
        return(out[0])
def double(x):
    return(2*x)
def half(x):
    return(x/2)'''

print serpent.compile_to_lll(code)
s = t.state()
c = s.abi_contract(code)
double = int('double'.encode('hex').ljust(64, '0'), 16)
print c.foo(1, double)

UPDATE: This is the correct way to do it, with the new delegatecall support:

import serpent
from ethereum import tester as t

code = '''\
def foo(x, flag):
    with prefix = 0:
        if flag == "double":
            return(self.double(x, call=delegatecall))
        else:
            return(self.half(x, call=delegatecall))
def double(x):
    return(2*x)
def half(x):
    return(x/2)'''

print serpent.compile_to_lll(code)
s = t.state()
c = s.abi_contract(code)
double = int('double'.encode('hex').ljust(64, '0'), 16)
print c.foo(1, double)


texts: When I send a transaction to call my contract, it's causing a bad JUMPDEST error. The Ethereum wiki says this error is caused when a JUMP instruction jumps to a location that wasn't marked as a jump destination. Since I wrote my contract in Solidity, shouldn't it be impossible to generate bad code?


texts: What does the ">>=" operator do in Solidity?

texts:
I've seen this operator used in one of Mikhail Vladimirov's articles:
function mostSignificantBit(uint x) public pure returns (uint r) {
    require (x > 0);
    if (x >= 2**128) { x >>= 128; r += 128; }
    if (x >= 2**64) { x >>= 64; r += 64; }
    if (x >= 2**32) { x >>= 32; r += 32; }
    if (x >= 2**16) { x >>= 16; r += 16; }
    if (x >= 2**8) { x >>= 8; r += 8; }
    if (x >= 2**4) { x >>= 4; r += 4; }
    if (x >= 2**2) { x >>= 2; r += 2; }
    if (x >= 2**1) { x >>= 1; r += 1; }
}

What is the difference between the normal shift operator >> and >>=?


texts: What happens when I provide liquidity for a small market cap token?

texts:
If I go to DeFI exchanges (ex Uniswap) and I provide liquidity for small tokens which might be traded in one direction mostly. I wonder what would happen to my share of fees? Would I be losing money or making money?
As in the example below:

If I provide token ABC->DAI LP and then all ABC holders start selling it, do I lose my DAI? Some relevant sources would be helpful


texts: Sending ERC20 token between Metamask wallets over Ropsten test network

texts:
I'm experimenting with creating an ERC20 token and sending it over Ropsten test network using Metamask (following a basic tutorial). I was able to successfully create the token, deposit the tokens in my metamask wallet (wallet A), send it to another metamask wallet (wallet B) and have it appear there. However, when I try to send the tokens from wallet B back into wallet A, the tokens are deducted from wallet B but don't seem to ever actually get sent. I can continue to send coins from wallet A without a problem. Note, wallet B does have test ether in it from a faucet.
Any ideas on why I'm unable to send token? I'm not sure if this is a problem with how I set up the token or if this is a limitation of test network.


texts: Error: sets the total supply upon deployment

texts:
Please help !

When i try to run test from truffle, i got this problem, here my test js code:

var DappToken = artifacts.require("./DappToken.sol")

contract(DappToken, function(accounts) {
    it ('sets the total supply upon deployment', function() {
        return DappToken.deployed().then(function(instance) {
            tokenInstance = instance;
            return tokenInstance.totalSupply();}).then(function(totalSupply){
                assert.equal(totalSupply.toNumber(), 1000000, "sets the total supply to 1000000");
            });
        });
    })

and here my contract code:

pragma solidity ^0.5.0;

contract DappToken {
    uint256 public totalSupply;
    function DToken () public {
        totalSupply = 1000000;
    }
}

and here the result of the test:

PS: for more information, I follow the instruction video "Code Your Own Cryptocurrency on Ethereum (Full)" from Dapp University chanel on youtube , at 40:03


texts: ERC20 Contract - OpenZeppelin - total confusion

texts:
Trying to launch a simple ERC20 Token.

I'm finding OpenZeppelin's extensive library - where every Contract seems to import about 4 other Contracts - to be both wonderfully well organized - but also totally confusing.

Here's a BIG question: their basic ERC20.sol contract has no constructor() function.

1) So where/how do you for example set the totalSupply of Tokens you want your contract to have when you deploy it?

2) where/how do you declare the name or symbol you want your Token to have?

For Q#2: I see you can "tack on" the name, symbol and decimals properties to your contract by also importing the ERC20Detailed contract - which by the way does have a constructor() - into your Contract's declaration, but then what? This still doesn't let you access totalSupply or the other properties of the original basic ERC20 contract.

So how are you supposed to be doing this?

Here's what I've got so far:

pragma solidity ^0.5.2;

import "./ERC20Detailed.sol";

contract MyToken is ERC20, ERC20Detailed {

    constructor(string memory _name, string memory _symbol, uint8 _decimals)
        ERC20Detailed(_name, _symbol, _decimals)
        public
    {

    }

}

NOTE: when I try to set a value for totalSupply in the public { .... } section of the constructor, I get all sorts of errors...

Very confused!


texts: Solidity ; not required after enum statement

texts:
Why is the ; not required after the end of the enum enuContractStates {Ready, Active, Paused} statement.  If I add the ; after this statement I get a compile error.
Thank you
contract Picard {

    string public constant strFullName = "Jean Luc Picard";

    enum enuContractStates {Ready, Active, Paused}

    enuContractStates public state;

}


texts: How does Ethereum deal with blockchain scalability?

texts:
The Bitcoin community are currently trying to solve the problems of blockchain scalability. Some are advocating an increase in block size, others are talking about things like Segregated Witness. Lots of arguments have ensued.

Firstly, what is the (maximum) size of Ethereum's blocks, and how many transactions can they hold? Are they bigger than Bitcoin's blocks, or are the technologies different enough that a direct comparison can't be made?

Following on from this, how does Ethereum deal with the problem of scalability, if at all?


texts:
I wrote a function to exchange an offer by an amount of ether. After checking the value of ether sent and the cost of the
offering, I record the subscription time in a mapping. My problem is that when I send a transaction with the command:

offer.subscribeOffer.sendTransaction(0,{from:eth.accounts[0], to:0x2333a7124d57795757239f0f86990ca9f429e032, value: 2,gas:4000000})

nothing is saved in the mapping, neither the address nor the time.

This is my contract code:

pragma solidity ^0.4.9;

contract Offer {

address public owner;
struct Offer {
    string title;
    string description;
    uint  offerTime;
    mapping (address => uint) subscribers;
    mapping (uint => address) subscribersAddress;
    mapping (uint => uint) nbrSubscribersPerID;
    uint price;
}

Offer[] public  offers;

// add offer
function addOffer(string  description1, string title1, uint price1,uint offerTime1)
  returns (uint, string, string, uint, uint) {
    uint offerID = offers.length++;
    Offer o = offres[offreID];

    o.description = description1;
    o.offerTime=offerTime1;
    o.title = title1;
    o.price = price1;
    return (offerID, offers[offerID].description, offers[offerID].title, offers[offerID].price,
      offers[offerID].offerTime);
}

//return the  number of offers
function returnNbroffer() constant returns(uint) {
    uint nbr_offer =offers.length;
    return(nbr_offer);
}

function subscribeOffer(uint offerID) public payable  returns(address,uint,address)   {

      Offer o = offers[offerID];
      uint i=0;
      uint count=0;
         if (msg.value>= o.price)
           { address addre=msg.sender;
             offres[offerID].subscribersAddress[count=++i]=msg.sender;
             offres[offerID].subscribers[msg.sender]=now;
             return(addre,offers[offerID].subscribers[msg.sender],offers[offerID].subscribersAddress[i]);

            }
    offers[offerID].nbreSubscribersParID[offerID]=count;

}
  function expirationOffer(uint offerID) constant  returns(bool,uint,uint)
  {
     Offer o = offers[offerID];
     bool expire=false;
     uint timenow=now;
     uint timeSpent=offres[offerID].subscribers[msg.sender]+o.offerTime ;
     if (timenow > timeSpent )
       {expire=true;}
   return(expire,timenow,timeSpent);
   }
 }


texts: Issue creating an Ethereum app with Node JS and web3

texts:
For the past week I have been trying to make an app that runs on a node.js server to control the balance going out of different ethereum accounts / wallets. Here is what I have done so far:

(on my Ubuntu 16.04)

install the mist wallet
run the following command to install web3:

npm install web3

(already have npm and node.js installed)

create a simple javascript program to test out using the web3 library:

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProviders("http://localhost:8545"));

var version = web3.version.api;
console.log("version: " + version);

and the output is:

  version: 0.19.1

Now to add an extra line to the above script and see how web3 communicates with the wallet:

var sender = web3.eth.accounts[0];
console.log("sender = " + sender);

but the output gives me the following error:

/home/ubuntuuser/node_modules/web3/lib/web3/httpprovider.js:91
        throw errors.InvalidResponse(request.responseText);
        ^

Error: Invalid JSON RPC response: undefined
    at Object.module.exports.InvalidResponse (/home/ubuntuuser/node_modules/web3/lib/web3/errors.js:38:16)
    at HttpProvider.send (/home/ubuntuuser/node_modules/web3/lib/web3/httpprovider.js:91:22)
    at RequestManager.send (/home/ubuntuuser/node_modules/web3/lib/web3/requestmanager.js:58:32)
    at Eth.get [as accounts] (/home/ubuntuuser/node_modules/web3/lib/web3/property.js:107:62)
    at Object.<anonymous> (/home/ubuntuuser/Desktop/Ethereum/ethy.js:17:22)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:442:10)

And I get the sa,me error when trying to use code like:

var ethVersion = web3.version.ethereum;

QUESTION:
What might I be doing wrong? Is web3 unable to communicate with the wallet because something is missing?


texts: How does web3.js verify that it is geth that is listening on port 8545?

texts:
With several web applications emerging that are essentially front-ends to dapps, there are RPC calls being made to localhost port 8545 (ostensibly by web3.js running in the web client). These local calls are even being made by web sites hosted on public urls, something that does not occur in the vast majority of secure web apps.

While users know that they "must be running geth on my computer", they may not fully understand that this is happening or the security implications. If "something" other than geth or another valid ethereum node is listening on port 8545, and implements the JSON RPC API, the user may be interacting with the ethereum network through that untrusted node.

How does web3.js know that the locally hosted RPC API is a valid node?


texts:
I just figured out how to deploy smart contracts on a test RPC with truffle. This is great! But when I do my tests, I am wondering how to keep the state of a deployed contract for the following test.

Let me explain this a little more detailed:

When I run $ truffle test with for example a transfer function from 0 tokens to 5 tokens. The next time I run the same test again the token balance of the account is 0 tokens again.

How can I run the test so that the state is updated after the previous test?

Example contract

pragma solidity ^0.4.4;

contract TestToken {

   mapping(address => uint256) balances;

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

   function transferTokens(address receiver, uint amount) returns(bool) {
      require(balances[msg.sender] > amount);
      balances[msg.sender] -= amount;
      balances[receiver] += amount;
      Transfer(msg.sender, receiver, amount);
      return true;
   }

   function balanceOf(address owner) {
      return balances[owner];
   }

}

Example test

var TestToken = artifacts.require("./TestToken.sol");

contract('TestToken', function(accounts) {

   it("should transfer 5 tokens from accounts[0] to accounts[1]", function() {

      var token;

      return TestToken.deployed().then(function(instance) {
         token = instance;
         return token.transferTokens(accounts[1], 5, {from: accounts[0]});
      }).then(function() {
         return token.balanceOf(accounts[1]);
      }).then(function(balance) {
         assert.equal(balance.valueOf(), 5, "5 tokens not transfered");
      });
   })

});


texts: Transfer funds to inherited smart contracts

texts:
How would I make this work - the balanceOf[Pool, System + Cube] doesn't seem to work ;-;
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.7.0;

import "./Pool.sol";
import "./Cube.sol";

contract System is Cube, Pool{

    // Variables.
    address public referer;
    bool internal registered = false;
    mapping(address => bool) public isRegistered;
    mapping(address => uint256) internal balanceOf;

    constructor() public {
        address adminWallet = msg.sender;
    }

    // Checks to see if msg.sender is registered.
    function viewRegister() public view returns(bool _isRegistered) {
        _isRegistered = isRegistered[msg.sender];
        return _isRegistered;
    }

    // Receives register payment. *Needs payments to be distributed to pool, cube and admin wallet!
    function initalRegisterPayment(uint256 defaultAmount) payable public returns(bool success) {
        require(isRegistered[msg.sender] = false, "You are already registered!");
        require(balanceOf[msg.sender] >= 0.13 ether, "You are already registered!");

        defaultAmount = 0.13 ether;

        balanceOf[msg.sender] -= defaultAmount;

        balanceOf[System] -= 0.03 ether;
        balanceOf[adminWallet] += 0.03 ether;

        balanceOf[System] -= 0.05 ether;
        balanceOf[Pool] += 0.05 ether;

        balanceOf[System] -= 0.05 ether;
        balanceOf[Cube] += 0.05 ether;

        return true;
    }

    function register(address _newAddress) public {
        require(isRegistered = false, "You are already registered!");
    }
}

The code for each inherited contract are like this one:
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.7.0;

contract Pool {

    fallback() payable external {}

}


texts: Hello I have to create dapp, and more specific I want to create something like store where people can create items and sell them. The problem is I want to keep information about the items offchain (like title, description, picture etc..). For backend dB I want to use Mongo, and I was wondering can I save addresses of my users together with the items which they choose to sell in mongodb, and all other transactions onchain?


texts: Why does Oraclize queries not result in DOS attacks?

texts:
Although I've already researched a lot about how Oraclize works, there is still an issue which is not clear to me.

As far as I understand the execution of smart contracts is done on all verifying nodes. Since Oraclize has to query some data from a public API and if thousands of nodes would perform such an action this may result in a DOS attack or is Oraclize off-chain and not realized as a smart contract?

I'll appreciate any explanation!


texts: How to recognize if a website is a DApp?

texts:
A Launch App button often appears on the top-right corner of Ethereum-platform websites. Is this an indication that a link is a link to a DApp (decentralized application)? Are the following two websites DApps?

https://app.ens.domains/ (Ethereum Name Service for buying decentralized domains)
https://app.uniswap.org/ (Uniswap decentralized exchange)

What signs, or how can I tell if a website is a DApp? You wouldn't be able to tell just be looking at the URLs above, since even the sub-domain reads "app", not "dapp".
And once you do recognize that a website is a DApp, what can you expect to do with it as givens, compared to regular websites that aren't DApps? I am not even aware of websites that are called "Apps" (centralized apps) in the first place, so what App website can I compare the above Dapps with?


texts: Parity Ethereum node missing CLI option to display configuration setting of a running node

texts:
I'm playing around with config.toml and using CLI options. Maybe I missed something, but I'm interested in executing a command by which I can exactly see what options are in effect when a Parity Ethereum node is running. This will help me fine tuning the node and when I'm experiencing issues. Preferable a CLI solution.
Could this be delivered?

KR Rene


texts: What is the transaction confirmation time for ERC20 based token?

texts:
In case of Bitcoin, it is 10 min.

What is the case for ETH or ERC20 based token? And what's the confirmation time change after Casper update?


texts:
I believe that the openzeppelin project have updated their StandardToken smart contract which is now called ERC20.sol.
One issue that I have is that the new smart contract has some missing functionalities that we previously had. In the past, when you imported StandardToken into your smart contract, you would be able to initialize your Token like that:
pragma solidity ^0.4.19;

import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "http://github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol";

/**
 * @title ExampleToken is a basic ERC20
 */
contract ExampleToken is ERC20, Ownable {
    uint256 public totalSupply;
    string public name;
    string public symbol;
    uint32 public decimals;

    /**
     * @dev assign totalSupply to owner of contract
     */
    constructor() public {
        symbol = "EXM";
        name = "ExampleCoin";
        decimals = 4;
        totalSupply = 10000000000;

        owner = msg.sender;
        balances[msg.sender] = totalSupply;

        emit Transfer(0x0, msg.sender, totalSupply);
    }
}

Because I am using the new smart contract, I can't do this anymore:
balances[msg.sender] = totalSupply;

because I am getting the error since openzeppelin has not implemented it:

DeclarationError: Undeclared identifier. Did you mean "balanceOf"?

balanceOf is obviously not suitable since this is a function returning the balance at a given address.
What's the most suitable way to initialize the balance?
Is it better to send it to owner's address or just leave it in the smart contract? Is there a risk for leaving the balance inside the smart contract and is this procedure widely used?
If I shouldn't leave it in the smart contract, then what's the best way to give the total supply to the contract creator?
Alternatively, is it possible to import previous openzeppelin smart contracts when StandardToken existed?


texts:
I'm running a local geth node, and I have a truffle project that was already migrated once, but I'm having issues migrating additional contracts, or even updating past contracts.

I create a new contract in the /contracts folder, compile it and add it to 2_deploy_contracts.js, but when I try running truffle migrate it says that the network is up to date. Any help?


texts: Does a virtual function increase gas usage?

texts:
Suppose we replace every expression balances[user] with a call myBalance(user) where
mapping(address => uint256) balances;

function myBalance(address user) returns (uint256) virtual internal {
    return balances[user];
}

and do not inherit from this contract.
Will this increase gas usage?
And what if I do inherit, will it increase gas usage for this base (parent) contract?
I am interested about Solidity 0.5.10 and above.


texts: Can I use OpenZeppelincontract to create your own contract on testnet and mainnet?

texts:
I'm learning ERC-1155 Multi Token Standard, and I found great OpenZeppelin tutorial. However, I'm not sure if I can use that OpenZeppelin contract when I deploy my contract to the testnet or mainnet.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SILVER = 1;
    uint256 public constant THORS_HAMMER = 2;
    uint256 public constant SWORD = 3;
    uint256 public constant SHIELD = 4;

    constructor() ERC1155("https://game.example/api/item/{id}.json") {
        _mint(msg.sender, GOLD, 10**18, "");
        _mint(msg.sender, SILVER, 10**27, "");
        _mint(msg.sender, THORS_HAMMER, 1, "");
        _mint(msg.sender, SWORD, 10**9, "");
        _mint(msg.sender, SHIELD, 10**9, "");
    }
}


texts:
Hi placed a self Ether transaction by error, where did the Ether go? can I recover it?

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


texts: Passing of a struct array from called contract to calling contract

texts:
I am currently developing a dAPP and I am splitting it in 2 distinct contracts. I will be calling functions from contract A to contract B. In contract B I have an array of struct which I can manipulate. However I need some functions called from A to B and B must return the struct array or a copy of it to contract A. How can I do this? If I use a mapping instead of struct arrays, can I still do it?

Thanks


texts: How to use web3j to observe transaction of ERC20 token

texts:
Leverage Web3j TransactionObservable together with filter, i can monitor ETH/ETC transactions as following code snippet illustrates.

web3j.transactionObservable().filter(tx -> isWantedTransaction(tx)).subscribe(processTransaction,errorHandler,OnCompleteHandler);

How to implement same function with web3j for customerized ERC20 tokens?


texts: Upgradable smart contract pattern - any issues regarding trust?

texts:
There are two contracts, the Manager and the Token, with the Manager being the actual world-facing address that people interact with, but all it does is delegate all calls back to the Token where the logic is, but the storage is in the manager, so if a bug is found the owner can swap the logic out and be fine. Also, though, the owner could swap that contract out with one that does nothing, so it would screw everyone over. Hence the trust. What's to stop me from changing the Token address on the manager to a dead end, or something that gives their tokens to me?
Has anyone implemented this, or is there a project with a pattern like this implemented already, and how did it go? What do people think?


texts: Are there any resources for "contract-oriented programming"?

texts:
Contract-oriented programming, like Solidity, is similar to OOP, in a syntactical sense. For example, both have concepts of encapsulation, abstraction, inheritance, and polymorphism. They also share similar keywords, and a contract seems analogous to an object. However, they are not.
Does anyone know of any resources regarding contract oriented design?


texts: ethereum wallet always loads "private net"

texts:
I have been running test with a private net. Now, no matter what I do (including removal of test dir), when I launch the wallet, it always open in Private Net mode.

Not sure what I am doing wrong.


texts: Restricting payment from one account only

texts: I am a beginner in ethereum DApp development and I am testing my Contracts in Remix IDE. My question is that can I restrict only one account to pay for all the transactions happening on my application since I don't want my application users to pay for the transaction fees at all as that would require that each user must have some wallet like MetaMask or Mist installed. Is this approach correct and is this possible ? How can I implement this ?


texts:
I got the "Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Internal JSON-RPC error." in remix while using the drawWinner function

    pragma solidity ^0.4.18;

    contract RecurringLottery {
         struct Round {
            uint deployBlock;
            uint endBlock;
            uint drawBlock;
            Entry[] entries;
            uint totalQuantity;
            address winner;
       }
struct Entry {
    address buyer;
    uint quantity;
}

uint constant public TICKET_PRICE = 1e15;

mapping(uint => Round) public rounds;
uint public round;
uint public duration;
mapping (address => uint) public balances;

// duration is in blocks. 1 day = ~5500 blocks
function RecurringLottery (uint _duration) public {
    round = 1;
    duration = _duration;
    rounds[round].deployBlock = block.number;
    rounds[round].endBlock = block.number + duration;
    rounds[round].drawBlock = block.number + duration + 5;
}

function buy () payable public {
    require(msg.value % TICKET_PRICE == 0);

    if (block.number > rounds[round].endBlock) {
        round += 1;
        rounds[round].deployBlock = block.number;
        rounds[round].endBlock = block.number + duration;
        rounds[round].drawBlock = block.number + duration + 5;
    }

    uint quantity = msg.value / TICKET_PRICE;
    Entry memory entry = Entry(msg.sender, quantity);
    rounds[round].entries.push(entry);
    rounds[round].totalQuantity += quantity;
}

function drawWinner (uint roundNumber) public {
    Round storage drawing = rounds[roundNumber];
    require(drawing.winner ==  address(0));
    require(block.number > drawing.drawBlock);
    require(drawing.entries.length > 0);

    // pick winner
    bytes32 rand = keccak256(
        block.blockhash(drawing.drawBlock)
    );
    uint counter = uint(rand) % drawing.totalQuantity;
    for (uint i=0; i < drawing.entries.length; i++) {
        uint quantity = drawing.entries[i].quantity;
        if (quantity > counter) {
            drawing.winner = drawing.entries[i].buyer;
            break;
        }
        else
            counter -= quantity;
    }

    balances[drawing.winner] += TICKET_PRICE * drawing.totalQuantity;
}

function withdraw () public {
    uint amount = balances[msg.sender];
    balances[msg.sender] = 0;
    msg.sender.transfer(amount);
}

function deleteRound (uint _round) public {
    require(block.number > rounds[_round].drawBlock + 100);
    require(rounds[_round].winner != address(0));
    delete rounds[_round];
}

function () payable public {
    buy();
}

}


texts: Script to automatically transfer ether to another address

texts:
Please, can anyone help with a script to use and watch my address for any incoming ether, and once it enters, the script would quickly transfer the ether to another address.
I would also love to know how to set up and run the script.


texts: How to understand from web3py if I need a transaction or a call

texts:
I have a contract with a function in which only if a certain condition is true, it changes the state of the blockchain otherwise it emits an event and returns:

address[] public global_state;
function test() public payable returns (bool) {
    if (condition on global_state) {
        emit Event();
        return false;
    }
    // change the state
    global_state.push(address("0x0"))
    return true
}

If I understand it correctly, I don't need a transaction if the condition is true and a simple call will do the job.

But when I call the function from web3py I don't know the state of the condition.
I was wondering if there is a way to understand it before and make the correct call with web3py because for the transaction I need to wait but for the call, I don't.


texts: How to write a message/string to the Blockchain?

texts:
I am not a programmer so my attempt to deploy a token is failing.

Is there any other way to write a string to the Blockchain?  An RPC command maybe?

*EDIT: Yes.  The answer is visible at How to replicate Bitcoin's OP_RETURN functionality on Ethereum? although the question was a different approach.


texts:
I want to play with a custom chain that has a gas price that's different from the ETH mainnet.  By "gas price" I mean how much gas is required to deploy a dapp.

But I don't see anywhere in the chain spec file that gasprice is specified.  So I don't know what the default is.  For reference:
https://github.com/paritytech/parity/blob/master/ethcore/res/ethereum/foundation.json

Also (separate question): does anyone know how I specify the gas price in the chain spec AND genesis files?


texts: Sending a transaction to a non-existent address

texts:
What happens if you initiate a transaction to a non-existent address in geth?
Is there any way to determine if an account exists as a legal address?
Hope you can give me some help, thanks!


texts: Missing Ethereum transaction from Poloniex to MyEtherWallet

texts:
I have sent my transaction from Poloniex to MyEtherWallet and transaction showed up only for ten minutes and after that it disappeared completely without any trace of it.

It didn't return to my original wallet and it didn't come to my new wallet. It just simply disappeared on the system.

I saw many other transactions same thing happening to them on the ether network right after mine!

Here is my TX:

0xe0ff12043430c5b3a69d59d7807d41717ba504fcb3b322fc221cce7c1b51102f

My wallet address:

0xF538e17853a641B986106E2006DEc96a6f0BA0E8

Here is a picture of the transaction before it disappeared

Can anyone tell me whats going on?


texts: Using oraclize and solidity-util - having trouble splitting string separated by space

texts:
I am learning to use Oraclize to connect it to random.org to generate random numbers.

Here's my test contract code:

pragma solidity ^0.4.25;

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
import "github.com/willitscale/solidity-util/lib/Strings.sol";
import "github.com/willitscale/solidity-util/lib/Integers.sol";
import "github.com/willitscale/solidity-util/lib/Addresses.sol";

contract Oraclize is usingOraclize {

    using Strings for string;
    using Integers for uint;
    using Addresses for address;

    string public randomNumbers;
    uint[] public randomNumbersArray;

    event newOraclizeQuery(string description);
    event randomNumbersGenerated(string randomNumbers);

    constructor() public {
        update();
    }

    function __callback(bytes32, string result) public {
        if (msg.sender != oraclize_cbAddress()) revert();
        randomNumbers = result;

        string[] storage split = result.split(" ");

        for (uint i = 0; i < split.length; i++) {
            randomNumbersArray.push(parseInt(split[i]));
        }

        emit randomNumbersGenerated(randomNumbers);
    }

    function update() public payable {
        emit newOraclizeQuery("Loading new set of random numbers, standing by for the answer...");
        oraclize_query('URL', '...');
    }

}

I've tested the above on http://remix.ethereum.org via Rinkeyby testnet. I deployed the contract and then called the update() function and then checked on both of the public fields and they were empty / 0:

What am I doing wrong here?

When I take out the random number splitting by space part of the code, the callback then start working.

Any ideas?


texts: Is it possible to deploy a contract from python web3 if I have the ABI and bytecode from Remix?

texts:
Question says it all. I have a contract that I've written and compiled via Remix. I've dumped the ABI and Bytecode into local files, and I'm reading them into my python application. I'm following the documentation (https://web3py.readthedocs.io/en/stable/contracts.html) and trying to instantiate like:

mycontract = w3.eth.contract(abi=ABI,bytecode=BYTECODE)

where ABI is the copy-pasted abi from Remix, and the BYTECODE is the copy-pasted bytecode from Remix.

But I get a TypeError: Could not format value {'linkReferences': {}, 'object': '6080604...

I should mention that I can instantiate the contract the the same ABI and an address that the contract has been deployed to via Remix, and then successfully monitor the contract to log events. But what I would really like to do is deploy the contract from Python, using the locally stored abi and bytecode generated by Remix.

Currently, the "bytecode" that Remix provides is in a structure like this:

{
  'linkReferences':[],
  'object': '6080604052336000806...',
  'opcodes': 'PUSH1 0x80...',
  'sourcemap': '50:1984:0:-;;;2...'
}


texts: Does bool take less storage than uint8 (or the rest of integer types)?

texts:
I want to keep track of a mapping of addresses with only 2 possible states. Does uint8 take more storage and consume more gas in my case?

contract MyContract {
    mapping(address => bool) boolBackedStatus;
    mapping(address => uint8) uint8BackedStatus;

    function setTrue(address user) {
        boolBackedStatus[user] = true;
        uint8BackedStatus[user] = 1;
    }

    function setFalse(address user) {
        boolBackedStatus[user] = false;
        uint8BackedStatus[user] = 0;
    }
}


texts: How much gas is included in transaction by default?

texts: I am getting an out of gas error when using transaction that creates another contract using truffle, but the transaction goes through fine in the solidity online compiler. The transaction uses 994220 gas.. Does the online compiler send more gas by default?


texts:
My understanding is that bootnode --genkey commands generate private key of node, and bootnode --writeaddress commands generate public key of node.

However, why node needs private key and public key?

Main usage of node's public key seems to be an identifier of nodes.
If the node key is only used as identifier, no need for cryptography.

What is nodekey of bootnode command?


texts: After deleting all elements from an array, how much gas refund will be made?

texts:
Following answer and solidity_link says that:

  Use delete on arrays to delete all its elements.

delete dataArray;

  This is exactly the same as dataArray.length = 0

From this answer as I understand that negative gas costs will be 15000.

  The only two OPCODEs with negative gas costs are STORAGEKILL(-15000)
  and GSUICIDEREFUND(-24000).

[Q] Overall, after deleting an array; how much gas refund will be made? Would it be only 15000 or 15.000 * 'length_of_the_array' ?

=> For example, I have an array with length of 100. When I delete it how much gas will I be refunded?

If only 15000; then should I traverse all the elements in an array and delete them rather than doing delete dataArray?

Something like:

for(uint i=0; i< dataArray.length; i++){
     delete dataArray[i]
}

=> For example, if I want to delete an mapping that maps a struct (uint[] that has 100 items), would it refund 15000 or the gas cost of the struct that is pointed (15000 * 100).

If only 15000; then should I traverse all the elements mapped by the element as well and delete them rather than doing delete mappingData?

mapping(address => uint[]) mappingData;  //'0xabcd' maps to length of the `uint[]` is 100
delete mappingData;

Something like:

for(uint i=0; i< mappingData[0xabcd].length; i++){
     delete mappingData[0xabcd][i];
}

Some observation: If I traverse an delete and delete items one by one, traversing will charge me additional gas cost, maybe equivalent to the refunded gas so where would be the motivation to use delete?


texts: Problem connecting with contract deployed on Ropsten Testnet

texts:
I am having issues with calling functions of contract deployed on the Ropsten Testnet. Previously, I tested this on testrpc and everything was working well. I'm working on transfer of ERC20 Standard tokens.

When I tried calling balanceOf using contract.call().balanceOf() it raised following error

web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

Then I also tried contract.transact().balanceOf() which threw the following error

raise ValueError(response["error"]) ValueError: {'code': -32000, 'message': 'unknown account'}

Is it because geth hasn't fully synced with the Ropsten chain? If I have to fully sync with the Ropsten Chain now, does that mean when the contract is later deployed into main net, the main net chain has to be synced fully as well?


texts: I created a POA chain using this tutorial, I created a network of 5 nodes and 3 are mining on the network. I tried to deploy token contract to the network from one account using truffle and it was successful. Now I want to call the functions of that smart contract from other accounts and play around. How can I do that? can i do it using "geth attach http://localhost:port" and then what command should i use to call functions of a contract deployed from other account?


texts: Truffle testrpc - public variable getter method error

texts:
I'm running into a weird issue where I couldn't retrieve the value of a public variable in truffle console.

It's a public variable used as a counter to track the number of records added. I spent almost a day troubleshooting it and found various issues which couldn't provide a logical justification.

Attempt 1 - using the default getter did not work.

// public variable name
uint public productIndex;
// using the default getter method did not work
 EcommerceStore.deployed().then(function (i) { i.productIndex.call().then(function (f) { console.log(f) }) })

Attempt 2 - I wrote a new function in my original smart contract to return the value of the variable - did not work.

// public variable name
uint public productIndex;
EcommerceStore.deployed().then(function (i) { i.getProdCount().then(function (f) { console.log(f) }) });

Attempt 3 - I renamed the variable and tried to return the value from the new function - did not work.

// public variable name
uint public productIndex1;
// not working without parameter
EcommerceStore.deployed().then(function (i) { i.getProdCount().then(function (f) { console.log(f) }) });

Attempt 4 - Renamed the variable and tried to return it from a function with dummy input parameter and it worked.

// public variable name
uint public productIndex1;
// working with parameter
EcommerceStore.deployed().then(function (i) { i.getProdCount(0).then(function (f) { console.log(f) }) });

I couldn't understand what's going on. I can do a screen share or put together a video for someone to review. Again not sure if it's truffle issue or testrpc issue. How can I go get this fixed? Who can help me understand this issue?
The same contract works on remix and I'm able to get the public variable method.


texts: Unvisible Sending of NAGA coins from Myetherwallet

texts:
It's the first time for me to send tokens out of myetherwallet.
Yesterday I send some NAGA coins from myetherwallet to the exchange HitBTC platform. Everything is going fine with creating transaction and the NGC should be on pending but they're not. I can't see them on the pending transactions and the coins are somehow still in my token wallet. As I tried to send them again, it says that I do not have enough NGC token to send.
So are they on the way? Why can't I see the transaction?
Regards
Kessy


texts:
May a message call change the gas price of the original transaction?

EOA's may call a contract function by means of a transaction. However, contracts can call each other in the execution environment.

Can message calls change the gas limit and gas price of the original transaction? If so, how would I do it in Solidity?


texts: Ethereum client-go RPC response 403 “invalid host specified”

texts:
I'm running ethereum/client-go docker image with the following flags:

docker run -p 8545:8545 ethereum/client-go --rpcapi personal,db,eth,net,web3 --rpc --rpcaddr 0.0.0.0 --rpccorsdomain * --rinkeby

This image is running on machine A and I can query the RPC within it. But when I try to query it from machine B I receive the following response:

Request:

curl -X POST http://<machine_A_address>:8545 -H "Content-Type: application/json" --data '{"jsonrpc":"2÷.0","method":"eth_coinbase","params":[],"id":64}' --verbose

Response:

< HTTP/1.1 403 Forbidden
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Wed, 18 Apr 2018 14:58:44 GMT
< Content-Length: 23
<
invalid host specified
* Connection #0 to host ... left intact

How can I query the ethereum client hosted on machine A from machine B ? Where I can find the ethereum client logs so I can debug it ?


texts: Get deployed contract details from Private network in all connected Peers

texts:
I have created one Ethereum private network and added two nodes inside that n/w.

I have migrate one contract using truffle in that n/w from one node.

Now I want to access that contract inside another node then how can we get it?

Is there any way to get deployed contract details from all the nodes?


texts:
Is there have a way to pass array parameter from the drizzle to my contract ?
I want to pass an array of uint[]

i have read a lot about getData() function and encodeABI but how to use it in Drizzle ?


texts: I sent Ethereum from Bittrex to ICO smart contract by a mistake

texts:
Was planning to send Eth to my ERC20 wallet, but by a mistake i sent it directly to the ICO smart contract. But the transaction shows up as a fail and the value says cancelled. I sent the ETH from Bittrex, but the ETH has not come back to my Bittrex wallet.
How can i get the ETH back?

TxHash:0x942ae095e7f407236f65a3e3b7f027f301b423fb38c9eb87b96d9085315d60cc


texts: Besides TheDAO - what are some examples of where Ether has been hacked, stolen or lost?

texts: Besides TheDAO - what are some examples of where Ether has been hacked, stolen or lost ?


texts:
I'm trying to understand this array overflow attack on Solidity.
(https://www.youtube.com/watch?v=gUqHgFuSsqg)

In that video, the code is basically like this

pragma solidity ^0.4.17;

contract ArrayOverflow{
    uint256 public target = 10;
    uint256[] public array = [9,8];

    function modifyArray (uint256 _index, uint256 _value){
        array[_index] = _value;
    }

    function popLength() public{
        // cause overflow
        array.length--;
    }

    function getLength() constant returns(uint256){
        return array.length;
    }

}

What he did is call popLength() three times to make the array overflowed.

After the above step, we can see the storage loaded is like this

So the 0xfffffff...fff is the length value.

Then we convert the hexadecimal value to address.

   web3.sha3('0x0000000000000000000000000000000000000000000000000000000000000001', {encoding: 'hex'})
// => 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6

The following part is what I felt confused.

He exeuted the following command to find the address of target

perl -Mbigint -E 'say ((2**256 - 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6 + 0)->as_hex)'

The output magically becomes the address of target, how does that happen?


texts: Return remaining ether for user: user lost too much ethers

texts:
I writing a smart contract using Truffle and testing for that. I current meet this problem:

I send 0.5 ether to smart contract.
After that, contract get 0.0016 ether. (tested)
Then transfer again remaining ether for end user.
The gas estimate is about 199529.

I expect end user only loose 0.0016 ether (or little more, if we count gas price. But after testing, I see that user lost about 0.049 ether. I think this number is too much. Please explain for me this is normal behavior or there is some problems in my contracts.

Here is my code:

function _getPrice(
    uint8 _clazz,
    uint256 _quantity
)
internal
view
returns (uint256 _totalPrice, uint256 _priceIncrement, uint256 _currentPrice)
{
    _priceIncrement = priceIncrements[_clazz];
    _currentPrice = currentPrices[_clazz];
    _totalPrice = 0;
    uint256 totalAdoptedInClazz = totalAdoptedCreeptomas[_clazz];

    require(totalAdoptedInClazz.add(_quantity) <= MAXIMUM_ADOPTED_PER_CLASS);

    for (uint256 i = 0; i < _quantity; i++) {
        _totalPrice = _totalPrice.add(_currentPrice);
        totalAdoptedInClazz++;

        if (totalAdoptedInClazz == 100 ||
        totalAdoptedInClazz == 300 ||
        totalAdoptedInClazz == 600 ||
        totalAdoptedInClazz == 1000 ||
        totalAdoptedInClazz == 1500)
        {
            // half the increment price
            _priceIncrement >>= 1;
        }

        _currentPrice = _currentPrice.add(_priceIncrement);
    }
}

Here is method use above:

function _adopt(
    address _adopter,
    uint8 _clazz,
    uint256 _quantity,
    address _referrer
)
private
returns (uint256 _totalPrice)
{
    (_totalPrice, priceIncrements[_clazz], currentPrices[_clazz]) = _creeptomaPrice(_clazz, _quantity);

    userAdoptedCreeptomas[_adopter][_clazz] = userAdoptedCreeptomas[_adopter][_clazz].add(_quantity);
    totalAdoptedCreeptomas[_clazz] = totalAdoptedCreeptomas[_clazz].add(_quantity);

    emit AdoptedCreeptomasEvent(_adopter, _clazz, _quantity, _referrer);
}

And here is final method:

function adopt(
    uint256 _beastQuantity,
    uint256 _aquaticQuantity,
    uint256 _plantQuantity,
    address _referrer
)
public
payable
whenNotPaused
{
    require(_beastQuantity <= 3 && _aquaticQuantity <= 3 && _plantQuantity <= 3);

    address adopter = msg.sender;
    address actualReferrer = 0x0;

    // An adopter cannot be his/her own referrer.
    if (_referrer != adopter) {
        actualReferrer = _referrer;
    }

    // sending ether
    uint256 value = msg.value;

    uint256 price;

    // calculate price for buying beasts
    if (_beastQuantity > 0) {
        price = _adoptCreeptomas(
            adopter,
            CLASS_BEAST,
            _beastQuantity,
            actualReferrer
        );
        require(value >= price);
        value -= price;
    }

    // calculate price for buying aquatics
    if (_aquaticQuantity > 0) {
        price = _adoptCreeptomas(
            adopter,
            CLASS_AQUATIC,
            _aquaticQuantity,
            actualReferrer
        );
        require(value >= price);
        value -= price;
    }

    // calculate price for buying plants
    if (_plantQuantity > 0) {
        price = _adoptCreeptomas(
            adopter,
            CLASS_PLANT,
            _plantQuantity,
            actualReferrer
        );
        require(value >= price);
        value -= price;
    }

    // return remaining ether again for user
    msg.sender.transfer(value);

}

I try to call adopt(3, 3, 3, 0). It means maximum is 9 loops. but total gas is 200,000.

I used method estimateGas for testing:

    let est = await this.contract.adopt
        .estimateGas(beastQuantity, aquaticQuantity, plantQuantity, referer,
            {from: this.investor, value: ether(15)});
    console.log('est: ' + est);

Thanks


texts: Decentralized File Storage on Ethereum white paper

texts:
I am reading white paper of Ethereum, and I am confused by this example of the Section. Decentralized File Storage, which is part of the Section. Applications:

  The key underpinning piece of such a device would be what we have termed the "decentralized Dropbox contract". This contract works as follows. First, one splits the desired data up into blocks, encrypting each block for privacy, and builds a Merkle tree out of it. One then makes a contract with the rule that, every N blocks, the contract would pick a random index in the Merkle tree (using the previous block hash, accessible from contract code, as a source of randomness), and give X ether to the ﬁrst entity to supply a transaction with a simpliﬁed payment veriﬁcation-like proof of ownership of the block at that particular index in the tree. When a user wants to re-download their ﬁle, they can use a micropayment channel protocol (eg. pay 1 szabo per 32 kilobytes) to recover the ﬁle; the most fee-efﬁcient approach is for the payer not to publish the transaction until the end, instead replacing the transaction with a slightly more lucrative one with the same nonce after every 32 kilobytes.

Especially the long sentence in the middle:

  One then makes a contract with the rule that, every N blocks, the contract would pick a random index in the Merkle tree (using the previous block hash, accessible from contract code, as a source of randomness), and give X ether to the ﬁrst entity to supply a transaction with a simpliﬁed payment veriﬁcation-like proof of ownership of the block at that particular index in the tree.

Can someone explain more of it?


texts:
Do you know why a single address of type contract is mining 38% of 0xbtc? Does it mean that a single person has find a way to mine as much 0xbtc as a whole mining pool? Plus how  come a contract is able to mine an ERC20 token, I really don't get it please help me understand what is going on!

https://0x1d00ffff.github.io/0xBTC-Stats/?page=stats&#miners


texts: Marketplace that only accepts first-party NFTs to be sold

texts:
There are two contracts:

ERC721 NFT contract (enables minting, etc)
Marketplace contract (has a sell function and buy function)

When somebody calls the function to put a NFT for sale in the marketplace contract, I want it to only permit NFTs that were created in the aforementioned NFT contract. If someone tries to sell an unrelated NFT using that marketplace contract, he should be denied.
How can I do this?


texts: Does the Minereum Automatic Token Creation Service Work?

texts:
I recently stumbled upon Minereum which they say is the first self mining smart contract token.

They released a service that supposedly allows anyone to create a Ethereum Token with just a Minereum transaction, their ANN thread: https://bitcointalk.org/index.php?topic=1867535.0

Here is the release post of the Token Service:

https://bitcointalk.org/index.php?topic=1867535.msg19583893#msg19583893

Is this service legit?

I don't have coding experience but if this works and is not a scam I will definitely create one too!


texts: How to get an output similar to remix in solc, woth opcodes + comments from source

texts:
I would like to compile my contracts and to get an output with the opcodes in detail (not just assembly) but with references to the solidity source code at each line. This is the output one gets by default when using the Remix editor and cliking on "details", but I can't find a way to get that using the solc binary: I get either assembly with comments using --asm or opcodes without comments --opcodes. Can I do that?

EDIT: to clarify, what I mean by assembly is something like

      tag_11
        /* "pot.sol":5259:5263  myid */
      dup3
        /* "pot.sol":5265:5271  result */
      dup3
        /* "pot.sol":5283:5284  0 */
      0x0
        /* "pot.sol":5273:5285  new bytes(0) */

and what I mean by opcodes is something like

      SWAP1             contract Coucou{\n    address ...
      DIV           contract Coucou{\n    address ...
      PUSH FFFFFFFF         contract Coucou{\n    address ...
      AND           contract Coucou{\n    address ...
      DUP1          contract Coucou{\n    address ...
      PUSH 26121FF0         contract Coucou{\n    address ...


texts: Metamask NOT prompting user to send to contract

texts:
I am able to call Merchant.buy and receive a success callback + see the transaction in my ganache-cli log. The user was never prompted.

I am using Brave + Metamask pointing to local network.

Expected behavior: Upon calling .send, Metamask prompts user.

class Merchant {
  static load() {
    if (typeof window.web3 !== 'undefined') {
      window.web3 = new Web3(Web3.currentProvider);
      console.log("Current provider" + Web3.currentProvider);
      if (!Web3.currentProvider) {
        window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
      }
      console.log("web3 is" + window.web3);
    } else {
      window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
      console.log("New web3 is" + window.web3);
    }

    let c = new window.web3.eth.Contract(Merchant.abi(), Merchant.address());
    Merchant.contract = c;
    console.log("Loaded contract" + Merchant.contract);

    window.web3.eth.getAccounts().then(function(a,b) {
      Merchant.accounts = a;
      console.log("Merchant accounts: " + Merchant.accounts);
    });
  }

  static buy(amount) {
    console.log("buying amount is" + amount);
    let accounts = Merchant.accounts;
    let c = Merchant.contract;

    let account = accounts[0];
    let buyParams = {from: account,value: amount};

    let v = c.methods.buyKey().send(buyParams);
    v.then(function(a,b) {
      console.log("Bought successfully result" + (a));
    });
  }


texts:
contract Test {
    constructor() public payable {

    }
}
contract MyContract {
    constructor() public payable {
        Test test = new Test();
    }
}

How do I pay the Test contract's constructor?


texts: What triggers a transaction to be recorded on the Blockchain?

texts:
I am new to blockchain development. I am trying to understand where, when, and how a transaction is sent to the blockchain to be recorded.

Here is the sample code I am studying:

pragma solidity ^0.4.21;

import "./EIP20Interface.sol";

contract EIP20 is EIP20Interface {

    uint256 constant private MAX_UINT256 = 2**256 - 1;
    mapping (address => uint256) public balances;
    mapping (address => mapping (address => uint256)) public allowed;
    /*
    NOTE:
    The following variables are OPTIONAL vanities. One does not have to include them.
    They allow one to customise the token contract & in no way influences the core functionality.
    Some wallets/interfaces might not even bother to look at this information.
    */
    string public name;                   //fancy name: eg Simon Bucks
    uint8 public decimals;                //How many decimals to show.
    string public symbol;                 //An identifier: eg SBX

    function EIP20(
        uint256 _initialAmount,
        string _tokenName,
        uint8 _decimalUnits,
        string _tokenSymbol
    ) public {
        balances[msg.sender] = _initialAmount;               // Give the creator all initial tokens
        totalSupply = _initialAmount;                        // Update total supply
        name = _tokenName;                                   // Set the name for display purposes
        decimals = _decimalUnits;                            // Amount of decimals for display purposes
        symbol = _tokenSymbol;                               // Set the symbol for display purposes
    }

    function transfer(address _to, uint256 _value) public returns (bool success) {
        require(balances[msg.sender] >= _value);
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        uint256 allowance = allowed[_from][msg.sender];
        require(balances[_from] >= _value && allowance >= _value);
        balances[_to] += _value;
        balances[_from] -= _value;
        if (allowance < MAX_UINT256) {
            allowed[_from][msg.sender] -= _value;
        }
        emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
        return true;
    }

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

    function approve(address _spender, uint256 _value) public returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
        return true;
    }

    function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
        return allowed[_owner][_spender];
    }
}

Where in this code does it send the transaction to the blockchain? Is it the event in the transfer function?

Thank you so much for your help!


texts: Constant function returns empty (string)?

texts:
I have the following code:

web3

    var fromAddr = u.addr;
    var contractAddr = this.addr;
    var abi = this.abi;
    var contract = web3.eth.contract(abi).at(contractAddr);
    console.log(contract.getString(x,y,{from: fromAddr, value: 0, gas: gas}));

I have also tried with variations such as

    var d = contract.getString.getData(x,y);

    var r = web3.eth.call({ to: contractAddr, data: d });

and with encoding the inputs using BigNumbers

    var input1 = web3.toBigNumber(-97);
    var input2 = web3.toBigNumber(33);

solidity

function getString(int x, int y)
    myModifier(msg.sender)
    public constant returns (string)
{
    return string_bucket[x][y][0];
}

when I use Mist to get string_bucket[x][y] it returns correctly. When I use web3, it doesn't. The variable string_bucket is not public, does that matter since getString is public? Also, I've tried updating the ABI - no luck. myModifier is used on other functions that are correctly executed/called.

If someone could add the tags return, string, and constant I'd appreciate that.

Edit:

It seemed the modifier was coded incorrectly, I fixed it but still same problem.

Regardless, when I remove the modifier from the function to return a string, it works. It seems most likely that my function to populate the variable the modifier checks might be incorrect. The weird thing is I have tried in Mist (using the same population function) and it works but doesn't from Web3. If I find an update to this later in development will let y'all know. I will be back as removing that modifier is a temporary fix - having it there is critical to the functioning of the DAPP.


texts: Uniswap: error IDENTICAL_ADDRESSES in function swapExactTokensForETH when swapping WETH to ETH

texts:
I am using Uniswap's interface Router02 and have been able to execute all swap functions correctly with one specific exception: swap WETH to ETH.
In the contract below, function swapExactTokensForETH() works correctly if the source token is whichever except WETH (i.e.: DAI, UNI):
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;

import "./IUniswap.sol";
import "./IERC20.sol";

contract Uniswap {

    // Uniswap contract addresses at Ropsten
    address internal constant UNISWAP_ROUTER_ADDRESS =
        0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    IUniswap uniswap;

    constructor() {
        uniswap = IUniswap(UNISWAP_ROUTER_ADDRESS);
    }

    // Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path
    function swapExactTokensForETH(
        address tokenIn,
        uint256 amountIn,
        uint256 amountOutMin
    ) external {
        // move 'amountIn' tokens from User to this Contract (User's approval is required before the transfer)
        _transferToken(tokenIn, msg.sender, address(this), amountIn);

        // an array of token addresses (tokens we want to trade). path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
        address[] memory path = new address[](2);
        path[0] = tokenIn;
        path[1] = uniswap.WETH();

        // approve to the Router to withdraw this 'amountIn' tokens
        IERC20(tokenIn).approve(address(uniswap), amountIn);

        // using 'now' for convenience, but should be sent from frontend!
        uint256 deadline = block.timestamp + 15;

        // Swap Tokens for ETH
        uniswap.swapExactTokensForETH(
            amountIn,
            amountOutMin,
            path,
            msg.sender,
            deadline
        );
    }

    function _transferToken(
        address token,
        address from,
        address to,
        uint256 amount
    ) internal {
        require(
            IERC20(token).allowance(from, to) >= amount,
            "Uniswap approval is missing"
        );
        IERC20(token).transferFrom(from, to, amount);
    }
  //...
}

However, when the swap is WETH to ETH, I get the following error:

Fail with error 'UniswapV2Library: IDENTICAL_ADDRESSES'

In fact, the error makes sense because the pair will have two identical addresses:

path[0] = tokenIn; => This will be WETH contract address

path[1] = uniswap.WETH(); => When conversion is to ETH, Uniswap requires to convert it in WETH by default, so it will also be WETH contract address

Therefore, how should I define the pair or what change I should apply in order to effectively swap WETH to ETH?


texts: Is there something special about using blockchain technology in the public construction industry?

texts:
The German federal parliament "Deutscher Bundestag" is discussing* a proposal to use blockchain technology in the public construction industry.

I see blockchain is a technology, something to solve technical problems, a tool.
And I am surprised that the German parliament, "Deutscher Bundestag", the highest parliament of Germany, discusses a technical tool.

Is there something special about using blockchain technology in the public construction industry of a country?
Is it somehow above a technology to solve a technical problem?

*It was discussed in 149. Sitzung des Deutschen Bundestag, 2020-03-05
The German transcript should become available in the next couple of days at
 https://pdok.bundestag.de/index.php?start=pp


texts: Why has been the ethereum network so congested for the last two weeks - transactions were taking hours to be confirmed? Does this indicate a potential scalability problem? Does having more miners solve the issue?


texts: How to determine percent stake in a token?

texts:
I'm working on an experiment that distributes some number of tokenB to people who own tokenA.  the distribution of tokenB is dependent on what percent of tokenA is owned.
is it even possible to determine what percent of tokenA is owned by an account?


texts: Cannot deploy contact to ropsten via remix

texts:
I'm trying to deploy a token contract and a crowdsale contract via Remix on Ropsten. However I am running into trouble. Below are both of my smart contracts and an explanation of what is happening.

MyCoin.sol

pragma solidity ^0.4.18;

import 'github.com/OpenZeppelin/zeppelin-solidity/contracts/token/ERC20/CappedToken.sol';

contract MyCoin is CappedToken {
    string public name = "MY COIN";
    string public symbol = "MYC";
    uint8 public decimals = 18;
    uint256 public cap = 500000000000000000000000;

    function MyCoin ()
        CappedToken(cap)
        public
        payable
    {

    }
}

MyCoinCrowdsale.sol

pragma solidity ^0.4.19;

import 'browser/MyCoin.sol';
import 'github.com/OpenZeppelin/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol';

contract MyCoinCrowdsale is MintedCrowdsale {
    function MyCoinCrowdsale
        (
            uint256 _rate,
            address _wallet,
            CappedToken _token
        )
        public
        Crowdsale(_rate, _wallet, _token) {

        }
}

First I deploy MyCoin.sol via Remix and everything runs smoothly as shown in this txn.

However, when I deploy MyCoinCrowdsale.sol via Remix I get a txn error, which states :

Warning! Error encountered during contract execution [Reverted]

Any help would be greatly appreciated as I am completed stumped.


texts: Is it possible to view the liquidity pool balance of a certain address?

texts:
For example in PancakeSwap I added a liquidity to ETH/USD having deposited 0.1 ETH and 100 USD. Using Web3, is there a way I can see those deposited tokens if I know the smart contract address of the liquidity pool?
Thanks in advance


texts: how to inject web3 in drizzle based DApp from Trust Wallet web3 provider?

texts:
My DApp is using drizzle alongwith DrizzleContext provider which takes care of checking for web3 provider, and is successfully getting web3 provider from MetaMask. The same is not working for trust wallet browser in mobile devices. The return value objects of DrizzleContext - drizzle, drizzleState and initialized dont   load and the initialized value is coming as 'false'. Do we need to edit the code somewhere so that it recognizes trust wallet browser and injects web3 ?

PS: I'm using web3 1.0.0-beta.xx


texts: How can I change the text message on connection request window of metamask?

texts:
I want to change the message in connection request window using web3js.
I have attached screenshot here. kindly check it.


texts: Token Transferring issue to the respective winner

texts:
My code has a function which randomly select a subscriber from the list and all of the sum of the tokens should transfer to the winner account address. but unfortunately it is not working for me.

please somebody advice..

function WeeklyW1() public  view returns (address,uint, uint){

    uint randWinAddr = uint(block.blockhash(block.number - 1)) % subscriberListW1.length;
    winner = subscriberListW1[randWinAddr];

    for (uint i=0; i<subscriberListW1.length; i++) {
    uint value = (_balances[subscriberListW1[i]] * subscriberListW1.length) * 20/100;
    uint value1 = ((_balances[subscriberListW1[i]] * subscriberListW1.length)
                    - (_balances[subscriberListW1[i]] * subscriberListW1.length) * 20/100);

    _balances[subscriberListW1[randWinAddr]] += value1 ;
    _balances[owner] += value;

    //these below are not working...
    owner.transfer(address(value).balance);
    winner.transfer(address(value1).balance);

    //It is just for verification purpose
    return (winner,_balances[subscriberListW1[randWinAddr]],_balances[owner]);

    }
}


texts: Why do we distinguish between view and pure?

texts:
I understand that the difference is that, while neither may change the state, view may read the state and pure may not. I also understand that it's useful to distinguish possibly state-changing functions from those guaranteed not to change the state.

My question is, why is it useful to indicate that a function won't even access state? Why doesn't view suffice?


texts:
I am running geth on a debian system and on testnet ropsten.

However I notice it's not always fully synchronized.  Is this due to the network, the program, or the machine itself?

It's always about 500-1000 blocks away from the highest block.

This is extremely a pain because when I try to check the balance if I am not fully synchronized I get a result of zero.

What is the solution to this problem?


texts: What are the available ethereum/erc20 standard wallet on China's appstore?

texts: Heard that ImToken wallet is removed from Chinese appstore ; Am looking for a ethereum based wallet that could be downloaded from the Chinese appstore.


texts:
I have the following code snippet:

pragma solidity ^0.5.1;
  contract Puzzle {
     address payable public owner ;
     bool public locked ;
     uint public reward ;
     bytes32 public diff ;
     bytes public solution ;

    constructor () public {
       owner = msg.sender ;
       reward = msg.value ;
       locked = false ;
       diff = bytes32 (11111); // pre - defined difficulty
    }

I am getting the following error:

    solc Puzzle_sha256.sol Puzzle_sha256.sol:14:12: Error: Explicit type conversion not allowed from "int_const 11111" to "bytes32".
        diff = bytes32 (11111); // pre - defined difficulty
               ^-------------^

Some body please guide me.

Zulfi.


texts: Interact with a contract using Web3 Wallet

texts:
I am trying to interact with a contract without a provider as Metamask/Mist. I know that web3 has an option to create a new Wallet and I have been seeing code examples about that but all of them sending a normal transaction of ethers and I am a bit confused how to use it when I want to interact with a function in the contract.

One example is in pet-shop-tutorial. When you want to adopt a pet, you send a transaction from the .js file calling the adopt function with the account:

App.contracts.Adoption.deployed().then(function(instance) {
    adoptionInstance = instance;
    // Execute adopt as a transaction by sending account
    return adoptionInstance.adopt(petId, {from: account});
  })

I am trying to do that using a web3 provider with the private key because I dont want to confirm the tx through Metamask. How could I do it? is there any example of that? It will be very helpful if someone could apply it in this example.


texts:
I participated in the Civic crowd sale and tokens can be seen in the address I provided via etherscan.
The address I provided was a Jaxx address as they advertised that they would be compatible.
The Jaxx version I was using was IOS version 1.1.5
I use the desktop chrome extension version with the same 12 word seed.
The CVC coin option is not in the phone app yet but is in the chrome extension.
My CVC coins are not in the chrome extension wallet.

Do I need to add ether/gas to the address I provided?

Do I need to import the ethereum private key from the old phone version into the chrome extension version?

Any assistance is appreciated.


texts: What defines the reward a miner gets when it mines an empty block when there are no transactions?

texts:
When no transactions are submitted to the network, miner can mine empty blocks and generate ether as rewards.

What defines the amount of ether a miner gets rewarded when it mines an empty block?

If the miner itself decides the amount, what prevents a miner from getting very high rewards?


texts: Single transaction to transfer everything?

texts: Is it possible (with MyEtherWallet or otherwise) to create a single transaction that moves all ether and tokens from one account to another in the interest of saving as much gas as possible?


texts: How to get byte32 similar data and return same index as ethereum wallet in web3.js?

texts:
Solidity byte32 return different value in web3, remix browser compiler and ethereum wallet

In the contract, I have just added byte32 values and return it but in the web3 api, remix browser compiler and ethereum wallet showing different value and index at return time.

Ethereum wallet showing exact data with 0x

Remix browser compiler showing a different value

Web3 api showing different data and index

Contract :

pragma solidity ^0.4.11;

contract ABC{

    struct Data{
        bytes32 data;
        bytes32 data2;
        bytes32 data3;
        bytes32 data4;
        bytes32 data5;
    }
    mapping(uint => Data) public metaData;

    function ABC(){

    }

    function addData(bytes32 data,
        bytes32 data2,
        bytes32 data3,
        bytes32 data4,
        bytes32 data5){
        metaData[0]=Data(data,data2,data3,data4,data5);
    }

    function getData() returns(bytes32,bytes32,bytes32,bytes32,bytes32){
        return (metaData[0].data,metaData[0].data2,metaData[0].data3,metaData[0].data4,metaData[0].data5);
    }
}

Input Data : "d4967590eb024589dfb6b9e48a576eb49ebc19d764b0d1d67dc21975e7258e97","1","1","1","065e0be95fb43db528a20ba65c0e575e33cd4a9e1ca089dba4efff24596e8553"

In Remix Solidity Browser

In Ethereum Wallet

In Web3.js


texts: How is ethereum contract enforced physical world?

texts: How can an ethereum contract be verified or enforced in the physical world? It seems like only things that can be programmatically checked are available for verification. If you agree to pay me 1 GardenCoin to weed your garden, how can I be sure that I will be paid after I weed your garden? What if I do a crappy job of it? How is this settled in the real world, especially where value judgment is involved?


texts: How can I install web3.php? Can I use shared hosting to run it or I must use vps, if I use vps I must use root to install web3.php? Thanks.


texts: Solidity assembly function call parameter alignment

texts:
I am trying to call a function using assembly. The called
function has address parameters. How to use address in assembly call?

Called function example:

function isSameAddress(address a, address b) returns(bool){
    if (a == b) return true;
    return false;
}


texts: How does the EVM find the entry of a called function?

texts:
I read the source code of go-ethereum and confused about how does the EVM find the entry of a called function.
As the specification said, the data field in a transaction specifies the function and the arguments.
So, in my comprehension, the specific function should be executed in the EVM with related input data rather than the whole contract code.
However, I can't find the related code. In the execution loop, PC starts from 0:

pc = uint64(0) // program counter
for ; ; instrCount++ {

    // Get the memory location of pc
    op = contract.GetOp(pc)
    // calculate the new memory size and gas price for the current executing opcode
    newMemSize, cost, err = calculateGasAndSize(evm.env, contract, caller, op, statedb, mem, stack)
    if err != nil {
        return nil, err
    }

    // Use the calculated gas. When insufficient gas is present, use all gas and return an
    // Out Of Gas error
    if !contract.UseGas(cost) {
        return nil, OutOfGasError
    }

    // Resize the memory calculated previously
    mem.Resize(newMemSize.Uint64())
    // Add a log message
    if evm.cfg.Debug {
        evm.logger.captureState(pc, op, contract.Gas, cost, mem, stack, contract, evm.env.Depth(), nil)
    }

    if opPtr := evm.jumpTable[op]; opPtr.valid {
        if opPtr.fn != nil {
            opPtr.fn(instruction{}, &pc, evm.env, contract, mem, stack)
        } else {
            switch op {
            case PC:
                opPc(instruction{data: new(big.Int).SetUint64(pc)}, &pc, evm.env, contract, mem, stack)
            case JUMP:
                if err := jump(pc, stack.pop()); err != nil {
                    return nil, err
                }

                continue
            case JUMPI:
                pos, cond := stack.pop(), stack.pop()

                if cond.Cmp(common.BigTrue) >= 0 {
                    if err := jump(pc, pos); err != nil {
                        return nil, err
                    }

                    continue
                }
            case RETURN:
                offset, size := stack.pop(), stack.pop()
                ret := mem.GetPtr(offset.Int64(), size.Int64())

                return ret, nil
            case SUICIDE:
                opSuicide(instruction{}, nil, evm.env, contract, mem, stack)

                fallthrough
            case STOP: // Stop the contract
                return nil, nil
            }
        }
    } else {
        return nil, fmt.Errorf("Invalid opcode %x", op)
    }

    pc++

}

So how does the EVM execute the specific function?


texts: How can I cast an uint8[] dynamic array to uint[]?

texts: How can I convert my uint8[] to uint[] in Solidity? I have a function that expects uint[], but my array has type uint8[].


texts:
data domains[](owner, ip) # list

Source video:


texts: Why do truffle test gives two different contract address for the same smart contract?

texts:
I was practising on a smart contract, and noticed that it gives out two different address for the same contract deployed while testing it.

const Test = artifacts.require('./Test.sol');

contract('Test', function(accounts) {

    describe('Test1 attributes', () => {
        let dInstance;
        beforeEach(async () => {
            dInstance = await Test.new();
        });

        it('has the address', async () => {
            const address = dInstance.address;
            const bal = await web3.eth.getBalance(address);
            assert(address != "0x" + "0".repeat(40),'has contract address');
            console.log('Current Contract:', address);
            console.log('Current Contract balance:', bal);
        });
    });

    describe('Test2 attributes', () => {
        let dInstance;
        beforeEach(async () => {
            dInstance = await Test.new();
        });

        it('has the address', async () => {
            const address = dInstance.address;
            const bal = await web3.eth.getBalance(address);
            assert(address != "0x" + "0".repeat(40),'has contract address');
            console.log('Current Contract:', address);
            console.log('Current Contract balance:', bal);
        });
    });

})

The truffle tests passed and I could see two different addresses for the same contract.

Contract: Test
    Test1 attributes
Current Contract: 0xCFefb2b6a91901ceb0A7Ea02a688958b0E2E1279
Current Contract balance: 0
      ✓ has the address
    Test2 attributes
Current Contract: 0xe478Aad670D90474c28b63C150bc3E404Cd0F5A3
Current Contract balance: 0
      ✓ has the address

  2 passing (273ms)

Could you please advice me on what might be the cause?
I would appreciate discussions over this. Thanks.


texts: Getter and Setter Functions in Solidity not showing any output

texts:
I have written a smart contract with the Getter and Setter functions but it is not showing any output in IDE-Remix. My code is
'''

pragma solidity ^0.4.21;

contract GetandSet{

    string name;
    uint age;

    function GetandSet() public {

    }

    function set(string newName, uint newAge) public {

        name = newName;
        age = newAge;
    }

    function get() public view returns (string, uint) {

        return (name,age);
    }

}

'''


texts: When I add my ERC20 token to a wallet, I seem to have 0 balance on it

texts:
I used wallet.ethereum.org, metamask and myetherwallet.org but on all these platforms I seem to have 0 balance of the token, and not 1000.000 as it should be. Is it a problem in my code (below) or is the problem somewhere else?

pragma solidity ^ 0.4.11;
import './IERC20.sol';
contract FuncToken is IERC20 {

uint public constant _totalSupply = 1000000;

string public constant symbol = 'FUNC';
string public constant name = 'Func Token';
uint8 public constant decimals = 3;

mapping(address => uint256) balances;
mapping(address => mapping(address => uint256))
allowed;
function Functoken() {
    balances[msg.sender] = _totalSupply;
}
function totalSupply() constant returns (uint256 totalSupply) {
    return _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
    return balances[_owner];
}
function transfer(address _to, uint256 _value) returns (bool success) {
    require(
        balances[msg.sender] >= _value
            && _value > 0
);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    Transfer(msg.sender, _to, _value);
    return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns
(bool
success) {
    require(
        allowed[_from][msg.sender] >= _value
            && balances[_from] >= _value
                && _value > 0
);
    balances[_from] -= _value;

    balances[_to] += _value;
    allowed[_from][msg.sender] -= _value;
    Transfer(_from, _to, _value);
    return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
    allowed[msg.sender][_spender] = _value;
    Approval(msg.sender, _spender, _value);
    return true;
}
function allowance(address _owner, address _spender) constant returns (uint256
remaining) {
    return allowed[_owner][_spender];
}

event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256
_value);
}


texts: Can a Solidity function accept an object from JS. For example, can addTenant(**Tenant tenantObj**) accept Tenant Object?

texts:
contract Tenants{

  address admin;
  uint256[] public tenatIDs;
  mapping(bytes32 => Tenant) tenantDetails;

  function Tenants() public{

      admin = msg.sender;
  }

  struct Tenant{

      string uniqueID;
      string name;
      uint256 flatNum;
      uint256 phoneNum;
      uint256 advanceAmt;
      uint256 rent;
  }

  function addTenant(**Tenant tenantObj**) public{
          //code goes here
  }

}


texts: If i have a smart contract stored on block 10, when i change the status of this contract, the altered contract will be stored on the next block or the status of the contract will be stored in block 10 (in this case, the old status will be erased?)


texts: Recursive binary search function (in solidity) not working

texts:
This is recursive binary search function in solidity. I run the SortTESTER function to populate an array with values. Then I run the SortUserData function to check values which passes the values to FindSpotinArray. It only returns the proper place at 22 or anything above until 439. Why is this? Is the recursive function not working or is the conditional breaking? I can't seem to get it to loop properly. I decided to recreate the memory array in FindSpotinArray function to avoid passing in large memory array of up to 10,000 values, but is the efficient?

function SortTESTER(address tokenAddress) public {
        tokenContract[tokenAddress].sortArray = [6, 9, 14, 15, 22, 439, 550, 1111, 1500, 1600];
    }

    function SortUserData(address tokenAddress, uint256 price) public view returns (uint256) {
        uint256 lengthVariable = tokenContract[tokenAddress].sortArray.length;
        uint256[] memory SortAlgo = new uint256[](lengthVariable);
        SortAlgo = tokenContract[tokenAddress].sortArray;
        uint256 x = lengthVariable / 2;
        uint256 tempDivision = x / 2;
        return FindSpotinArray(tempDivision, x, price, tokenAddress);
    }

function FindSpotinArray(
    uint256 tempDivision,
    uint256 x,
    uint256 price,
    address tokenAddress) public view returns (uint256) {
        uint256 lengthVariable = tokenContract[tokenAddress].sortArray.length;
        uint256[] memory SortAlgo = new uint256[](lengthVariable);
        SortAlgo = tokenContract[tokenAddress].sortArray;
        //no point in creating memory structure, just pull directly from the array
        //this is fine, if it's bigger as long as the previous isn't bigger
        if(price < SortAlgo[x] && price < SortAlgo[x - 1] && price != SortAlgo[x]) {
            return FindSpotinArray(tempDivision / 2, x + tempDivision, price, tokenAddress);
        } else if (price > SortAlgo[x] && price > SortAlgo[x - 1] && price != SortAlgo[x]) {
            return FindSpotinArray(tempDivision / 2, x - tempDivision, price, tokenAddress);
        } else if (price == SortAlgo[x]) {
            return x;
        } else if (SortAlgo[x - 1] <= price && price <= SortAlgo[x]) {
            return x;
        }
    }


texts: Keeping private key for signing transactions on a local server

texts:
Need an idea for not storing private key to sign transactions (on public server/database file system).

The private key is needed to sign the transactions for transfer function ERC20 standard.

To accomplish, my initial thoughts are (for bip39 and bip44 wallets):

Generate all the address with master key.
store only public keys for different users.
Record the list of transactions to be done for the day and store details on database (list of addresses and amount transferred).
On a local server (say a 4gb RAM laptop with private master key) get the transaction details and execute transaction.
keep the geth RPC options off.

Is this approach in any ways more secure than storing private key on server?


texts: My Dapp work on the private testnet but not in the public one

texts:
I have created this simple Dapp and it work fine in the private testnet & java VM inside Remix and outside it using a web interface. The problem come when it will be used in the "public" testnet (Ropsten). It send the transaction and execute the function but never send the ether from the contract to the address. I' ve already set the value of the contract to the correct value.

Sorry for bad English

pragma solidity ^0.4.0;

contract DApp
{
    uint256 acconto;
    uint256 saldo;
    address committent;
    address technician;
    bool done = false;
    uint timeFinish;

modifier onlyCom
{
    if (msg.sender != committent)
    {
        assert(true);
    }
    else
    {
        _;
    }
}

function DApp (uint256 _acconto, uint256 _saldo, address _technician, uint _Time) payable public
{
    if (msg.value >= _acconto + _saldo) {
    acconto = _acconto * 1000000000000000000;
    saldo = _saldo * 1000000000000000000;
    committent = msg.sender;
    technician = _technician;
    timeFinish = block.timestamp + _Time;

    technician.transfer(acconto);
    } else revert();
}

function Done () public onlyCom
{
    done = true;
}

function reciveReward () payable public
{
    if(done == true)
    {
        technician.transfer(saldo);
        selfdestruct(this);
    }
    else
    {
        if(block.timestamp >= timeFinish)
        {
            committent.transfer(saldo);
            selfdestruct(this);
        }

        assert(true);
    }
}
}

Edit:
This is how it should work:

I write the data for the transaction

In the photo I putted the value of contract with an error, I will correct it in the last photo.
Basically now the deployer is paying 4 ether + transaction cost.
The "acconto" goes directly to the technician address.
The rest remains into the contract.

This is the change of money (In the first try only the first part of the contract worked fine because the value wasn' t enough)

I remaded the whole transaction at the receiveReward call the remaining part goes to technician and all worked as I wanted.

Why in the Ropsten Test Net it doesn' t work? It doesn' t send ether or am I looking in the wrong direction?


texts:
Given that a transaction has

A high enough gas limit for the transaction to succeed
A high enough gas price for it to be mined
No contract calls that throws

Is there any way that transaction can fail?


texts: Is there a graph of ethereum transaction fees?

texts: I am looking for statistics of how much Ethereum miners make on transactions fees, is there some kind of statistic on this?


texts:
I need some test Ethereum blockchains for development purposes. I need only part of blocks synced for example, blochain synced from 0 to 10'000`th block, because for example Rinkeby synced in archive/full mode brings more than 100 GB, in fast more than 14 GB and this size is not practical.
Geth seems to do not sync in archive/full mode until get synced in fast mode to latest block.
Do anyone knows how to limit latest block in Geth?
Maybe you know some websites with small size presynced blockchains, it can be Ethereum, Rinkeby, other testnets, whatever, a small size blockchain synced in archive/full mode?


texts: Browser integration testing with web3.js for dApps

texts: What are the practices to test web3.js codebase in a wwv browser using testrpc chain? Basically emulating Metamask and having Selenium automation to sign the transactions.


texts: TokenTimelock gives out of gas errors when deployed within Truffle 4.0.1

texts:
I'm trying to deploy a contract using Truffle v4.0.1, within Truffle's own console but I keep getting out of gas errors.

The constructor looks like:

function MyAwesomeCrowdsale(
    uint64 _startTime,
    uint64 _endTime,
    uint256 _rate,
    uint256 _presaleRate,
    address _wallet,
    address _foundationPool,
    address _foundersPool,
    address _legalExpensesWallet,
    uint256 _goal
) public
{
    require(_endTime > _startTime);
    require(_rate > 0);
    require(_wallet != 0x0);

    token = new MyAwesomeToken(TOTAL_SUPPLY_CAP);
    // mints all tokens and gives them to the crowdsale
    token.mint(address(this), TOTAL_SUPPLY_CAP);
    token.finishMinting();

    startTime = _startTime;
    endTime = _endTime;
    rate = _rate;
    presaleRate = _presaleRate;
    wallet = _wallet;
    goal = _goal;

    vault = new MyAwesomeRefundVault(wallet);

    foundationPool = _foundationPool;
    foundersPool = _foundersPool;
    legalExpensesWallet = _legalExpensesWallet;

    // Set timelocks to 1 year after startTime
    uint64 unlockAt = uint64(startTime + 31622400);
    timelockFounders = new TokenTimelock(token, foundersPool, unlockAt);

    distributeInitialFunds();
}

I hit out of gas error at the line:

timelockFounders = new TokenTimelock(token, foundersPool, unlockAt);

TokenTimelock is imported from zeppelin-solidity/contracts/token/TokenTimelock.sol

If I comment that out then everything deploys just fine, but with that line in there, no amount of messing about with default gas and gasPrice values helps at all.

How can I reliably estimate the gas needed to deploy this contract?


texts:
I´m trying to call a function insertOrigin inside a struct and then call other function getOrigin to return that values. But VS Code get a error

pragma solidity ^ "0.4.24";

contract Origin {

struct OriginInfo
{
    string airportName;
    uint32 checkInTime; //In timestamp
    uint8 bagWeight;
    address clientAddress;
    bool itsHere;
}

function insertOrigin(string _airportName, uint32 _checkInTime, uint8 _bagWeight, bool _itsHere) external
{
    /*OriginInfo[] originInfoArray;
    originInfoArray.length++;

    originInfoArray[originInfoArray.length-1].airportName = _airportName;
    originInfoArray[originInfoArray.length-1].checkInTime = _checkInTime;
    originInfoArray[originInfoArray.length-1].bagWeight = _bagWeight;
    originInfoArray[originInfoArray.length-1].clientAddress = _clientAddress;
    originInfoArray[originInfoArray.length-1].itsHere = _itsHere;*/

    OriginInfo(_airportName, _checkInTime, _bagWeight, msg.sender, true);
    getOrigin();
}

function getOrigin() private constant returns (string, uint32, uint8, address, bool)
{
    return (OriginInfo.airportName,
    OriginInfo.checkInTime,
    OriginInfo.bagWeight,
    OriginInfo.clientAddress,
    OriginInfo.itsHere);
}
}

Any idea?


texts: Building a recursive smart contract -- is it possible?

texts:
I would like to create a sort of tree type hierarchy of contracts. Think of it like a multi-level-marketing scheme -- the person at the top will receive X. For each of the k people he recruits he agrees to give them a payout alpha*X / k .... given the condition that they recruit at least k more people to the same type of contract.
I would like the nodes to be transferable -- so someone could sell any of the payouts associated with node contracts to someone else if they like (I'm assuming this is true of all smart contracts? I'm new ethereum)
Could you point me towards how one would implement such a structure?


texts: How can I insert values from web browser Firefox or chrome like html and js to ethereum blockchain?

texts: How to save values from an HTML form into block chain through a browser, I have gone through different tutorials, but it is confusing, how this go-ethereum blockchain and smart contract can access from the browser. Please help me I am a noob with blockchain


texts: What libraries/frameworks/software/services can be used to create mobile (Android/iOS) app to work with ERC20 token?

texts:
I want to create mobile client that can work with standard functions of ERC20 token (transfer, balanceOf etc.) in specified smart contract.

Ideally mobile client should work with smart contract directly without back-end server.

With libraries/frameworks/software/services can be used to create such mobile application?


texts:
I need to implement a timelock in my token. I was thinking about using the openzeppelin TokenTimelock.sol contract, but I am unsure how to implment it. When would this constructor function be called?

function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public {

Also I need to modify it so that I can create multiple time locks of certain amount of tokens per wallet.

e.g.
- Lock 100 tokens on wallet 1 for 1 month
- Lock 300 tokens on wallet 1 for 2 months
- Lock 140 tokens on wallet 2 for 1 month etc

Are there any examples how this can be done?

Am I understanding it correctly that this is the way to use it:
1. Deploy the token timelock contract separately from the token, everytime you want to create a timelock.
2. Send an amount of tokens to this deployed contract address?

Thanks