texts: Repository and packaging standard for open-source smart-contract modules

texts:
Is there a standard way to package the source code of a smart contract and publish it on a public repository? In such a way to enable structured reuse, with versioning and easy ways to update an component. Similar to what search.maven.org for Java, bower and npm for JavaScript or PyPI for Python offers.

There's a repository of sample contracts on https://github.com/ethereum/dapp-bin and various blog posts and sites containing sample code of smart contracts. However, this doesn't solve the problem of copy&paste code and versioning.


texts: How to initialize an empty array and push items into it?

texts:
Here's my function:

function Test() constant returns (uint[]) {
   var myArray = uint[];
   myArray.push(123);
   return myArray;
}

Here's an error I get in the solidity online compiler:

  ballot.sol:25:9: Error: Member "push" not found or not visible after argument-dependent lookup in type(uint256[] memory)
          myArray.push(123);


texts: Flow Modeling in Ethereum Smart Contract

texts:
I have deployed a smart-contract which is basically a money sending application. The established frontend asks user address [from] and the [to] address. When the amount is given the smart-contract initiates with the Metamask wallet for approval. I am testing it in the Rinkeby network.

What I am trying to achieve here is to create an anomaly detection tool based on profiles. Therefore I need to extract the transactional logs of the deployed smart contract continuously.

The sequence of my project is given below:

1- Extracting the data constantly to elastic search so the transactional logs must be up to date all the time
2- Then extract the data constantly to my python backend.
3 - Analyze the data on a profile (address) basis.
4- Creating a dashboard for smart-contracts insights.

How do I constantly extract (For instance the data should be updated every 5 minutes) data from Ethereum and inject into elastic search?

Also the transactional data originally in .JSON how do I change it to the .csv format with the regarding parameters.

I am going to analyze the smart contract data in python backend every 5 minutes and update to the dashboard.

Would you please help what should I do?


texts: How to convert BigNumber returned by Truffle Console

texts:
I have a simple contract Foo which is deployed to a Ganache network.

pragma solidity ^0.4.18;

contract Foo {
    uint storageData;

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

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

Now when I want to interact with it using truffle console, first I set the value

truffle(development)> Foo.at("0x4d4337B075a442cF3351Fa11c425C350cE2984F5").set(123)

Question 1: Then I tried to retrieve that value but it is returning a BignNumber. Why is it not an integer?

truffle(development)> Foo.at("0x4d4337B075a442cF3351Fa11c425C350cE2984F5").get.call()
BigNumber { s: 1, e: 0, c: [ 123 ] }

Question 2: How can you convert it to an integer or string?

truffle(development)> Foo.at("0x4d4337B075a442cF3351Fa11c425C350cE2984F5").get.call().toNumber()
TypeError: Foo.at(...).get.call(...).toNumber is not a function

Tried to console.log it after a .toNumber, it prints out the right value 123, but why is it printing an undefined too?

truffle(development)> Foo.at("0x4d4337B075a442cF3351Fa11c425C350cE2984F5").get.call().then(a => console.log(a.toNumber()))
123
undefined


texts: In Solidity, can i store the value of keccak_256 in bytes32?

texts:
var uniqueIdentifier = keccak_256(firstName+LastName+studentId);

This line returns me a value and can i store that value in bytes32 in solidity?


texts: How can we confirm that ether was really sent using getTransactionReceipt?


texts: ERC20Mintable contract call return wrong number

texts:
I use OpenZeppilin ERC20Mintable contract and add MaxSupply parameter to contraint the ERC20 token amount allowed to issue.

what I want is only permit contract ower to view MaxSupply info, my function is below:

uint256 MaxSupply;//contract static variable
...
// self defined function
function ViewMaxSupply() public view onlyMinter return(uint256) {
 return ( MaxSupply* (10 ** uint256(decimals)) );
}

decimals is equal to 18.

I found when I use onlyMiner modifier, the return value is a very strange number: 3963877391197344453575983046348115674221700746820753546331534351508065746944.
when not use modifier onlyMinter, the result is correct: 100000000000000000000

How to fix the error?
Thanks.


texts: Accessing contract functions from web3 and javascript

texts:
I have deployed a contract in a private blockchain using remix and ganache. Now I want to interact with it trough web3 and the console from my browser, but I'm not managing to interact with the contract functions in the browser. This in my index.html:

index.html

var simpleStorageAbi =
    [
        {
            "constant": false,
            "inputs": [],
            "name": "getValue",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "name": "val",
                    "type": "uint256"
                }
            ],
            "name": "setValue",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "inputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "constructor"
        },
        {
            "constant": true,
            "inputs": [],
            "name": "value",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }
    ];

var SimpleStorageContract = new web3.eth.Contract(simpleStorageAbi);
var simpleStorageInstance = new web3.eth.Contract(simpleStorageAbi, "(address)");

When I open the console from the browser the contract I type:

simpleStorageInstance

and I would expect the contract functions:

{…}
> getValue
> setValue
> value

instead I get this

Contract {_requestManager: RequestManager, givenProvider: null, providers: {…}, setProvider: ƒ, …}
BatchRequest: ƒ ()
clearSubscriptions: ƒ (keepIsSyncing)
currentProvider: (...)
defaultAccount: (...)
defaultBlock: (...)
defaultChain: (...)
defaultCommon: (...)
defaultHardfork: (...)
events: {allEvents: ƒ}
extend: ƒ ex(extension)
givenProvider: null
handleRevert: (...)
methods: {getValue: ƒ, 0x20965255: ƒ, getValue(): ƒ, setValue: ƒ, 0x} etc

I tried accessing the functions in this way

simpleStorageInstance.methods.setValue(5);

but I get nothing in return (no transaction returned).

{arguments: Array(1), call: ƒ, send: ƒ, encodeABI: ƒ, estimateGas: ƒ, …}

What am I doing wrong?


texts: Hashnot matching generated from solidity contract and web3js

texts:
I want to make hash same as generating by solidity contract from web3 or ether's js.

In solidity contract hash generation by below :
sha256(abi.encodePacked(no of parameters)).

Kindly help for it. how can i generate using web3 or ether's js same hash.


texts: Delete a particular value mapped with array - contract

texts:
I written a contract that has one to many relationship elements. Each id holds different names(Eg: id = 1 holds name a,b and c). I need to delete name 'a' from id = 1.

struct IdStruct{
    bytes12[] structArray;
}

mapping(string => IdStruct) idStructs;

function appendNames(string id, bytes12 name) payable returns (bool success){
 idStructs[id].structArray.push(name);
}

function getName(string id) returns(bytes12[]){
  return idStructs[id].structArray;
}

I tried delete idStructs[id].structArray[name];
but nothing is deleted and when I try delete idStructs[id].structArray;, it deletes all names under id=1.


texts: Does the Raiden client ever deploy TokenNetworkRegistry?

texts: Is there any code in the Raiden client that deploys a TokenNetworkRegistry contract?


texts: A terse description of the theDAO hardfork

texts:
As I understand it, at block 1920000 the blockchain was forked and there are now two blockchain strands; ETH (hard-forked) or ETC (non-hard-forked) blockchain. This is known as "the DAO hardfork".

Please, in terse language;

describe what was was done
compare the size/other useful metrics of
the two blockchains (as of Sept 2016)
state the basic
configuration changes the average user must make to switch between
the two chains

Note, I'm not interested (in this question) in why this was done, just a consise explanation of what has been done what the current status is.

I have also seen this related question and answer:

Give a summary of the fork state changes in block 1920000


texts:
From the solidity docs:

  Use the Checks-Effects-Interactions Pattern
  Most functions will first perform some checks (who called the function, are the arguments in range, did they send enough Ether, does the person have tokens, etc.). These checks should be done first.

  As the second step, if all checks passed, effects to the state variables of the current contract should be made. Interaction with other contracts should be the very last step in any function.

  Early contracts delayed some effects and waited for external function calls to return in a non-error state. This is often a serious mistake because of the re-entrancy problem explained above.

  Note that, also, calls to known contracts might in turn cause calls to unknown contracts, so it is probably better to just always apply this pattern.

Does the statement "Interaction with other contracts should be the very last step in any function" also apply to "constant interactions", i.e., when calling a pure or view function in another contract?

I think that the answer is naturally No, however, the docs do emphasize any function.

Isn't this restriction a little too harsh? Or am I wrong?

Thank you!


texts:
Is there a template available for a smart contract which automatically sends tokens back when users send ETH or tokens to it?

Hello,

I am looking for code for a smart contract which automatically dispatches tokens to anyone that sends ETH or tokens to it. Has this been written yet? Maybe there is a template in GitHub somewhere?

If anyone knows where to find it, please post a link below.

Vesa


texts:
I am trying to get geth to synchronize behind my office firewall. I have a TCP and UDP port opened (incoming and outgoing) as requested in other similar threads, but it doesn't seem to be enough. Specifically, I can listen for peers correctly but then geth attempts to connect to them using different TCP ports, which are obviously blocked by the firewall; netstat shows that these connections are stuck at SYN_SENT, as shown below.

netstat -b
[...]
[geth.exe]
  TCP    xxx.xxx.xxx.xxx:64801   ip2504fbb9:30303       SYN_SENT
[geth.exe]
  TCP    xxx.xxx.xxx.xxx:64802   185.31.136.69:30303    SYN_SENT
[geth.exe]
  TCP    xxx.xxx.xxx.xxx:64803   95.85.21.43:30303      SYN_SENT
[geth.exe]
  TCP    xxx.xxx.xxx.xxx:64804   wallets:30303          SYN_SENT
[...]

Am I actually correct that more ports need to be open for geth to work? Is there a way to specify a range?


texts: how do I loop through a mapping of address

texts:
I have a mapping of list of struct (mapping (address => struct[]))
I'm having a trouble in how to display all them together in the front end (i'm using React js).

Thnx.


texts: How can Ethereum be used to prevent fake art sales?

texts:
According to this article, some very expensive art pieces are going to be auctioned, and "the auction will be conducted on the Ethereum blockchain. A smart contract will determine the final price for Warhol’s painting".

If I understand correctly, the smart contract collects the money from all bids, calculates the maximum bid, keeps the money from that bid, and returns all other money to the losing bidders (is that correct?).

What I do not understand is the final paragraph: "At a recent convention in London, the co-founder of blockchain identify company Codex Protocol, Jess Houlgrave, stated that over 40 percent of all art pieces on the market are fraudulent. In this regard, blockchain’s benefits immediately come to mind – specifically the maintenance of traceable records on a public database that art collectors can view to verify their pieces."

