texts: Designing a smart contract that can buy (or bid) on an NFT on behalf of a user

texts:
I am a server-side developer who started learning solidity a few weeks ago.
I am writing smart contracts for practice.
Currently, I am stuck conceptually and need help from industry experts.
Imagine a smart contract that contains a pool of funds (e.g. 100 DAI). Further, imagine that the said smart contract is Ownable. How do I create functionality whereby the owner can instruct this smart contract to, say, buy (or bid on) an NFT?
I can see the ERC721 anatomy here. There does not seem to be bid or buy methods built into this smart contract. How do I go about designing this smart contract? An illustrative example with an explanation of the pattern would be great.


texts: How to sign transactions using metamask while developing in nodejs?

texts:
I am developing an application in nodejs. I need to interact with my smart contract and also want to sign the transaction using metamask as I don't want to manage they keys. I copied the following code from the web3 docs but my id condition is never satisfied and "web3 is undefined" is printed in the conosle. On the other hand, if I enter web3 in my chromes console, web3 object with

  currentProvider: MetamaskInpageProvider

is returned.

const express = require('express');
const Web3 = require('web3');

const router = express.Router();

router.get('/',(req,res)=>{

    if (typeof web3 !== 'undefined') {
        console.log('Web3 found');
        web3 = new Web3(web3.currentProvider);
        web3.eth.defaultAccount = web3.eth.accounts[0];
    } else {
        console.error('web3 was undefined');

    }
    res.send('hello');
})

Please help me to sign transactions using metamask while developing in nodejs.
P.S i tried to execute the above code with a timer to check race condition but still same result.


texts: contract inline assembly - return array parts by using assembly

texts:
I've a couple of questions.

mload function returns the data that resides on the address we pass to mload. Is this correct ?

add function is used to give us the address from 0 to whatever we pass. add(arr, 64) would return the address from arr + 64 bytes. correct. ?

I want to achieve same things with storage variables (x_slot and x_offset).. I have the following code.

uint[] storageArr;
    function assembly2() public view returns (uint a, uint b, uint c) {
        storageArr.push(111);
        storageArr.push(222);
        storageArr.push(333);

        assembly {
            a := sload(0)
            b := sload(32)
            c := sload(64)
        }
    }

This returns {3, 0, 0,}. The first one(slot) is 3, since it stores the length of the array. why is the second and third one 0 ?


texts: ethers.js interact with a unit256 input parameters of a function of smart contract

texts:
I am a newbie of javascipt--ethereum.
I try to call a function: function getRewards(uint256 amount1, uint256 amount2, uint256 out_min).
What kind of format or value should I use in my frontend codes, string, big number or hex string?
I am using ethers.js now.
myContract.getRewards( 1, 1, 1);
I tried, serveral format:
1 as number
"1" as string
ethers.utils.parseUnits('1', 6)
ethers.constants.Two ,
ethers.utils.toUtf8Bytes('1'),
none of them works.
my boss asks me to solve this asap.
it is highly appreciated if any of experts can provide me any hints?
it will save me all days.
Thanks a lot!


texts:
Is there any way i can derive private and public keypairs from a Master Key? The Master Key should be able to decrypt every encryption made with the generated Keypairs.

to explain a bit further i want to save encrypted data on IPFS, which can only be accessed by the creator with its own private key and an admin which should have access to all encrypted data within the system.

I have read about deterministic wallets but i'm not sure if these are capable of what i want and how they work.


texts: i want to buy some true USD tokens, how should i add it on myetherwallet?


texts: Does Solidity include all code of parent (base) contract in child contract?

texts:
Suppose I've two contracts animal and dog, and lets say that:

contract dog is animal {
...
}

Does dog include ALL code of animal, or just the code that it uses?

What if dog uses only a few function of animal? How do I make Solidity skip the other "unused" functions?


texts: How to set multiple unit64 values in a uint256 variable

texts:
I have followed following answer for: Having trouble storing multiple values in a uint256.

For example, I want to pass four uint64 variables merged together as a single argument into smart contract and extract those values.

#python-script:

variable1 = 11;
variable2 = 12;
variable3 = 13;
variable4 = 14;

bits1='{0:064b}'.format(v1)
bits2='{0:064b}'.format(v2)
bits3='{0:064b}'.format(v3)
bits4='{0:064b}'.format(v4)
mergedVariable = int(bits1 + bits2 + bits3 + bits4, 2)
storagetest8.setCharacter(mergedVariable)
print(storagetest8.getVariables())

contract storagetest8 {

    uint256 variable;

    function setCharacter(uint variable_)
        external
    {
        variable = variable_;
    }

    function getVariables()
        external view
    returns(uint64 variable1, uint64 variable2, uint64 variable3, uint64 variable4) {
        variable1 = uint64(variable);
        variable = uint64(variable>>64);
        variable2 = uint64(variable);
        variable = uint64(variable>>64);
        variable3 = uint64(variable);
        variable4 = uint64(variable>>64) // simplified
    }
}

[Q] Is the approach I implemented in the smart contract correct?


texts:
contract Puzzle {
     address payable public owner ;
     bool public locked ;
     uint public reward ;
     bytes32 public diff ;
     bytes public solution ;

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

  function () payable external{ // main code , runs at every invocation
    if ( msg. sender == owner ){ // update reward
       //if ( locked )
       //throw ;
       require(!locked);
       bool val=owner.send ( reward );
       reward = msg.value ;
    }
    else
    if ( msg . data . length > 0){ // submit a solution
        require(!locked);
       //if ( locked ) throw ;
          if ( sha256 (msg. data ) < diff ){
             bool val=msg. sender . send ( reward ); // send reward
             solution = msg. data ;
             locked = true ;
       }}}}

I am getting following warning message:

    solc puzzle_sha256.sol puzzle_sha256.sol:39:8: Warning: Unused local variable.
           bool val=owner.send ( reward );
           ^------^ puzzle_sha256.sol:47:14: Warning: Unused local variable.
                 bool val=msg. sender . send ( reward ); // send reward
                 ^------^

Some body please guide me how to remove the warning. Also please check if I have used the require correctly or not.

Zulfi.


texts:
I am working on an ethereum powered mobile app and want to know the best to way to integrate an exchange for new users who do not have an existing accounts to purchase ether?

What's the best way for new users of my app to create accounts on an exchane, like Coinbase for example, and then purchase ether and send it to the mobile app wallet? Can it be done programmatically with the app via an API?


texts: I recently saw this video about dual mining of ETH and ZIL. The video especially targets GPUs with 3-4GB of VRAM. I still have to try it, but I'm wondering: isn't ETH dagger size bigger than 4GB? How is it possible to mine it with GPUs of 3-4GB? I know about the Zombie mining but I read it will give decent results only for a very short time now. Is this the case?


texts: During data insertion function pushes data only once

texts:
I wonder why data insertion in users occurs only once, while userCount updates correctly?

pragma solidity >=0.4.22 <0.7.0;

contract TestChainStorage {

address private owner;
uint256 public userCount;

    struct User {
        uint256 userNumber; // User number at registration time
        uint256 regTime;    // Registration time (unixTime)
        string userName;
        address userWallet;
    }

    User[] public users;

    modifier isOwner() {
        require(msg.sender == owner, "Caller is not owner");
        _;
    }

    constructor() public {
        owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
    }

    function store(uint256 unixtime, string memory username) public {
        userCount++;
        users.push(User({
        regTime : unixtime,
        userName : username,
        userWallet : msg.sender,
        userNumber : userCount
        }));
    }

    function compareWallet (string memory a, string memory b)  internal pure returns (bool){
       return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
   }

    function kill() public isOwner {
       selfdestruct(msg.sender);
   }
}

Any help appreciated!


texts: How to get Hash of function with many returns types?

texts:
I have a method :

function getBalance(address _add) public view
            returns (uint256, string memory, bool, uint256, uint256, uint256) {
        return(accountBalance[_add].amount,
            accountBalance[_add].valueDateTime,
            accountBalance[_add].credit,
            accountBalance[_add].bankId,
            accountBalance[_add].branchId,
            accountBalance[_add].accountId);
    }

I have tried many ways to get some hash which will work for my json rpc.
But I am not able to get through.
Tried combinations which didn't work :

  web3.sha3('getBalance(address) returns (uint256, string,bool,uint256,uint256,uint256)');
  "0x2560a3f9b1f28442f55de402532d55bffa0794ee53310ed4dc65d3dda6a8fc4b"

  web3.sha3('getBalance(address) returns (uint256, string memory,bool,uint256,uint256,uint256)');
  "0x963fc1d2d6f67d205b9f56340f6f9853ea45969dcc25182fbd9705abe74cfcbf"

  web3.sha3('getBalance(address) view returns (uint256, string memory,bool,uint256,uint256,uint256)');
  "0xdcd78e55620fe9302439c2ccb0c23d69f7399b61e3b0b6c9c15142f85fe6b3fa"

  web3.sha3('getBalance(address) view returns (uint256,string,bool,uint256,uint256,uint256)');
  "0x97abd19f4ac051fb6b277f2c947801a9120e0935a7225ff322d1cf2a2dcb1b8a"

  web3.sha3('getBalance(address) view returns (uint256,string memory,bool,uint256,uint256,uint256)');
  "0xc174d458674c0f18ffbf8addc06d41eb80a9bcab82d31fee290be4368339840e"

  web3.sha3('getBalance(address) returns (uint256,string,bool,uint256,uint256,uint256)');
  "0x02cd8e0e733ce057edefbb512190a6e6ecdae93ea96aa413d83cc7ad5c3d312c"

  web3.sha3('getBalance(address) returns (uint256,string memory,bool,uint256,uint256,uint256)');
  "0x48a0f2e06a2c0c3b033efbad3ecde8042792381edf9c600c2d1f7fb35a43c986"

  web3.sha3('getBalance(address)');
  "0xf8b2cb4f3943230388faeee074f1503714bff212640051caba01411868d14ae3"

Can someone please help.


texts: Fail to transafer Ether to child contract from parent contract

texts:
I created a contract factory (parent contract) for creating a child contract. In the parent contract, there is a function to transfer the balance of the parent contract to the child contract, by entering the child contract address. I found that the transfer will be successful when the receive function is plain (no other action in the receive function). When I add other actions like changing the state variable, then the transaction will fail and show the error:
transact to ContractFactory.pay errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
Here is the contract code:
pragma solidity >=0.6.0 <0.8.0;

