texts: Is it possible to change an already assigned bytes32 variable?

texts:
If I assign a bytes32 variable such as

bytes32 x = 0xffff;

but then I want to change the last byte (or any byte really) so that x is now 0xffaa, is there any possible way to do this?  I want the change to be persistent so that any changes in x are reflected in the blockchain, not just mask into a particular byte and use the result.


texts: How do i create a wallet from a smart contract in Solidity?

texts:
Is there a way to create a wallet from a smart contract in Solidity ? If there is how can i do it ?
For example i want to create a smart contract that on deploy creates a new wallet and saves its address into an array.
Thanks for the help.


texts:
I am try to compare a string variable in solidity code, mainly i have to check if the string is empty or not. How can it be achieved and also how much long/large of a string i can save in a string variable.

contract BOLData{
struct Data {
    string sData;
    string ssCompanyData;
    string ConsigneeData;
    string BOL_ID;
}

mapping(string => Data) private BOL_Data;
//Add the initial value
function BOLData (string s_Data, string  bolid)
{
    BOL_Data[bolid] = Data(s_Data,'', '', bolid);
}
//Add data, hash to Block Chain
function addData(string ssCompany_Data, string Consignee_Data, string bolid) public {
    string s_DataO = BOL_Data[bolid].sData;
    string ssCompany_DataO = BOL_Data[bolid].ssCompanyData;
    string Consignee_DataO = BOL_Data[bolid].ConsigneeData;
    if(ssCompany_DataO == '')
    {}
    BOL_Data[bolid] = Data(s_DataO,ssCompany_Data, Consignee_Data, bolid);
}

//Fetch data, hash values from block chain
function getData(string DataID) returns (string, string, string){
    string s_Data = BOL_Data[DataID].sData;
    string ssCompany_Data = BOL_Data[DataID].ssCompanyData;
    string Consignee_Data = BOL_Data[DataID].ConsigneeData;
    return(s_Data, ssCompany_Data, Consignee_Data);
}

}


texts: Compile error - Warning: Unused local variable

texts:
I am getting warning errors on a few variables such as
deposit, totalpayment and duration which are necessary for taking payments from users.

The error I am receiving is:

  Warning: Unused local variable.

Questions:

What does this mean?
And how come that payment or charges are not coming out of the user
balance?

Screenshots:


texts: Function not returning address when using web3 provider

texts:
I have a contract that works fine when only using remix. I needed to test the block size and block number. here someone suggested me to use ganache which I did but now I don't get the output I'm supposed to get in this function:
function promiseRentalCompleting() public
         atCFact(C_facts.Requested)
         onlyBy(initiator)
         transitionNext(true)
         returns (address){
             rental.car=rental.carGroup.freeCars[0];
             DepositPaying depositPaying = new DepositPaying(address(this));
             return address(depositPaying);
         }

Basically I need this function to give me an address where I will deploy the DepositPaying contract but the  decoded output at remix is coming out empty what was not happening before I added ganache. Should I be doing something different to accommodate the web3 provider?
(using remix on the browser chrome, got ganache from here, not using de command line)


texts: Why did my balance return to Zero after stopping Geth? (newbie)

texts:
I am a complete newbie just started trying this out last night.
I was able to get geth up and running as well as ethminer. I woke up and when i did the check balance command it said i had 500000000 not sure how many zeros were actually there i know thats Wei. I had to shut my computer of and know when I check the balance it says zero. please help?

Thanks


texts: Binance Smart chain - private network implementation - guideline required

texts:
I am trying to understand the way Binance proof of stake authority(PoSA) works by implementing a private local blockchain. Therefore, I tried their official documentation but it seems like they simply created multiple nodes by using proof of authority (PoA). I could not distinguish what is the difference between the classical ethereum PoA and Binance PoSA.
Please help to get a proper working guideline. Thanks in advance.


texts: Calling a contract from another contract: issue with paramenter passing

texts:
I have two cntracts with one calling the other.
The first is

contract A_int
{
    event called(string str,uint ts,address addr,string tr);
    function callme(address addr,uint ts,string tr)
    {
        called("called me",ts,addr,tr);
    }
    function kill()
        {
        suicide(msg.sender);
        }
}

and another contract which calls this contract

contract caller_tracker_string
{
    address curr_tracker;
    address owner;
    function change_contract(address addr)
    {
        curr_tracker=addr;
    }
    function caller_tracker_string(address current_trcker)
    {
        owner=tx.origin;
        curr_tracker=current_trcker;
    }
    function adduser(address usr_new,uint ts,string tr)
    {
        curr_tracker.call(bytes4(sha3("callme(address,uint256,string)")),usr_new,ts,tr);
    }
    function kill()
        {
        suicide(owner);
        }
}

The issue I am facing is that the string argument is not getting logged in contract A's log event. why could that be happening?


texts: Does an Ethereum contract address hold two different kinds of files, one for the contract bytecode and another for the ABI?

texts: Does an Ethereum contract address hold two different kinds of file, one for the contract bytecode and another for the ABI?


texts:
From what I understand, ENS is less than one year old at the time of this post.
So, it follows that no domain has expired for any owner. No person has experience renewing the rights to their ENS domain.

Do expired domains go back into the auction like the first owner of the domain had to win in the first place? Or is there a first right for the current owner of a domain has to extend the expiration out for as many years into the future as he is willing to pay?

I am afraid to make the mistake that my free association understanding of what I imagine the process should be is not actually the case in the real world. I'm afraid to use ENS because I see no confirmation that I have a means to keep the domain after it expires. I am concerned that if I have a good domain then it is very easy to lose that domain at the expiration date.

Are there any sources available that address these concerns?


texts: If it's possible to recover a broken Ledger Nano S, how is it theft-proof?

texts: I understand that if I break/lose my Ledger Nano S, it's possible to recover it if I get a new Ledger, and using my seed combination. But then it means that any hacker can do the same, no?


texts:
I pay for goods with tokens. But after the first call to the function, tokens are not removed from the wallet. Please tell me why when I call the function for the first time, tokens are removed, but are not removed during the next calls? Thanks

function placeBid(uint amount)  public notOwner returns(bool) {
    require(auctionState == State.Running);
    require(count>=amount);
    goods[msg.sender].add(amount);
    startPrice = startPrice*100000000*amount;
    bids[msg.sender].add(startPrice);

    trc20.approve(msg.sender, address(this), startPrice);
    // Move to tokens to contract address
    trc20.transferFrom(msg.sender, address(this), startPrice);
    count = count-amount;
    startPrice=0;
    return true;
}


texts:
interface I { }

contract A is I { }

contract B is A { }

contract C is A { }

contract D is B, C { }

What would happen in this situation? How is this kind of diamond inheritance resolved in solidity? Should I be aware of any "gotchas"?


texts: How do you use Geth to send a transaction?

texts: I want to send ether from one account to another using the geth client. I don't want to wait several days or use up tens of gigs on my hard drive before doing so either. How can this be done?


texts: I'm running a node with geth, and would like to operate on the live chaindata using pyethereum. Is there a clever way to get around the lock imposed by LevelDB? Thanks!


texts: Issues during installing geth client in windows docker container

texts:
I have been trying to get a windows instance of a container with geth client installed within it. Following the link below, I have been successfully able to use chocolatey to get go, git, etc.
https://github.com/ethereum/go-ethereum/wiki/Installation-instructions-for-Windows
Particularly in the last step of the installation:

C:\Users\xxx\src\github.com\ethereum\go-ethereum> go install -v ./...

I have been seeing the following issues:

open Documents and Settings: Access is denied
open Program Data/: Access is denied
go\src\golang.org\x\net\html\charset\charset.go:20:2: cannot find package "..."
....(GOPATH)
....(GOROOT)
can't load package: package ./tools/go/test found packages...

As an alternative I tried attaching to the container and running the command manually and although I dont see the permission denied errors, the errors around finding and loading necessary packages still exist. Any suggestions would be immensely helpful


texts: Sign raw transaction offline with C++ on arduino

texts: I'm exploring the IoT side of the EVM. I've programmed Arduinos and ESP8266s to interact with a Geth JSON RPC. I'm trying to be minimalistic and avoid NodeJS on the Geth JSON server side. Currently the ESP8266 just unlocks the accounts via the Personal.sendTransaction function. I know this is poor security if someone infiltrated my wifi LAN (my Geth node is running on my wifi Router OpenWrt) I've seen examples of ethereumjs-utils being used to sign transactions offline. Is there a LIGHTWEIGHT (under 500k) C++ version of this, at least the ECDSA secp256k1 keccak256 algorithms?? Ideally the microcontroller would sign the transaction, then broadcast the the raw transaction. The only way a thief could get access to the IoT wallet would be physical access to the device, dump the flash ROM, reverse engineer the binary to extract the private key. Any suggestions?? Here is working example of ESP8266 ESP-01 pushing and pulling temperature data to the Rinkeby blockchain, the majority of the code being the JSON parsing https://github.com/gusgorman402/ESP8266_Geth


texts: What is the scope of State Variables and Storage?

texts:
I refer to this - http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html

pragma solidity ^0.4.0;

contract SimpleStorage {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function get() public constant returns (uint) {
        return storedData;
    } }

It states:

  Of course, anyone could just call set again with a different value and
  overwrite your number, but the number will still be stored in the
  history of the blockchain

I understood the state variables are stored in contract storage which is persistent. Are their previous values stored in the blockchain itself?

My question is really what happens if someone is storing db keys, and they have a lot of them in an array - thousands or millions.

How exactly would the array be stored when one element is changed? Does the historical storage hold only the changed array element and an index or is the whole array stored?

If I have say -

Student {
 uint age;
 uint studentId;
 uint studentScore;
 uint studentCourseFee;
}

Student[] public students;

Then I have 40,000 students so Student[] has 40K elements, and then I change one entry. What happens to the whole array? If I change entry 22,045 in the array (eg delete it), how does the historical storage record that and how does the new array get stored, now it is one entry shorter?

I can foresee scaling problems with am approach under any design here.


texts: Correct way to execute a function in Web3 to avoid "invalid address"?

texts:
I am executing a function with Web3 like this:

MyContract.deployed().then(function (contractInstance) {
      return contractInstance.MyFunction(parameter1, parameter2, { gas: 200000, from: web3.eth.accounts[0] })
    })

This works fine running the app on http://localhost:8080 with Chrome in incognito (so there's no MetaMask, which I have installed) - so the web3.eth.accounts[0] that executes the function will be the account I setup in Geth.