How can the blockchain say anything about a certain fungible piece of art? How can the blockchain prevents the owner of a real artwork from replacing it with a fake artwork and selling the fake as real?


texts: How to automatically schedule the execution of a function in the future?

texts:
I need a function in my contract to be executed daily by itself.
I know that Ethereum Alarm Clock and Oraclize do it but none of them worked for me.

For example this code using Oraclize

pragma solidity ^0.4.2;

import "http://github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol";

contract MyContract is usingOraclize {

    uint public tmp = 0;
    function callThisToStart() {
        oraclize_query(60, "URL", "");
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        doSomething();
        callThisToStart();
    }

    function doSomething() {
        tmp++;
    }

}

I do not really know why it does not work (tmp is not increased)
I do not care about using EAC or Oraclize, but I really want to get that for example every minute the value of a variable increases

Thank you.


texts: How to calculate number of ETH that got bought in transaction by trading?


texts: Is it possible to set a limit for the number of transaction each token can have in solidity? for example, a token can only transfer 10 times.


texts: Token transfer on rinkeby by myetherwallet fail

texts:
I try to transfer erc20 token I made on rinkeby by myethereallet
Finally it says
Error transaction was not mined with 750 seconds please make sure your transaction was properly sent.
Whether my token created is wrong or the rinkeby wrong?


texts: On the blockchain I can inspect the code of a contract, and see the EVM opcodes. Is there a way to decompile this and convert it back to (Solidity) source code?


texts:
I have the following code:

var filter = web3.eth.filter({
    fromBlock:4076955,
    toBlock:"latest",
    address:"0x0123456789012345678901234567890123456789"
});