contract ContractFactory {
    address[] contractsAddress;
    mapping(address => Contract) private contracts;

    function createContract(uint price) public {
        Contract newContract = new Contract(msg.sender, price);
        contractsAddress.push(address(newContract));
        contracts[address(newContract)] = newContract;
    }

    receive() external payable{
    }

    function pay(address payable contractAddress) public payable{
        contractAddress.transfer(address(this).balance);
    }

    function getAllContractsAddress() view public returns(address[] memory) {
        return contractsAddress;
    }
}

contract Contract {
    enum Status {Unavailable, Available}
    Status public contractStatus;

    address payable public contractOwner;
    address payable public buyer;

    uint public price;

    event Occupy(address _occupant);

    constructor(address payable _contractOwner, uint _price) {
        contractOwner = _contractOwner;
        price = _price;
        contractStatus = Status.Available;
    }

    modifier onlyWhenAvailable {
        require(contractStatus == Status.Available);
        _;
    }

    modifier notOwner {
        require(msg.sender != contractOwner);
        _;
    }

    modifier payEnoughAmount {
        uint priceInEther = price * 1 ether;
        require(msg.value >= priceInEther);
        _;
    }

    receive() external payable onlyWhenAvailable notOwner payEnoughAmount {
        contractStatus = Status.Unavailable;
        buyer = msg.sender;
    }
}


texts: My button created on my HTML file resulted in failed transaction when it interacted with smart contracts function

texts:
I created a simple html to register an address in smart contracts. The function in smart contracts have been tested and it passed. So i believe my problem should be in how the input data transferred from HTML file to index.js file, to contract.js file and lastly to smart contract function. the picture given is button front-end
Here is the snippet HTML code button in index.html file.

1. Submit Airline

            <input class="address" id="submit-airline-address" placeholder="Airline Address"/>
            <btn class="btn btn-primary" id="submit-airline">submit registration</btn>

only registered airline can perform this task

in index.js file, here is the DOM of the HTML button at line 21
DOM.elid('submit-airline').addEventListener('click', submitAirline);

the second part of it in index.js file is here. it is at line 89 to 94
const submitAirline = async () => {
const element = DOM.elid('submit-airline-address');
await contract.submitAirline(element.value);   //calling to contract.js file and submitAirline function
await refreshStatus();
element.value = '';
};

in contract.js file, the code is here. at line 54 to 61
async submitAirline(_address) {
    let self = this;
    try {
       await self.flightSuretyApp.methods.submitRegistration(_address).send({from: self.account, gas: self.gasLimit});      //calling to flightSuretyApp smart contract and function submitRegistration
    } catch (error) {
        console.log(JSON.stringify(error));
    }
}

lastly, Here is the FlightSuretyApp.sol file. the function is here. at line 196 to 214, again, this function has been tested and it passed when I 'truffle test' it.
function submitRegistration (address _airline) external payable requireIsOperational requireRegisteredAirlines {

    uint256 _regIndex = registrations.length;
    registrations.push(Registration({
        airline: _airline,
        executed: false,
        regIndex: _regIndex,
        numVotes: 0
    }));
    currentSubmittedAirlines.push(_airline);
    regIndexAirline[_airline] = _regIndex;
    bool statusExecuted = false;
    uint256 numberOfVotes = 0;
    emit submittedRegistration(_airline, _regIndex, statusExecuted, numberOfVotes);
}

I believe I might have done something wrong in trying to pass the input of of airline address (wallet address) from HTML to smart contract but I can't seem to figure it out. Any help and tips are greatly appreciated!
Here is the link to the repo for better context
https://github.com/MuhdRaffiq/FlightSuretyDapp


texts: Why solc does not detect issue in this code?

texts:
I wrote a sample Solidity code below: in function call() of contract sample_call, I make a call to function add_car() function of another contract sample, but this is a bug, since variable v is never initialized.

I assumed that solc should detect this issue, and complain, but in contrast it happily compiled the code.

Do you think that this is where solc should be improved?

pragma solidity ^0.4.1;

contract sample_call {
    function call() public pure {
        uint a;
        sample v;   // v is never initialized

        a = v.add_var(0x22); // BUG HERE, because v is uninitialized
    }
}

contract sample {
    function add_var(uint a) public pure returns(uint) {
    return a + 0x55;
    }
}

Thanks.


texts: Is there any specification for Decentralized Token Exchange?

texts:
Is the way of doing decentralized token exchange (DEX) on Ethereum blockchain specified in some ERC ?

Exploring event data in Etherscan I found that there are many types of events:

  event Order(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
  event Cancel(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s);
  event Trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address get, address give);
  event Deposit(address token, address user, uint256 amount, uint256 balance);
  event Withdraw(address token, address user, uint256 amount, uint256 balance);

Are those specified in some ERC ? Do all exchanges have to have these events? What are the methods that all decentralized exchanges share? What is the minimal set of standard methods/events a DEX has to have? Is somebody trying to standarize this? If so, who? Any realated EIP? Are non-fungible tokens out of DEX ?

Those events don't tell me how do I get the list of pending orders, i.e. the tokens available for its sale or purchase. How is this done?


texts:
I'm trying to use the buyTokens function of the Zepellin Crowsale interface, but this gives me an error, without any log to be able to debug

contract TokenA is MintableToken, PausableToken, DetailedERC20 {
    constructor(string _name, string _symbol, uint8 _decimals)
        DetailedERC20(_name, _symbol, _decimals)

}

contract TokenACrowdsale is Crowdsale, MintedCrowdsale {

  constructor(
    uint256 _rate,
    address _wallet,
    ERC20 _token
  )
    Crowdsale(_rate, _wallet, _token)

}

truffle console

  balances

  account[0]=8eth account1=4eth

let token=await TokenA.new('va','va',18)

token.balanceOf(accounts[0])  //0

await token.mint(accounts[0],web3.utils.toWei(10000000),token.address)
token.balanceOf(accounts[0]) //10000000 va

let crow=await TokenACrowdsale.new(web3.utils.toWei('500'),accounts[0],token.address)

await token.transfer(crow.address,web3.utils.toWei('200000','ether'))

token.balanceOf(crow.address) // 2000000 va

await crow.buyTokens(accounts[1],{from:accounts[1],value:web3.utils.toWei('1','ether')}) //Error

ropsten transaction

how do i fix this


texts: How to configure extraData field in genesis file

texts:
I am in the process of setting up a private, permissioned Quorum blockchain with Istanbul consensus for simple use cases. When I specify the number of validators when generating the genesis file it works as expected.

But how can I add validators dynamically? For example I have generated genesis file with two validators and it is up and running. Now if I want to add a new node as validator how I should configure? If I use the same genesis file and added new node's enode address to permissioned-list it is connecting successfully but getting unsealed signature error. Do I need to modify the genesis file extraHash field for new nodes?


texts:
Having a smart contract mined on testnet at address 0x5a6661c75df7de88ba74437a6dc372ccfa72a564 with the following function:

    function whoAmI() constant returns (address) {
        return msg.sender;
    }

should return caller always. And that's what I am trying to verify. I works ok when calling synchronously from geth console like this:

// creation of contract object
var aContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"kill","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"account","type":"address"}],"name":"queryBalanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"initialSupply","type":"uint256"}],"name":"MyToken","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"whoAmI","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"payable":false,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]);

// initiate contract for an address
var sc = aContract.at('0x5a6661c75df7de88ba74437a6dc372ccfa72a564');

// calling function
sc.whoAmI();
    "0x47978a69f410d0f61850c92acdb0d4c464d70937"

The problem comes when trying to call it asynchronously from another account like this:

sc.whoAmI.sendTransaction({from:"0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d"});
txHash => "0x5fc3f7454d558ad4bd01294448b45bc7072b46958375fafe32e277a770d48e90"

Where is the output of the transaction stored? Trying this:

eth.getTransactionReceipt("0x5fc3f7454d558ad4bd01294448b45bc7072b46958375fafe32e277a770d48e90")
{
  blockHash: "0xa19553677ede1d1eed791d1658a4229629346f90db5907c14c915dda13926df9",
  blockNumber: 1821495,
  contractAddress: null,
  cumulativeGasUsed: 21612,
  from: "0x3b877e80b5c0b29d88f3768ed4292b35fdd93a9d",
  gasUsed: 21612,
  logs: [],
  root: "31aa355a0a7534b18c7874a31fd78926a6869f0e9e309a972d1b5505405c6421",
  to: "0x5a6661c75df7de88ba74437a6dc372ccfa72a564",
  transactionHash: "0x5fc3f7454d558ad4bd01294448b45bc7072b46958375fafe32e277a770d48e90",
  transactionIndex: 0
}

I couldn't find it. Any help? Thx!


texts: Call contract and send value from Solidity

texts:
I have a pre-deployed contractA with known ABI. I would like to call function func1(string,string) in the contractA (and pass the arguments) from a new contractB and send some value at the same time. So far, I managed to write the following  (which does not send the arguments properly):

    contract contractB is mortal  {
        function invokeContractA() {
            address contractAaddress= 0x1234567891234567891234567891234567891234;
            uint ValueToSend = 1234;
            contractAaddress.call.value(ValueToSend)(bytes4(sha3("func1(string,string)")),
                 "arg1TEXT", "arg2TEXT");
        }
    }

Would appreciate your suggestions on what else is missing here (perhaps, need to convert the arguments into bytecode somehow?).


texts: Calling a smart contract function with an unsigned transaction

texts:
I'm new to working with Ethereum smart contracts and would appreciate some guidance by the community on a task that I'm trying to solve.

This is the contract I want to use - https://github.com/chatch/hashed-timelock-contract-ethereum/blob/master/contracts/HashedTimelock.sol

For the sake of the questions, let's focus on two users - Alice and Bob.
Alice has some data that Bob wants. Bob uses the HTLC to retrieve that data from Alice in exchange for some tokens.

I'm playing around with the idea of Alice not having to actively be involved in this process and allow her part of the transaction to be delegated to some automated process. The part I'm stuck on is the signing of the transaction.

Alice needs to call the withdraw function in the HTLC. If I create an application that does this process for Alice, I see a few options:
1. The process has access to Alice's private key so that it can send a signed transaction with the data to the withdraw function.
2. A temporary address is created by the process for Alice. This temp address is sent to Bob and using this address, the HTLC is created. This way, the process I create only has access to the temp private key and not Alice's permanent address' private key.
3. (Not sure if this is feasible) An unsigned transaction is used to call withdraw so that the process does not need access to Alice's private key. Only the data to be sent is needed for the contract to be satisfied.