However, if I run the app in a normal Chrome window, where MetaMask will be active (thus it'll be using a different account) the following error will occur:

  Uncaught (in promise) Error: invalid address

Removing the web3.eth.accounts[0] part, so I run the function like this:

return contractInstance.SetMessage(key, string1, string2, string3, string4, { gas: 200000})

Also fails. How should this be done correctly?


texts: admin.addPeer not working on private blockchain

texts:
I'm having so much trouble getting geth to talk to a private blockchain of Parity nodes.  Here is where I am right now:

I have fired up geth with a custom data director and a genesis file that think should be a match for the Parity chain spec file.

But geth does not detect the Parity peers.  So I add them manually using the JS console.  The command returns "true" but then admin.peers shows no peers.

> admin.addPeer("enode:<string>:<port>")
true

> admin.peers
[]

Can anyone think of why this might be?


texts: How are the arguments of the constructor encoded in the contract creation transaction?

texts: The Ethereum ABI defines how arguments are encoded and passed when a method is called. But how are the arguments to the constructor encoded in the contract creation transaction which creates the smart contract?


texts: How to set values for Solidity contract state variables from JavaScript front-end?

texts:
I am trying to set values to the following contract public state variables from a frontend javascript code. But it seems not working.
Contract public state variables:
// Current state of the auction.
address public highestBidder;
uint public highestBid;

In the below Javascript code, I get the values for address and amount from UI and assign to highestBidder & highestBid. But it seems not working. How do I do this?
// Submit bid details, triggered by the "Bid" button
SimpleAuction.prototype.startAuction = function() {
    console.log("inside startAuction");
    var that = this;
    console.log("inside startAuction");
    // Gets form input values
    var address = $("#enter-address").val();
    var amount = $("#enter-amount").val();
    console.log(amount);

    // Validates address using utility function
    if (!isValidAddress(address)) {
        console.log("Invalid address");
        return;
    }
    that.highestBidder = address;

    // Validate amount using utility function
    if (!isValidAmount(amount)) {
        console.log("Invalid amount");
        return;
    }
    that.highestBid = amount;

This code fixed the issue. Passing address and amount as a transaction object in the bid() function in JS
// Submit bid details, triggered by the "Bid" button
SimpleAuction.prototype.startAuction = function() {
    console.log("inside startAuction");
    var that = this;
    console.log("inside startAuction");
    // Gets form input values
    var address = $("#enter-address").val();
    var amount = $("#enter-amount").val();
    console.log(amount);

    // Validates address using utility function
    if (!isValidAddress(address)) {
        console.log("Invalid address");
        return;
    }

    // Validate amount using utility function
    if (!isValidAmount(amount)) {
        console.log("Invalid amount");
        return;
    }

    // Calls the public `bid` function from the smart contract
    this.instance.bid(
         {
            from: address,
            value: amount,
            gas: 100000,
            gasPrice: 100000,
            gasLimit: 100000
        },

        function(error, txHash) {
            if (error) {
                console.log(error);
            }
            // If success, wait for confirmation of transaction,
            // then clear form values
            else {
                that.waitForReceipt(txHash, function(receipt) {
                    if (receipt.status) {
                        $("#enter-address").val("");
                        $("#enter-amount").val("");
                    } else {
                        console.log("error");
                    }
                });
            }
        }
    );
};


texts: What does etherscan mean by "Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)"?

texts:
I'm inspecting a contract on etherscan, at the following URL:

https://etherscan.io/address/0x5cb5f46a655c02889172323760d12d0e5d83cdaf#code

At the bottom of the web-page, I see two sections:

Contract Creation Code
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

The contents of the 2nd section is most certainly not equal to the last bytes in the 1st section.

So what exactly does it mean "the last bytes of the Contract Creation Code above"?

My ultimate goal is in fact to obtain the constructor arguments of some other contract.

However, when I inspect this contract on etherscan, the 2nd section does not appear at all.

So I was hoping I could somehow extract it from the 1st section, but I cannot figure out the relation between them (if any).

The other contract can be inspected on etherscan at the following URL:

https://etherscan.io/address/0x5248e5fd5d3b43126e5352807f75d6a7d6d7eafb#code

Thank you!


texts: How to easily share Solidity code so that others can test it?

texts:
Say you have some Solidity code and something doesn't work and you'd like for somebody to take a look at it and do some quick tests.

What is an efficient way to share Solidity code with others?


texts:
I'm trying to make a contract which will check if there is already some data in mapping. If so, it will then replace the old data with the new. If not - insert new record. Sounds easy, but im learning and spent hours triyng to find a solution. How can I do that?

function MyToken() public
{

}

struct DATA
{
    uint Id;
    uint Date;
}

mapping (uint => DATA) public data;
uint public total = 0;

function add(uint Id, uint Date) public returns (uint)
{
    if(data[Id].Id == 0) // Checking if there is some records with this ID
    {
        data[total] = DATA(Id, Date);
        total++;
        return total;
    }
    else // If some data found - replace it with new
    {
        data[Id].Date = Date;
    }
}

For some reason this code just insert new records. I need to have it changing old data.


texts: Switching from 'storage' to 'memory' increases the gas-cost

texts:
I've read several related answers and blog posts, all of them suggesting that for the sake of reading complex state variables (i.e., arrays and structures), one should always prefer declaring the local variable used for this purpose as memory rather than as storage:

Ethereum SE Answer #1
Ethereum SE Answer #2
Ethereum SE Answer #3
Blog Post

I've conducted several tests, performing let response = await someTransaction() and then recording the value of response.receipt.gasUsed. All of these tests have unanimously shown that declaring the local variable as memory yields a higher gas-consumption than declaring it as storage.

Here is a very simple Truffle test which illustrates this:

Contract:

pragma solidity 0.4.25;

contract MyContract {
    struct Record {
        bool valid;
        uint val1;
        uint val2;
        uint val3;
    }

    mapping(uint => Record) public table;

    uint public count;

    function insert(uint key, uint val1, uint val2, uint val3) external {
        Record storage record = table[key];
        if (record.valid == false) {
            record.valid = true;
            record.val1 = val1;
            record.val2 = val2;
            record.val3 = val3;
            count += 1;
        }
    }

    function storage_remove(uint[] keys) external {
        for (uint i = 0; i < keys.length; i++) {
            Record storage record = table[keys[i]];
            if (record.valid == true) {
                delete table[keys[i]];
                count -= 1;
            }
        }
    }

    function memory_remove(uint[] keys) external {
        for (uint i = 0; i < keys.length; i++) {
            Record memory record = table[keys[i]];
            if (record.valid == true) {
                delete table[keys[i]];
                count -= 1;
            }
        }
    }
}

Test:

contract("MyContractTest", function() {
    const keys = [...Array(10).keys()];

    it("storage_remove gas consumption", async function() {
        const myContract = await artifacts.require("MyContract").new();
        for (let key of keys)
            await myContract.insert(key, key, key, key);
        const response = await myContract.storage_remove(keys);
        console.log(response.receipt.gasUsed);
    });

    it("memory_remove gas consumption", async function() {
        const myContract = await artifacts.require("MyContract").new();
        for (let key of keys)
            await myContract.insert(key, key, key, key);
        const response = await myContract.memory_remove(keys);
        console.log(response.receipt.gasUsed);
    });
});

Results:

Contract: MyContractTest storage_remove gas consumption: 142257
Contract: MyContractTest memory_remove gas consumption: 145976

Side Note:

The above is essentially a comparison between:

The gas cost of reading record.valid using storage record
The gas cost of reading record.valid using memory record

So what course of action should I take - use memory as suggested everywhere, or use storage which has proved to be less expensive?

Thank you!


texts: Does a DAO protect real inventors from Patent trolls?

texts:
The DAO is a Decentralized Autonomous Organization” (DAO); it can be defined as:-

a fully automated business entity (FAB), or distributed autonomous corporation/company (DAC) is a decentralized network of narrow-AI autonomous agents..  Source

Vitalik Buterin coined the term  DAOism, these may comprise;-

Autonomous Agents
Decentralized Applications
Decentralized Organizations
Decentralized Autonomous Organizations

"a DAO contains some kind of internal property that is valuable in some way, and it has the ability to use that property as a mechanism for rewarding certain activities." Buterin

Scenario A
an inventor develops an opensource project / idea / software  / process
many people deploy/ enact / build upon said process / idea
patent trolls jump into patent with said idea
meanwhile the DAO chugs along happily..

Alas this is not a hypothesis ..if one looks at the tip of the iceberg patent applications from legacy financial organisations like;-

Goldman Sachs
Bank of America
Coinplug (select Patents, enter Coinplug, wait 8000/12000 m/sec)

or indeed patent trends within fintech space the idea of patenting Fintech ideas is not simply an opinion it is already a reality.

In the context of the above is it accurate to say that it  will be impossible to sue / prevent a DAO from operating simply / primarily because it operates in the ether and does not exist in the physical realm?


texts: how to get erc20 token balance using web3

texts:
I am still new with web3

How can I get balance of token?

On ropsten network, I have 100 LINK token.

Below is my code

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

let tokenAddress = "0x20fe562d797a42dcb3399062ae9546cd06f63280";
let walletAddress = "0xdD440e8eCA5F1F3e6D5ffE903148EFB374942df2";

// The minimum ABI to get ERC20 Token balance
let minABI = [
  // balanceOf
  {
    "constant":true,
    "inputs":[{"name":"_owner","type":"address"}],
    "name":"balanceOf",
    "outputs":[{"name":"balance","type":"uint256"}],
    "type":"function"
  },
  // decimals
  {
    "constant":true,
    "inputs":[],
    "name":"decimals",
    "outputs":[{"name":"","type":"uint8"}],
    "type":"function"
  }
];

let contract = new web3.eth.Contract(minABI,tokenAddress);
async function getBalance() {
  balance = await contract.methods.balanceOf(walletAddress);
  return balance;
}

console.log(getBalance());

The code return:

Promise { <pending> }

based on my search on google, this promise pending should be solved by using async function but in my case, it still showing promise pending.

I am using latest node 14 and web3.js 1.26


texts: I'm new to smart contracts. is it possible to credit ethereum addresses with ERC20 tokens? basically "write" the balance instead of airdropping them via transactions. asking because gas-fees are so high


texts: Mapping multiple structs to a struct and call them

texts:
I have a question about how I should design my contract to achieve the following: I want to create products identifiers (can be struct or string) something like: "product#123abc". Then I want to map a struct to it (in my case this struct holds location information)
Example:

struct Location {
    string city;
    string street;
    uint time;}

And finally I want to map multiple different location structs to my product so that I can call it like this:

function viewLocation(uint _productID, uint _location) public returns(struct){
    return Product[_productID].Location[_location].city;
}

Would it also be possible to just call the productID and show me all mapped locations to it? Something like this:

function viewLocation(uint _productID) public returns(array){
    return Product[_productID].Location;
}

If it doesn't work like I think about it, how would a workaround look like?
I hope you can help me :)


texts:
I want to use web3.eth.sign to create a signature that will be stored in blockchain and verified later by a contract (with ecrecover). I'd like to use as few libraries as possible.

Web3 docs specify that to use web3.eth.sign a public key should be provided and account should be unlocked.

can I unlock an account without running an ethereum node?
I know private key for this account, can I create signature using private key instead of public key and without unlocking? Seems like it can be done with a help of secp256k1 package, but is this doable with web3 alone?


texts:
I am using this repo to begin testing UniSwap flash swap contracts. I've installed all dependencies correctly and cleanly.
The project uses ganache-cli, hardhat buidler, and yarn in the terminal and I can use all 3 methods to start up a local chain and I get a different error message with all three. If I use:
ganache-cli -f - Error: VM Exception while processing transaction: revert
buidler node - Error: Transaction reverted: function call to a non-contract account
yarn start-chain - Error: VM Exception while processing transaction: revert UniswapV2: LOCKED
The repo states to use yarn start-chain so I think that's the one to focus on.
This is what I see in Terminal
All contracts have already been compiled, skipping compilation.

  Example

Setting up signer...
  signer: 0x8199Bcbd047e404d6c192969590CB7fCc0CCe2f0

Deploying example contract...
  example contract: 0xEA645fB4c45c22E2E75eD2ABB1fAD9525A7329f8

Testing swap - borrows 1 ETH, paying with ETH

Ensuring that contract can cover fees...
  contract ETH balance 0
  contract will not be able to cover fee, sending from signer...
  signer ETH balance 19228617140000000000
  new contract ETH balance 0

Performing flash swap...
    1) successfully flash swaps

  0 passing (2s)
  1 failing

  1) Example
       successfully flash swaps:
     Error: VM Exception while processing transaction: revert UniswapV2: LOCKED
      at HttpProvider.send (node_modules/@nomiclabs/buidler/src/internal/core/providers/http.ts:36:34)
      at wrapper_1.wrapSend (node_modules/@nomiclabs/buidler/src/internal/core/providers/accounts.ts:219:21)
      at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12)
      at wrapper_1.wrapSend (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:23:21)
      at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12)
      at wrapper_1.wrapSend (node_modules/@nomiclabs/buidler/src/internal/core/providers/gas-providers.ts:41:21)
      at Proxy.cloningSendWrapper (node_modules/@nomiclabs/buidler/src/internal/core/providers/wrapper.ts:9:12)
      at EthersProviderWrapper.send (node_modules/@nomiclabs/buidler-ethers/src/ethers-provider-wrapper.ts:13:48)
      at /Users/justinsacco/TESTcointaker1/uniswap-flash-swapper/node_modules/@ethersproject/providers/lib/json-rpc-provider.js:164:35
      at process._tickCallback (internal/process/next_tick.js:68:7)