filter.get(function(error,logs){
  if (!error) {
    console.log("Found block " + logs.blockNumber);
    console.log(JSON.stringify(logs,null,2));
  }
}

and when I run the code, I get:

Found block undefined
[]

I would have expected to get a number for logs.blockNumber and an object as the return value (source: https://github.com/ethereum/wiki/wiki/JavaScript-API#watch-callback-return-value)

Question: Why might I not be getting the expected result?


texts: Event filter not returning correct events web3js

texts:
I am trying to filter certain events emitted in the past based on the value of a certain field. The code I have used corresponds to the method specified on the web3js documentation page. However, the code seems to return the wrong event for some reason.

Here is the code for fetching the events:

let events = supplychainInstance.ItemProduced({
    filter: {epc: 111},
    fromBlock: 0,
    toBlock: 'latest'
});

events.get((error, logs) => {
    logs.forEach(log => console.log(log.args))
});

I have just 2 events with different values of the "epc" field. The response I get is the latest event but with the wrong epc:

Is there something wrong with my approach? How should I filter all past events based on value of a field?

NOTE:
The list of all events and the code for retrieving the same is:

let events = supplychainInstance.ItemProduced({}, {
    fromBlock: 0,
    toBlock: 'latest'
});

events.get((error, logs) => {
    logs.forEach(log => console.log(log.args))
});


texts: Stepping through Solidity source code with deployed transaction from blockchain

texts:
Let's say I have deployed a contract in the blockchain. I have send in a transaction into that contract and it apparently went to through and got accepted to blockchain.

If I have the contract source code (Solidity) is it possible to take an existing transaction data (from etherscan.io or similar service) and step through it against the source code line-by-line to see how the transaction modified the contract state. Preferably also get the contract state from the blockchain how was it before the transaction was run.

This is akin to old fashioned symbol debugging with more traditional compilers.


texts: Does PoW validate transactions too? In other words, would it be possibile to mine wrong transactions (yet I know they are not trasmitted to other peers). Thanks in advance!


texts: How to fix missing cudart64_70.dll for ethminer?

texts:
I'm barely starting my main rig to mine. I installed Nvidia's latest CUDA 7.5, but when I run my ethminer batch file, it gives me an error:

program can't start because cudart64_70.dll is missing

I've been googling everywhere but can't find a solution. I've read it means I don't have nvidia's cuda software installed but I do! I reinstalled it several times as well to make sure.

Not sure this helps but at the end of the installation of the cuda software, it mentioned that it didn't install Nsight for Visual Studio 2012 and 2010 because they were not found on my PC. I've installed 2012 community as nvidia mentioned but it still does not detect it, and no avail on 2010 since Microsoft removed the download for it.

My setup:

Windows 10 Pro x64
Nvidia Titan X
Intel Core i5 4570K
8GB RAM

Any ideas?


texts: Oraclize Is it possible to run simultaneously oraclize query?

texts:
Is it possible to run simultaneously oraclase query?
Because i have a probleme with this function:

 function closePhase1(uint contestID) payable MustBePhase1(contestID) ownerOrOrganiserOnly(contestID) {
    contests[contestID].phase = 2;

    for (uint i = 0 ; i < contests[contestID].nbVideos ; i++) {
        string ytID = contests[contestID].videos[i].youtubeID;
        debugStr(ytID);
        oraclize_query('URL', 'html(https://www.youtube.com/watch?v='.toSlice().concat(ytID.toSlice()).toSlice().concat(').xpath(concat("['.toSlice()).toSlice().concat(ytID.toSlice()).toSlice().concat(']", //*[contains(@class, "watch-view-count")]/text()))'.toSlice()));

    }
    debugStr('Demand send to oracle...');

}


texts: Which scope of variables changes the state of the contract?

texts:
I had been reading about the state of a smart contract. Here

It also gives a small example of a contract.

contract SimpleStorage {
    uint storedData;

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

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

Here we have a variable storedData and if we want to set it, a transaction with x is send and the state of the contract changes. As far as I understood it correct it is not necessary to send a transaction to read storedData. I can perform a local call.

Now what about the following contract:

contract SimpleStorage {

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

storedData is now within the function and saves the content but will this change the state of the contract? Do I have to send a transaction to call this function or is a local call enough?

From my programming knowledge I would say not but I am not sure when it comes to smart contracts :)

Thank you


texts: How can we make sure we are connected to the provider?

texts:
I'm looking to connect to a WebSocket Provider, and intermittently I'll get  an error saying:

Error: connection not open
[0]     at WebsocketProvider.send

Does a WebSocket connection contain callback data that I can reference so that I can begin calling functions AFTER my provider has been set?


texts: Get proof that a transaction was included within a block

texts:
I see that the web3 api has the getProof method: https://web3js.readthedocs.io/en/1.0/web3-eth.html#getproof

My question is - is there a similar way to get (and verify) a proof that a transaction x is within a block y? Similar to BTC's gettxoutproof (http://chainquery.com/bitcoin-api/gettxoutproof)?


texts: Why exposing the personal API is unsafe?

texts:
From what I am reading in various places such as  here ,here or here, it is not safe to expose the personal api to the front-end Dapp via RPC.

Hence asking the users to run geth --rpc --rpcapi "eth,net,web3,personal" --rpccorsdomain "http://yourDomain is not safe.

My question is why is that the case? I have the impression the links I provided gloss through it but I am still a bit unclear.

Thanks!

EDIT

From the answers I would like to expand/clarify a bit on my confusion:

A user logs into his computer and typesgeth --rpc --rpcapi "eth,net,web3,personal" --rpccorsdomain "http://yourDomain.com" on the terminal.

This enables his node to listen to http://yourDomain.com . Then he opens a browser and goes to the Dapp at http://yourDomain.com.

Then sure he would be able to mess around with his own node and accounts but how an external attacker could do that?


texts:
My Solidity linter warns me if I have more than 15 variables declared, and I got around this by packing multivariable into an array, such as changing
unit public x1;
unit public x2;

into
unit[2] public x;

I noticed the array uses a couple thousand less gas on initial creation (trivial), but after that, no difference when reading or writing.
It seems there is no explicit constraint on variables declared though there was at some earlier time. Is this true, and so for clarity I should separate out variables rather than pack them in to arrays?


texts: What is ethereum harmony for and what is a good starting point to get into Ethereum Dapp development?

texts:
I think, I understand what Geth is for, and I think I understand that EthereumWallet uses Geth to do all the blockchain io.

I thought to understand that Mist is the wallet, but that seems aiming too low.

What is harmony for? Does it initialize a private Ethereum network?

Finally: Could you suggest a good starting point to get into Ethereum Dapp development?

Thanks!


texts:
I am attempting to collect event information from a contract. When I call the event, I am attempting to collect a specific return value event.returnValue.pubkey. When I run the code below, I get the following type error TypeError: Cannot read property 'pubkey' of undefined.
Can you help me determine why this is happening
const Web3 = require('web3');

// instantiate Deposit Contract and web3 interface
const web3 = new Web3(new Web3.providers.HttpProvider("https://goerli.infura.io/v3/942365ea7fa043ac845ac1ba4aae57bc"));
const abi = [{"name":"DepositEvent","inputs":[{"type":"bytes","name":"pubkey","indexed":false},{"type":"bytes","name":"withdrawal_credentials","indexed":false},{"type":"bytes","name":"amount","indexed":false},{"type":"bytes","name":"signature","indexed":false},{"type":"bytes","name":"index","indexed":false}],"anonymous":false,"type":"event"},{"outputs":[],"inputs":[{"type":"address","name":"_drain_address"}],"constant":false,"payable":false,"type":"constructor"},{"name":"get_deposit_root","outputs":[{"type":"bytes32","name":"out"}],"inputs":[],"constant":true,"payable":false,"type":"function","gas":95389},{"name":"get_deposit_count","outputs":[{"type":"bytes","name":"out"}],"inputs":[],"constant":true,"payable":false,"type":"function","gas":17683},{"name":"deposit","outputs":[],"inputs":[{"type":"bytes","name":"pubkey"},{"type":"bytes","name":"withdrawal_credentials"},{"type":"bytes","name":"signature"},{"type":"bytes32","name":"deposit_data_root"}],"constant":false,"payable":true,"type":"function","gas":1754607},{"name":"drain","outputs":[],"inputs":[],"constant":false,"payable":false,"type":"function","gas":35793},{"name":"drain_address","outputs":[{"type":"address","name":"out"}],"inputs":[],"constant":true,"payable":false,"type":"function","gas":663}];
const address = '0x0F0F0fc0530007361933EaB5DB97d09aCDD6C1c8';
const depositContract = new web3.eth.Contract(abi, address);

//helper function + instantiating variables
const first_block = 2845084
let unique_addresses = [];
let validatorcountperidentity = {};

let getEventProperty = async (block_start, block_end) => {

    let events;
    await depositContract.getPastEvents('DepositEvent', {fromBlock: block_start, toBlock: block_end})
        .then(results => { events = results });

    for (event of events) {

        if (!(event.returnValue.pubkey in unique_addresses)) {
            unique_addresses.push(event.returnValue.pubkey)

            // validatorcountperidentity[]
        }
    }
}

getEventProperty(first_block, first_block);


texts: Calling contract method from already deployed contract

texts:
I have deployed a token contract, and now I want to use multiple transfers. I figured I can do this by deploying another contract which will run iteration over transfer function of my deployed token contract.

But I am getting failed transaction. I have run another test to clarify as well, below are the details:

Deployed Contract Sample:

contract MyToken {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function MyToken(
        uint256 initialSupply
        ) {
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        require(balanceOf[msg.sender] >= _value);           // Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
        balanceOf[msg.sender] -= _value;                    // Subtract from the sender
        balanceOf[_to] += _value;                           // Add the same to the recipient
    }
}

Caller Contract Sample:

pragma solidity ^0.4.21;

contract MyToken {function transfer(address _to, uint256 _value) public; }

contract ADTest {

    function CallTransfer(address tokenAddress, address _to, uint256 _value) public {
        MyToken(tokenAddress).transfer(_to, _value);
    }

}

Can someone please help with the solution? I am not sure what I am doing wrong.

UPDATE
I figured If I send some tokens to the caller contract, then caller contract sends to different addresses, without any problem. Not sure weather its a suitable solution for now, but might will help someone.


texts: I can add a mint to increase the supply but how do I decrease the supply of my token? I can send it to 0x0000000000000000000000000000000000000000 or create a contract which immediately self destructs and sends to its own address to make them unrecoverable but technically that doesn't change the total supply and frankly it's a bit crude. Is there a more elegant solution that preferably decreases the supply?


texts: How to fix CompilerError: Stack too deep, try using fewer variables?

texts:
When attempting to compile the following contract I am receiving the following error: InternalCompilerError: Stack too deep, try using fewer variables. How can I fix this?I want the getPerson function to emit all the data from AddPerson. If I reduce the variables in the functions,how do I achieve that?

pragma solidity >=0.5.0 <0.7.0;

contract PersonData {
    function AddPerson(
        string memory fullName,
        string memory residentialAddress,
        string memory sex,
        uint age,
        uint weight,
        uint height,
        string memory eyeColor,
        string memory hairColor,
        string memory complexion,
        string memory maritalStatus,
        string memory educationalLevel,
        string memory occupation,
        string memory placeOfBirth,
        string memory nationality
    )
        public
        returns (bool)
    {
        personCounter = personCounter + 1;
        Person memory person; //Person struct gives inbuilt method which is called person
        person.fullName = fullName;
        person.residentialAddress = residentialAddress;
        person.sex = sex;
        person.eyeColor = eyeColor;
        person.hairColor = hairColor;
        person.complexion = complexion;
        person.maritalStatus = maritalStatus;
        person.educationalLevel = educationalLevel;
        person.occupation = occupation;
        person.placeOfBirth = placeOfBirth;
        person.nationality = nationality;
        persons[msg.sender] = person;

        return true;
    }

    function getPerson(address _personToGet) public view returns (
        string memory fullName,
        string memory residentialAddress,
        string memory sex,
        uint age,
        uint weight,
        uint height,
        string memory eyeColor,
        string memory hairColor,
        string memory complexion,
        string memory maritalStatus,
        string memory educationalLevel,
        string memory occupation,
        string memory placeOfBirth,
        string memory nationality
    ) {
        fullName = persons[_personToGet].fullName;
        residentialAddress = persons[_personToGet].residentialAddress;
        sex = persons[_personToGet].sex;
        age = persons[_personToGet].age;
        weight = persons[_personToGet].weight;
        height = persons[_personToGet].height;
        eyeColor = persons[_personToGet].eyeColor;
        hairColor = persons[_personToGet].hairColor;
        complexion = persons[_personToGet].complexion;
        maritalStatus = persons[_personToGet].maritalStatus;
        educationalLevel = persons[_personToGet].educationalLevel;
        occupation = persons[_personToGet].occupation;
        placeOfBirth = persons[_personToGet].placeOfBirth;
        nationality = persons[_personToGet].nationality;
    }
}


texts: How do I get the "create" button to display?

texts: I am new to programming in general and solidity in particular. I wish to create a contract on the remix IDE, but can't locate the create button, rather it shows deploy. Here is a screen of the basic code and the problem I am facing. Many thanks for your kind assistance.


texts:
Deploy we are using  truffle

  truffle migrate --reset --compile-all --network rinkeby

when i am deploying i will be getting build folder in my project directory  while deploying through  the rinkeby will it  take the build folder  and  deploy. or what file we are deploying  in the solidity using these command


texts: I want to have some USDT and send that to my metamask account. If I have only USDT on my empty metamask account can I sed that USDT to another person without having ETH for the gas price? Cause other coins I used like Bitcoin and Litecoin always payed in their own currency the network price, but if I'll have USDT on my metamask account will I pay in USDT or I have to have USDT plus some ETH for the network price?


texts: Web3.py filter.get_new_entries() returns nothing if over 10 events have been emitted?

texts:
I'm using the following loop to try and add the metadata for tokens generated in my own smart contract, it all works exactly as intended when I am generating up to 9 "bots" at a time, but as soon as it's 10 or more, it doesn't seem to fire at all? Any idea as to why this could be? I know for a fact that the events are being emitted as I can see that in the smart contract.
Also, is this the best way to do this? Will this work with a real Ethereum infura node? Thanks a bunch!
def log_loop(newBot_filter, poll_interval):
    while True:
        for event in newBot_filter.get_new_entries():
            bot = event['args']
            print(bot)
            dbh.add_bot(bot['_id'], ...)
        time.sleep(poll_interval)

newBot_filter = contract.events.NewBot.createFilter(fromBlock='latest')
Thread(target=log_loop, args=(newBot_filter, 2)).start()


texts:
Is there a theoretical limit for transaction data size when you send a transaction to Ethereum network?

Ref.

Is there a (theoretical) limit for amount of data that a contract can store?


texts:
I am following this tutorial. Everything worked fine. Now I want to getBalanceOf tokens on my nodejs app, but I keep getting this error:

tokenContract.methods.balanceOf is not a function.

My code is as follows:

var provider = new web3.providers.HttpProvider(node.url);
            var w3 = new web3(provider);

            var tokenContract = new w3.eth.Contract(abi, query.token_address);

            console.log(tokenContract);

            w3.eth.call({
                to: query.pub_address,
                data: tokenContract.methods.balanceOf(query.pub_address).encodeABI()
            }).then(function(balance) {
                console.log(balance);
            }).catch(function(error) {
                console.log(error)
                reject(error)
            })

If I check my tokenContract methods in console, by printing (tokenContract.methods) I see there is no balanceOf method exposed.

Any ideas?


texts: How to move from testrpc development to geth?

texts:
I've made an application in nodejs in which I'm doing truffle migrate to deploy contract and it make my contract's build saving my ABI which i use for contract invocation and the http provider for web3 is localhost:8545???
How should I switch to Geth environment if I want to test it on a public test network?? Been stuck at this query, any help appreciated.


texts: Issue sending ETH to smart contract with web3js/metamask

texts:
So I have a simple smart contract (shown below).
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract Casino {

    function pay() external payable{

  }

    function getContractBalance() public view returns (uint256 balance){
       return address(this).balance;
    }

    function getContractAddress() public view returns(address){
           return address(this);
    }

    receive() external payable{

    }
}

What I want to do:
Send ether to Casino smart contract.
My issue:
I've been using web3js to interact with my smart contract. From there,
I call:
await web3.eth.sendTransaction({from: sender, to: CasinoContractAddress, value: someValue})

What happens is metamask opens and I can submit the payment. But in the end, the transaction fails and I get this error in console:
Error: Transaction has been reverted by the EVM:
{
  "blockHash": "0x53b67f247f1fb81265767bcf3d6987c7cdfd230dad2fe3e7d79fa67c1ba9dd1e",
  "blockNumber": 9715752,
  "contractAddress": null,
  "cumulativeGasUsed": 54114,
  "from": "0xc106b46180d0ad4e5302e7ccb9485c819adc3fff",
  "gasUsed": 21045,
  "logs": [],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "status": false,
  "to": "0xdc1812ae654aa8556d64b300c0527541f911b797",
  "transactionHash": "0x4373e277493fa4f478ffd2a929c7023e463bfbd2cdf3b520abc3b230b0f6de21",
  "transactionIndex": 1
}
    at Object.TransactionError (errors.js:87)
    at Object.TransactionRevertedWithoutReasonError (errors.js:98)
    at index.js:394

I'm stumped on this issue and would really appreciate some help. Thanks!


texts: Solidity 'real' type and fixed point regimes

texts:
I'm sure I read somewhere that Solidity had a fixed point type 'real' of format 32byte.32byte, though the docs say Fixed Point numbers are still to come.

Until it's implemented, is there any best practice or existing library for Fixed Point maths?


texts:
I just made some updates to my contracts and tried to redeploy them - but I'm getting this message, over and over again.

Its not even attempting any of the migrations - it just goes right to this message - and obviously, despite what its saying, everything is not up to date.

I also tried adding the --reset flag to my migration command - same result.

I also deleted the build folder and did everything again: re-compiled, then tried the migration again - same result:

Everything is up to date ...

Any idea what's going on?


texts: Efficient approach to delete element from array in Solidity

texts:
For each user, I want to keep an array of holded assets (each asset has an ID).

My solution up until now is :

struct User {
        uint userId;
        uint[] assets;
    }

For every asset the user holds I push to the user's array the ID of the asset.

I want to give the user an option to delete an asset.

What would be the most efficient approach to this?

Allocating all of the available assets for every user (would be very wasterful given you have a lot of assets available) VS. iterating over all of his assets everytime he'd like to delete an asset, finding it in the array, then deleting it from it and shifting all of the array accordingly - also, the code for this is kinda hideous :

function deleteAsset(uint assetId) external returns(uint) {
        bool assetFound = false;
        // Check if the asset found is the last asset (or we go out of boundaries)
        if (allUsers[msg.sender].assets[allUsers[msg.sender].assets.length - 1] == assetId){
            assetFound = true;
        }

        else{
            // Iterate over all user assets and find its index
            for (uint i = 0; i < allUsers[msg.sender].assets.length - 1; i++) {
                if (!assetFound && allUsers[msg.sender].assets[i] == assetId)
                    assetFound = true;

                if(assetFound)
                    allUsers[msg.sender].assets[i] = allUsers[msg.sender].assets[i + 1];
            }
        }

        if (assetFound){
            delete allUsers[msg.sender].assets[allUsers[msg.sender].assets.length - 1];
            allUsers[msg.sender].assets.length--;
        }
    }

Would be a lot easier if I could save a mapping for each user indicating what asset does he have, but you can't return a mapping from a function and I don't know the benchmarks of view functions and "brute-forcing" all of the assets available for each user can take a plenty of time I assume.


texts: Getting Metamask account's balance using fromWei

texts:
Using web3 javascript code to get selected account's balance in Metamask and show it in html,

web3.eth.getCoinbase(function(err, account) {
  if (err === null) {
    App.account = account;
    $("#account").text(account);
    web3.eth.getBalance(account, function(err, balance) {
      if (err === null) {
        $("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
      }
    });
  }
});

and now I'm using angular 4 trying to convert above code to typescript.

const Web3 = require('web3');
const contract = require('truffle-contract');
const myBettingArtifact =
require('../../../build/contracts/Test.json');
declare var window: any;
...
account: any;
accounts: any;
web3: any;
balance: number;

this.web3.eth.getAccounts((err, accs) => {
  if (err != null || accs.length === 0) {
    return;
  }
  this.accounts = accs;
  this.account = this.accounts[0];

  this.web3.eth.getBalance(this.account, function(err, balance) {
    this.balance = this.web3.fromWei(balance, "ether") + " ETH"
  });
});

However I get an error

    Uncaught TypeError: Cannot read property 'fromWei' of undefined

What is the problem here?


texts: Is it possible to send erc20 token when I have 0$ ether but $1000 in the token?

texts:
Long story short I have $1000 in one erc20 token contract but 0$ in ETH.
Can I at least transfer these $1000 from the token to another address without ethereum asking for gas? That is: just change owner of token funds without transaction occuring on the ethereum blockchain? 10x!


texts: Deploy contract - have total supply but no token holder and balance

texts:
I deploy my contract to etherscan (rinkedby and etherscan). I have my total supply set but i can't see any in in network after deploy.

I even copy the contract ceration code exactly from this contract address to deploy but it does not work: Contract code here. And from several ICO contract address that is live too. (including those with event Transfer to transfer token to owner)

Can anyone verify that is this a code/deployment problem or etherscan testnet problem?

Note: Similar question asked in this stackoverflow post
This is another link to smart contract that shows the same thing

sample code:

function Token(address _crowdSaleAddress) public {

        locked = true;  // Lock the Crowdsale function during the crowdsale
        totalSupply = 300000000e18;
        name = "TGAME"; // Set the name for display purposes
        symbol = "TGAME"; // Set the symbol for display purposes
        decimals = 18; // Amount of decimals for display purposes
        crowdSaleAddress = _crowdSaleAddress;
        balances[crowdSaleAddress] = totalSupply;
    }


texts: Dividing Ether Past Smallest Unit Possible?

texts:
I've read that ether is divisible to 1018.

Say you're writing a simple contract which takes deposits sent to it divides the deposit in 2 and sends it to 2 separate addresses. What happens if someone doesn't take into account the smallest possible amount being deposited? Will the contract simply not accept the deposit or will it accept it then fail?


texts: How to accept bitcoin and transfer tokens from smart contract to sender ethereum address

texts:
I have created sample tokens Smart Contract with the payable feature/constructor, if someone pay from their Ethereum address to Smart Contract will get instant token into their Ethereum address.

But how can I accept bitcoin like most of ICO provide an option to buy their Tokens with bitcoin, how they provide unique bitcoin addresses to every new user, and after receiving bitcoins on that address, how they manually/automatically transfer tokens into payee Ethereum address?


texts:
I am looking into getting the public key from ANY ethereum address (not owned by me) that has sent a transaction at least once. It seems that the most viable solution here would be to use ethereumjs-utils

/**
 * ECDSA public key recovery from signature
 * @param {Buffer} msgHash
 * @param {Number} v
 * @param {Buffer} r
 * @param {Buffer} s
 * @return {Buffer} publicKey
 */
exports.ecrecover = function (msgHash, v, r, s) {
  var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64)
  var recovery = v - 27
  if (recovery !== 0 && recovery !== 1) {
    throw new Error('Invalid signature v value')
  }
  var senderPubKey = secp256k1.recover(msgHash, signature, recovery)
  return secp256k1.publicKeyConvert(senderPubKey, false).slice(1)
}

The user mentions that

  when you send a transaction, you sign the transaction and it includes these v r and s values. You parse these from the signed tx and then pass these v r and s values and the has of the transaction back into a function and it'll spit out the public key

This last step is completely unclear to me. I do not understand how we parse "v", "r" and "s".

Picking a random transaction hash on Etherscan.io, how are we going to "parse" the v,r and s parameters?


texts: Error while deploying contract to the Ropsten testnet

texts:
I'm trying to deploy a contract (called "FilesDetailsManager") to the Ropsten Testnet using Truffle and Infura as provider.
But when I type into terminal truffle migrate --network ropsten, I get this error:
Error:  *** Deployment Failed ***

"FileDetailsManager" -- only replay-protected (EIP-155) transactions allowed over RPC.

I searched online but I did not get any advice for solving the issue, and I actually don't know what this error means.
Do you have any idea about how to solve the problem or what the error means?
Thank you in advance for the time spent reading.
PS: The truffle-config.js file looks like this (if it can be useful):
const HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
const MNEMONIC = 'wallet key censored';

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    develop: {
      port: 8545
    },
    ropsten: {
      provider: function() {
        return new HDWalletProvider(MNEMONIC , "https://ropsten.infura.io/v3/infura api key censored")
      },
      network_id: 3
    }
  }
};


texts: How much is visible to someone who looks at a contract without having the ABI definition?

texts: My question is if I deploy a contract online, say for example, a contract that represents a loan between Mary and Peter. How much would someone see who tried to decode the block? Is it correct to say that any variable that is public would be visible in hex (so visible as text after decoding)? What about private variables? How about function code itself? Can you store data in the blockchain such that it is not readable?


texts: Problem calling function with web3.eth.contract

texts:
How come when I call a function and pass it parameters, it spits out an error? I try to print the updated name (UPDATED) but it's unable to pass it back.

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

var myContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"x","type":"string"}],"name":"setTokenName","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_tokenName","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}])
var contractInstance = myContract.at('0x8b3c0bf558d5b25a91d8c5a5cbc48648285ad136');