While testing this with Ganache I did not need to sign any transactions, I assume Ganache handled this. What is a good way to achieve this on main net?


texts:
I have tried to verify my account by SMS method so I can request Kovan ethers.

I have followed this video https://youtu.be/99UucFzYCRc.
Unfortunately someting have messed up (I have changed transaction fee and was also switching between tabs, can't really tell exact steps) and after signing transaction I was not redirected to tab with text "The transaction has been posted to the network with a hash of..."
The same situation occured once again.

These are performed transactions:
https://etherscan.io/tx/0xb5e37be779bb78ada4eab56897e0844baa267d7161c7432d0dcd27d956fd1496
https://etherscan.io/tx/0x19feedcb37b260695905a7ccae7d13e9a0f82d45d321260ade28088e37a7bd21

I have not received any SMS, account is still unverified, lost ~ $8.

Is this possible to resume verification process from this transactions?


texts: How to stop miner who does not execute operations?

texts:
When a miner evaluate operations on VM there might be a case when there is not enough gas to fulfill operation.

In such cases

  "The miner will stop processing the transaction, revert any changes it
  made, but still include it in the blockchain as a "failed
  transaction", collecting the fees for it. This may seem harsh, but
  when you realise that the real work for the miner was in performing
  the computation, you can see that they will never get those resources
  back either. So it's only fair that you pay them for the work they
  did, even though your badly designed transaction ran out of gas."

Suppose there is a fraud miner who does not execute operations at all but marks any transaction as failed and takes all the gas.

What stops the miners from such behavior? Mining is faster (because no operations are executed at all), fraud miner took all the gas (and ether).

Could somebody explain or show a place in the docs or client where the case is prevented?


texts: Toshi browser vs. Google Chrome browser to interact with Dapp?

texts:
Toshi is a browser to interact with Dapps such that after uploading our Dapp (including solidity smart contract, Javascript and HTML code) on a server, we can search our Dapp using its URL (ex: www.MyDapp.com). Then, we can invoke functions of our contract and send transaction.

Toshi Github: https://github.com/toshiapp/toshi-web/blob/master/README.md

Now, question is that is it possible to do this by Google Chrome instead of Toshi browser?  (of course without installing any Add-on on Google Chrome or installing any package on Android phone.)


texts: what will happen to ethereum mining after next fork

texts: I would like to ask what will be the future of GPU mining  after the next fork and change to be Prove to Stake


texts: How to pass account address to truffle deployer?

texts:
How do I pass my account address to the contract constructor while deploying with truffle migration? I want to pass address into MyAdress like below.

deployer.deploy(MyContract, MyAddress)

My contract looks like this

address payable public admin;
constructor(address payable _admin) {
        admin = _admin;
}


texts: Is it possible to temporarily transfer ownership of a staked token to another wallet address without unstaking,

texts: Is it possible to temporarily transfer ownership of an ERC20 staked token to another wallet address without unstaking, for example if I have wallet address X, and I have staked my tokens with a particular project. However I also have wallet Y and want to transfer ownership of the staked token from Wallet X to Wallet Y without unstaking from the contract or project.


texts: Sending ether directly from metamask to fallback function

texts:
I want to send some amount of ether to a smart contract from metamask (without using web3) and want it to perform some specific tasks based on that amount. For example, if I send 0.9 ether, I want it to set a variable named planid to 1101 in the fallback function. The following piece of code is from my contract:
 function() external payable {

    if (msg.sender == bank_owner) {
        emit AdminDeposit(msg.value, bank_owner);
        //invest(msg.value, msg.sender, plan_id, _referrer);
    } else {
        address _referrer = bytesToAddress(msg.data);
        _init(msg.sender, msg.value, _referrer);
    }
}

function _init(address payable _investor, uint256 _investValue, address _referrer) private {
    bool doInvest = true;
    if (_investValue == PLAN_PRICE[0]) {
        planid = 1101;
    }
    else if (_investValue == PLAN_PRICE[1]) {
        planid = 1102;
    }
    else if (_investValue == PLAN_PRICE[2]) {
        planid = 1103;
    }
    else if (_investValue == PLAN_PRICE[3]) {
        planid = 1104;
    }
    else{
        doInvest = false;
        emit TestEvent(planid);
    }

    if (doInvest == true){
        invest(_investValue, _investor, planid, _referrer);
    }else
    {
        revert("Incorrect value sent!");
    }
}

In the above piece of code, If someone (other than bank owner which is already defined in the constructor) send 0.9 ether from metamask to the contract (directly), the _init() function will be called. I expect that else part of the second if statement does not executes. However, it executes and transaction fails.
When I replace revert() with something else, everything is ok. I was wondering if you help me with this case. Thanks.


texts: How do I do the equivalent of Solidity's bytes32(a_signed_integer) in JavaScript?

texts:
I've got an app that takes various kinds of input via an HTML form, but always ends up sending it to a contract as bytes32. The expectation is that another contract that ultimately consumes the data will cast it into the type that it's expecting, which may be bytes32, uint256 or int256.

For unsigned integers I'm taking a BigNumber object, calling toString(16) on it to get hex, then left-padding it to 64 digits, and appending 0x. But for signed integers, which may be negative, I presumably need to handle the two's complement system; What's the appropriate way to do this?


texts: Get latest transaction hashes from inside a contract

texts:
I am working on private test net. Can I get the latest transaction address inside my contract. At the basic level I am trying to have a function getLatestTransaction() which will return me the latest transaction address.

At advanced level I want to have an array containing address of all the transactions.


texts: web3 API not returning instance of contract when used with eth-lightwallet and hookedweb3provider

texts:
I have managed to get a hooked web3 provider with eth-lightwallet creating a contract on a private geth node.  I see the tx on the geth logs and see it get added to a block when mined.

However I am not getting the contract.address returned in the callback.  I get the transaction hash. My gut feeling tells me there are two steps happening underneath: the tx hash is provided in the JSON RPC response underneath but a corresponding eth_getTransactionReceipt is not  being done or processes before comingback to the callback.

Help appreciated.

var ethClient = "http://localhost:1234";
var web3 = new Web3();
var global_keystore;

// setting up a web3 provider but using a keystore to get access to account information
function setWeb3Provider(keystore) {

    var web3Provider = new HookedWeb3Provider({
        host: ethClient,
        transaction_signer: keystore
    });

    web3.setProvider(web3Provider);

}

// .....

var password = prompt('Enter Password to encrypt your seed', 'Password');

var providedSeed = document.getElementById('seed').value;

lightwallet.keystore.deriveKeyFromPassword(password, function (err, pwDerivedKey) {

global_keystore = new lightwallet.keystore(
    providedSeed,
    pwDerivedKey);

global_keystore.generateNewAddress(pwDerivedKey, 2);

setWeb3Provider(global_keystore);

// .... important bit....

var contract = web3.eth.contract(_contractABI);
    var myContract = contract.new(
        {
            from: _ethWalletAddress,
            data: _contractCode,
            gas: 3000000,
            gasPrice: 18000000010
        }, function(e, contract){

            console.log("error object: " + e );
            console.log("contract object: " + contract);

            if (typeof contract != 'undefined') {
                console.log('address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);

                });

            }
        });

Example of logs from a private geth network:

I0424 13:28:13.816421 eth/api.go:1177] Tx(3645d30afa7923cca42359dc2d1e46084f0da11f0b5476111a1e2ac7a82eb56f) created: 0746c6c2fde77b607e83e2bb6c25f919817e8459
I0424 13:28:23.028763 miner/miner.go:119] Starting mining operation (CPU=8 TOT=9)
I0424 13:28:23.036100 miner/worker.go:565] commit new work on block 4446 with 1 txs & 1 uncles. Took 7.286103ms

and the result of a manual getTransactionReceipt with JSON RPC:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x3645d30afa7923cca42359dc2d1e46084f0da11f0b5476111a1e2ac7a82eb56f"],"id":1}'

{"jsonrpc":"2.0","id":1,"result":{"blockHash":"0x3a524c681be27a65d6058e54de35e5502d8353e85b7a5b013c86a6909eb63dd3","blockNumber":"0x115e","contractAddress":"0x0746c6c2fde77b607e83e2bb6c25f919817e8459","cumulativeGasUsed":"0x101716","from":"0xa57f54760210a39a376231bd20d5fcec4eaf75fa","gasUsed":"0x101716","logs":[],"root":"38789ca516316c1303eda94b690202875a77d66e3116f8733081197f7157f093","to":null,"transactionHash":"0x3645d30afa7923cca42359dc2d1e46084f0da11f0b5476111a1e2ac7a82eb56f","transactionIndex":"0x0"}}

ps. I don't know what the log report 1 uncle. Other contract creation logs didn't report any uncles but all exhibit the same issue with the callback.


texts: Does a Solidity Interface Contract need to implement all functions, or only the function subset used in the contract that implements the interface?

texts:
Let's assume the following:

There is a master contract A, an interface contract IB, and a slave contract B
A implements IB to allow upgrading B without redeploying A

Question:

Does IB need to have all functions of B, or only the ones used by A?


texts: DeclarationError: Undeclared identifier issue

texts:
Can't figure out this error. Please help!
"DeclarationError: Undeclared identifier. (bool success, ) = recipient.call; value; amount ;(""); ^---^"