Any ideas what might be causing this?


texts: Does installing geth download the entire blockchain?

texts: If I install geth, will it download the entire blockchain?


texts:
I'm trying to make a proxy to make a contract that I can change for an ethereum project. I did what it says here: https://hackernoon.com/how-to-make-smart-contracts-upgradable-2612e771d5a2 but it doesn't work. I looked everywhere I could on the internet but I couldn't find a solution. Here is my code:
pragma solidity ^0.4.23;

contract StorageStructure {
    address public implementation;
    address public owner;
    mapping (address => uint) internal points;
    uint internal totalPlayers;
}

contract ImplementationV1 is StorageStructure {

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

    function addPlayer(address _player, uint _points)
        public onlyOwner
    {
        require (points[_player] == 0);
        points[_player] = _points;
    }

    function setPoints(address _player, uint _points)
        public onlyOwner
    {
        require (points[_player] != 0);
        points[_player] = _points;
    }
}

contract Proxy is StorageStructure {

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

    /**
     * @dev constructor that sets the owner address
     */
    constructor() public {
        owner = msg.sender;
    }

    /**
     * @dev Upgrades the implementation address
     * @param _newImplementation address of the new implementation
     */
    function upgradeTo(address _newImplementation)
        external onlyOwner
    {
        require(implementation != _newImplementation);
        _setImplementation(_newImplementation);
    }

    /**
     * @dev Fallback function allowing to perform a delegatecall
     * to the given implementation. This function will return
     * whatever the implementation call returns
     */
    function () payable public {
        address impl = implementation;
        require(impl != address(0));
        assembly {
            let ptr := mload(0x40)
            calldatacopy(ptr, 0, calldatasize)
            let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0)
            let size := returndatasize
            returndatacopy(ptr, 0, size)

            switch result
            case 0 { revert(ptr, size) }
            default { return(ptr, size) }
        }
    }

    /**
     * @dev Sets the address of the current implementation
     * @param _newImp address of the new implementation
     */
    function _setImplementation(address _newImp) internal {
        implementation = _newImp;
    }
}

I'm on IDE remix, I compile and deploy my three contracts, I enter the ImplementationV1 contract address, found with getContractAddress() in the upgradeTo() function of the Proxy to upgrade it. Then, I copy the data from the SetPoint function to put it in the CALLDATA of the Proxy. I put for example ten but when I look at GetPoint, I still don't have the number 10. Thank you for your help.


texts: Block timestamp or block number as short time check

texts: Which one is better to check short period of time change 60seconds block.timestamp or block.number?


texts: How to see that a constant method threw an exception?

texts:
Consider this contract

pragma solidity ^0.4.11;

contract GoodAndBad {

  function exec(uint flag) public constant returns (uint) {
    assert(flag == 1);
    return 0;
  }

}

How do I know that calling method exec() using web3.js or geth JSON RPC was successful and I received a number?

If it is not possible what is the best practice for the methods like above?


texts: Can someone help me take a look at this smart contract

texts:
I keep getting a transaction revert error when i call the startSwap function. Please what am i doing wrong?
error
Warning! Error encountered during contract execution [execution reverted]
code

pragma solidity =0.6.6;

import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Callee.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Router01.sol';
import './interfaces/IERC20.sol';
import './libraries/UniswapV2Library.sol';
import './interfaces/IPancakeCallee.sol';