contractInstance.setTokenName('UPDATED');

var updatedresult = contractInstance.get();

console.log(`updated name should be here: ${updatedresult}`);


texts: H81 Pro BTC R2.0 + 6x ASUS ROG Strix GeForce® GTX 1070

texts:
I'm interesting to buy H81 Pro BTC R2.0 and 6x ASUS ROG Strix GeForce® GTX 1070
Does it work, how much mh/s can I get normally with 1x ASUS ROG Strix GeForce® GTX 1070?


texts:
Here is some random contract: 0x8055d0504666e2B6942BeB8D6014c964658Ca591

Pretend that the ABI was not uploaded on etherscan.io.

I want to run the function supportsInterface(bytes4) with data 0xa9059cbb on that contract.

How do I do this with geth?


texts: How make other machines join my private ethereum network.

texts:
I have created a private ethereum network in my machine, and now I want that other machines join my network.

I think I have to send them the IP of the bootnode, but the question is : what about the genesis block ? ..

to init a node we run "geth --datadir node1/ init genesis.json" so do they need my genesis file ?


texts: Uncaught TypeError: CoursetroContract.at is not a function

texts:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
    // If a web3 instance is already provided by Meta Mask.
        web3 = new Web3(web3.currentProvider);
} else {
    // Specify default instance if no web3 instance provided
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

web3.eth.defaultAccount = web3.eth.accounts[0];

var CoursetroContract = new web3.eth.Contract([ {abi address
]);
var Coursetro =CoursetroContract.at ("address");

console.log(Coursetro);
</script>
</body>
</HTMl>


texts: Parsing ethereum chaindata using leveldb

texts:
I'm new here :)

I'm writing a c++ program that parses ethereum chain data. As of present I was able to get the key value pairs by using leveldb::ReadOptions command (as illustrated in the below code) and convert them into hex. I know there is some sort of RLP encoding to encode the "value" Values and hex prefix encoding to encode the "key" values. Some sort of hashing might also be used.

My issues are:

How can i know what data i'm getting
How can i verify the data is correct

The below code is what i have written so far:

leveldb::DB* db;

leveldb::Options options;

leveldb::Status status;

leveldb::ReadOptions readOptions;

options.error_if_exists = false;

options.create_if_missing = false;

status = db->Open(options, path, &db);

if (!status.ok()) {

    std::cout << status.ToString() << std::endl;

    return -1;
}

try {

    leveldb::Iterator* iterator = db->NewIterator(leveldb::ReadOptions());

    iterator->SeekToFirst();

    while (iterator->Valid() && iterator->status().ok()) {

        leveldb::Slice key = iterator->key();
        leveldb::Slice value = iterator->value();
        std::string keyString = key.ToString();
        std::string valueString = value.ToString();
        const char* keyData = key.data();
        const char* valueData = value.data();
        std::cout << "Key: " << GetHex(key.ToString()) << std::endl
        std::cout << "Value: " << GetHex(value.ToString()) << std::endl;
        iterator->Next();
    }
}
catch (const std::exception& e) {

    std::cout << e.what();
}

Thanks In Advance and sorry if the code is not really readable but this is the first time i'm writing a post.


texts: Suicide became Selfdestruct, kill became destroy. What would be a good replacement for "mortal"?

texts:
Mortal is not a reserved word but it's a pretty explicit qualifier for contracts subject to self-destruction.

The change from suicide/kill to selfdestruct/destroy is a good initiative, but mortal kind of lost its meaning. What would be a good replacement ? I can't find anything satisfying.


texts: Trying to initialize accounts as global variable before starting Node console

texts:
Basically, I am trying to run a script that initializes all the variables I'll need during my Node console session. The script looks like this:

global.Web3 = require('web3');
global.web3 = new Web3(new
Web3.providers.HttpProvider('http://localhost:8545'));

global.Tx = require('ethereumjs-tx');

global.solc = require('solc');

global.accounts;
web3.eth.getAccounts().then(_accounts => {
    accounts = _accounts;
});
require('repl').start({});

So far, everything works fine, until time to set the accounts variable. Running the script and calling it produces the following:

➜  ethtest node init.js
> accounts
ReferenceError: accounts is not defined
    at repl:1:1
    at ContextifyScript.Script.runInContext (vm.js:35:29)
    at REPLServer.defaultEval (repl.js:342:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:539:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:232:10)
    at REPLServer.Interface._line (readline.js:583:8)

I'm pretty sure I'm misunderstanding something simple, but so far, I've been unable to figure it out. Any help would be much appreciated. Thanks!


texts: Solidity concatenate uint into a string?

texts:
How would I concatenate an integer into a string using solidity?

For instance, say I have the following:

uint myInteger = 12

How can I create the following string "My integer is: 12" with 12 being the value of myInteger.

In other words have, "My integer is: " + myInteger


texts: Metamask not returning the current address

texts:
I am using web3.eth.getcoinbase() function to get the address of the current account but instead, it returns null. Can someone help me with this? This is the code

web3.eth.getCoinbase(function(err, account) {
  if (err === null) {
    App.account = account;
    $("#accountAddress").html("Your Account: " + account);
  }
});

The entire code is in here


texts: How does this smart contract have multiple contracts with one address?

texts:
https://etherscan.io/address/0xabc1c404424bdf24c19a5cc5ef8f47781d18eb3e#code

Notice that this contract has:

contract SafeMath
contract BasicAccessControl
contract EtheremonEnum
contract EtheremonDataBase
contract EtheremonData

All under one contract address. How would one deploy all of these to one contract address?


texts:
I have a ERC-20 contract with the main function´s. I generate 1000000 coins and I´m trying to do the following:

There are 3 user´s (a, b, c)
The c user have 10 coins, and wants to aprove to the b account to be able to manage 5 coins of the c user. For send to the a account.

I make this:

Unlock accounts
Send 10 coins to the c account
Call to the approve function with the account c address and the quantity of coin´s

Now I don´t know what I have to do. Because in the approve function I approve 5 coins to the c account. But I don´t specified that the b account will be able to manage that coins.

Once that is made i have to call to the transferFrom and give like parameter the the b account (allowed account), the a account (receiver) and the quantity


texts: What does tokens/smart contract owner do about the fund sent to smart contract

texts:
I am new in blockchain technology and interested to learn more about Ethereum. I have followed some tutorial about creating my own tokens. I have successfully created tokens on test network but I don't seem to be able to find information what to do with ether sent to the smart contract address.

I read some discussion here about how smart contract owner can withdraw from smart contract but I am not sure if that's the right practice.

I want to create tokens not only to raise funds but also to use it for other application. So I would like to reserve some tokens to fund the development but then others can buy/trade tokens.

Any pointer to references about this would be appreciated. Thank you.


texts:
Can someone, please, explain, how this works:

I have contract MigrationAgent which has migrateFrom() function (not implemented). And I have NewContract is MigrationAgent which implements migrateFrom(). I deployed that contract, have its address 0x*****.

To call this function from other contract, as I see in example, I have to do this: MigrationAgent(0x*****).migrateFrom();

Why is this? I can't understand logic of this syntax. Why can't I write 0x*****.migrateFrom() and what if I write MigrationAgent(0x*****).migrateFrom() when 0x***** is not MigrationAgent?


texts: Paid Ether to ICO but tx failed, however the Ether is not returning to my wallet!

texts:
Earlier today I have made an ether payment to an ICO, due to I just updated my ethereum address on that ICO web page, it wasn't updated correctly on their database, hence when I sent the ether it failed :

Ether transaction: here

Block information: here

This is the first time I send ether and it gone missing now. Hope you experts can help!

Many thanks in advance.


texts: how to curl to etherium geth node on local network (not localhost)

texts:
I have geth running on local network (separate machine). curl'ing to http://localhost:8545 works just fine. How do I curl to that geth node from another machine on my private network? Curling to http://10.x.x.x:8545 just returns connection refused.
geth itself is all up and running on the other 10.x.x.x machine just fine and geth attach, curl, etc all work on localhost on that box.
e.g. this works:
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}' http://localhost:8545
result: ➜ {"jsonrpc":"2.0","id":67,"result":"Geth/v1.9.17-unstable-5b081ab2-20200714/darwin-amd64/go1.13.6"}
this fails (from another machine on that private network):
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":67}' http://10.x.x.x:8545
result ➜ curl: (7) Failed to connect to 10.x.x.x port 8545: Connection refused
(using real IP's instead of x's of course)
Both nodes communicate just fine otherwise (ssh, browse websites, file sharing, etc...)


texts: Contract is not deploying properly on Geth private network using web3j SDK

texts:
I am new to Ethereum.
I have created private blockchain using Geth on my local and trying to deploy my smart contract using java web3j SDK.
I am able to deploy my contract using java and getting contract address but when I try to call createItem() method to set some values then its not able to set those values. Infact, if I will try to access the contract using the contract address in remix, I am still not able to set those value. Whilst if I will deploy my contract from remix IDE then I am able to call createItem() methods from both remix and my java code. Here is my contract file Item.sol

pragma solidity >=0.4.22 <0.6.2;

contract Item{

    uint id;
    uint items;
    uint startDate;
    uint endDate;
    bool isValid;

    address public owner;

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

    modifier restricted() {
        require(
            msg.sender == owner,
            "Only owner can call this."
        );
        _;
    }

    function createItem(uint _id,  uint _startDate, uint _endDate, uint _items, bool _isValid) public {
        id = _id;
        startDate = _startDate;
        endDate = _endDate;
        items = _items;
        isValid = _isValid;
    }

    function validateItem() public {
        isValid = true;
    }

    function getItemData() public view returns (uint, uint, uint, uint, bool) {
        return (id, startDate, endDate, items, isValid);
    }

    function getId() public view returns (uint) {
        return id;
    }

    function getItems() public view returns (uint) {
        return items;
    }

    function getStartDate() public view returns (uint) {
        return startDate;
    }

    function getEndDate() public view returns (uint) {
        return endDate;
    }

    function isValidItem() public view returns (bool) {
        return isValid;
    }

}

This my java code to deploy the contract

        Web3j web3j = Web3j.build(new HttpService());
        Credentials credentials = WalletUtils.loadCredentials(“password”, PRIVATE_KEY);
        String contractAddress = Item.deploy(web3j, credentials, new DefaultGasProvider()).send().getContractAddress();
        log.info("contract deployed at address : " + contractAddress);
        Item contract = loadContract(contractAddress, web3j, credentials);
        TransactionReceipt receipt = contract.createItem(BigInteger.valueOf(20), BigInteger.valueOf(1577880090),
        BigInteger.valueOf(1580472090), BigInteger.valueOf(1000), true).send();


texts:
Hello is it possible to execute this "multiplicate" function? Assume I put 1 ETH to the contract as an owner, but when a hacker sends 2 ETH to the multiplicate, this.balance becomes 3 at the beginning of the function and then it's always greater than the msg.value. I wonder if I am missing something.

contract Multiplicator
{
    address public Owner = msg.sender;

    function() payable{}

    function withdraw() payable public
    {
        require(msg.sender == Owner);
        Owner.transfer(this.balance);
    }

    function multiplicate(address adr) payable
    {
        if(msg.value >= this.balance)
        {
            adr.transfer(this.balance+msg.value);
        }
    }
}


texts: I have designed a lottery contract which allows users to purchase tickets from a ticket pool of a given size. Once all the tickets have been allocated, the lottery is carried out and the winner obtains the funds. The issue is that my code triggers the lottery when the final user purchases the tickets, therefore the gas used by the final purchase is 30% higher than the gas used by all other purchases, due to the additional code being executed. For the purpose of fairness, is there a way I could optimise this so that all users pay the same amount of gas. I was thinking of periodically checking if all the tickets have been issued and if so, carrying out the lottery. I am not sure how to do this though.


texts: How to get array elements in JavaScript from contract call with JSON-RPC returning an array?


texts: How to make an action to send record to my database?

texts:
I want all transaction of the tokens send to my database through smart contract.

For example, A send 10Token to B, it will show on blockchain, but I also want a function which smart contract will let my server save and record this transactions.

I am using php for this record.


texts:
There is a "move" command in Bitcoin, Litecoin, Dash etc. which lets you move balances between wallets in your node without paying a transaction fee.

I wonder if there is a similar command in geth? I'm currently using geth and transferring balances between wallets with eth.sendTransaction command which costs me extra tx fee.


texts: Mining, Ethers and Private Blockchain DAPPs

texts: I am building a private Blockchain cluster DAPP envisaged to have 5 to 10 parties owning their own nodes (or node clusters). At this moment, there is no specific mandate to incentivize miners, though we would like to do so in future DAPP releases. In fact, the only reason mining is done is because there is no other option to validate and commit transactions onto the Ethereum Blockchain. In this context - a.) What good are the Ethers that are produced due to the afore-mentioned mining? b.) Is this an Ethereum usage anti-Pattern, in that - am I doing something that Ethereum was not built for. Aspects of Blockchain such as Immutability/ decentralized ledger / P2P nodes / Encrypted data : all of these are very germane to the work that I am doing, in that sense - Ethereum is a good fit. So, happy to hear comments .. Thanks