function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call; value; amount ;("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }


texts: I am getting Returned error: VM Exception while processing transaction: invalid opcode error

texts:
I am getting an Invalid Opcode error while calling the refundAmount function which will refund the amount to the customer and cancel his/her ticket bookings. registrations is a structure mapping and the structure includes 3 variables that are in the below manner.
struct Registration {

uint8 noOfTickets;
uint amount;
string email;
}
address payable public owner;
uint public ticketsSold;
uint8 public totalTickets;
uint public price;

mapping (address => Registration) public registrations;

The below is the refundAmount function. I could have used msg.sender for this but my javascript takes care of it by using the coinbase address.
    function refundAmount(address payable _customer)
                      external
                      payable {
    if(registrations[_customer].amount > 0){
        if(address(this).balance >= registrations[_customer].amount) {

            ticketsSold = ticketsSold - registrations[_customer].noOfTickets;
            registrations[_customer].noOfTickets = 0;
            registrations[_customer].email = " ";
            uint refundCustAmount = registrations[_customer].amount;
            registrations[_customer].amount = 0;

            _customer.transfer(refundCustAmount);

            emit Refund(_customer, refundCustAmount);
    }

}

Please help me.
Thank you in advance and Cheers to Ethereum!!
Edit: - This works completely fine on Rinkeby testnet but reverts while using Ganache.


texts: When start geth(Ethereum client) First time,showing message like "generating DAG for epoch ........." mining is taking too much to start

texts:
What i have
Case 1. following command line without --dev option (take too much time to start to mining)

geth --datadir ~/privateBlockChain1 --mine --minerthreads 1 --networkid 1300 --rpcport 8000  --port 30301 --rpcapi="db,eth,net,web3,personal,admin" --rpc --maxpeers 0 --nodiscover --targetgaslimit 110000000000 console

Case 2. following command line with --dev option(using this command line argument , mining works fine)

geth --datadir ~/privateBlockChain1 --mine --minerthreads 1 --networkid 1300 --rpcport 8000  --port 30301 --rpcapi="db,eth,net,web3,personal,admin" --rpc --maxpeers 0 --nodiscover --targetgaslimit 110000000000 **--dev** console

Scenario

Start geth by case 1 command.   Step 2.
suppose block created by case 1 command as for example -> #34544 block
Start geth by case 2 command
Block start creating from #1
block , it is not resume from #34544 block, how to fix it.

What i want?

a) how to mining start quickly(with in a second or a minute) when i start geth command line
b) if i do'nt want to use --dev option , then how can start mining fast?
c) suppose if you say, --dev is only option to start mining fast in startup, then how can i resume mine block from previous(i.e #34544 not from #1 block)
d) what is the advantage and disadvantage of --dev option with geth.


texts:
sir,

I have two contracts. I want to test the import statement in geth.
My first contract is names strtest.sol. The code is below:

pragma solidity ^0.4.2;
import "global_functions.sol";
contract strtest
{
    bool ib_equal;
    function test(string p1,string p2) returns(bool) {
        ib_equal = strcompare(p1,p2) ;
        return true;
    }
}

Another contract is named  "global_functions.sol". The code is below:

function strcompare(string p_source,string p_target) external returns(bool) {
    bytes memory lbt_left;
    bytes memory lbt_right;
    lbt_left = bytes(p_source);
    lbt_right = bytes(p_target);
    bool lb_equal = true;
    uint li_length = lbt_right.length;
    for( uint p = 0 ;p < li_length;p++){
        if (lbt_left[p] == lbt_right[p] ) {
            continue;
        } else {
            lb_equal = false;
            break;
        }
    }
    return lb_equal;
}

My question is:
How to compiler strtest in geth? ( Not in Browser-Solidity)

Below is my test situation:

> var test1 = "pragma solidity ^0.4.2;import '/barkely/lend/global_functions.sol';contract strtest { bool ib_equal; function test(string p1,string p2) returns(bool) { return true;  }}"
undefined
> var test1Compiled = web3.eth.compile.solidity(test1)

Error: solc: exit status 1
/tmp/geth-compile-solidity119170518:1:24: Error: Source "/barkely/lend/global_functions.sol" not found: File not found.
pragma solidity ^0.4.2;import '/barkely/lend/global_functions.sol';contract strtest { bool ib_equal; function test(string p1,string p2) returns(bool) { return true;  }}
                       ^------------------------------------------^

    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at <anonymous>:1:21

>

Now,
How I change the import path,ex:

import '/barkely/lend/global_functions.sol'  //absoulte path

or

import './global_functions.sol'  //the same path with strtest.sol

,it doesn't work.

So how should I do?

Thanks!
        Barkely


texts: Looking for working example of web3.getStorageAt() API usage

texts:
The documentation at http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage commonly linked to in other questions does not go into enough detail to replicate the process for complex types like dynamic arrays.  Following the instructions I to try access my contract storage, I can easily get the first few elementary types but I can't seem to find the right address for a dynamic sized array.

The dynamic array is at index 3 (position 4) and it is an array of struct.

I can easily get the array length with:

  web3.eth.getStorageAt(myContractAddress, 3);

But I cannot get any array values using:

  var hash = web3.sha3("0x04"), {encoding:"hex"});
  web3.eth.getStorageAt(myContractAddress, hash);

I have also tried with "0x4" and "0x3" and "0x5" and many other combinations.

Can someone please provide specific examples using the web3 library to retrieve the address of a dynamic array?


texts: How to give out ERC20 tokens w/o receiving eth?

texts: Is there a way to give out ERC20 tokens indiscriminately under a certain condition, but not by receiving eth? i.e without using the fallback function?


texts: What's the difference between the two ways of calling the function of another contract, i.e., interacting with another contract?

texts:
1.Here is an example from official doc:https://solidity.readthedocs.io/en/v0.7.3/control-structures.html#external-function-calls
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 <0.8.0;

contract InfoFeed {
    function info() public payable returns (uint ret) { return 42; }
}

contract Consumer {
    InfoFeed feed;
    function setFeed(InfoFeed addr) public { feed = addr; }
    function callFeed() public { feed.info{value: 10, gas: 800}(); }
}

2.Here is my another option:
IInfoFeed.sol
interface IInfoFeed {
    function info() external payable returns (uint) {}
}

and then in the example:
import "./IInfoFeed.sol";

contract Consumer {
    IInfoFeed feed = IInfoFeed(addressOfInfoFeed);
    function setFeed(InfoFeed addr) public { feed = addr; }
    function callFeed() public { feed.info{value: 10, gas: 800}(); }
}

Question:
What's the difference between the two ways of calling info() of contract InfoFeed?


texts: How can an NFT pay royalties to more than one creator?

texts:
Many NFT marketplaces have an option to declare royalty percentage to be paid to the NFT creator for each secondary sale of the NFT. Unfortunately, only one person (wallet address) can be assigned royalties: 10% to Joe.
What would be the best way to go about adding other creators of the NFT who each receive different shares of the royalty (5% to Joe, 3% to Billy, 2% to Alice)?


texts:
it seems to me that the mining model has it "flaws" too since it tends to concentrate mining power with very  few  (which might be a risk). I understand the incentive of it but .... somehow we end up with centralization.
Maybe the future of crypto currencies lies somewhere else  unless I have not understood the present situation.


texts: How deployment in the ETC network is cheaper than in the ETH network?

texts:
What factors differ in deployment & transaction cost in ETC compared with ETH network?
I checked the gas for deployment in ropsten and kotti which costs the same at a gas price of 20 gwei. In what sense ETC is cheaper than ETH?


texts: What are the main design pattern examples for using Callbacks in Smart Contracts?

texts:
In the ERC721 standard, there is a Wallet interface standard called ERC721TokenReceiver which includes a function called onERC721Received. I believe this is so that Wallets can listen to events and update the balance of the wallet (please correct me if not).

What are other design pattern uses of "Solidity callbacks"?


texts:
I use Parity's trace facility extensively to help me account for all transactions on individual accounts. I've been able to get almost complete accuracy (off-chain) of account balances for each block, but I'm having trouble with suicide calls.

This contract...

pragma solidity 0.4;
contract BadIdea {
    address recipient;
    function BadIdea(address _r) { recipient = _r;  }
    function () payable {}
    function kill() { suicide(recipient); }
}

...which is admittedly ridiculous--it accepts money from anyone and sends it to recipient--helps me ask my question. The transaction of a 'kill' call to this contract looks something like this:

Transaction:
=============
{
    "date": "2017-03-15 20:43:44 UTC",
    "block": 3189912,
    "from": "0xb970..."
    "to": "0xd450aa..."
    "input": "0xdaf3450000000..."
    ....
}

and the trace generated by Parity looks like this:

Trace:
=============
{
    "blockHash":  "0x9ee74ad...",
    "blockNumber": 3189912,
    "subtraces": 0,
    "traceAddress": [],
    "transactionHash": "0x8324490c...",
    "transactionPosition": 7,
    "type": "suicide",
    "action": {
        "from": "0x0",
        "gas": 0,
        "to": "0x0",
        "value": 0
    },
    "result": {
        "gasUsed": 0
    }
}