contract FlashSwap is IPancakeCallee {

    address factory;
    IUniswapV2Router01 router;
    uint deadline;

    function startSwap (address _factory, address _router, address _token0, address _token1, uint _amountToken0, uint _amountToken1,  uint _deadline) external {
        factory = _factory;
        router =  IUniswapV2Router01(_router);
        deadline = _deadline;
        address pairAddress = IUniswapV2Factory(factory).getPair(_token0, _token1);

        IUniswapV2Pair(pairAddress).swap(
            _amountToken0,
            _amountToken1,
            address(this),
            bytes('not empty')
        );

    }

    function pancakeCall(address sender, uint amount0, uint amount1, bytes calldata data) external override {

        address[] memory path = new address[](2);
        uint amountToken = amount0 == 0 ? amount1 : amount0;

        address token0 = IUniswapV2Pair(msg.sender).token0();
        address token1 = IUniswapV2Pair(msg.sender).token1();

        assert(msg.sender == UniswapV2Library.pairFor(factory, token0, token1)); // ensure that msg.sender is actually a V2 pair
        assert(amount0 == 0 || amount1 == 0); // this strategy is unidirectional

        path[0] = amount0 == 0 ? token1 : token0;
        path[1] = amount0 == 0 ? token0 : token1;

        IERC20 token = IERC20( amount0 == 0 ? token1 : token0 );
        IERC20 otherToken = IERC20( amount0 == 0 ? token0 : token1);

        token.approve(address(router), amountToken);

        uint amountRequired = UniswapV2Library.getAmountsOut(
            factory,
            amountToken,
            path
        )[1];

        uint amountReceived = router.swapExactTokensForTokens(
            amountToken,
            amountRequired,
            path,
            address(this),
            deadline
        )[1];

        require(amountReceived > amountRequired, 'amountReceived < amountRequired');

        otherToken.transfer(msg.sender, amountRequired);
        otherToken.transfer(tx.origin, amountReceived - amountRequired);
    }

}```


texts: Can someone please explain this to me? I tried to mint a NFT. I changed the gas price to low and gas price limit to 32000. It showed me 8 dollars something I minted the NFT. But it shows nothing in my creators page or profile page. And the 8 eth has also been deducted from my wallet. https://etherscan.io/tx/0x515a0c9acfe8605ef051546de9fd348bdfec72e413dc432fea0a56cc5167e084


texts: Do I need a Linux VPS to start interacting with smart contracts?

texts:
I have only none to basic information about hosting with a VPS.
I would like to deploy a smart contract and build a website to interact with the contract. Normally I use shared hosting which is very easy to install and use.
But now my question is:
Do I need to rent a Linux VPS and install web3 and an ethereum client on it to interact with my contract? Or could I even use a shared hosting offer, as I want to use MetaMask as a verifier?
Thank you for information.


texts:
How to setup a ethereum testnet node locally?

I am new to ethereum please some one help sharing step by step links


texts: my python event listener create duplicates in case of multiple event in one transaction

texts:
I have an issue to manage with my listener in python, here is my code :
def handle_event(event, log_index):
    receipt = w3.eth.waitForTransactionReceipt(event['transactionHash'])

    contract_events = [contract.events._BlockOnSale, contract.events._BlockPurchased]

    for contract_event in contract_events:
        result_event = contract_event().processReceipt(receipt)
        for result in result_event:
            result_request = switcher[result['event']](result['args'], event['blockNumber'])
            print(result_request)

def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event, event['logIndex'])
        time.sleep(poll_interval)

my issue is that, if there is 2 transactions in the same block, I can have duplicate. I mean :
in the event_filter.get_new_entries(), I have two entries with exact same transaction hash, but logIndex is different. So I have 2 loop in my log_loop function.
the issue is that the line :
receipt = w3.eth.waitForTransactionReceipt(event['transactionHash'])

is getting the two event in one shot because the transactionHash is the same.
So is there a way to properly manage this issue ?
In a first point I do that :
def handle_event(event, log_index):
    receipt = w3.eth.waitForTransactionReceipt(event['transactionHash'])

    contract_events = [contract.events._BlockOnSale, contract.events._BlockPurchased]

    for contract_event in contract_events:
        result_event = contract_event().processReceipt(receipt)
        for result in result_event:
            if result['logIndex'] == log_index:
                result_request = switcher[result['event']](result['args'], event['blockNumber'])
                 print(result_request)

to process only the event with the good logIndex, but it is not acceptable : If I have 60 event in the same block, I will do a loop of 60x60 just to parse 60 event.
So in the receipt, is there a way to get the event by transactionHash AND logIndex?
or in the get_new_entries, if the transactionHash is the same, to have only 1 entries ?
I want to stop having a lot of duplicate event to manage
Thanks


texts: ethereum javascript webpack smart contract

texts:
I'm trying to send the value from html dropdown to the smart contract, the value is extracted from the js function but I'm not able to add it to SetVote function, the execution breaks there.

Html:

            <button class="btn btn-vote btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              Dropdown button
            </button>

              value1
              value2
              value3

JavaScript:

 App = {   web3Provider: null,   contracts: {},

  init: function() {

    console.log("inside init");

    return App.initWeb3();   },

  initWeb3: function() {

    console.log("inside initWeb3");

    // Is there an injected web3 instance? if (typeof web3 !== 'undefined') {   App.web3Provider = web3.currentProvider; } else {   // If no injected web3 instance is detected, fall back to Ganache   App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:9545'); } web3 = new Web3(App.web3Provider);

    return App.initContract();   },

  initContract: function() {

    console.log("inside initContract");

    $.getJSON('voting.json', function(data) {
      // Get the necessary contract artifact file and instantiate it with truffle-contract
      var votingArtifact = data;
      App.contracts.voting = TruffleContract(votingArtifact);

      // Set the provider for our contract
      App.contracts.voting.setProvider(App.web3Provider);

      // Use our contract to retrieve and mark the adopted pets
     // return App.markAdopted();
    });

    return App.bindEvents();   },

bindEvents: function() {

  $(document).on('click', '.btn-res', App.GetVote);

 //$(document).on('click', '.btn-vote', App.SetVote);

 $(".dropdown-menu a").click(function(){var vote = $(this).text(); });
   console.log("voted value",vote);
   App.SetVote(vote);

         },

SetVote: function(account) {

  var votingInstance;
  //var vote="voteValue"

  App.contracts.voting.deployed().then(function(instance) {

    votingInstance = instance;

    return votingInstance.setVote(vote);   }).then(function() {

    // modal for successfully voting
    // open index page

  }).catch(function(e) {
    console.log("error in voting");   });

},

GetVote: function() {

   web3.eth.getAccounts(function(error, accounts) {
    if (error) {
      console.log(error);
    }

    var account = accounts[0];

    var self = this;

    var data;
    voting.deployed().then(function(instance) {
      data = instance;
      return data.getVote.call();
    }).then(function(value) {

      console.log(value);

      //table of winners
     //list of voters

    }).catch(function(e) {
      console.log(e);
      self.setStatus("Error getting balance; see log.");
    }); }); } }; $(function() {   $(window).load(function() {
    App.init();   }); });


texts: Loading truffle library in remix browser IDE

texts:
Besides writing smart contracts in the browser, I would also like to write my test in this IDE. Any suggestions how to load the truffle files in http://remix.ethereum.org?

I appreciate your help!


texts:
Ok, this has been asked before, but there was no solution. I am trying to add some token contracts to my MetaMask, but they simply do not show up. I am using the Chrome extension.

However, this issue happens only on my laptop. I also have a MetaMask wallet on my desktop PC for Firefox and it works just fine.

Is there something wrong with the laptop/Chrome extension? I had been able to add tokens just fine up until 1 month ago or so.

Thank you.


texts: Invalid block XX: unknown ancestor while restoring the chain - private blockchain

texts:
I'm trying to restore blockchain using import a rlp file
geth import backup.rlp

It show an error

Is there any way to exclude the bad blocks while exporting the chain data?
Also, if the gcmode is archive then only can get past data of smart contract state?
Geth version: 1.8.16


texts: Is address.send(1) an alias for address.call.value(1).gas(2300)()?

texts:
As I understand it, these two statements do exactly the same thing and they can be used interchangeable in the code. Is their bytecode identical?

address.send(1)
address.call.value(1).gas(2300)()


texts: Smart contracts execution without money exchange

texts:
Most of the examples that I see on smart contract, involves ether being transferred to someone as part of the transaction. My question is, if my smart contract is just doing X++, where X is some counter, then

What would be the transaction that will be sent out to miners to be included in the block as there is no transfer of ethers.
The gas fee to execute the transaction by the user of the smart contract, is it allocated to the miner who mined the transaction?
IF all the rest of the nodes, that verify the block also have to run the smart contracts, wouldnt they be wasting their resource but doing equal amount of work as the miner did? (minus the proof of stake).


texts: Access modifiers for properties of a struct

texts:
I am relatively new to Solidity. I am following a tutorial and came up with the following contract:

contract Election {
  struct Candidate {
    uint id;
    string name;
    uint voteCount;
  }

  mapping (uint => Candidate) public candidates;
  // keep a counter to track the number of candidates
  uint public candidatesCount;

  constructor () public {
    addCandidate("Candidate 1");
    addCandidate("Candidate 2");
  }

  function addCandidate (string memory _name) private {
    candidatesCount++;
    candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
  }

}

I am using Truffle for development. Now, once the contract is deployed locally, I am running these on the truffle console:

> Election.deployed().then(instance => app = instance)
> app.candidates(1).then(res => candidate1 = res)

So basically I am getting an instance of a Candidate from candidates to candidate1. Now, when I am assigning the voteCount property of candidate1 from the console like this:

> candidate1.voteCount = 100

To my surprise the voteCount is actually set to 100. I assumed the properties of a struct to be private. I tried adding the private access modifier to the struct properties but it is throwing errors.

What is the valid/correct way to add access modifiers to the struct so that the voteCount property cannot be set without a setter?


texts: Executing the Truffle console script:Error: ENOENT: no such file or directory,

texts:
I am trying to execute the following script:
module.exports = (callback)=> {
  Message.setProvider(web3.currentProvider);
const MyContract = require("~/Truffle programs/script_transfer_Eth_thr_Truffle/contracts/MyContract");
const MyContractTester = artifacts.require("~/Truffle programs/script_transfer_Eth_thr_Truffle/contracts/MyContractTester");
var acc1 = accounts[1]
var acc2 = accounts[2]
const myC = await MyContract.deployed()
const myCT = await MyContractTester.deployed()
web3.eth.sendTransaction({to:myC.address, from:acc2, value: web3.utils.toWei('11')})
myC.sendTo(myCT.address, web3.utils.toWei('3',"ether"), {from:accounts[0]})
myCbal = await web3.eth.getBalance(myC.address)
web3.utils.fromWei(myCbal, "ether")

My script is located at:
zulfi@lc2530hz:~/Truffle programs/script_transfer_Eth_thr_Truffle$ pwd
/home/zulfi/Truffle programs/script_transfer_Eth_thr_Truffle
zulfi@lc2530hz:~/Truffle programs/script_transfer_Eth_thr_Truffle$ ls my*
myscript.js

When I am executing the script on the truffle console, I am getting the following error:
truffle(development)> truffle exec myscipt.js
Using network 'development'.

Error: ENOENT: no such file or directory, open '/home/zulfi/Truffle programs/script_transfer_Eth_thr_Truffle/myscipt.js'
    at Object.openSync (fs.js:443:3)
    at Object.readFileSync (fs.js:343:35)
    at Object.file (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/require/require.js:28:1)
    at Object.exec (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/require/require.js:121:1)
    at Promise (internal/util.js:274:30)
    at new Promise (<anonymous>)
    at bound exec (internal/util.js:273:12)
    at Object.run (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/exec.js:80:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)

truffle(development)>

Somebody please guide me.
Zulfi.


texts: Is there a need to remove entries from mapping?

texts:
I am adding approximately 3 ~ 5 new entries into the mapping, while the old one will be obsolete after a week.

If the mapping grow larger, is it going to consume more gasses?

Is there a need for me to remove them since they are no longer needed.


texts:
geth comand

geth --rpc --rpcapi db,eth,net,web3,personal

Truffle.js

module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},
live: {
network_id: 1,
host: "127.0.0.1",
port: 8545, // Different than the default below
from: "address",
gas: 4612388
}
}
};

Truffle MIgration:

truffle migrate --network live
Using network 'live'.

Running migration: 1_initial_migration.js
Deploying Migrations...
... undefined
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: exceeds block gas limit
at Object.InvalidResponse (/usr/lib/node_modules/truffle/build/cli.bundled.js:43303:16)
at /usr/lib/node_modules/truffle/build/cli.bundled.js:331156:36
at /usr/lib/node_modules/truffle/build/cli.bundled.js:175492:11
at /usr/lib/node_modules/truffle/build/cli.bundled.js:314196:9
at XMLHttpRequest.request.onreadystatechange (/usr/lib/node_modules/truffle/build/cli.bundled.js:315621:13)
at XMLHttpRequestEventTarget.dispatchEvent (/usr/lib/node_modules/truffle/build/cli.bundled.js:70159:18)
at XMLHttpRequest._setReadyState (/usr/lib/node_modules/truffle/build/cli.bundled.js:70449:12)
at XMLHttpRequest._onHttpResponseEnd (/usr/lib/node_modules/truffle/build/cli.bundled.js:70604:12)
at IncomingMessage. (/usr/lib/node_modules/truffle/build/cli.bundled.js:70564:24)
at emitNone (events.js:91:20)

OS: Ubuntu 16.04
Node: 6.2
npm: 3.10
Contract is being deployed easily on testrpc and rinkeby only problem is publishing it on live network.
git hub error link.
https://github.com/trufflesuite/truffle/issues/773


texts:
EDIT #2: I believe this actually may be a non-issue after all. Am I wrong to believe that the DTH will use a contract to withdraw the ETC and in order to avoid duplication of addresses on both ETC and ETH chain that it would have to be withdrawn to an entirely new address on the ETC chain? Therefore, all I would need to do is decrypt my address using my password - similar to the ETH withdrawn from the DAO, but this time, there will be added functionality to send it to a particular address, instead of the address where the DAO tokens were purchased and held?

EDIT: I'm happy to donate 10% of my ETC holdings that is released from the DAO if you can help me release the funds. That 10% would be somewhere around 345-360 ETC. My plan is to cash out immediately and convert to ETH.

I decided to "clean" up any unused addresses that displayed within my Mist Wallet and ended up deleting an address that I used for the DAO. On August 30th ETC will be able to be retrieved for DTHs, is it possible for me to get this wallet address back in Mist?

To clarify, I do not have a backup of the key file anywhere. I do however know the address and the type in password that I used to create the address via Mist.

Also, I've done this several weeks ago and do not believe I have windows recovery going back that far.

Thanks in advance!


texts: Calling function from existing truffle contract in node.js

texts:
This is probably a very simple problem to solve, but I am setting up a node.js backend using express for my Dapp and I can now deploy new contracts just fine.

I now need to figure out how to make calls to a function in an existing contract (created previously in Remix). I have the following syntax for setting up the provider. This works, at least for creating a new Insurer:

const Web3 = require("web3");
const HDWalletProvider = require("@truffle/hdwallet-provider");

require('dotenv').config();
const provider = new HDWalletProvider(process.env.MNEMONIC, process.env.INFURA_URL);

var contract    = require("@truffle/contract");

const insurerArtifacts = require('./build/contracts/Insurer.json');
var myInsurerContract = contract(insurerArtifacts);
myInsurerContract.setProvider(provider);

const platformArtifacts = require('./build/contracts/Platform.json');
var myPlatformContract = contract(platformArtifacts);
myPlatformContract.setProvider(provider);

The function call I make is as follows:

var insurerAddress = '0x...';
var myClientUIC = req.body.clientUIC;
var myClientName = req.body.clientName;
var myClientGroup = req.body.clientGroup;
var myClientNACE = req.body.clientNACE;
var myCreditLine = parseInt(req.body.creditLine);
var myCreditLineDate = parseInt(req.body.creditLineDate);
var myClientCurrency = req.body.clientCurrency;
var myClientCity = req.body.clientCity;
var myClientCountry = req.body.clientCountry;

myPlatformContract.at("0x...").methods.createClient(myClientUIC, myClientName, myClientGroup,
    myClientNACE, insurerAddress, myCreditLine, myCreditLineDate, myClientCurrency, myClientCity, myClientCountry,
    { from:provider.getAddress() })
    .once('transactionHash', function(hash) {
        console.log("TxHash: " + hash);
    }).on('receipt', function(receipt) { console.log("receipt: " + JSON.stringify(receipt)); })
        .then(function(result) {
    }, function(error) {
        console.log(error);
    });

The error I get is:

TypeError: Cannot read property 'createClient' of undefined

However, createClient is a function and I have checked that all the parameters have values. Does createClient itself need to be called differently?

I would appreciate any help you an give me with this beginner's issue! Many thanks. Phil


texts: Is there any major difference between Truffle's Ganache and TestRPC? Do they run irrespective of each other as test blockchains, are there any side effects running both at same time? Is the only improvement that Ganache has a more handy ui?


texts:
Is it possible to get personal information of a person using his ETH wallet address?

I did sell my ETH to one person, due to a technical glitch, multiple ETH transaction happened without my confirmation. Now, the company is asking me to give back their ethereum. Duplication happened while sending ETH to another person, is it possible to get that person's personal information using ETH address? or with any legal ways?


texts: I can't able to understand the following function in the solidity

texts:
function multiowned(address[] _owners, uint _required) {
    m_numOwners = _owners.length + 1;
    m_owners[1] = uint(msg.sender);
    m_ownerIndex[uint(msg.sender)] = 1;
    for (uint i = 0; i < _owners.length; ++i)
    {
        m_owners[2 + i] = uint(_owners[i]);
        m_ownerIndex[uint(_owners[i])] = 2 + i;
    }
    m_required = _required;
}

Can anyone help me understand the above solidity code and use of    m_owners[1] = uint(msg.sender); ?

Source code here https://github.com/ConsenSys/MultiSigWallet/blob/master/MultiSigWalletWithDailyLimit.sol


texts: If one was to build a web app, and an iOS/Android app that are designed to run as one (iOS/Android on the phone and web app on the PC), like how facebook works, can both apps interact with ethereum, to provide blockchain technology no matter what device a user is interacting with the app on?


texts: How to generate Private key, public key and address

texts:
I can't find any documentation online about doing this in Javascript other than this.

I want to know how does authentication work in a ethereum dApp's.. As per my understanding user seed somehow gets generated into a private key, then using  that private key to derive the public key and from that you derive the address.. does anyone have any further information on how this achieved with javascript or what is the architecture for this kind of setup.. any help on understanding it would be great.

i know how to generate the seed phrase etc with the js bip39 library after that im a bit stuck.

this is basically what i am attempting so far:

    const mnemonic = "vacant element sleep harsh stick else salt great kitten clutch salad subway"
    const privateKey = new Buffer( mnemonic )
    const publicKey = ethUtil.privateToPublic(privateKey).toString('hex')
    const address = ethUtil.privateToAddress(privateKey).toString('hex')


texts: How to use gas price for faster transaction in erc20 transafer event?

texts:
I'm trying to provide a customised gas price for faster transaction ,how can achieve that ?

Web3j web3 = Web3j.build(new HttpService("http://"));
    ERC20 javaToken = ERC20.load(contractAddress, web3, creds, new DefaultGasProvider());
    TransactionReceipt receipt = javaToken.transfer("0x6D594E3C913059e3AB2b3CEAc37b3050c689Da10", value).send();


texts: ping / pong pattern for infura websocket

texts:
Infura websockets disconnect after an hour of in-activity so they suggest you ping / pong the connection at an interval less then an hour.

My problem is I'm new to server-side programming and don't know how to ping the websocket connection from my back-end (node.js).

When googling I found this framework of code (below). Is this what I'd put in my back-end to 'ping' the connection?

I'm unclear if the conditional socket.readyState !== 1 is universal/'the norm' for all websockets in JS. Same with socket.send("heartbeat"). If it is then I assume it would work for Infura as well.

If anyone already has a ping pattern set-up I'd love to hear your insight!

let socket = null;

function connect_socket() {
  socket = new WebSocket(ws_url);
  socket.on("close", connect_socket); // <- rise from your grave!
  heartbeat();
}

function heartbeat() {
  if (!socket) return;
  if (socket.readyState !== 1) return;
  socket.send("heartbeat");
  setTimeout(heartbeat, 550000);
}

connect_socket();

Thanks for any help!


texts: msg.sender.balance showing incorrect amount

texts:
I've written a smart contract that should return the balance of the current user using it and for some reason when I call the function it's returning the incorrect amount. I've used Remix and the Ropsten network for development/testing this.
  function getBalance() public view returns (uint){
    return msg.sender.balance;
  }

I am seeing 115792089237316195423570985008687907853269984665640564039457581007913129639935 as the result even though I have 0.35 ETH in my Ropsten wallet
Anybody know why this is happening?


texts: How to generate the full list of function selectors for a contract?

texts:
A contract has many functions and how to automatically generate the full selector list, including inherited functions, for the whole contract?

Preferred solution shouldn’t require more than a web browser.


texts: How to get events on android with infura?

texts:
I am developing an app on Android, but Web3j does not support events on infura ( Should I use Infura with Web3j for Event filter? ) .

What are the options, I did not find any alternative library?


texts: Python creat payment and send it with private key

texts:
I am thinking/trying to create payment system. Just to learn more about crypto.
I would like to generate public and private key. And send(broadcast) payment into the eth network using python.
How should I do it?
Btw. Thanks for any help and info.


texts: truffle deploy: Network state unknown when geth is synced

texts:
eth.syncing false eth.blockNumber 5199029
truffle deploy --network=live
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

I understand I need to add funds to my wallet. But why "network state unknown"?

Yes I ran with RPC. I first got an error that the account was locked so I unlocked it.

Reran the truffle deploy --network=live command and still got "network state unknown"

~/truffle version
Truffle v4.1.3 (core: 4.1.3)
Solidity v0.4.19 (solc-js)
~/geth version
Geth
Version: 1.8.2-stable
Architecture: amd64
Protocol Versions: [63 62]
Network Id: 1
Go Version: go1.10
Operating System: darwin
GOPATH=/Users/quantum/code/go
GOROOT=/usr/local/Cellar/go/1.10/libexec
~/


texts: Synchronisation failed on private ethereum network

texts:
I created a private network using go-ethereum with 2 clien which are VMs(ubuntu 14.04).

On VM1 (IP:192.168.217.131):,my command to create  private network:

 ./geth --genesis private.json --port "50301" --networkid 1234 --datadir /home/user/Documents/genesisdata  console

On VM2 (IP:192.168.217.132):,my command to create my private network:

./geth --genesis private.json --port "50302" --networkid 1234 --datadir /home/user/Documents/genesisdata  console

Where private.json  is the same and has content below:

{
  "nonce": "0x0000000000000042",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "difficulty": "0x4000",
    "alloc": {
     "0xcef9d7c780ab257c563e9ece3d28a176d6ce86c5": {
    "balance": "10000000000000000000"},
  "0x25eda5d755638ff6c8b433c20364f0c8b5a5684a": {
    "balance": "20000000000000000000"}},
    "coinbase": "0x0000000000000000000000000000000000000000",
    "timestamp": "0x00",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "Custem Ethereum Genesis Block",
    "gasLimit": "0xffffffff"
}

0x25eda5d755638ff6c8b433c20364f0c8b5a5684a is an account I created on VM1,and I import some ether to it by above "alloc".

After Created and join to private network, I tried add peer by admin.addPeer, and check again by admin.peers. Everything is ok, I can see the other clients from any VMs.

Also on VM1, I'm continue to create a simple contract and start to mining by miner.start(1). After mined, i check and see that my new contract work very well.

But on VM2, I receive this message:

I0715 06:49:16.089919 eth/downloader/downloader.go:299] Synchronisation failed: block time is in the future: BlockFutureErr, 1469151037 > 1468540186
I0715 06:49:26.090252 eth/downloader/downloader.go:299] Synchronisation failed: block time is in the future: BlockFutureErr, 1469151037 > 1468540196
I0715 06:49:36.085763 eth/downloader/downloader.go:299] Synchronisation failed: block time is in the future: BlockFutureErr, 1469151037 > 1468540206
I0715 06:49:46.089321 eth/downloader/downloader.go:299] Synchronisation failed: block time is in the future: BlockFutureErr, 1469151037 > 1468540216
I0715 06:49:56.076320 eth/downloader/downloader.go:299] Synchronisation failed: block time is in the future: BlockFutureErr, 1469151037 > 1468540226

I tried to find a solution to solve "Synchronisation failed" issue. But I don't know what is the reason and how to solve it.

May be the configuration of my private network has problems or the other?

Please give me the suggestion or solution to solve it.
Thank in advance.


texts: Where is truffle IDE after installation?

texts: I have installed truffle using npm install -g truffle (windows), however I cannot find truffle IDE editor.


texts: Can i mine with ATI Mobility Radeon HD 5400 Series GPU?

texts: i have ATI Mobility Radeon HD 5400 Series integrated gpu in my laptop can i use it for mining ?


texts: How to make synchronous web3.js function calls?

texts:
I am using the web3.js library directly in HTML, not via Node.js to interact with my local geth node. The following code gives me an error (web3.min.js:2 Uncaught TypeError: e is not a function) when running in a minimal test website in Chrome:

document.getElementById("output").innerText = "block number: " + web3.eth.getBlockNumber();

Instead, I have to go via an asynchronous call:

web3.eth.getBlockNumber(function(err, res){document.getElementById("output").innerText = "block number: " + res; });

Is there no way to make this call synchronous? I know that it does work synchronously in the geth JS console, why is this different when using via web3.js in a browser? This is especially confusing since the wiki states:

  As this API is designed to work with a local RPC node, all its functions use synchronous HTTP requests by default.

Just for completion here my complete page:

default


texts: How do I make a smart contract on MyEtherWallet?

texts:
I've tried downloading the Ethereum wallet but it's taken weeks to download blocks. The only other option is MyEtherWallet. I asked on Reddit someone said theirs a way to do it with MyEtherWallet and MetaMask but I need to know exactly how to do it.

Any online tutorials or detailed explanations on how to do this?


texts: How to loop an array and store values in another after if conditions

texts:
I am trying to do something that I believe it should be simple enough.
I want to make a getter function iterating a struct array find the min value and the values that is equal to this minvalue of a property and store the addresses coresponding to this value on another array. The code I am using is as follows.

pragma solidity ^0.5.1;

contract arraytest{

struct Player {
    uint estimation;
    // address player // maybe
    // other elements
}

Player[] public playersArr;
address[] public playersaddress;

    function setbid(uint _prediction, address _playeraddr) public{
    Player memory player;
    player.estimation = _prediction;
    playersArr.push(player);
    playersaddress.push(_playeraddr);

}

    function getWinnersArray() public view returns (address[] memory) {
    uint i=0;

    uint counter = 0;
    uint j=1;
    uint minvalue=playersArr[i].estimation;

    address[] memory winners = new address[](j);
    winners[counter] = playersaddress[i];
    counter++;

    for (i = 1; i < playersArr.length; i++) {

        if (playersArr[i].estimation < minvalue) {

            minvalue=playersArr[i].estimation;
            delete winners;

            winners = new address[](j);
            counter=0;

            winners[counter] = playersaddress[i];
            counter++;
        }else if(playersArr[i].estimation == minvalue){

            //append to winners array
        }
    }
    return (winners);
}

I tried several ways but I couldnt achieve my goal.
Should i use mapping somehow.
Appreciate any help.


texts: why go-ethereum client auto send all balance to outer

texts:
My repotest net go-ethereum client auto send all banlance to outer address?

You can click here.


texts: I want to connect local ethereum network to metamask , it says that it need chain id but when i entered the chain id for local node it shows the error "Could not fetch chain ID. Is your RPC URL correct?" I am running geth consol on local pc. What should i do ? thank you


texts:
I am new to remix and can't figure out what is wrong with this basic function.

pragma solidity ^0.5.1;
  contract Pie {
  uint256 public p;
}

function pie () public returns (uint256) {
         uint256 x = p;
         returns x;
         }


texts: what are the technological limits of a smart contract?

texts:
I know that:

a smart contract cannot initiate any type of transaction but needs an external trigger. Each transaction is triggered by an EOA
Smart contracts cannot subscribe to events or access them directly

but are there other limits?


texts: I keep getting this Error when i tried to use contracts instance to call a contract's function?

texts:
I tried creating instance by:

const certificate = Certificate.deployed();

OR

const certificate = Certificate.at(config.contract_id);

ANd i get this Error below:

TypeError: Cannot read property 'apply' of undefined
at Provider.sendAsync (/home/manzik/esatya/ecertificate/node_modules/truffle-contract/contract.js:23:36)
at RequestManager.sendAsync (/home/manzik/esatya/ecertificate/node_modules/truffle-contract/node_modules/web3/lib/web3/requestmanager.js:80:19)
at Object.get [as getNetwork] (/home/manzik/esatya/ecertificate/node_modules/truffle-contract/node_modules/web3/lib/web3/property.js:116:33)
at /home/manzik/esatya/ecertificate/node_modules/truffle-contract/contract.js:477:27
at new Promise (<anonymous>)
at Function.detectNetwork (/home/manzik/esatya/ecertificate/node_modules/truffle-contract/contract.js:468:14)
at Function.deployed (/home/manzik/esatya/ecertificate/node_modules/truffle-contract/contract.js:416:19)
at Object.<anonymous> (/home/manzik/esatya/ecertificate/server/helpers/web3.helper.js:42:33)
at Module._compile (module.js:652:30)
at loader (/home/manzik/esatya/ecertificate/node_modules/babel-register/lib/node.js:144:5) }


texts: How long does it take it typically take for call value of changed variable to update?

texts:
I'm trying to mine a proof of work contract. Each time a solution is found, the return value for units.functions.getChallengeNumber().call() should change.

I ran two instances of this script (with different PUBLIC_KEYs) to see what would happen if multiple people were trying to solve a problem for the same contract.

From what I see on etherscan, it appears that sometimes the solutions found are not valid. The only feasible way I can see this being true is if units.functions.getChallengeNumber().call() is not returning the current challenge_number_hex. What should I do to prevent this problem?

Here's my script for replication.

import numpy as np
import os
import time

INFURA_ROPSTEN_URL = "https://ropsten.infura.io/v3/<api>"

# metamask account information
PUBLIC_KEY = "0x3FaD9AccC3A39aDbd9887E82F94602cEA6c7F86f"
PRIVATE_KEY = "<private_key>"

UNITS_ADDRESS = "0x8C4D48B42cdff260F14BBaD4E10d4144F1898bD4"
# from truffle build. For ABI
JSON_PATH = "../truffle/build/contracts/Units.json"

import logging
extra = {'miner_public_key': PUBLIC_KEY}
logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(miner_public_key)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)

logger = logging.LoggerAdapter(logger, extra)
logger.setLevel(logging.INFO)

def set_up_web3():
    web3 = Web3(Web3.HTTPProvider(INFURA_ROPSTEN_URL))
    web3.eth.defaultAccount = PUBLIC_KEY
    return web3

def get_units_contract_object():
    with open(JSON_PATH, 'r') as json_file:
        abi = json.load(json_file)['abi']
    return web3.eth.contract(address=UNITS_ADDRESS,abi=abi)

def solve(web3, units):
    nonce = np.random.randint(0,1e10)
    while True:
        challenge_number_hex = HexBytes(units.functions.getChallengeNumber().call()).hex()
        my_digest_hex = web3.solidityKeccak(
                            ['bytes32','address','uint256'],
                            [challenge_number_hex, PUBLIC_KEY, nonce]).hex()
        my_digest_number = int(my_digest_hex,0)
        target = units.functions.getMiningTarget().call()
        if my_digest_number < target:
            return (nonce, my_digest_hex, int(challenge_number_hex,0))
        else:
            nonce += 1

def build_transaction(units, nonce, digest_hex, txn_count):
    return units.functions.mint(
                    nonce,
                    digest_hex
            ).buildTransaction({
                "nonce" : txn_count,
        })

if __name__ == "__main__":
    web3 = set_up_web3()

    txn_count = 11000 # web3.eth.getTransactionCount(PUBLIC_KEY)
    units = get_units_contract_object()

    _cycle_goal = 20
    _prev_finish = time.time()
    _wait_time = 0
    while True:
        target = units.functions.getMiningTarget().call()
        nonce, digest_hex, challenge_number = solve(web3, units)

        mint_txn = build_transaction(units, nonce,digest_hex, txn_count)
        signed_txn = web3.eth.account.sign_transaction(mint_txn, private_key=PRIVATE_KEY)
        txn_address = web3.eth.sendRawTransaction(signed_txn.rawTransaction)
        txn_count += 1

        log = f"Solution found! nonce={nonce}, digest_hex={digest_hex}, challenge_number={challenge_number}, txn_address={signed_txn}"
        logger.info(log)

        _finished = time.time()
        _elapsed = _finished - _prev_finish
        _additional_wait = _cycle_goal - _elapsed
        _wait_time += _additional_wait
        log = f"Waiting {_wait_time}"
        logger.info(log)
        _prev_finish = _finished
        time.sleep(_wait_time)


texts: Unlocking accounts for a back office app

texts:
I'm writing a "back office" app and need a way to unlock an account in an automated fashion.

Yes, I know security of nodejs is questionable, but there are ways of solving this.  blocking web3 from doing this at all doesn't seem like a comprehensive solution.

The current answer says "use a browser/mist" because they have an browser based API to do so, but that's not acceptable for a back office app written in nodejs (or python, or ...).   So what is a good answer?

web3 doesn't support this API according to a related answer.

This answer will also be needed for something like a split key unlock (e.g. like some of the newer bitcoin wallets).  I'd actually prefer an n-way split key unlock for my use anyways.   Hmm, can we write a smart contract for this?...


texts: Limitation on amount of data that can be sent on Geth

texts:
We are creating a small private network with the purpose of sharing data. We thought that the main concern about writing large amounts of data in Ethereum would be the gas cost, which is not a problem to us, as this will be a private network.

As we developed our POC, we stumbled across this error message on Geth:

content length too large

We investigated and saw that there is a limitation on Geth about how much data can be sent in a single request on http.go file:

const (
    maxHTTPRequestContentLength = 1024 * 128
)

My question is: is there a technical reason for this limitation? Or is it just because is not reasonable in a public network to send this amount of data due to gas costs?

Can I increase the value or remove this constraint in my private network?


texts: Find contract address inside the contract?

texts: How to find contract address inside a contract method? I mean the address of the instance of the contract.


texts: What happens to eth.sendTransaction when the target account is offline?

texts:
I am running geth --rpc on a local machine and have sent ether back and forth between local and non-local accounts successfully.  Now I am wondering what happens if I shut down my target machine and send ether to a local account on that shut down machine?

If I bring the machine back up, start geth --rpc back up, when it syncs the blockchain does my local account get updated with the money that was sent?


texts:
I have a problem that I'm really stuck with so I'm coming to the experts:)
I have a personal project I'm working on. I'm minting tokens in large batches, once a condition is met, a new batch of tokens is minted and any older batches are worthless.
This isn't quite ERC20 since a token in batch 1 has a different batchID than a token in batch2, but it also isnt really in the spirit of ERC721 since each token in a batch is identical.
What do i do? I thought of potentially giving tokens some kind of lifespan but that get's convoluted. Is there any obvious solution that I'm missing?


texts: Is there a solidity string limit of 32 bytes?

texts:
I know there was a string limit but I thought that was long ago. I had a smart contract working but there is a limit of 32 bytes on the string input. I am unsure if  a version changed or something like that. I had tested before and it was handling strings longer than 32 bytes. Now it does not.

When that is exceeded it does not insert any data. I ma using PoA now, I was testing with PoW before. But that should not make any difference.

I am running addInventory in the following contract.

Can someone clarify the allowed string length?

pragma solidity ^0.4.18;

// this contract stores the inventory strings, the hash of the string, and the keys to storage areas
// to add - events for updates, sha to check passed sha (if an error reject),

contract RegisterContract {

    uint public inventoryWeight;

    mapping(bytes32=>string) public inventories; // stores of json strings
    bytes32[] public inventoryHashes; // this is used mainly in testing eg inventoryHashes(uint) for the sequence of inventories added
    bytes32[] public inventoryHashesStorage; // keys to storage

    event eventNewInventory(bytes32 hashInventory);
    event eventNewStorageInventory(bytes32 hashInventory);

    function addInventory ( string inventory, bytes32 hashInventory) public {
        inventories[hashInventory] = inventory;
        inventoryHashes.push(hashInventory);
        eventNewInventory(hashInventory);
     }

     function addInventoryHash(bytes32 hashInventory) public {
         // storage key - kept separate in case add addInventory fails due to gas limits
         // during testing addInventory did sometimes fail due to long strings
         // this hashInventory would be a key to IPFS or a database
         inventoryHashesStorage.push(hashInventory);
         eventNewStorageInventory(hashInventory);
     }

    function getAllInventories() public view returns (bytes32[]) {
        return inventoryHashesStorage;
    }

    function addWeight (uint weight) public {
        inventoryWeight = weight;
    }

    function () payable public {
    }

}


texts:
I installed and run geth on local node in my Ubuntu 16.04.
After start the geth in testnet, I got highest block by eth.sync.
This highest block was similar with the latest block of ropsten.etherscan.io.
But eth.sync is returning same result with first one.
So I can't get the latest block from syncing.
Is this right way?
How can I get highest block?


texts: Just a noob question ! How to add my custom token the list of "show all token" list on MEW . Just like a this

texts: I know it should need something qualified to do it . I just want to find a way do that .  Appreciate it if anyone could give me a help or instruction !


texts: Oraclize bridge with private blockchain, deterministic OAR disabled

texts:
I created a geth console with

geth --datadir /Users/test/data/privateEthereum --networkid 42 --nodiscover --rpc --rpcport "8042" --port "30303" --maxpeers 3 --nat=any --rpccorsdomain \"*\"  --unlock "0,1" --password /Users/test/data/privateEthereum/password.txt console

and started the miner

When I started the bridge with

node bridge -H localhost:8042 -a 1

I get

  Please wait...

  [2017-11-03T17:22:51.822Z] INFO you are running
  ethereum-bridge - version: 0.5.5

  [2017-11-03T17:22:51.823Z] INFO
  saving logs to: ./bridge.log

  [2017-11-03T17:22:51.823Z] INFO using
  active mode

  [2017-11-03T17:22:51.823Z] INFO Connecting to eth node
  http://localhost:8042

  [2017-11-03T17:22:53.256Z] INFO connected to
  node type Geth/v1.7.2-stable-1db4ecdc/darwin-amd64/go1.9.2

  [2017-11-03T17:22:53.885Z] WARN Using
  0x974e5ce3d49bacb3d6d47b827e12972940fb764d to query contracts on your
  blockchain, make sure it is unlocked and do not use the same address
  to deploy your contracts

  [2017-11-03T17:22:54.025Z] INFO deploying the
  oraclize connector contract...

  [2017-11-03T17:23:04.410Z] INFO
  connector deployed to: 0x879db369b9b06260c59e7123f2d9dd650353a689

  [2017-11-03T17:23:05.705Z] WARN deterministic OAR disabled/not
  available, please update your contract with the new custom address
  generated

  [2017-11-03T17:23:05.706Z] INFO deploying the address
  resolver contract...

  [2017-11-03T17:23:16.482Z] INFO address resolver
  (OAR) deployed to: 0xabd00b99c13644df9f0b5c2f91ea3f718615e075

  [2017-11-03T17:23:16.482Z] INFO updating connector pricing...

  [2017-11-03T17:23:26.730Z] INFO successfully deployed all contracts

  [2017-11-03T17:23:26.735Z] INFO instance configuration file saved to
  /Users/test/code/blockchain/ethereum-bridge/config/instance/oracle_instance_20171103T102326.json

How do I correct this?

  WARN deterministic OAR disabled/not available

There must be a mistake in my configuration. Any suggestions?


texts: Need help: Error: Transaction has been reverted by the EVM:

texts:
Could anyone point me at what is the problem here?

I tried to send ERC20 tokens by using ERC20 trasferFrom function.
I have executed a sendSignedTransaction and got an error as follows:

Error: Transaction has been reverted by the EVM:
{
  "blockHash": "0xf8c3f5d7552bce0c3191160af6bedd1dccdee15de1605301d225b54d84bc219c",
  "blockNumber": 5432016,
  "contractAddress": null,
  "cumulativeGasUsed": 576475,
  "from": "0xc17fe972be596e119d7e51270f1c7d3bda726db9",
  "gasUsed": 30631,
  "logs": [],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "status": false,
  "to": "0x6c9ba85bb7d0acba49aa13e1882565efd823a4c9",
  "transactionHash": "0x338a60122583f3aff3c797dfd8fe5c25b8201ec1d1baff76af0a140dea20f8ce",
  "transactionIndex": 3
}
    at /Users/gemcutter/demo_peak/node_modules/web3-core-method/src/index.js:364:46
    at process._tickCallback (internal/process/next_tick.js:68:7)````

the execution code is as follows:

    var tx=myContract2.methods.transferFrom(from,to,amount)
    var encodedTx = tx.encodeABI();

    tx.estimateGas({to:to, data:encodedTx, from:approved}).then((gasAmount) => {
    console.log('app.js: estimated gas: ' + gasAmount.toString(10));

        web3.eth.getTransactionCount(from).then(_nonce => {
            nonce = web3.utils.toHex(_nonce);
            console.log('app.js: tx nonce: ' + nonce + ' at account[0]: ' + to);

            var tx = new ethTx({
                nonce: nonce,
                gasPrice: gasPrice,
                gasLimit: gasLimit,
                from: approved,
                to: contract2Addr,
                data: encodedTx
            },{chain: 'rinkeby' , hardfork: 'petersburg'});

            tx.sign(privKey);
            var signedRawTx = '0x' + tx.serialize().toString('hex');

            web3.eth.sendSignedTransaction(signedRawTx)
            .on('receipt', receipt => {
                console.log('app.js: signed tx receipt:\n' + JSON.stringify(receipt));
                console.log('Successfully transferred a token!');
            }).catch((err) => {
                console.log(err);
            });
        });
    }).then((result) => {
        console.log('Transfered tokens:'+JSON.stringify(result));
    }).catch((err) => {
        console.log('ERROR: app.js: Gas Estimate failed');
        console.log(err);
    });

The smart contract is as follows:

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

The contract was successfully deployed.

I use following versions.
Truffle v5.0.3,
web3@1.0.0-beta.37,
node.js v10.16.0

I checked etherscan.io, but do not know how to deal with it.


texts: Do private keys work across chains and networks?

texts:
If I generate a private key on mainnet now, would I be able to use it at the same address on Ethereum Classic? What about testnets?

In what cases would the keys not give the same address on different networks / chains?

A follow up question would be: since deployed contract addresses are derived from nonce and sender address, does it mean if I deploy n contracts on different networks and chains, the n contracts would have the same set of addresses on different networks?


texts: Using Python trie to build transactionsTrie. Why is my Transactionsroot wrong?

texts:
I am trying to build a TransactionsTrie with python. I am using this [trie][1]-Library. I followed the Instructions.

Edit: Removed the original question because it was stupid.

@carver
Thank you very much. Your reply was really helpful. So I am trying to use the method You referenced from py-evm.

Here is my full code:

import requests
import json
import ethereum.utils as utils
from eth.db.trie import make_trie_root_and_nodes as make_trie
from eth.rlp.transactions import BaseTransactionFields
from eth.rlp.transactions import BaseTransaction

url = 'https://ropsten.infura.io/1234'

headers = {
    "Content-Type": "application/json"
}
data = {}
data['jsonrpc'] = '2.0'
data['id'] = 1
data['method'] = 'eth_getBlockByHash'
data['params'] = ["0xd993562b847a2b61f858ee2baa2351f05e22d755d3657444f06a8c51f88a11f8", True]
data = json.dumps(data)

response = requests.post(url, headers=headers, data=str(data) )
print(response.text)
block = json.loads(response.text)
result = block['result']
raw_transactions = result['transactions']

transactions = tuple()
for tx in raw_transactions:
    nonce = tx['nonce']
    nonce = utils.int_to_big_endian(int(nonce[2:], 16))
    gas_price = tx['gasPrice']
    gas_price = utils.int_to_big_endian(int(gas_price[2:], 16))
    gas = tx['gas']
    gas = utils.int_to_big_endian(int(gas[2:], 16))
    to = tx['to']
    to = bin(int(to[2:], 16))
    value = tx['value']
    value = utils.int_to_big_endian(int(value[2:], 16))
    data = tx['input']
    print(data)
    if data != '0x':
        data = bin(int(data[2:], 16))
    else:
        data = bin(0)
    print(data)
    v = tx['v']
    v = utils.int_to_big_endian(int(v[2:], 16))
    r = tx['r']
    r = utils.int_to_big_endian(int(r[2:], 16))
    s = tx['s']
    s = utils.int_to_big_endian(int(s[2:], 16))
    f = BaseTransactionFields(nonce = nonce, gas_price = gas_price, gas = gas, to = to, value = value, data = data, v = v, r = r, s = s)
    transactions += tuple(f)

tx_root, _ = make_trie(transactions)
print(tx_root.hex())

Still my txRoot is not the same as the one in the Block. What am I doing wrong?


texts: Where can i find a documentation of all `wallet_` RPC calls?

texts:
Looked everywhere, and all I can find are a bunch of EIPs. Is there a document/repo somewhere listing all available RPC calls that interact with the wallet (wallet_...)?
Specifically, I'd like to switch a user to one of the testnets when they log into my dApp. However, wallet_addEthereumChain, mentioned in EIP-3085 does not work for mainnet, or any of the 4 testnets (returns May not specify default MetaMask chain.), and wallet_updateEthereumChain mentioned in EIP-2015, returns May not specify default MetaMask chain. as well.


texts: Make a transaction from a node not in network

texts:
I have a smart contract deployed on one node. This node has another node in the same network.

Is it possible to make a transaction from a 3rd node to the 1st, when both are not in the same network?


texts:
I am getting rather desperate. What can I do ?

https://etherscan.io/txsPending?a=0xf48920e191f304d69f9f55d0db602f7e7fe5a62d


texts: Attempting to transfer erc20 elrond to elrond gold in trust wallet - error insufficient funds

texts:
Does anyone have a step by step guide to transfer my 7566 elrond to elrond gold?
My elrond is in Trust Wallet and tried to send to my elrond gold wallet but network said I have insufficient funds and the charge was about $54.
I'm sure this charge is too high and 7566 elrond must be worth 7.56 elrond gold if you divide by 1000.
Any help or a step by step guide would be much appreciated.


texts: How to disable a function from a parent contract?

texts:
Say I have this contract:

contract Foo {

    uint256 public foo;

    function setFoo(uint256 _foo) public {
        foo = _foo;
    }

    function setFooToZero() public {
        foo = 0;
    }
}

And I want to inherit from it like so:

contract Bar is Foo {

    function setFooToZero() public {}
}

This way, setFooToZero gets updated to a function that does nothing, but is there a way of disabling it? Of not having it in the bytecode of the contract at all?


texts:
Using truffle , I am able to deploy private smart contracts using privateFor clause. However, I am not able to use in truffle test. I get the following error. Is there a way we can  use privateFor ?

Transaction: 0x0e390b0d04d6285bd098f76ebfa961b8be875ce2a744511e13eb312414f835a8 exited with an error (status 0).
 Please check that the transaction:
 - satisfies all conditions set by Solidity require statements.
 - does not trigger a Solidity revert statement.

Sample Test

const truffleAssert = require('truffle-assertions');
const DEF_Test = artifacts.require("DEF_Test");
const Testing_V1 = artifacts.require("Testing_V1");
const Event_V1 = artifacts.require("Event_V1");

// Test cases
contract("Testing_V1 Testing", async accounts => {

    let Testing_V1Instance;
    let Event_V1Instance;

    it("1. Setting up Contract instances", async () => {
        Testing_V1Instance = await Testing_V1.new();
        Event_V1Instance = await Event_V1.new();
    })

    it("set", async () => {
        let result = await Testing_V1Instance.set("ID","Name",["ph1","ph2"],Event_V1Instance.address,
            {from:"0x12eac5277d794e1a0d65c95f9fe2b721a86d096f",
            privateFor:["l/VcNHe+p+KX79dbGpAydcMiKGkaBbwSkdInlP6PHD0=",
                        "K76aVoHUc5RkNpkreFd64DYyzxG1UO5aCd05h1u97EA="]});
            console.log(result)
        });

    it("get", async () => {
        let result = await Testing_V1Instance.get("ID");
        console.log(result)
    })

})

Sample code

pragma solidity 0.5.13;
pragma experimental ABIEncoderV2;

import "../definitions/DEF_Test.sol";
import "./Event_V1.sol";
import "../interface/ITesting_V1.sol";

contract Testing_V1 is ITesting_V1 {

mapping (string => DEF_Test.Employee) private mapEmp;

function set(string memory empID, string memory empName,string[] memory phone,address eventAddr) public{
    mapEmp[empID].empID = empID;
    mapEmp[empID].empName = empName;
    mapEmp[empID].phone = phone;
    Event_V1(eventAddr).emitEmpEvent(mapEmp[empID]);
}

function get(string memory empID) public view returns (DEF_Test.Employee memory) {
    return mapEmp[empID];
}

}

pragma solidity 0.5.13;
pragma experimental ABIEncoderV2;
import "../definitions/DEF_Test.sol";

contract Event_V1 {

    event EMP_EVENT(string empID,string empName,string[] phone);

    function emitEmpEvent(DEF_Test.Employee memory emp)  public  {
        emit EMP_EVENT(emp.empID,emp.empName,emp.phone);
    }

}

pragma solidity 0.5.13;
pragma experimental ABIEncoderV2;

library DEF_Test {

struct Employee {
    string empID;
    string empName;
    string[] phone;
}

}

pragma solidity 0.5.13;
pragma experimental ABIEncoderV2;

import "../definitions/DEF_Test.sol";

interface ITesting_V1 {

function set(string calldata empID, string calldata empName,string[] calldata phone,address eventAddr) external;
function get(string calldata empID) external view returns (DEF_Test.Employee memory);

}


texts: Remove an element in array but the struct is still inside

texts:
I have this array of struct

struct Prodotto {
    string titolo;
    address owner_address;
}

Prodotto[] public prodotti;

And I create two products like this:

titolo: titolo stravolto
owner: 0x144c9617C69B52547f7c2c526352E137488FAF0c

titolo: titolo secondo prodotto
owner: 0xa53709839ab6Da3ad9c1518Ed39a4a0fFCbA3684

I want to delete the element with index 0

in my contract I have this function

function deleteProdotto(uint _id_prodotto) external payable onlyOwnerOf(_id_prodotto) {
  delete prodotti[0];
}

If I retrive element to index 0, I have a product like this

titolo:
owner: 0x0000000000000000000000000000000000000000

How can I delete that index?
I know that after that I have to do

prodotti.length--

But before I have to resolve this issue


texts: ERC20 Contract created but how to access those funds?

texts:
I have created a ERC20 token, and whilst creating a token Wallet my system got hanged, I can see the contract in Custom Token but its greyed out also I can see the token on etherscan.io/token.
Is there any way I can send and receive money through this newly created token?


texts: Metamask web3.eth.account[0] is undefined

texts:
I am facing some problem with metamask.
I ve copied the code below from the metamask documentation to load the web3 but i get always web3.eth.accounts[0] returns undefined when i try to get the account's address even if metamask is connected to ropsten. The same code works with Mist perfectly.

window.addEventListener('load', function() {

    if (typeof web3 !== 'undefined') {
        // Use Mist/MetaMask's provider
        window.web3 = new Web3(web3.currentProvider);
        console.log("Metamask used");
    } else {
        console.log('No web3? You should consider trying MetaMask!')
        // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
        window.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/token"));
    }

    console.log('test1'+web3.eth.accounts[0]);

});
console.log('test'+web3.eth.accounts[0]);

i get the output of the first log.


texts:
We are running chains in PoA using Geth 1.8 - with just one sealer (this is our staging chain).
We wanted to upgrade our chain to Geth 1.10 and decided to try the following:

First, we generated a new sealer cryptographic material.
We then started our sealer.
We then called `clique.propose("...", true) on both sealers (the 1.8 one and the 1.10 one).