texts: Testing Contract: Transaction has been reverted by the EVM

texts:
I am writing a testing file for my coin flip project here is the beginning of the coin flip project:
contract CoinFlip {
address payable player;

address payable casino;
uint256 public casinoDeposit;
uint256 betAmount;
uint256 maxBet = .001 ether;
bytes32 commitHash;
uint gameTimeOut;
uint256  matchBetTimeOut;
uint256 revealTimeOut;
uint256 result;
bool win;
address payable contractAddress = address(this);

constructor () public payable{
    require(msg.value == 1 ether);
    casinoDeposit = msg.value;
}

Here is the testing file:
contract CoinFlipTest {
CoinFlip v;
function beforeAll() public {
    // create a new instance of Value contract
    v = new CoinFlip();
}

Every time I try to run the testing file I get this error. I would appreciate some help on what I am doing wrong:
✘ Before all
Error Message:
"Transaction has been reverted by the EVM: { "transactionHash": "0x0e839950a7737797d4c9fca76adb24d1ec0ff7d07b3b87eea5c3a8487d123043", "transactionIndex": 0, "blockHash": "0x9cc0f6017494c03c53ebbe39aef033623ed7f6e6937c6d376b7c3a0d78392b86", "blockNumber": 8, "gasUsed": 5000000, "cumulativeGasUsed": 5000000, "status": false, "to": "0xd2a5bC10698FD955D1Fe6cb468a17809A08fd005", "events": {} }"


texts: Add a transaction fee for each time a function is called

texts:
currently I'm writing my first contract in Solidity.
Now I have a function which looks like this:

function sellEnergy(uint kwh) public {
    coinAccount[msg.sender] += (kwh * kWh_rate);
}

What I want to do is that everytime this function is called, the user who calls it, should pay a fee of a few cents to the owner. Is that possible? If so, how?


texts: Why does a miner still pay gas for a reverted transaction?

texts:
I ran a contract here, I got the message "Transaction mined but execution failed". :

  [vm]from:0xca3...a733cto:Will.deceased() 0xbbf...732dbvalue:0
  weidata:0x72f...af2d9logs:0hash:0xac5...6c5be  status     0x0 Transaction
  mined but execution failed  transaction hash
    0xac5e9ba96b61041582a22490d2947cc4d7f0f153255fb0ac273d931035c6c5be
  from  0xca35b7d915458ef540ade6068dfe2f44e8fa733c  to  Will.deceased()
  0xbbf289d846208c16edc8474705c748aff07732db  gas   3000000 gas
  transaction cost  56697 gas   execution cost  35425 gas   hash
    0xac5e9ba96b61041582a22490d2947cc4d7f0f153255fb0ac273d931035c6c5be
  input     0x72f...af2d9  decoded input    {}  decoded output  {}  logs    []
  value     0 wei  transact to Will.deceased errored: VM error: revert.

Why is the miner still paid?


texts: Dollar price of PYRO on Coinbase has risen 400% but relative swap rate for ETH on Uniswap remains the same - why?

texts:
I swapped ETH for PYRO when the Australian dollar (AUD) price of PYRO  was showing as around $0.00008 on Coinbase. The AUD price of Ether was around $2314 (AUD), so I swapped 0.04 ETH for 1,157,000 PYRO. In other words, the ETH 'price' I paid for PYRO was what was showing on Coinbase ($0.00008 AUD).
The Australian Dollar cost of PYRO on Coinbase later increased sharply, and showed as $0.00040 (500% of my original purchase cost). When I previewed a swap from PYRO back to ETH around 90 minutes after this price rise first showed on Coinbase, it's shows that I would get 0.036 (actually less than my original ETH purchase cost). Why is this? I would expect to be able to swap for around 500% of my original ETH purchase cost, i.e. 0.2 ETH.
UPDATE
The Etherscan page (filtered for me as a token holder), and showing details of the PYRO token contract address (0x14409b0fc5c7f87b5dad20754fe22d29a3de8217) is here - (https://etherscan.io/token/0x14409b0fc5c7f87b5dad20754fe22d29a3de8217?a=0xf8e3c5b22db3d1b1b6aaee35440eff1981fcb53e). This shows my current holding, correctly reflects the price rise of my holding (actually around 800% at the time I'm writing this). It shows that my holding is now valued at 0.33 ETH, but this still isn't reflected on Uniswap


texts: Running out of gas when deploying contract in Ropsten Testnet

texts:
I am trying to create a Fomo3d clone contract in Ropsten testnet for debugging purpose. Here is the code: https://etherscan.io/address/0xa62142888aba8370742be823c1782d17a0389da1#code

But I am constantly getting out of gas error even I specified the maximum gas possible.
https://ropsten.etherscan.io/tx/0x854a0172c8ec78c3c5af3c45e7bd05385cb41ad7f635fa5e80c2781ec147b4fd


texts: why are transactions per block so small using web3.js?

texts:
When utilizing web3.js and calling on the "getBlock" using "latest" as a parameter, there are only several hundreds transactions.. but when I look at the average transactions per block charts on various websites, it mentions that there are 2.5k on average.
    web3.eth.getBlock('latest', true, (err,data) => {

    console.log(data.transactions.length)
    // --> 160
})

Context: I'm trying to build an application that monitors transactions as they come in real time to render graphically what is going on. What is the best way to go about it? My current approach is just to keep polling the latest block and using that data as my primary data source


texts: BigNumber string error when passed as uint256

texts:
I get the following error when passing (new BigNumber('2')).exponentiatedBy(100) big number value as uint256

Error: invalid BigNumber string value (arg="value", value="1.267650600228229401496703205376e+30", version=4.0.28)

I am using Truffle, but seems like a web3 issue? I'm not sure. Anyone seen this before. Wouldn't a valid uint256 go up to 2^255 ?


texts: Blockchain use case – Trying to understand provenance tracking

texts:
I am trying to understand how blockchain would be helpful in provenance tracking of goods.

Example:
Company X is using blockchain technology to import pork into USA. Let us assume there are many agents in between who transfer porks and finally reaches USA.

My understanding is a every agent who is sending pork would generate a public key + private key combination and add it into blockchain. By doing this way, one can track who the origin.

If my understand is right, why can’t this be done with a normal database ?


texts:
In the parity chain spec file, there is a value for NetworkID.  Is this in hex or decimal?

On the geth command line, you can specify the network with "--networkid X".  Is that hex or decimal?

I am starting to wonder if the reason my geth and parity nodes cannot talk to each other is because I'm encoding the numbers differently.


texts:
function() payable external {
    eth_balance[msg.sender] += msg.value;
}

This is not working. The execution is reverted and uses about 21,000 gas. No matter if I set the gas crazy high like 800,000 it still fails. This is on rinkeby network. Any ideas? I'm using Remix IDE.


texts: How can I call a function that performs a transfer in web3?

texts:
I would like to call a function in smart contract using web3. In the function, I perform few transactions.
The first method that I tried is await myContract.methods.endAuction().call();. This reverted the transaction with the error message "Auction owner is not authorized" which is strange since I succedded in calling previous function from the same smart contract which had the same restriction.
The second method I tried is await myContract.methods.endAuction().plasticBaleSC.methods.endAuction().send({from: accounts[0]}); which caused the transaction to fail with no revert message.
The function that I want to call is this:
function endAuction() onlyOwner public{

        require( isOpen, "Auction is not avalible.");
        require(endTime < now, "Auction duration is not up yet.");
        require(highestBidder != address(0), "No bids have been placed");

        isOpen = false;

        uint halfAmount = highestBid/2;

        (auctionOwner).transfer(halfAmount);

        uint contributionRate =0;
        uint reward;

        for(uint i=0; i < contributors.length; i++){
                uint j;
             for(j=0; j < i; j++)
                  if(contributors[i] == contributors[j])
                      break;
                if(i==j)
                tempArray.push(contributors[i]);
              }

        for(uint i=0; i < tempArray.length; i++){
            contribution=0;
             for(uint z=0; z < contributors.length; z++){
                  if(tempArray[i] == contributors[z])
                      contribution++;
             }
             contribution = contribution *100;
             contributionRate = contribution / (plasticBale.length);
             reward = ((contributionRate * halfAmount)/ 100)+1;
             tempArray[i].transfer(reward);
             rewardRecycler(tempArray[i], reward);

        }

          for(uint i=0; i< plasticBale.length; i++)
          updateBottleStatus(highestBidder, plasticBale[i]);

        emit auctionEnded(address(this), highestBidder, highestBid , now);

    }

modifier onlyOwner{
        require(msg.sender == auctionOwner, "Auction owner is not authorized");
        _;
    }

Any advice on what should I do?
Edit: This is a link to the full contract code although you might want to remove the modifiers for now since onlyBuyer interfaces with another smart contract EthFiddle


texts: Detecting smart-contract calls and reacting to 0-conf?

texts:
My question. Let's say I have a contract like

contract PowerManager {
    function unlock() { ... }
}

I want to respond to the unlock() function by unlocking an IoT device. Is it possible to detect this in the mempool as soon as it appears?


texts: Yesterday I made a tron transaction but I never got it verified by etherscan and it appears but in my balance it does not appear what should I do?


texts: Constantinople hard fork and Ethereum based tokens

texts: I have a question: Do we have to deposit all of our Ethereum tokens into some exchange before the Constantinople hard fork, otherwise our tokens will become worthless? Or we can leave our tokens in our ETH wallets as we did until now? This hard fork is very confusing, it makes people fear they will lose their tokens or their tokens value...


texts: What does the keyword `super` in Solidity do?

texts: I came across the super keyword in Solidity in the context of overriding functions. What does it do?


texts: What s the fake deposit attack affecting some exchanges with erc20?

texts:
There are a lot of articles about hacked tokens affecting centralized exchanges only when Googling fake erc20 deposit but
I failed to find a reference describing how the attack works technically.
The only technical description I found is not usefull because of the language https://mp.weixin.qq.com/s/3cMbE6p_4qCdVLa4FNA5-A


texts: Can you please suggest me some test use cases that are applicable for a smart contract that has a multi-signature wallet in Ethereum?


texts:
I'm developing a contract whose storage is very large.

I have exactly 23 fields in a struct, that is the value part of a mapping.
All the data must be included at once, but given the stack size limit, I can't have all of them declared in the function signature.

So I was thinking about "compressing" most of the parameters into a serialized string (JSON, maybe), but I really need this data to be stored as independent fields. Therefore, I'd need to unserialize this big chunk of data.

Another possibility is to consider everything a big byte array, with fixed size fields, and then split it up in a predefined order.

Is any of these possible?


texts: How can i reset ether balances in truffle?

texts:
If you use truffle for a while, you gradually deplete all your ether from the default account.  Now truffle is defunct.  How do I top-up the ether?

Note I think truffle uses testrpc in the default when you run truffle test or truffle develop.  But I don't know how to take advantage of this, and can't find where testrpc is installed.

Clarifications added after initial post:

Truffle starts testrpc internally when you run truffle test, so I can't provide parameters to testrpc.  Truffle/testrpc save the ether balances from run to run, so that the ether balance for accounts[0] is continuously depleted over time.  I have been constantly replenishing the ethers in accounts[0] by transferring ether manually from higher numbered accounts in the truffle develop console.  Also, I can't find where testrpc is installed so I can't run it manually.  Additionally, I can't figure out how truffle runs testrpc, though I have looked in the truffle executable file (/usr/local/bin/truffle on my computer).

Solution:

Turns out my problem was I had an instance of truffle develop running in another tab.  That is why the ether balances were continuously depleting.  Oops!


texts:
I have ETH and I am building a portfolio.

How will I be able to stake my ETH holdings and make sure these are safe?

Can someone please provide some guidance? Thanks


texts:
I want to create a simple page to interact with my deployed contract. I don't want to use Node.js. I want to use html + web3.js browser version. I got a link: https://github.com/ethereum/web3.js/tree/develop/dist

But the above link contains web3.js files that contains "require" keyword which cannot run in browser. I want browser version of web3.js.


texts: How to add burn function to an ERC20 and ICO smart contract?

texts:
I have found and deployed an ERC20 smart contract with a crowdsale function.
I could set up:

the number of initial tokens which were minted on my address when I deployed the contract
the number of tokens reserved to be minted in the crowdsale
the price of crowdsale: number of tokens / 1 ETH

I tested it and it's working as supposed. All great.
But now I thought some more and I want a burn function to it. I want to burn 3% from each transaction until total supply reach a specific number or a percentage from the initial supply.
I am not a developer, I just found the code, and I'm afraid to add new functions.
I think the contract is not upgradeable but I am willing the deploy another one with the burn function added.
Can someone help me with the code for the burn functions and explain me where exactly should I insert them in the initial code? Thank you!


texts: I can't get rid of the error "Uncaught ReferenceError: web3js is not defined"

texts:
I've been trying to get rid of this error, but no matter how much I try, I just can't figure this out. I've finished the tutorials of cryptoZombies, and all I know about web3 I got from there.
I created the simplest app possible to show the error I'm getting. This is my contract, deployed on Ropsten:

pragma solidity ^0.4.24;

contract SimpleRegister {
   string name;

   function setName(string _name) external {
      name = _name;
   }

   function getName() external view returns (string) {
      return (name);
   }
}

My frontend is the following:

<!DOCTYPE html>

   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>

Simple Register

   <button type="submit" onclick="getName();return false;">Get Name</button>

Does anyone has an idea about what's going on and how to fix that? Thank you.


texts: Remix is not connecting to my private network

texts:
I have initialized the genesis file then run that command in the console-

    geth --rpc --rpcaddr 0.0.0.0 --rpcport 8549 --rpccorsdomain "*" --rpcvhosts "*" --rpcapi "network,admin,personal" --datadir /home/ethereum --networkid 8982 console

I am running the provider in my console.

 IPC endpoint opened                      url=/home/ethereum/geth.ipc
 HTTP endpoint opened                     url=http://0.0.0.0:8549
 cors=* vhosts=*

I have given the web3 provider endpoint as :
 http://localhost:8549
Remix is showing this message --

Not possible to connect to the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).


texts: Can there only be one instance of a contract?

texts:
Say we have:

contract TestFooContract{
//bunch of stuff and state
}

Does this mean that there is only 1 "TestFooContract"?
Or can I instantiate 10 of them? What if I want multiple of these contracts?
In OOP terms, is a contract thought of as a class? Or perhaps just a singleton object?


texts: What does the get Status () method return with a pending state transaction?

texts:
If a transaction has a successful state it returns 0x1 but if the transaction has a failed state it returns 0x0. My questions is, what to return when the transaction has a pending status?

    public String estado(Web3j web3j, String txhash) {
    String status = "0";
    try {
        EthGetTransactionReceipt ethGetTransactionReceipt = web3j.ethGetTransactionReceipt(txhash).sendAsync().get();
        String status1 = ethGetTransactionReceipt.getTransactionReceipt().get().getStatus();
        System.out.println("estado :" + status1);
        if (status1.length() > 1) {
            status = status1.substring(2);
            System.out.println(status);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return status;
}


texts:
Eth command solo mining CMD does not run as expected
I have downloaded ethminer-0.19.0-alpha.0-cuda10.0-windows-amd64.zip
from https://github.com/ethereum-mining/ethminer/releases
ethminer-0.19.0-alpha.0-cuda10.0-windows-amd64.zip
ran and placed the ethminer.exe in C:\
Created a bat file with the below commands
setx GPU_FORCE_64BIT_PTR 0

setx GPU_MAX_HEAP_SIZE 100

setx GPU_USE_SYNC_OBJECTS 1

setx GPU_MAX_ALLOC_PERCENT 100

setx GPU_SINGLE_ALLOC_PERCENT 100

ethminer.exe -P stratum1+tcp://0x9571C7D673D1ef4F640dCa2e29DF1F178B18318d.Bolle@us1.ethermine.org:4444 -U -R

Whenever I run the bat file , It runs for a second and the command prompt window closes.
I'm not sure what is causing the issue.


texts: Unable to set variable from other contract, able to from outside

texts:
I've got two contracts, A and B, I set them up in a truffle test separately.

A.new()...
B.new()...

A has a function bar, which sets a public boolean boo to true that is never read anywhere. B has a function, foo, that calls bar on a previously instantiated A.

contract A(){
    bool public boo = false;
    function bar() public {
        boo = true;
    }
}
contract B(){
    A public myA;
    function setA(address addr){
       myA = A(addr);
    }
    function foo() public {
       myA.bar();
    }
}

Now in my truffle test, I call bar two ways, directly, and thru b.foo().

a.bar();
b.setA(a.address);
b.foo();

The first call to bar works fine. The second call thru foo throws out of gas no matter how much gas I give it. What am I doing wrong?


texts: Sapphire Radeon HD 4870 2GB Vapor-X hashrate

texts:
I want to learn Sapphire Radeon HD 4870 2GB Vapor-X hashrare but there is no info in anywhere.How can I learn that gpu hashrate?

here is some info about that gpu.Can we learn hashrate from core clock or memory clock?I want to use that gpu card for mining

Sapphire Radeon HD 4870 2GB Vapor-X

Manufacturer: Sapphire
Core Clock: 750MHz
Memory Clock: 3,600MHz (effective)
Memory: 2GB GDDR5


texts:
I have this method where I make a transaction to the network rinkeby, but to know how I can get the hash of the transaction made. I am using java with web3j, in addition to using infura to connect to the network.

public void CrearCertificado(CareerCertificate careercertificate, String id, BigInteger fecha, String nombre, String rutalumno, String instituto, String rutinstituto, String titulo,
                                                        String totalhash, String fechatitulacion, String registronumber, String codigoV ) throws Exception{

                    careercertificate
                    .createCertificate(id, fecha, nombre, rutalumno, instituto, rutinstituto, titulo, totalhash, fechatitulacion, registronumber, codigoV )
                    .send();

}


texts: Using delete keyword on storage variables

texts:
Here is an implementation:
I am running delete keyword on two different struct variables. on storage variable remix gives an error but not on memory. Why is this so?

pragma solidity ^0.4.0;

contract myContract
{
    struct abc {
        uint8[] m;
        uint a ;
    }

    function myFucn() returns(bool)
    {
        abc storage b;
        abc memory a;
        delete a;
        delete b; // error unary operator cannot be applied to storage pointer.
        return true;
    }
}


texts: Will staking Ether work with any amount?

texts:
Once Ethereum moves to PoS, will someone 'staking' 100 - 200 ETH have any incentive to do so? Or will it only be worth while to those holding thousands or tens of thousands of coins?

Once all ETH has been released/mined, where will the ETH come from to reward those 'staking' under PoS?


texts: Treatment of constant contract functions in Solidity (privacy and access to msg.sender)

texts:
I have a simple contract:

pragma solidity 0.4.8;

contract SimpleContractTest {
    event ReturnValue(address _from, uint256 _value);
    function SimpleContractTest()
    payable
    {

    }
    function myBalanceConstant() constant returns (uint256 amount)
    {
      return msg.sender.balance;
    }
    function contractBalanceConstant() constant returns (uint256 amount)
    {
      return this.balance;
    }
    function myBalancePublic() public returns (uint256 amount)
    {
      ReturnValue(msg.sender, msg.sender.balance);
      return msg.sender.balance;
    }
    function contractBalancePublic() public returns (uint256 amount)
    {
      ReturnValue(msg.sender, msg.sender.balance);
      return this.balance;
    }
}

The public functions work fine and return contract / calling account balances as expected. However the constant functions only work for the contract balance.

Specifically the function myBalanceConstant() always returns:

  115792089237316195423570985008687907853269984665640564039455084007913129639935

Looking at the documentation on contracts at:
http://solidity.readthedocs.io/en/develop/contracts.html#constant-state-variables
it states that for constant state variables execution data (e.g. msg.gas) is not allowed to be used. However there doesn't seem to be any such information around the use of execution data for constant functions as in the example above.

Q1

Any ideas as to why the above doesn't work, and what the rules are governing constant functions (my example doesn't change state which seems to be the only stated rule) would be very much appreciated for my understanding!

Q2

On a related note, is it reasonable to rely on calls to constant functions not being exposed publicly (i.e. the arguments to the call and the return values)? This seems reasonable to me assuming the user is running a local node (as the constant function call will be just executed locally) although presumably if there isn't a local node (e.g. if using MetaMask) then the values will be exposed at least as far as the MetaMask nodes, even if not the full blockchain?

Thanks very much for any advice, hints etc. - I am just starting out as a Dapp developer!


texts:
I'm trying to call a method in my contract with web3 but keep getting the error :

Unhandled Rejection (TypeError): contract.methods.Add_Services is not
a function

For some reason its not recognizing my method contained in the ABI. But when I log the ABI it shows my method is in fact there.
Here's my code -
import ABI from '../contracts/Cryptocares.json'

...

const web3 = new Web3(Web3.givenProvider || "http://localhost:7545")

var contract = new web3.eth.Contract([ABI], '0x2Dab42C8Ff8A4Acb7384A86F9a1d1F484B5196dc');

const handleSubmit = async event => {

    event.preventDefault();
    console.log("minimum donation amount: " + minDonation)
    console.log(ABI)
    contract.methods.Add_Services({minDonation, duration, amount, description, uri}).send({from:
account, gas: 0x00,
        gasPrice: 0x00})
    .on('transactionHash', (hash) => {
        console.log(hash)
    })
    .on('receipt', (receipt) => {
        console.log(receipt)
    })

}


texts: Smart contract on a private Ethereum Blockchain - Workflow & questions

texts:
I am trying to build a small app that would rely on a private Ethereum Blockchain. I am relatively new to this and am still having a few questions about the whole process. I will try to be as clear as I can explaining the difficulties I am facing.

What I have

A running private blockchain, installed on a specific server (that I manage)
A working synchronisation between multiple nodes
A smart contract that I have written

What I want to do

I want to add the smart contract to my private blockchain

What I am trying now

I am using Browser-Solidity and selected the Web3 Provider, where I wrote down the IP address of my server and the port 8545.

I then see the Create button... but am told that the account is locked.

Here are my current thoughts:

How do I know which account is to be unlocked? When I type web3.eth.accounts, 4 accounts are returned...
I tried unlocking an account but I am running into the following error : Failed to unlock account (no key for given address or file). I do not remember setting up a key for any account. Am I doing something wrong? How can I get past this step?
I am guessing that once the smart contract will be added to my private blockchain, it would have to be mined. How would I go on and do this? Would it be by simply executing miner.start() from one of my nodes? Every time I mine, it never stops until I make it stop, and to be honest, I haven't really understood what is being mined.

Looking forward to your input, I appreciate any kind of help!


texts: Call solidity function synchronously in express

texts:
I am retrieving data from mysql and looping through each row. up till here everything executes in the order I want it to. However in the same loop I need to call a smart contract function in order to verifyHash and return a value of true or false and then if true store data in an array of objects. However the call im using is asynchronous so it doesn't let it execute first before moving on, so its a complete confusion.

contract.methods.verifyHash(id,hash,addr).call().then(function(result){});

I would like to call the same method synchronously inside the for loop.

Thanks in advance.


texts: Send ether to a payable function from nethereum

texts:
I have created a payable function in a smart contract and deployed it in a private blockchain network. Now I am using Nethereum to make rpc calls to the geth node on which the network is running.

But I am unable to find how to pass ether while calling a payable function from nethereum.

The geth equivalent of what I want is

Contract.function({from:"address, value:"amount"})


texts: How can I get balance of an account in range of defined block numbers?

texts:
Following answer guide us how to get the balance of the accounts.

=> How could I get balance of an account in range of some block number. This would help us to observe the balance activity of an account.

For example I have a list of account. I want to get the balance of all of them in between block-number 100 and 1000.

Thank you for your valuable time and help.


texts: How can I browse mempool in Ethereum? Is it possible from EthereumJ or on some websites?


texts:
I want to test some api calls using web3.js and so I am using geth as HttpProvider. Can I start geth without the syncing?

Is something like geth --nosync --rpc available?


texts: What is the difference between bytes and bytes32?

texts: I know bytes32 stores 32 bytes, but what does bytes store? And what is the difference between the two?


texts: How are we able to send 512 bit hash as a bytes32 variable?

texts:
I have a code that is working:
solidity
function checkSignature(bytes32 h, uint8 v, bytes32 r, bytes32 s) public pure returns (address signer) {
    bytes memory prefix = "\x19Ethereum Signed Message:\n32";
    bytes32 prefixedHash = keccak256(abi.encodePacked(prefix,h));
    signer = ecrecover(prefixedHash, v, r, s);
}

javascript
    const message = "Hello";
    const h = web3.utils.soliditySha3(message);
    console.log(h.length);
    let signature = await web3.eth.sign(h, second);

    var r = signature.slice(0, 66);
    var s = "0x" + signature.slice(66, 130);
    var v = "0x" + signature.slice(130, 132);
    v = web3.utils.toDecimal(v);
    v = v + 27;

    const result = await multisig.checkSignature(h, v, r, s);
    //result === second

The logged length of h is 66. 512bit hash should be 64bytes. The first 2 bytes(0x)denotes this is a hex value.
I am sending it as a solidity bytes32 variable which has a fixed length of 32. How is the code working?
I might be missing something very obvious. Please point it out. Thanks in advance.


texts: Transfer ethers from a smart contract to another smart contract in Truffle

texts:
I am beginner in Solidity, So my problem may be simple. I have two contracts "BankA" and "customer". Whenever i deploy BankA in Truffle development environment and call pay() the following Error will emerge:
Error: Returned error: VM Exception while processing transaction: revert    at PromiEvent (C:\Users\lenovo\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\contract\lib\promievent.js:9:1)

What is the solution. Thank you.
BankA:
pragma solidity ^0.5.12;

import "./customer.sol";
contract BankA{
  function pay() public returns(uint256){
    customer client=new customer();
    address(client).transfer(1000);
    return address(client).balance;
  }
  function() external payable{}

}
customer:
pragma solidity^0.5.12;
contract customer{
  function() external payable{}
  }
}


texts: Exceeds Gas Limit even though chain fully synced

texts:
I'm attempting to send a transactions via Ethereum Wallet, the latest version, and have run geth --syncmode="light" .  On the last 200k blocks or so I just opened Ethereum Wallet and let it sync the rest.  When I go to send a transaction, it says "exceeds gas limit" even though I have the gas limit max.  How can I solve this issue?
Thanks.


texts:
I have a website with NODEJS and it's a Dapp.
There is some button to click and open MetaMask for signing a transaction.
I think an attacker car replace my ABI+Contract address and inject them with his contract and ABI. So if he take advantage of it, he can redirect ETH fund to his own benefit.
Is there any security to avoid this ?


texts: Is it possible that the same address sends out two transactions at the same time

texts:
Several articles say that a transaction can be canceled or replaced with the same nonce and higher gas price.

Then does this indicate that the same address can NOT send two transactions at the same time?

As the nonce is the number of transactions sent from a given address, may I just increase the number of nonce when sending the second transaction?

However I don't think it is possible to know which transaction will be mined firstly, so it confuses me that I can not determine which transaction should be given a higher nonce.

Please correct me if anything is wrong.


texts: Which type is more expensive for a smart contract? If I just have static text messages to display which type is better?


texts: How to model mapping inside smart contract

texts:
My use case:
I have to keep track of all "submitted quotations" from one person to another.

My solution:
For this I am keeping a mapping of uint and struct mapping (uint => quotation) allQuoatations. I am appending inside this method on addQuoatation method.

My doubts:

Is it the correct way to model arrays.
Should I only keep last quotation inside contract, remove the array and emit an event after addition of quotation.


texts: Looking at a wallet address, how can I know if it is Ethereum, Litecoin, Bitcoin, etc?

texts: How can I find out what kind of coins a wallet holds based on the wallet's address? For example, if I saw a random wallet address, how can I know whether that wallet is for Ethereum, Bitcoin, Litecoin, or another coin?


texts: How to modify my own ethereum node to mine transactions from my DAPP which uses ERC20 tokens?

texts:
Could someone please explain the below,

I am developing a DAPP which uses ERC20 tokens that already deployed in the mainnet. In order to mine the transactions for these ERC20 tokens, How I can use the ethereum node..?, I am planing to mine the transactions using my own ethereum node!! is it possible..? Suggestions are welcome.


texts: How to check the size of a contract in Solidity?

texts:
I want to measure the size of my compiled contract using solc.

I can dump the binary using --bin or --bin-runtime and then count how many hexadecimal digits it contains.

Is there an easier way to do it?


texts:
I have an escrow contract where party A is sending some token to party B and right now held in escrow. I want to use the timer function in smart contract so that the token will be held for a certain period of time. After that time, the token will be reverted back to originator account, that is party A.

I am adding the escrow in an ERC20 smart contract so I can call it inside the smart contract.

How can I create a holding frame of 30 days in smart contract and after 30 days the token will be reverted back?


texts: How will the existing Smart Contract handle ETH Fork Upgrades (E.g., ETH's Istanbul Upgrade) or Outages

texts: I have created my token and deployed on ethereum network before ETH Fork Upgrades (E.g., ETH's Istanbul Upgrade), What will be the huge impact of Fork update on my smart contracts and how can i manage to update my smart contracts.


texts: What if I transfer mainnet tokens to an xDai address?

texts:
What if I transfer mainnet ERC-20/721/1155 tokens or ETH to an xDai address?
Transferring to a different blockchain generally doesn't work, but xDai has a token bridge. Will it work for xDai?


texts:
I just tarted to write solidity and i have some questions that i could not find the answer to.

When you declare a map like this:

struct UserAccount{
    string name;
    uint id;
}

mapping (address => UserAccount) public accounts;

How will that be initialised? or with what?

For example, accessing

accounts[0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc]

will return an instance of an UserAccount? If yes, that means that the map creates an instance of UserAccount for every possible address? Doesn't that consume very much memory? If not, then how comes you can do this:

accounts[_address].name = _name;

?

And the second question:

I keep reference in my contract of an address that is the owner, the address that created the contract:

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

After i call this function:

uint userCount=0;
mapping (address => UserAccount) public accounts;

function createAccount(string _name, uint _id, address _address) onlyOwner() public {
    UserAccount user;
    user.name = _name;
    user.id = _id;
    accounts[_address] = user;
    userCount += 1;
    // accounts[_address].name = _name;
    // accounts[_address].id = _id;
    // userCount += 1;
    emit UserCreated(_address, _id, _name);
}

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

the owner address changes. The commented lines from createAccount function are the way to do it, i know, but i want to understand why it does not work.

To clarify my problem i will also post a js test.

beforeEach(async () => {
    voting = await Voting.new({from: owner});
});

it("Should delete poll, as owner", async () =>{
    var name = "Sandu";
    console.log("LOCAL OWNER= " + owner);
    console.log("OWNER BEFORE CREATE ACCOUNT FROM SOL= " + await voting.owner());
    await voting.createAccount(name, 1, firstUser,{from:owner});
    console.log("OWNER AFTER CREATE ACCOUNT FROM SOL= " + await voting.owner());
    var pollName = "First Poll";
    var endDateS="2018-08-11T10:20:30Z";
    var endDate=new Date(endDateS)
    await voting.createPoll(pollName, 1, endDate.getTime()/1000,{from:firstUser});

    try{
        await voting.deletePollById(1,{from: owner});
    }catch(err){
        console.log(err.message);
    }

    assert.notEqual(pollName, await voting.getPollById(1));
});

The test above prints this:

LOCAL OWNER= 0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc //Owner that o have in my js file local, first address from the ganache accounts.
OWNER BEFORE CREATE ACCOUNT FROM SOL= 0x79d66c53ad6f1847288c0d06c01a2b38c38f15bc  //The owner account from my contract before calling the function
OWNER AFTER CREATE ACCOUNT FROM SOL= 0x000000000000000000000000000000000000000a   //The owner account from my contract after calling the function

I can't understand why the value from owner changes as i don't touch that in my function.

If anyone can help it would be much appreciated. Again, i know the right way to do it but i am posting this out of the desire to understand what i am doing not to get the job done.