The transaction tells us which contract is suiciding (the transaction's 'to' value), but I don't see any way (from the perspective of the trace alone) of finding out what address the balance of the contract was sent to.

Of course, we know that the value was sent to recipient, but because I want to account off-chain (and I want to do so totally ignorant of the source code), I need something that indicates which account received the balance from the suicide. It does not appear to be included in the trace.

Question: Is there any way to tell which account receives the value from a suiciding contract from the RPC retrieved transaction and/or trace data alone?


texts:
There are two ways to subscribe/watch to logs/events:

Subscribe:

var subscription = web3.eth.subscribe('logs', {
    address: '0x123456..',
    topics: ['0x12345...']
}, function(error, result){
    if (!error)
        console.log(log);
});

Unsubscribe:

subscription.unsubscribe(function(error, success){
    if(success)
        console.log('Successfully unsubscribed!');
});

But how do I unsubscribe if I watch the logs / events like this:

myContractWebsocket.events.MyLogName({
    filter: {'orderId': '0x123456...'},
    fromBlock: 0
    })
    .on('data', data => { console.log(data); })
    .on('error', error => { console.log(error); });


texts: Is it possible to batch transactions together?

texts:
In bitcoin-land, it's advised to batch transactions to send them to (a) reduce fees and (b) reduce network congestion.

Does the same apply to ethereum land? It seems that the to can be only one address / account. But can there be many froms?

Is there a benefit to doing so?


texts:
I'm working on a project related to blockchain and need to figure out, how raw transaction can be possible, I got no reference for this as of now. Can anyone help me? I have tried this lib: https://github.com/matterinc/web3swift

but unable to get the exact thing?
Please Help me


texts: How to convert geth genesis to parity genesis?

texts:
In order to convert geth genesis to parity genesis I have guided into following link: github.com/keorn/parity-spec. I followed the explained usage.

When I try to run: cargo run -- example-geth.json I am faced with following error:

error: An unknown error occurred

To learn more, run the command again with --verbose.

-

*[master][~/parity-spec]$ sudo cargo run --verbose

error: could not execute process `rustc -vV` (never executed)

Caused by:
  No such file or directory (os error 2)

[Q] How could I prevent this error from happening? or is there any other way to convert geth genesis to parity genesis?

Thank you for your valuable time and help.


texts:
I have a function to set nickname:

function setNickname(bytes32 _nickname) public payable {
    lords[msg.sender].lordAddr = msg.sender;
    lords[msg.sender].nickname = _nickname;
    emit SetNickname(msg.sender, _nickname);
}

Then, I have deployed in Remix IDE and run function setNickname with input "Name one". But I received this response from Remix:

Error encoding arguments: Error: invalid bytes32 value

What is the correct input?


texts: Accessing to a contract's public array from javascript

texts:
Look at this basic Solidity contract:
// SPDX-License-Identifier: MIT

pragma solidity 0.6.11;

contract MyContract {
   string[] public tmp;
   ...

   function read_tmp() public view returns(string[] memory){
      return tmp;
   }
}

I have create a scaffolded truffle react project.
First, i get an error when trying to deploy this contract with this command:
truffle migrate --network ropsten --reset

The error is:

TypeError: This type is only supported in ABIEncoderV2. Use "pragma
experimental ABIEncoderV2;" to enable the feature.

This error is due to string[] return type of read_tmp.
I am not happy do to that but i have add this line at the top of my contract and the deploy works now:
pragma experimental ABIEncoderV2;

My first question is: Why should i enable experimental features ? My 0.6.11 compiler version should allow this feature natively...
My second question is i have tried this in App.js file:
await this.state.contract.methods.tmp().call();

Solidity should create automatically a getter called tmp() for tmp public field.
I do not understand why but i have this javascript error in my browser:

Uncaught (in promise) Error: Invalid number of parameters for "tmp".
Got 0 expected 1!

Everything works if i call read_tmp(). So my question is why tmp() needs an argument ? (i have tried to pass an integer but it does not work)
Thanks a lot


texts: Contract to Contract Execution Visiblity

texts:
Contract A
Contract B
Sender ---> Contract A ---> Request Information ----> Contract B
Action Complete <--- Contract A <--- Return Information <---- Contract B
Is the returned information visible anywhere? I am not asking about caller data or the original sender, I am saying that the contract question asked of Contract B, can it be linked to the original caller because of the requested action of Contract A.


texts: Is gas used during truffle tests on ganache the same as main net?

texts: I am testing the amount of gas used for my contract functions using Truffle and Ganache CLI. Does anyone know if I can assume that the gas usage reported during my tests will be an accurate representation of the gas that will be used when I deploy to the main ethereum network?


texts: How to convert address to string (for use in chainlink request)?

texts:
I'm a solidity beginner...
This
Chainlink.Request memory request = buildChainlinkRequest(clJobId, address(this), this.registerConfirm.selector);
request.add("repo", msg.sender);

says
TypeError: Invalid type for argument in function call. Invalid implicit conversion from bytes20 to bytes memory requested.
The chainlink docs tell me that there are also the methods addBytes, addInt, addUint, addStringArray and setBuffer.
My first thought was to convert the address to a string but that doesn't seem to be so trivial in solidity. So I wonder how to handle this all in all.
Answers like this one confuse me because comments say it doesn't do what you'd expect.


texts:
I've seen many functions using a returns (bool). What does it do? What can it be used for?

function transferFrom(address from, address to, uint256 value) public returns (bool);


texts: I'm stuck on how to subscribe to events to non-contract addresses. Is this possible? All I'm seeing is subscription to eth contracts only.


texts: Change default wallet address in ethers.js

texts:
I am trying to change the default address used by the wallet to send transactions.

let wallet = Wallet.fromMnemonic('hurdle cloud ...').connect(provider);

wallet.address // 0xfB98c...

How do I change the wallet's address to another address from the same private key? I feel like this should be obvious but digging through the documentation it doesn't appear possible.

Edit

Given that a single private key only has a single public key (and public address), the question needs adjusting. How would it be possible to generate new private keys (and therefore public addresses) from this mnemonic using ethers.js?


texts: web3.contract.events.EventName.on('data', () => {}) expiring after ~15 minutes

texts:
I am using the following code:
const web3 = new Web3.providers.WebsocketProvider(host);
const contract = web3.eth.Contract(...);

contract.events.EventName.on('data', console.log);

The EventEmitter for the EventName event works for the first 15 minutes, but after around 15 minutes of inactivity the events will stop being logged. I am using Infura as a web3 provider. I have setup code to automatically reconnect the WebsocketProvider should it disconnect but it is not disconnecting.
Anyone know a solution? Thanks.


texts: Ethereum transaction pending for some time

texts:
My transaction has been pending for some time, just hoping someone might be able to shed some light on it?

Tx hash is: 0x4c7ac93e6d65de9b6276b54a7386300d6a7d48b9c39f4091f8509a0b2a4ead3c


texts: geth - web3 : checkBalance not supported

texts:
Here is what I did :

Terminal 1 :

geth --syncmode "light"

Terminal 2 :

geth attach
> web3.fromWei(eth.getBalance(eth.coinbase), "ether")
Error: not supported
    at web3.js:3104:20
    at web3.js:6191:15
    at get (web3.js:6091:38)
    at <unknown>

What am I missing?


texts: What are the bandwidth requirements to run a full node?

texts: Is running a full node (mining) bandwidth heavy or is it hardware (GPU) heavy?


texts:
Another question regarding Ethereum chain size

I downloaded the blockchain with geth in fast mode the weight is 14Go, but i can see on https://etherscan.io/chart2/chaindatasizefast that it is in geth fast mode around 60Go. What size is correct ?

On another site we can see that the full ethereum weight is around 387Go https://bitinfocharts.com/ethereum/
Is this the current Ethereum chain size ?

I am talking about the folder /chaindata not the other folders containing DAG


texts: Remix (or any other tool): Solidity program to EVM opcode

texts:
I am interested in obtaining sequence of opcodes for a Solidity program:
One example is given in the following program obtained from
Link of paper
I have attached the image also
I need a link to a tool which can perform this task. How can we do it on Remix?
Somebody please guide me.
Zulfi.


texts: Is it possible for Bitcoin to live on the Ethereum Blockchain?

texts: It seems to me that once Casper is fully implemented, the best of both worlds would be for the valuable and scarce BTC token to live on the expedient, efficient Ethereum blockchain. But would this be technically feasible?


texts: Simple contract question, am I the owner?

texts: I started a contract through etherscan's publish and verify. But the contract hash it isn't under my verified address? Is this normal?


texts:
I am on a private net. I try sending ether to a contract address. It just doesn't work.

eth.sendTransaction({from: eth.coinbase, to: "0x39ce9b3b171da836afb02cbe2eff8d4e4fd6f174",
     value: web3.toWei(3, "ether"), gas:90000000})

I did unlock my account. I also run a miner. Increased the gas to other higher values, etc. I really do not know what is wrong with it?


texts: Can anyone tell me how I can improve gas requirement?

texts:
Below is my smart contract. Remix gives warnings on each of the following functions:

Gas requirement of function MedicalRecord.addNote(bytes32,bytes32) high: infinite.
Gas requirement of function Voting.allCandidates() high: infinite.
Gas requirement of function  Voting.indexOfCandidate(bytes32)  high: infinite.
Gas requirement of function Voting.transferBalance()  high: infinite.
Gas requirement of function Voting.voteForCandidate(bytes32,uint256) high: infinite.

Here is smart contract code:

pragma solidity ^0.4.23;

contract Voting {
  bytes32[] public candidateList;
  uint public totalTokens;
  uint public balanceTokens;
  uint public tokenPrice;

  address public owner;

  struct voter {
    address voterAddress;
     uint tokensBought;
     uint[] tokensUsedPerCandidate;
  }

  mapping(address => voter) public voterInfo;
  mapping(bytes32 => uint) public votesReceived;

  constructor(uint _totalTokens, uint _tokenPrice, bytes32[]
    _candidateNames) public {
    totalTokens = _totalTokens;
    balanceTokens = _totalTokens;
    tokenPrice = _tokenPrice;
    candidateList = _candidateNames;
    owner = msg.sender;
  }

  function transferBalance() public {
    owner.transfer(address(this).balance);
  }

  function buy() payable public {
    uint tokensToBuy = msg.value / tokenPrice;
    require(tokensToBuy <= balanceTokens);
    voterInfo[msg.sender].voterAddress = msg.sender;
    voterInfo[msg.sender].tokensBought += tokensToBuy;
    balanceTokens -= tokensToBuy;
  }

  function voteForCandidate(bytes32 candidate, uint tokens) public {
    // Check to make sure user has enough tokens to vote
    // Increment vote count for candidate
    // Update the voter struct tokensUsedPerCandidate for this voter

    uint availableTokens = voterInfo[msg.sender].tokensBought -
    totalTokensUsed(voterInfo[msg.sender].tokensUsedPerCandidate);

    require(tokens <= availableTokens, "You don't have enough tokens");
    votesReceived[candidate] += tokens;

    if(voterInfo[msg.sender].tokensUsedPerCandidate.length == 0) {
      for(uint i=0; i<candidateList.length; i++) {
        voterInfo[msg.sender].tokensUsedPerCandidate.push(0);
      }
    }

    uint index = indexOfCandidate(candidate);
    voterInfo[msg.sender].tokensUsedPerCandidate[index] += tokens;
  }

  function indexOfCandidate(bytes32 candidate) view public returns(uint)
  {
    for(uint i=0; i<candidateList.length; i++) {
      if (candidateList[i] == candidate) {
        return i;
      }
    }
    return uint(-1);
  }

  function totalTokensUsed(uint[] _tokensUsedPerCandidate) private pure
  returns (uint) {
    uint totalUsedTokens = 0;
    for(uint i=0; i<_tokensUsedPerCandidate.length; i++) {
      totalUsedTokens += _tokensUsedPerCandidate[i];
    }
    return totalUsedTokens;
  }

  function voterDetails(address user) view public returns (uint, uint[])
  {
    return (voterInfo[user].tokensBought,
      voterInfo[user].tokensUsedPerCandidate);
  }

  function tokensSold() public view returns (uint) {
    return totalTokens - balanceTokens;
  }

  function allCandidates() public view returns (bytes32[]) {
    return candidateList;
  }

  function totalVotesFor(bytes32 candidate) public view returns (uint) {
    return votesReceived[candidate];
  }
}

The contract is deployed on ropsten testnet, voteForCandidate fails during contract execution.


texts: Zeppelin OS: revert Cannot call fallback function from the proxy admin

texts:
I have been attempting to create a simple upgradable contract using Zeppelin OS:

Following the tutorial I have been able to:
- Create a new contract
- Deploy it using zos push
- Create the proxy using zos create MyContractName --init initialize --args singleArgValue

After I have deployed I fire up truffle via truffle console --network local and instantiate access to the contract via `contract = MyContractName.at('0xProxyDeploymentAddress')

Every attempted call or sendTransaction always throws with the same error:

Error: VM Exception while processing transaction: revert Cannot call fallback function from the proxy admin
    at XMLHttpRequest._onHttpResponseEnd (/Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at XMLHttpRequest._setReadyState (/Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest.request.onreadystatechange (/Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at /Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
    at /Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at Object.InvalidResponse (/Users/machine-name/.nvm/versions/node/v8.11.4/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)

I am able to refer to the original contract (not the proxy) and execute correctly, but everything throws on the proxy.


texts:
I have a contract on the Ropsten test network and I am trying to return an array of structs but I am receiving the following error in my JS console.

I am including the following at the top of my contract

pragma solidity ^0.4.18;
pragma experimental ABIEncoderV2;

and this is the function I am calling

 function getAllLand() external view returns (Land[]) {
        return landRegister;
    }

I know that this particular feature is experimental but any idea why this error might be thrown?

Thanks


texts:
I build a smart contract on solidty and website with Nethereum.

One of variable include the current status of all the users like this :

mapping(address => Status) public StatusUsers;

I did a loop(offchain) and call this public variable to get the status of all users that take  9 seconds for 31 wallets address .

The problem that I need to call the variable for every address  to get the current status and its very very slow.

If someone can help me and find a better way and much faster .

Thanks you.


texts: Generating random numbers in solidity based on block hash

texts:
My intended contract scenario:

The player makes bets. The contract remembers its block number. Then player again makes a request to the contract with the next transaction and receives the result of his bet based on the hash of his bet block

Is there a vulnerability in this scenario? (not considering miner attacks and a limit of 256 blocks)?


texts: How to get Truffle to generate artifacts for contracts outside of project?

texts:
Say I have a contract MyToken.sol which has already been deployed to a public Ethereum network. Its source is maintained in an external repository and is included in my package.json file so that it falls under the node_modules/ directory. I create my own contract MyContract.sol in the local project's contracts/ directory. In order to prevent compiling the entire contract (and its imported contracts) of MyToken.sol, I use an interface IMyToken.sol in my local project to give MyContract.sol only the functions that it needs from MyToken.sol. This is also beneficial to prevent Truffle from displaying compiler warnings for older contracts which have already been deployed.

The project structure is as follows:

MyProject
    |
    |
    +- contracts
    |     |
    |     +- interfaces
    |     |     |
    |     |     +- IMyToken.sol
    |     |
    |     +- MyContract.sol
    |
    +- node_modules
          |
          +- my_token
                |
                +- contracts
                      |
                      +- MyToken.sol

The source of MyContract.sol is similar to the following:

pragma solidity ^0.4.24;

import "interfaces/IMyToken.sol";

contract MyContract {
  IMyToken token = IMyToken(0x...);
  ...
}

Compiling this locally works perfectly fine. I can even deploy it to a network where MyToken is already deployed and interact with it as expected. However, for local testing, I need to deploy my own instance of MyToken.sol, but I want to avoid including it in my project. Since the actual MyToken.sol is not located within my project's contracts/ directory, Truffle does not generate artifacts for it. Therefore, the following does not work for any migrations script:

var MyToken = artifacts.require("../node_modules/my_token/contracts/MyToken.sol");

My question is: What is the best practice for generating artifacts in Truffle for contracts which reside outside of the local project?

To give one possible solution (which I'm not too fond of), I can create a contracts/lib/ directory and store a base contract which imports from the node_modules/ directory. For example:

pragma solidity ^0.4.24;

import "my_token/contracts/MyToken.sol";

The only problem that I have with this solution is I still get all of the old compiler warnings because MyToken was deployed with an older Solidity version.


texts:
I have transferred ether to my contract but contract balance showing 0 and contract Creator balance increased . So I want to show that ether to my contract .

Please Help.


texts: How to call "payable function" via interface in solidity

texts: I have a function marked as payable in contract A and I want to call it from contract B so that msg.value in contract A can have its desired value and contract A must have balance of sent amount , how it is possible ?


texts: What factory (UniswapV2Factory) shoud I use when deploy Sushiswap clone?

texts:
Hi I'm forking Sushiswap and about to deploy contract to mainnet.
While I'm writing deploy_contract.js in Truffle.
Which Factory shoud I use in my migration code? I saw several code example but somebody just use Uniswap Factory address in Mainnet and somebody use their own UniswapV2Factory. Which one shoud I use at mainnet?
And If you have some migration code(deploy_contract.js) example for Sushiswap or Uniswap. Please let me know about it.


texts: GraphQl Query to get Uniswap OHLC data through The Graph

texts:
I tried searching through whole doc of The Graph but couldn't get a way to get OHLC data of Uniswap pair swaps.
Where can I find such a query. Is this even possible?
Thanks


texts: Subscribe to events using local geth in light mode?

texts:
I've followed this guide to subscribe to events. I succesfully subscribed to the new block headers using Infura provider. But when I try to use local geth node syncing in light mode, it connects, but can't receive new events. Waits for a while, and then throws with unexpected EOF.

I think it's impossible to subscribe to the new events using the node in light mode, but I can't find any information to proove this. Is it right?


texts: How Can I Sign A Transaction Server-Side?

texts:
I have a server-side Node.js app that sends a transaction to an Ethereum smart contract like so:

const transaction = await contract.methods
    .method_name([params]).send({
      from: [wallet_address]
    });

I have my private key stored on the server but I don't know where to reference it and how to sign the transaction.

Any help is greatly appreciated.


texts: Execute a contract from bash or inside a python script

texts:
I have a Mist wallet and a contract (with its address) that i execute from mist GUI "manually".
I was wondering how i can execute it from command line (bash not geth) or call that execution from a python script.
If this is possible could you provide a toy example or a roadmap?
Thanks in advance!


texts: using web3js on a server without geth or any client

texts:
related to for using web3.js it is necessary to install geth into your system

I want to use web3js with nodejs server to get interact with a smartcontract deployed on rinkeby/mainnet. Do I need to setup geth on my server and sync all the rinkeby/mainnet data to use web3 with nodejs or I can interact without setting up geth?


texts: Are there any existing native libraries (not whole wallets, I do not need a UI but want to sign transactions and call smart contract functions embedded in another app) for iOS or Android? If not, are there efforts currently ongoing or what is the closest I could get right now?


texts: what's the difference between assembly part and opcode part in remix?

texts:
In the remix, there's compilations details button. When you click, one can see Bytecode and also assembly parts.
Bytecode is an object which has object key and opcodes key in it. As far as I can see, object is the bytecode itself. and opcodes is the opcodes sequence which is assembly.
Why is the assembly part which is at the end of the compilations details page different than the opcodes key from Bytecode ? It seems like they both contain opcodes, but they are still different.


texts: Solidity: TypeError: Member "unbond" not unique after argument-dependent lookup in contract super EthGatedMarket

texts:
I'm getting this error:

TypeError: Member "unbond" not unique after argument-dependent lookup in contract super EthGatedMarket.
    super.unbond(msg.sender, gatewaySpecifier, quantity);
   ^-----------^

EthGatedMarket.sol:

///unbond to obtain eth in exchange for gateway tokens
function gatewayUnbond(uint quantity) public payable {

    require(unbondAllow, "unbond not allowed");
    super.unbond(msg.sender, gatewaySpecifier, quantity);
}

EthAdapter.sol:

function unbond(address payable wallet, bytes32 specifier, uint quantity) internal{

    bondage = BondageInterface(coord.getContract("BONDAGE"));
    uint issued = bondage.getDotsIssued(address(this), specifier);

    currentCost = CurrentCostInterface(coord.getContract("CURRENT_COST"));
    uint reserveCost = currentCost._costOfNDots(address(this), specifier, issued + 1 - quantity, quantity - 1);
    FactoryTokenInterface tok = FactoryTokenInterface(curves[specifier]);

    //unbond dots
    bondage.unbond(address(this), specifier, quantity);
    //burn dot backed token
    tok.burnFrom(wallet, quantity);
    //send wallet eth
    wallet.transfer(reserveCost * adapterRate);
}


texts: Why `address.call` function "saves" unnecessary gas for after the internal execution?

texts:
I deployed a contract of a multisig wallet to ropsten and try to test its abilities:
https://ropsten.etherscan.io/address/0x8bf20c41ee6a9fd84e81d6f6df872d9628cd08b2

Things that worked fine:

Withdraw ETH
Sending transaction to other contract (transfer erc20 tokens)

Things that didn't worked as expected:

add owner
replace owner
basically every wallet change transaction failed

Why and how it failed?

Example transaction: https://ropsten.etherscan.io/tx/0xf4074abba33252d79dcdd234071dff25c7eba205ddb777076e623d6d108b7392

First I use the wallet submitTransaction function and submitted a transaction to the same wallet contract with data that call the internal transaction change, addOwner.
Then I used another owner key to confirm it.
When the transaction got the required confirmations the contract called the method executeTransaction which execute this call:

txn.destination.call.value(txn.value)(txn.data)

In this example

txn.data is 0x7065cb480000000000000000000000009ac4f6e64d56043991f486e375994f67ecbfdde0 calling addOwner("0x9ac4f6e64d56043991f486e375994f67ecbfdde0")

txn.value is 0

As you can see, the internal transaction is failing due to out of gas.

Did a little research and found out that after the call function, the contract "saves" some gas for after the internal transaction invoke, and the internal transaction invoked with only 700 gas that consumed immediately by the CALL opcode.

https://ropsten.etherscan.io/vmtrace?txhash=0xf4074abba33252d79dcdd234071dff25c7eba205ddb777076e623d6d108b7392
line 728:

Funny thing is, that at the end of the external transaction, the execution left with 27511 gas.

Some other wired stuff:

If I give the transaction a lot of gas (x10) it works fine.
If I use different contract to interact with (for example erc20.transfer) it works fine.
If I use the executeTransaction by itself (after the transaction is confirmed), it works fine.

So, What is going on? Why the gas estimation not working?

PS I tried it both with MEW and web3 js code for gas estimation.


texts:
I am using PhoenixMiner on Nanopool. It notes in the past week (2/10-2/17) I had a maximum reported share of 209622.1TH. I assume this share produced a block provided the average difficulty this week was ~5000TH. I have tried looking through etherscan at the reported blocks for nanopool, though it's a pretty futile attempt provided the number of blocks they produce daily. I am also unsure if the "Total Difficulty" field for a reported block on etherscan represents the actual difficulty of the block or something else.
Is there a way I can search etherscan, or any Ethereum explorer, for a block with the given difficulty in the quoted time frame?
I'd just like to see the block I think I potentially mined, I think it's neat.


texts:
If I store 10 blocks from Ethereum, with the block difficulty, mixHash and nonce etc. Transactions etc. Is it possible for me to back trace that the information I have stored is actually correct and matches the information that is actually on the blockchain? So essentially a Merkle tree.
What I want to validate is; that the data I sit on matches what is on the Ethereum blockchain.
This will always be retrospective. So if I'm testing block 2, I already have the information of the next block (in this case block 3).
I haven't stumbled upon any resources on how to do this.


texts: Can you change a variable outside of a function (assuming this variable may be a constant)?

texts:
In other words if a contract looks like this:

contract tokenX  {

bool public started = true;

function end()
{
started = false;
}

}

So everyone should be able to call end() but can someone call "started"?
What if the owner of the contract is the contract itself? Can the contract simply call unknown function and trigger "reinitialization" or is this impossible? Thanx!


texts: What is the easiest way to interact with your contract in a development environment?

texts:
Is there some form of toolkit which generates a console similar to the one on etherscan, where you can call functions that are defined in your contracts ABI?
It seems quite painful having to write the code out in a truffle console


texts: Calling transfer function of an ERC-20 contract

texts:
I want to call the transfer function of any ERC-20 contract in my Smart Contract.
I have seen that i should use "callcode" in a similar way of https://gist.github.com/critesjosh/68593429fd2f84f8f55d4ff7b74f0323.

function callcodeSetNum(address c2, uint _num) public {
    if(!c2.callcode(bytes4(sha3("setNum(uint256)")), _num)) revert(); // C1's num is set
  }

I could reproduce inter-contract calls to one-parameter function. However, I always get a strange error when trying to call a function with more than one parameter (as is the case of transfer).

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

Anyone has a clue?
Thank you


texts:
Lately I've been wondering about setting delays after initialization and resolution to avoid having more than a single transaction occur.

I've yet to give the docs a thorough enough of a read, but i'm thinking of something like

contract GameStake {

adress public playerOne;

address public playerTwo;

delay(15) {

//delayed execution, sends payment after 15 blocks of initialization.

...

}

}

Thanks.


texts: Ethereum Node I want to export transactions from a token

texts:
I have an Ethereum node running and I am wanting to export transaction history for a specific ERC20 token to a local database every 10 minutes.

Does anyone have any suggestions on how they would do this?


texts: Decrease the time between new blocks in Ethereum Development

texts:
I'm trying to create a DAPP (with docker-compose) which will require many transactions, and I am currently experiencing nonce problems with my Transaction Manager.

However, I'm not looking for help with this problem. What I would like to do is decrease the time between blocks getting mined in my dev environment. Currently, blocks get mined every 2 minutes, whereas blocks on the ethereum network get mined every 17 seconds or so.

Is it possible to change the time on my local machine in order to simulate a real life environment?


texts: Parity-like Solution for using Ledger Nano Anywhere

texts:
I'm looking for a "Parity-like" solution so that I'm able to use my Ledger Nano on any Ethereum-powered website that doesn't support a Nano natively (something like Radar Relay).

I know I can do this with Parity, BUT, I also need it check a few more boxes:

1) I need to be able to use it anywhere... not just on the host that's running Parity (I know about Parity public nodes and how to tunnel SSH, these options don't support the Nano).

2) Prefer not to have to do any syncing at all - would like to be able to do "light"

It seems that if MetaMask supported Ledger Nanos, it would be exactly what I'm looking for. Something I can login to on any computer, connect my Nano and start signing transactions from the Nano on sites that don't explicitly support the Nano.

Hoping there's something out there.

Thanks!


texts:
I'm deploying two contracts, one of which depends on another, plus they depend on a number of other contracts via the import statements. However, although in my deployment script I haven't included any link statements, all my tests pass.

Why does it work without linking, and should I add the link statements before deploying to a live net?

Here's what I have in my .sol file:

pragma solidity ^0.4.18;
import '../node_modules/zeppelin-solidity/contracts/token/StandardToken.sol';
import '../node_modules/zeppelin-solidity/contracts/math/Math.sol';
import '../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol';
import '../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol';

contract NppToken is StandardToken, Ownable {...}

contract CrowdSale is Ownable {
  NppToken private token;
...
}

Here's my migrations file:

var NppToken = artifacts.require("./NppToken.sol");
var CrowdSale = artifacts.require("./CrowdSale.sol");

module.exports = function(deployer, network, accounts) {
  deployer.deploy(NppToken);
  deployer.deploy(CrowdSale, NppToken.address);
};


texts: Batch dust ETH from multiple private keys / wallets together as one transaction?

texts: I use metamask and have many accounts that have small amounts of ETH and other ERC20 tokens. Some accounts have $5-$20 worth of USDC or ETH and I want to make a batch transaction to send all these dust amounts into one account. Is there such a tool or way of doing this?


texts: How can i pause the token transfer of specific tokenid only in openzeppelin ERC721 contracts?

texts: I want to lock the transfer of specific tokenId of ERC721 Tokens owned by EOA for specific amount of time. Is it possible to achieve that?


texts:
I am starting geth like the below command

Geth "--ipcdisable --rpc --fast --datadir="path" --rpcapi personal"

I want to get the blockchain synchronization details from geth.

So I issue the following command

curl -x http://127.0.0.1:8545/ {"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}

But I get this exception

{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"The method eth_syncing does not exist\/is not available"}}

I can see from the logs that blockchain is synchronizing but I cant run this command. How to fix this.


texts: How do I make Populus talk to a node on Infura?

texts:
I signed up for Infura and they gave me a URL for a node to talk to, like https://ropsten.infura.io/mytokenjsifejsij39kdjkjfdk. (The part beginning mytoken isn't my real token.)

I'd like to deploy and manage my contracts using Populus; How do I get it to connect? I tried setting the following in my populus.ini and various other permutations of port numbers, but when I try to connect to it, for example with populus chain init testnet, it results in socket.error: [Errno 111] Connection refused.

[chain:testnet]
rpc_host = https://ropsten.infura.io/mytokenjsifejsij39kdjkjfdk
is_external = True
provider = web3.providers.rpc.RPCProvider

Is it possible to connect to an Infura node from populus, and if so how should I configure it?


texts: Transfer Token value is decimal when define decimals in smart contract?

texts:
I am new to ethereum block-chain. I create a ERC20 base smart contract. I set decimals values 18. When I call transfer function and pass the address and value parameters. So it's convert no.of token value into decimals. I want to it integer number.

I follow answer:- Correct way to transfer ERC-20 tokens and keeping decimals in count?

But one thing I can not understand how to intelize temporary variable and pass it on transfer function. I can do this way:-

Solidity code:-

contract StandardToken is ERC20, BasicToken {

using SafeMath for uint256;

   // Name
string public name = "Autobay";
// Symbol
string public symbol = 'ABX';
//standard
string public standard = 'ABX 0.1';
//token price
uint256 public tokenPrice = 100000; //in wei

uint256 public  amount;

//decimals
uint256 public constant decimals = 18;

uint256 public totalSupply;

constructor(uint256 _intialSupply) {
            balances[msg.sender] = _intialSupply;
            totalSupply = _intialSupply;
         }

event Transfer(address indexed _form,address indexed _to,uint256 amount);
event Approval(address indexed _owner,address indexed _spender,uint256 _value);
mapping (address => mapping (address => uint256)) internal allowed;

 function transfer(address _to, uint256 _value) public returns (bool) {
    amount = _value * 10**decimals;
    require(_to != address(0));

    require(amount <= balances[msg.sender]);

    // SafeMath.sub will throw if there is not enough balance.

    balances[msg.sender] = balances[msg.sender].sub(amount);

    balances[_to] = balances[_to].add(amount);

    emit  Transfer(msg.sender, _to, amount);

    return true;

}

When I call transfer function nothing change. So where I do mistake. Please anyone resolve my query.

It might be a silly question but here i want to understand this concept more deeply.

Please help to clear my above query.

Thanks


texts:
These entries show Statement has no Effect issues. WHy so?

The entries have "Statement has no Effect" problems

    startTime = _startTime; "1513683938";
    endTime = _endTime; "1513687538";
    rate = _rate; "5000";
    wallet = _wallet; "3242t536..."; // <----- sample
    token = createTokenContract();
  }


texts: What is the simplest way I can build a blockchain app using embark framework? where does it store the data if I don't use IPFS? How do I run it on multiple instances in my machine for testing?


texts: Stack too deep, difference between memory variables local variables

texts:
Got a "stack too deep" error, and saw on stack exchange that I could try and use memory variables instead of local variables, and moved 8 uint into a uint[8], no error anymore. Why does that work while using individual unit did not?

Code example

uint a;
uint b;
uint c;
uint d;
uint e;
uint f;
uint g;
uint h;

"using too many variables, stack too deep"

and with

uint[8] memory abcdefgh;

no problem


texts: What is the difference between transfer() and trasnferfrom() and when should i use it

texts:
I want to ask what is the difference between transfer and transferfrom and AND WHEN should i use them in the following examples:
1- My firend wants to give tokens to other friends. what function is he gunna call to send it to another and why(and also if transferfrom dont forget to allowance function).
2- my friends want to send tokens to me vice versa


texts: Ensuring a transaction is included in a specific block

texts:
I have been sending myself transactions back and forward between MEW and Parity trying to get a transaction included in a specific block number however I seem to be always 3 - 6 blocks behind where I want it.

This is in preparation for the Golem crowdsale, I want to make sure I don't miss out and ideally my transaction lands in the first block from when the sale starts.

A few questions:

Is it a sound strategy to broadcast the transaction 1, 2, or 3 blocks before the start block (on my 6 test transactions this still put me a few blocks after the 'start block'), what about the risk of my transaction being confirmed before the sale start block?
What are the best gas setting to get my transaction confirmed as fast as possible, if I include 2,000,000 gas how much is that in Eth and do I need to alter the gas price to give myself the best chance of it getting confirmed quickly?

Thanks for having a read, would be interested to hear what others would do in this situation to give the best chance of getting my Eth into the Golem crowdsale.

I have recorded my tests, what block I was hoping for and what block the transaction confirmed and the gas setting I used if that info is handy I could post it.

Thanks in advance!


texts:
I have a storage array and I able to use push method. But, in another part of my code, I have a memory array and I can't do that. What's the reason? Doesn't exist push method in memory arrays?
        Individual[] memory newPop = new Individual[](popSize);
        for(uint i = 0; i < popSize; i++){
            uint index1;
            uint index2;
            (index1, index2) = getIndex();
            Individual newIndiv = crossover(index1, index2);
            newPop.push(newIndiv);
        }

And the error:


texts:
I have get 1.7.2. on Ubuntu 16.04, which is currently stucked at block 3768477
and is not syncing (eth.syncing = false). How do I get it to sync (and not loose my accounts on which I already have some ether).
Thanks


texts: create offline ethereum wallet in android

texts: How to create an Ethereum wallet (Keystore JSON file) in android using org.web3j:core:3.3.1-android (web3j library). Please guide me to create one.


texts: Update account passphrase over RPC(using web3)?

texts: Like web3.personal.lockAccount() and web3.personal.newAccount() is there any method available or any other API's exist to update account passphrase over RPC?


texts:
This  is the Project

I am getting error while i deploy my smart contract to ropsten test network(The same project successfully deploy on rinkeby test network)
it is the error

~/Voting-Application/Voting_App2$ truffle migrate -reset
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... undefined
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: insufficient funds for gas * price + value
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-core/~/truffle-migrate/index.js:225:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)


texts: How to find transfer value in internal transaction by go ethereum?

texts:
How can I know how much ether is transfer to the receiver such as 0xa1ca8da0496cFA2f8579F58db30AE8aD8dbe6F0C?
Is its method id 0x2da91fa2 important?

I found the transaction in EtherScan, its hash is 0x9aca88a62adb439fd737f43a6e8f3ddee27e124a9e4bb42f95f2a8db1198e5a4, and block height is 4371625.

I can find the addresses of receiver in input data, such as 0000000000000000000000006008767265b0060733884b59768ded777cf0930b and 000000000000000000000000a1ca8da0496cfa2f8579f58db30ae8ad8dbe6f0c. And the method id is 0x2da91fa2.

I cannot find the 2.019 Ether in input data, but EtherScan can display that TRANSFER  2.019 Ether  to 0xa1ca8da0496cFA2f8579F58db30AE8aD8dbe6F0C.

I am developing an Android wallet application by go-ethereum in light client mode. User can see the list of send/receive Ether when pressing ETH button.


texts: How safe are the view functions, can anyone see the data I am sending to a view?

texts:
I would like to create a contract that uses the view function, however, I must make sure that nobody can see what data I am sending to a view since it is a sensitive content. The contracts simply acts as the logic and view simply verifies that whatever is inputted (without changing the state of the contract) gives some output according to this logic.
Is it possible to have some privacy with the views?
Also, can the miners always see what data is passed and collect the sensitive data I just mentioned ?


texts: Not enough funds for a transaction example in testrpc

texts:
I try to test one of my first Smart Contract in Solidity, a simple sub currency example, as you can see below :

pragma solidity ^0.4.0;

contract Coin {

  address public owner;
  mapping (address => uint) balances;

  function Coin() {
    owner = msg.sender;
    balances[tx.origin] = 1000;
  }

  function send(address receiver, uint amount) returns (bool success) {
    if (balances[msg.sender] < amount) {
      return  false;
    }
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    return true;

  }

  function getBalance (address user) constant returns (uint balance) {
    return balances[user];
  }
}

After migration and compile, please look my truffle command in the console

> var a = web3.eth.accounts[0]
> var b = web3.eth.accounts[1]
> var coin = Coin.deployed()
> coin.then(function(instance) {return instance.getBalance.call(a);})
{ [String: '1000'] s: 1, e: 3, c: [ 1000 ] }
> coin.then(function(instance) {return instance.getBalance.call(b);})
> { [String: '0'] s: 1, e: 0, c: [ 0 ] }

At this point I'm agree with these output, but when I want to make the transaction, they said I don't have enough funds ...:

> coin.then(function(instance) {return instance.send(b,500);})
Error: Error: sender doesn't have enough funds to send tx. The upfront cost is: 724579920256558730963659928732440307373701337785 and the senders account only has: 99835768400000000000
    at runCall (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/lib/runTx.js:97:10)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:3686:9
    at replenish (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:882:17)
    at iterateeCallback (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:867:17)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:840:16
    at /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:3691:13
    at apply (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:21:25)
    at /usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/ethereumjs-vm/node_modules/async/dist/async.js:56:12
    at Object.async.eachSeries (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/async-eventemitter/node_modules/async/lib/async.js:130:20)
    at VM.AsyncEventEmitter.emit (/usr/local/lib/node_modules/ethereumjs-testrpc/node_modules/async-eventemitter/lib/AsyncEventEmitter.js:42:9)
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/node_modules/truffle-contract/node_modules/web3/lib/web3/errors.js:35:16)
    at /usr/local/lib/node_modules/truffle/node_modules/truffle-contract/node_modules/web3/lib/web3/requestmanager.js:86:36
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/node_modules/web3/lib/web3/httpprovider.js:119:13)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:509:12)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/node_modules/xhr2/lib/xhr2.js:469:24)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

I tried with other accounts available in Testrpc, I've same results ... May be I missed something in my command or set up I Don't know. But this cost seems to important, no ?

Thanks for your help !


texts: How does delegatecall work from Solidity 0.5.0 onwards?

texts:
I am trying, for learning purposes only, to make a mutable smart contract, but I couldn't find anything useful on stackexchange because everything I found was using pragma solidity ^0.4.x;

So, I have 2 contracts

pragma solidity ^0.5.0;

contract first {
    uint calculationResult;
    address public linkedContract;

    function calculate(uint firstNumber, uint secondNumber) public {
        calculationResult = firstNumber * secondNumber;
    }
}

and the other

pragma solidity ^0.5.0;

contract second {
    uint calculationResult;
    address public linkedContract;

    function changeContract(address newContract) public {
        linkedContract = newContract;
    }

    function delegatedCalculation(uint firstNumber, uint secondNumber) public {

    }
}

I am trying to make on the second contract the function delegatedCalculation to use the function from the first contract, so later I can change this to another calculation, I can for example create a third contract where the calculation is a sum, not a multiplication, I have tried 2 ways to do that, the way every tutorial and guide and even stackexchange answer I found does this is

linkedContract.delegatecall(bytes4(keccak256("calculate(uint, uint)")), firstNumber, secondNumber);

but when I try to compile on remix I get a not very helpful error

  browser/firstContract.sol:20:9: TypeError: Wrong argument count for function call: 3 arguments given but expected 1. This function requires a single bytes argument. If all your arguments are value types, you can use abi.encode(...) to properly generate it.`

And upon reading about that abi.encode I have found that if I do

linkedContract.call(abi.encode("calculate(uint, uint)", firstNumber, secondNumber));

it compiles, but then if I execute it nothing happens. I have created a function

function getReturnedView() public view returns(uint){
    return returnedValue;
}

I compile and run on Remix EVM the first, get it's address, compile the second, run it, execute the changeContract to give it the address of the first one, call the delegatedCalculation, and when I call the getReturnedView() it says just 0: uint256: 0

I can't figure out how to make it work.


texts: How to limit minimum amount of value transfer Tx that can be included in a block by a miner : Dapp?

texts:
In my scenario, I would like to keep a restriction on the min value on a transaction.

For example, if A is to transfer some ETH to B, the min amount he can is > 0.01 ETH.
So that a miner cannot include transactions < 0.01 ETH.

How can I achieve this? Any idea would help.


texts: Create signed message without JSON RPC node in PHP

texts:
I am trying to recreate effect of web3's eth.accounts.sign in PHP and I struggle to find good resources how to do it properly.
I have seen this
(found it thanks to this thread) and based on what I figured out, I've put together script, that outputs something but it's definitely invalid signature.
<?php

use kornrunner\Keccak;
use Elliptic\EC;

//used libraries simplito/elliptic-php kornrunner/keccak

require_once "vendor/autoload.php";

$ec = new EC('secp256k1');
$pkey = "cdf6a858b71520aedaf50442a761af94a516a3d0e36f2b5b6c9bcf0bfbe45820";
//$addr = "0x703632A0b52244fAbca04aaE138fA8EcaF72dCBC";

$ecPrivateKey = $ec->keyFromPrivate($pkey, 'hex');

$hash = Keccak::hash('Hello World', 256);

$signature = $ecPrivateKey->sign($hash, ['canonical' => true]);

$r = $signature->r->toString(16);
$s = $signature->s->toString(16);
$v = $signature->recoveryParam + 35;

echo "Signed Hello world is:\n";
echo "Using my script:\n";
echo "0x" . $r . $s . $v . "\n";
echo "Using MEW:\n";
echo "0x2f52dfb196b75398b78c0e6c6aee8dc08d7279f2f88af5588ad7728f1e93dd0a479a710365c91ba649deb6c56e2e16836ffc5857cfd1130f159aebd05377d3a01c\n";

There are some confusing parts of this, I am unsure why 35 is added to recoveryParam and why it's allways 0 from get-go. Also, apparently, chain ID influences V, but this behaviour isn't present in MEW signing. I don't know which order is correct - r s v, or s r v, or v s r, I've seen it used in seemingly random orders (except v is allways last or first), I tried with adding 0x before pkey, and at this point Im out of ideas.
My question is either what am I doing wrong, or where can I learn how to achieve desired effect (without reading tons of JavaScript code that I struggle to understand).
Background:
I need this to generate server-side parameter to smart contract (that's signature to other parameters for smart contract) that will be given to user, and smart contract must be able to trust this parameter. Signing it server-side will prevent potentially malicious actor to for example burp proxy the website and mix up said parameters.


texts: Creating a web3py contract -- TypeError: contract() takes from 1 to 2 positional arguments but 3 were given

texts:
from web3 import Web3
import json
from web3.providers.rpc import HTTPProvider
contractAddress = '0xmasked'
web3 = Web3(HTTPProvider('https://mainnet.infura.io'))
with open('contract.abi', 'r') as abi_definition:
    abi = json.load(abi_definition)

fContract = web3.eth.contract(abi,contractAddress)

Has anyone encountered the following error? From what I see I'm calling two arguments not three.

TypeError: contract() takes from 1 to 2 positional arguments but 3 were given