We realised that for some reason, they don't connect to each other - even when adding each sealer to the other manually using admin.addPeer - for some reason we get something like this from the 1.10 sealer: TRACE[05-20|13:26:34.599] Rejected peer id=bdc5722d94baefb7 addr=10.0.83.11:30304 conn=staticdial err="useless peer".
But more importantly, our main 1.8 sealer is now stuck - INFO [05-20|13:16:32.724] Signed recently, must wait for others.
It seems that the proposal passed, but since both sealers are not connecting to one another, then the old sealer cannot continue adding blocks to the canonical chain.
We checked on our old sealer using clique.getSealers() and clique.getSnapshot(), and it seems to have registered the other sealer...
What can we do so that our old sealer can resume its work and get things unstucked? Either one of:

Reverting the proposal to exclude the 1.10 sealer from the 1.8 one.
Or getting them to connect to one another, getting rid of that Rejected peer id=bdc5722d94baefb7 addr=10.0.83.11:30304 conn=staticdial err="useless peer" error.

EDIT: Today, we're experimenting. Given that 1.10 doesn't seem to want to connect to 1.8, we've spin-up a 1.9 node using the same cryptographic material as the 1.10 one. It seems to be connecting to 1.8 and catching up on the blocks. But the 1.10 doesn't connect to 1.9. We're really not sure how to get 1.10 up and running while conserving our block history.


texts: why can not stop mining in geth console?

texts:
System information

Geth version: geth version
Version: 1.6.6-unstable
Architecture: amd64
OS & Version: Windows/Linux/OSX
win10

Expected behaviour

I create a private chain in my pc. After mining for a while, I just want to stop mining

Actual behaviour

,so I type "miner.stop()", but it can't stop. the console still show information incessantly.

> INFO [07-07|09:42:20] Successfully sealed new block            number=203 hash=c11ed3…0bec95
INFO [07-07|09:42:21]  block reached canonical chain          number=198 hash=769f09…0fdd3f
INFO [07-07|09:42:21]  mined potential block                  number=203 hash=c11ed3…0bec95
INFO [07-07|09:42:21] Generating DAG in progress               epoch=1 percentage=72 elapsed=24m35.334s
INFO [07-07|09:42:21] Commit new mining work                   number=204 txs=0 uncles=0 elapsed=0s
> miner.stop()
true
> INFO [07-07|09:42:27] Generating DAG in progress               epoch=1 percentage=73 elapsed=24m40.957s
INFO [07-07|09:42:30] Generating DAG in progress               epoch=1 percentage=74 elapsed=24m43.627s
> miner.stINFO [07-07|09:42:32] Generating DAG in progress               epoch=1 percentage=75 elapsed=24m46.275s
> miner.stop()
true
> INFO [07-07|09:42:36] Generating DAG in progress               epoch=1 percentage=76 elapsed=24m49.595s
INFO [07-07|09:42:39] Generating DAG in progress               epoch=1 percentage=77 elapsed=24m52.717s

> miner.INFO [07-07|09:42:42] Generating DAG in progress               epoch=1 percentage=78 elapsed=24m55.622s
> miner.stop()
true
> INFO [07-07|09:42:45] Generating DAG in progress               epoch=1 percentage=79 elapsed=24m58.961s
INFO [07-07|09:42:48] Generating DAG in progress               epoch=1 percentage=80 elapsed=25m2.255s
INFO [07-07|09:42:52] Generating DAG in progress               epoch=1 percentage=81 elapsed=2


texts: Getting INVALID_ARGUMENT error when passing zero to a view function with a parameter of type address?

texts:
I recently upgraded to solidity 0.8.1 from 0.4.21.  I have a view function in my contract with an address parameter.  In the past I could pass 0 for this argument and that would be written to the contract.  Now, I get an INVALID_ARGUMENT error with argument="address" and value=0, with the offending address parameter's name in the second argument error field.
I use the value zero to let the contract know that the address has not been received yet (i.e. - the same idea as an uninitialized user).  Later when the address becomes available the correct value is set.
Am I right in believing the latest code does not allow zero addresses?  If so, what is the "standard" technique for passing a value to a view function with an "address" type parameter to let it know that the address isn't known yet?  In other words, that it should be treated as an "unitialized" address?
Also, can I convert a plain "address" type value passed to a (non-view) function and convert it to a "address payable" value so it can now be used in a value transfer (i.e. - be "paid")?  Or do/should all addresses that will at any point in time be used for value transfers be declared as "address payable", view function or not?


texts: How to invoke a contract function in the future (under 10 blocks)

texts:
This is not a duplicate question, as the alarm contract only allows function calls to be made in the future, over a period of at least 10+ blocks...

The current thinking is to just use the alarm clock contract, however, this only allows for a minimum future contract function call of at least 10+ blocks in the future, I need to do it in e.g. 3.

What is the current thinking to invoke a contract function e.g 3 blocks in the future.

Is there anyway to do this, that does not rely on client-side invocation 3 blocks down the track?

I cannot rely on client invocation, I need a definitive, stable, guaranteed way to invoke a function on a smart contract 3 blocks from the time (block) a client had first invoked the contract.


texts: geth setup on aws for custom wallet application

texts:
I need to create an app that will hold custom wallet per user, I was using Infura earlier, but now I have to create wallets so will need "Personal" on rpc. I see that Infura don't expose it so will need my own private node.
How can I setup personal node on AWS with bare minimum configurations so thats I don't need more storage and computing power.

If some one can explain the steps and also things to do, it will be highly appreciated.


texts: Events dont fire when called too quickly

texts:
I have a very simple solidity function that just calls an event:

     function sendMessage(int id, string title, string message){
       Message(id, method, parameters);
     }

When I call it using web3:

communicationChannelInstance.sendMessage(45, 'exampleTitle', '{}');

I can see it with an event watch just fine.

The problem comes when I call that functions multiple times inside a loop:

      ids.forEach(function(id) {
        communicationChannelInstance.sendMessage.sendTransaction(id, 'exampleTitle', '{}');
      })

No matter how many times this loop is called, it only shows the latest event.

This is the watch I'm using:

var events = contractInstance.allEvents();
  events.watch(function(error, event){
      if (error) {
        callback(error, null);
      } else {
         var eventRet = event;
        callback(null, eventRet);
      }
  });

Why does this happen? How can I fire multiple events really fast and execute all of them?

Thanks for the help.