texts: crypto-signing in a smart contract -> verify the identity of a smart contract

texts:
my Question in short is:

-> is it possible to digitally sign some data by a smart contract (e.g. with a secret key of the contract) and thus confirm that it was exactly this smart contract, who signed the data?
-> I already kind of know, that it probably won't work that way, because a contract's data and code is entirely public and thus it can't keep a secret. So are there any clever on-chain workarounds, or would I have to use off-chain steps with this one..?

Now with a bit of background:

I'm trying to create a dapp, in which a creator can sign a document and have it timestamped on the Blockchain, so that anyone can verify wether the document existested at  a certain point in time.

My concept so far was:

Document gets hashed and then signed by the creator's private key (client side, off chain) -> thus creating a digital signature of the document
The signature is then sent to a smart contract, which appends a timestamp to the signature, hashes both together and then the contract signes the hash)(the timestamp represents the current block's time)
The Contract stores a mapping where each row (one row for each document or its version) is accessed with the hash of the document, pointing to a struct with: the timestamp, the signature of the creator and the timestamp signed by the contract itself.
Now anyone with access to the document, the creators public key and the contracts public key could verify (with the signed hashes in the mapping), that

a) the document was signed by the creator

b) the document was timestamped and signed by the smart contract

-> My original goal was to avoid having trusted third parties included into the process at all (neither for timestamping, nor signing)

So the Problems seem to be:

-> since a smart contract cannot store a secret on chain(as far as I know), I cannot securely store a private key in the contract, with which it could sign data

-> also, if I stored a secret key somewhere off chain, how could a smart contract be authorized to access it? (since it has no private key to be identified with)

It would really be awesome if you could help me out! Thank you!


texts: Constructing contract with an address array

texts:
Please correct me if I am wrong but I understand you cannot initialise a contract with a string array as it is a dynamic type but can I initalise a contract with a fixed type? specifically an array of addresses.

Also how would this be serialised if I am trying to deploy through bytecode?


texts: How to connect more than 2 nodes in private ethereum network

texts:
I'm quite new to ethereum, I followed some tutorial to create a private ethereum network. I created 3 nodes, and to connect these 3 nodes, I need to run on node 1: admin.addPeer(enodeofNode2), admin.addPeer(enodeofNode3). Besides, I also need to run on node 2: admin.addPeer(enodeOfNode3). I want to ask that is there any option that I don't need to manually run like that because if I have 100 nodes, the job will be much difficult.
Regards,
eth.cat


texts: Can I move some DAO token to another account to vote twice?

texts:
If I split my DAO tokens to 2 accounts before voting, will I be able to vote twice?

Thanks.


texts:
I have been trying to listen to the event of my smart contract; however, I receive the error.
MyContract.events.myEvent(

function(error, event){
    if(!error){
        $("#instructor").html(event.args.name + ' (' + event.args.age + ' years old)');
    }else{
        console.log(error);
    }

})

I receive the following error
 Error: The current provider doesn't support subscriptions:

Web3.js version is web3@1.3.0
I am well aware of the following solution; however, it doesn't work on my case anyway.
My smart contract
contract Coursetro {

   string fName;
   uint age;

   event Instructor(
    string name,
    uint age
    );

   function setInstructor(string _fName, uint _age) public {
       fName = _fName;
       age = _age;
       Instructor(_fName, _age);
   }

   function getInstructor() public constant returns (string, uint) {
       return (fName, age);
   }

}


texts: How does blockchain and decentralization work?

texts: Does every node or computer keep track of all of every user's transactions every single dollar as a separate unit or do they group together units in transactions? (eg. transfer of 5 dollars would be looked as one transaction or 5 different ones) Additionally, if every server records all user transactions ever, isn't there a space limit?


texts: Why is my ether balance 0 in geth, even though the sync is nearly complete?

texts:
My geth --fast sync is nearly complete, and the balance shows correctly on Etherscan.

I was running geth on linux and haven't synced in a while, so I deleted the chaindata and updated the wallet and started re-syncing with geth --fast. Even after what seemed like a full sync my balance showed 0. I can see the account has more than 0 ether on Etherscan.

I copied my keystore file to a Windows machine and tried Ethereum Wallet, same thing is happening. The last transaction was at about block 3800000, I am synced up to 235 blocks left and still have a 0 balance. The sync is also stuck, can't seem to get the last 235 blocks, but my balance should be showing the full amount right now.

Losing my mind right now, it's a lot of money. Even if my keystore was somehow corrupted, the wallet should still show the balance since that is public info. I also verified I'm on the main network.


texts: How to view custom token balance in ether wallet using web3

texts:
Hello I am newbie to cryptocurrency. I have created my erc20 custom token. Now, I want to create an API to view the balance(in my token as well as in ethers) using web3 and node js.Can someone please suggest how I can do that?

Thanks in advance!


texts: Gas for internal transactions (and transactions in general)

texts:
I am trying to design a SmartContract for a Token and I am having some issues with the gas calculations. When a user sends a token to someone, I would like there to be a fee. Where it gets fuzzy for me is the gas. I read that a minimum of 21k in gas must be paid for all transactions but it is not clear what is included in this. I read that storing data (SSTORE) costs 20k in gas the first time, 5k in gas for updates and 5k to reset (set to zero) + you get a 15k in gas refund. From my understanding when you send tokens this is just updating the balance on two wallets (using SSTORE?), thus it should be one of the following:

User has 10 tokens, sends 5 to a new wallet: 5k + 20k = 25k in gas? (above 21k)
User has 10 tokens, sends 5 to an existing wallet : 5k + 5k = 10k in gas? (but since less than 21k then 21k is used?)
User has 10 tokens, sends 10 to an existing wallet : 5k + 5k = 10k in gas? (but since less than 21k then 21k is used?), when tx done 15k in gas reimbursed? (does this reimbursement happen because of the 21k limit?)
User has 10 tokens, sends 10 to a new wallet : 5k + 20k = 25k in gas (above 21k), when tx done 15k in gas reimbursed? (does this reimbursement happen because of the 21k limit?)

so I am not sure I understand where the 21k limit comes from / how it is calculated. The above is important for me to understand, because it will determine how I write my code.
I have not been able to find this information anywhere, someone told me that internal transactions cost less than 21k, someone else told me that all transactions are SSTORE operations and 21k is just a lower limit to the cost of a transaction, so if you had a user sending some tokens to an existing wallet (vanilla ERC-20 SmartContract) it would be 5k + 5k + 11k (network fee) = 21k but if you had some other operations (incl. sending inner transactions) making the gas above 21k you would have 5k + 5k + other_ops >= 21k
The algorithm I am trying to write is:

UserA (sender) sends a token to UserB (receiver)
A fee is calculated by the SmartContract
The fee amount is transferred to a fee wallet
UserB receives the amount sent minus the fees

There are timestamps involved in the calculations, thus I broke this down the gas cost to (excluding all other calculation costs):

update timestamp variable UserA (SSTORE) : 5k gas (or 20k if 1st time)
update timestamp variable UserB (SSTORE) : 5k gas (or 20k if 1st time)
send fee to fee wallet (update fee wallet balance using SSTORE internally?) : 5k gas
update UserA balance from sending tokens to UserB & Fee wallet (using SSTORE internally?): 5k gas
update UserB balance from receiving tokens sent by UserA (using SSTORE internally?): 5k gas (or 20k if 1st time)

Total : 25k - 70k gas
Is this correct? Or is step 3 going to cost 21k in gas and steps 4 + 5 (together) going to also cost 21k in gas, like this:

update timestamp variable UserA (SSTORE) : 5k gas (or 20k if 1st time)
update timestamp variable UserB (SSTORE) : 5k gas (or 20k if 1st time)
send fee to fee wallet : 21k gas
tx cost of sending tokens from UserA to UserB (original amount - fees) : 21k gas

Total : 52k - 82k gas
Thank you!
Gab


texts:
How can I instrument the EVM bytecode for runtime monitoring?
Is there any technique or implementation for that?


texts:
I have created a dapp where the user can sign a contract using metamask. However, the account that gets the money send to keeps getting locked. Sure, I can manually unlock it, but this is really annoying. Is there any way to automate this, that it remains unlocked?

Seems like you can unlock it for as long as the geth instance is running using a 0 as duration parameter:

web3.personal.unlockAccount("address", "pass", 0);


texts: How to build an address book for Ethereum addresses?

texts:
I would like a simple address book referencing a user name to an ethereum address like,

mapping (string => address) addressOf;

Unfortunately I can't access that mapping as a public call, as strings are dynamically-sized.

Is there any existing solution or work around, to access a string key mapping without .sendTransaction?


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


texts: Truffle - call migration file multiple times

texts:
I would like to execute migration file "6_deploy_and_register_group.js" every time when I need to create a new group.
Is this a proper way to use migrations?
If yes, how can I make it working? Calling:

truffle migrate 6_deploy_and_register_group.js

gives me that "network is up to date". Is there any way to execute only that file but have stored other addresses unchanged?

2_deploy_registry.js:

var Registry = artifacts.require('./Registry');

module.exports = async function(deployer, network, accounts)
{
    await deployer.deploy(Registry);
};

6_deploy_and_register_group.js:

var Group = artifacts.require('./Group');
var Registry = artifacts.require('./Registry');

const args = require('minimist')(process.argv.slice(2));

module.exports = async function(deployer, network, accounts)
{
    let units = args["itemscount"];
    if(units == null)
    {
        console.log('\x1b[31m%s\x1b[0m', 'did you forget to use --itemscount=xyz argument?');
    }
    let groupName = args["groupname"];
    if(groupName == null)
    {
        console.log('\x1b[31m%s\x1b[0m', 'did you forget to use --groupname=xyz argument?');
    }
    await deployer.deploy(Group, groupName, units);
    let registry = await Registry.deployed();
    await registry.register(Group.address);
};


texts: Is the Ethereum client Javascript API supposed to be publically available?

texts:
I am still trying to understand the Ethereum design, and one thing I can't work out is if all Ethereum nodes are supposed to expose the JavaScript API and if that is supposed to be publically available?

So if I want to consume Ethereum "as a server" from something like a mobile app, can I just point to some random public node and call it using web3.js?


texts:
First I'm sorry for the inconvenience, and I'm sorry for this question (If it violates the laws of society) but I have a curiosity to start mining Ethereum.
I start with https://ethereum.org/ to know about it, but unfortunately without any result.
Can you please share with me the official application to start mining Ethereum? and all positive and negative information about Ethereum? and where I can create my wallet?


texts: In blind auctions from solidity documentation what value should I insert under the bid function?Even I inserted string value,integer value under the bid function but it is showing the error as invalid value....


texts: How to have an address inside a solidity Struct?

texts:
My problem

Suppose I have this struct:

struct TextThatWorks {
        bytes32 text;
        uint reads;
}

How can I add a address variable to it?

What I tried

I tried simply adding address someadress; inside the struct declaration, like so:

struct TextThatDoesNotWork {
        bytes32 text;
        uint reads;
        address addr;
}

I have seen many examples doing this exact same thing. Example: Solidity Docs

But when I do this, my functions break.

What happens when I try the above

What works

So, in my contract I have a Text array:

TextThatWorks[] public textArray;

And I have a function to recall the texts inside this array, which returns arrays:

function listTexts () public view returns (bytes32[], uint[]) {

        bytes32[] memory texts = new bytes32[](textArray.length);
        uint[] memory readsArray = new uint[](textArray.length);

        for (uint i = 0; i < textArray.length; i++){
            texts[i] = textArray[i].text;
            readsArray[i] = textArray[i].reads;
        }

        return (texts, readsArray);

}

This returns a nice array in the format [["some hexadecimal example"],[12]]

What does not work

The second struct, TextThatDoesNotWork, only differs of TextThatWorks because it has an address field.

When I use it, my listTexts() function stops working. It always returns empty arrays like [[],[],[]]

To accomodate the additional field, my listTexts() function becomes the following:

function listTexts () public view returns (bytes32[], uint[], address[]) {

        bytes32[] memory texts = new bytes32[](textArray.length);
        uint[] memory readsArray = new uint[](textArray.length);
        address[] memory addresses = new address[](textArray.length);

        for (uint i = 0; i < textArray.length; i++){
            texts[i] = textArray[i].text;
            readsArray[i] = textArray[i].reads;
            addresses[i] = textArray[i].addr;
        }

        return (texts, readsArray, addresses);

}

How I fill the array

function put(bytes32 _text, uint _reads) public returns (uint){
    return textArray.push(TextThatDoesNotWork({
        text: _text,
        reads: _reads,
        addr: msg.sender
    }))-1;
}


texts:
I have a background in security, so i try to understand what is hapeneing to Ethereum project.

Recently, i heard that Ethereum will make a fork to stop the Ddos attack. here i want to know how the attacker perform its attack, what is he exploiting (a code bug or what)?

I understand that the opcodes have gas price to prevent such attack and the fork aims to reprice their cost but is it enough to stop him?


texts: mapping not updating after function call

texts:
struct allowanceInfo {
     address allowedAddress;
     bool isAllowed;
     }

    mapping(address => allowanceInfo) public allowed;

    function allow() public {
        require(msg.sender == allowanceInfo[allowedAddress].allowedAddress);
        allowanceInfo[allowedAddress].isAllowed == true;
        }

Why is my mapping not updating the boolean value of my isAllowed variable, when I look up the allowedAddress in the mapping?


texts: Oraclize_ Error: The contract code couldn't be stored, please check your gas amount

texts:
When i am going to deploy this code its give error:The contract code couldn't be stored, please check your gas amount.

Solidity CODE:

pragma solidity ^0.4.0;

import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

contract OraclizeFetch is usingOraclize{

string public ETHXBT;

event newOraclizeQuery(string description);
event price(string price);

function OraclizeFetch() payable{
    oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
    update();
}

function __callback(bytes32 myid, string result, bytes proof) {
    if (msg.sender != oraclize_cbAddress()) throw;
    ETHXBT = result;
    price(ETHXBT);
    update();
}

function update() payable {
    if (oraclize.getPrice("URL") > this.balance) {
        newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
    } else {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query(60, "URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHXBT).result.XETHXXBT.c.0");
    }
}

}

My genesis.json file:

{
    "nonce": "0xdeadbeefdeadbeef",
    "timestamp": "0x0",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x0",
    "gasLimit": "0x8000000",
    "difficulty": "0x400",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x3333333333333333333333333333333333333333",
    "alloc": {

}

}


texts: Non-stop "Served eth_signTransaction" warnings after upgrading geth to 1.9.x for private network?

texts:
I just upgraded the geth nodes of my private PoW network from 1.8.27 to 1.9.1, and right after starting up the nodes, it spills out tons of warnings non-stop like

WARN [07-30|18:33:52.134] Served eth_signTransaction               conn=82.196.0.91:48454 reqid=0 t=14.7128ms err="authentication needed: password or unlock"

It seems the private Ethereum network itself is functioning ok, and the miner can mine blocks and process transactions alright, but the tons of non-stop warning messages quickly eat up the log, so what does it mean and how may I fix or silence this warning? Thanks.


texts: How to gather all addresses of nodes in a private network?

texts:
I am currently learning core-development in go-ethereum. I am a little weak with networking, RPC and connections.

I am trying to write a function in my own consensus mechanism that gathers all currently connected node addresses into a struct and then uses it to display them. it currently has a structure like this.

type NodeAddresses struct {
    connectedNode []ConnectedNode
}

type ConnectedNode struct {
    address common.Address
}

func GatherNodeAddresses() {
    nodes := &NodeAddresses{
        ......
    }

}

What I'm having trouble with is how to populate the struct of NodeAddresses with connecting nodes in a private network. Each node has their own personal account set up with an address. Could someone give me an insight of how to move forward from here? Cheers!


texts: How do I tell whether the Mist/Wallet is "fast" or "full" syncing?

texts:
I'm currently installing Mist/Ethereum Wallet from the pre-built binaries.

Having the run the ./Ethereum-wallet executable, it's now part-way through syncing the blockchain. It seems to be taking quite a while, so I'm assuming it's a full sync, rather than a fast one. However, I'm unsure about this and want to find out for certain.

It doesn't appear to be possible to geth attach to the node that the Wallet has started in the background, so I have no visibility into what's going on, and can't use the console logs as a way to determine which type of sync is happening. [See "Console message difference between --fast and normal syncing", here.]

So my question is as follows:

In the absence of console logs, is there a way to tell from the chaindata/ itself whether fast or full sync is occurring?


texts:
There are 2 transfer functions in Dexaran's ERC223 contract. One includes data and the other one doesn't. Does this mean we should choose one transfer function to use in our contracts and ignore the other?

Also, what if a contract only includes the transfer with data function:

transfer(address _to, uint _value, bytes _data)

And someone calls the function but doesn't include a data parameter? Will the function fail, or will it assume the _data is something like "0x" and perform the function with that?


texts: Error: Invalid number of arguments to Solidity function at Object.InvalidNumberOfSolidityArgs

texts:
I have the following code in a contract

contract UserBasic {
    bytes32 test;
    function getBytes() constant returns(bytes32) {
        return test;
    }
    function setBytes(bytes32 _bytes) {
        test = _bytes;
    }
}

And the following in my node app (as part of an object)

getBytes: function getBytes(contractAddress) {
    // Fetching the contract related data
    const input = fs.readFileSync('contracts/UserBasic.sol').toString();
    const output = solc.compile(input);
    const bytecode = output.contracts[':UserBasic'].bytecode;
    const abi = JSON.parse(output.contracts[':UserBasic'].interface);
    const contract = web3.eth.contract(abi).at(contractAddress);
    // Interaction with the contract
    contract.getRecords.call((err, res) => {
        // Log transaction to explore
        if (err) {
            console.log(err);
        } else {
            console.log("Raw Bytes: " + res);
            const hex = res;
            const padded = web3.toAscii(hex);
            const firstNull = padded.indexOf('\x00');
            const id = padded.slice(0, firstNull);
            console.log(id);
            console.log("Treated Bytes: " + id);
        }
    });
}

When I click the button in my user interface to trigger setBytes everything works. But getBytes returns an error

Error: Invalid number of arguments to Solidity function

The function doesn't take any arguments and I'm not passing any either so I don't understand where the error is coming from. Can anyone point me to it?


texts: Does Eth have an equivalent to Geth's --fast flag?

texts: In a previous question, I asked how Geth's --fast flag worked. I'm now moving over to using Eth, so my question is: is there an equivalent option to allow Eth to quickly sync the block data? If so, what is the syntax?


texts: How to deploy Ethereum Smart Contract through Brownie to the Private Network

texts:
I have a geth node that is connected to a private network on my computer that uses port: 8545. Hence, I have a smart contract that is tested using Brownie on the ganache-cli network.

  Brownie is a Python framework for Ethereum smart contract testing,
  interaction and deployment.

=> I want to deploy a smart contract using Brownie, how can I do it?


texts: Calling a function in another contract (invalid checksum error)

texts:
I know there are plenty of questions like this but I believe this is different.

Based on this question, I wrote this

pragma solidity ^0.4.11;

contract Registry {
    mapping(string => address) ID;
    mapping(address => address) Contract;

    function addID(string _id, address publicAddress) {
        ID[_id] = publicAddress;
    }

    function addContract(address _owner) {
        Contract[_owner] = msg.sender;
    }
}

contract User {
    // The GMC contract
    address regAddress = 0xf70ce669d4fa2bdeae1c4c61021627fc4b1d463c;
    address owner = msg.sender;

    function addID(string _id){
        // Get the GMC contract
        Registry registry = Registry(regAddress);
        registry.addID(_id, owner);
    }

    function addContract(address _owner) {
        Registry registry = Registry(regAddress);
        registry.addContract(owner);
    }
}

Also, I'm 100% sure that the contract Registry has been mined at address 0xf70ce669d4fa2bdeae1c4c61021627fc4b1d463c.

Pasting as is on Remix returns an error

This looks like an address but has invalid checksum

Following this answer, I tried converting the address to upper case. That returns

TypeError: Invalid literal value

One suggestion in the question is to use import. I'm not doing that because of another (unanswered) question I asked here (can't use import when deploying with NodeJS).

Help would be much appreciated!


texts:
I am trying to store and send some ERC20 tokens from myetherwallet.

My wallet does not show me the right balance of tokens.
When trying to send those tokens to another Ethereum address (that I specify), what is broadcasted to the blockchain is a tx to a different address.

I am getting 2 error messages:

  Transaction execution error

(from MEW, but I am not prevented from generating and sending the tx)

  Warning! Error encountered during contract execution [Bad instruction]

(from Etherscan)


texts: how can I use smart contract to sign a transaction on an offline machine

texts: How can I use smart contract to sign a transaction on an offline machine?I want to use geth to sign a transaction offline,who can tell me what I do?Thanks!


texts: Do over-ridden functions affect dependent parent functions?

texts:
Imagine a ParentContract with functions a() and b(), where b() calls  a()

contract ParentContract{
    function a() {...}
    function b() {
        a()
    }
}

Now, I have a Child contract that over-rides function a() with onlyOwner

contract ChildContract is ParentContract{
    function a() onlyOwner() {
       super.a()
    }
}

In this case, have I modified function b as well to be onlyOwner?


texts: Ethereum: How to use ERC20 token in python project?

texts:
I'm gonna develop python project for ehtereum using populus framework.
In my project, I also planed to use ERC20 token.
In fact, I didn't select any library and framework for my project.
Can anyone tell me which framework and library I need to select and how to use ERC20 token?
Help me.


texts: myContract.events.MyEvent() vs web3.eth.subscribe('logs', ...);

texts:
I'm confused about the difference between myContract.events.MyEvent() and web3.eth.subscribe('logs', ...);
Both are subscriptions to events, correct?


texts: The difference between contract address and wallet address

texts:
Disclaimer: this is a rather long question.

To my understanding, contract address and wallet address are two profoundly different concepts, with the only thing in common being the fact that they are both given as the hexadecimal representation of a 160-bit number.

The difference is described below:

When a contract is deployed, it is allocated at a unique address, i.e., no other contract on the chain can be allocated on that address.

Moreover, suppose that the contract holds state (global) variables with a total size of X bytes (including whatever padding added by the Solidity compiler).

The next time a contract is deployed to the chain, it will necessarily be allocated at the address of the previous contract + X, or higher.

So every contract occupies "real" memory.

A wallet address, on the other hand, is "flat".

It does not store any data, so two wallets can technically have two consecutive addresses.

So while the state variables of a contract are allocated "right after" the address of the contract, the money that a wallet holds is not allocated "right after" the address of the wallet, and in fact - is not allocated at all.

Instead, the money that a wallet holds is ascribed to the wallet address in one or more ERC20 contracts.

For example, suppose I have a wallet with 20 CoffeeCoins at address 0x1234....

Then it means that there is some ERC20 contract deployed on the chain, which stores this information:

contract CoffeeCoin is ERC20Basic {
    mapping(address => uint256) balances;
    ...
}

And in that contract, balances[0x1234...] = 20.

A minor implication of the difference described above:

Some wallet address out there can be equal to some contract address out there.

I believe that in the case of block-chain, the word address is probably more suitable to be used alongside contract rather than alongside wallet (while using it for both creates this confusion to begin with).

A wallet address is in fact nothing more than a public key.

Am I correct in each one of the claims made above?

Is my understanding of the difference between contract address and wallet address correct?

I will be happy to get any constructive comment.

Thank you.


texts: Can I create a signature in the contract?

texts:
I can use the function ecrecover to verify a signature in the contract, but I want to know how to create a
signature in the contract. What should I do?


texts: What I need to verify contract with open-source license?

texts:
i m deployed contract in etherscan mainnet. i m verify it with open-source license like (MIT, GNU). now the problem were i don't know were to define license in etherscan ?? and etherscan will validate license when we update the token profile ??

contract example :- https://etherscan.io/address/0x230451cc96eb02df59fb2dc99dd1b701fd119329#code


texts:
While trying to upload a public key on Ethereum, I have faced a problem.

Given the following code in Solidity browser, it seems that I can only insert string values (using the browser compiler). For example, when I "create" and "set" values as "0x1234", it outputs:

  "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000063078313233340000000000000000000000000000000000000000000000000000"

What I want was something like "0x1234" but instead of that it interprets as a string. The work around is use bytesN where N is actual number of bytes. But then it becomes a static. Could anyone help?

contract SimpleStorage {
    bytes storedData;
    function set(bytes x) {
        storedData = x;
    }
    function get() constant returns (bytes retVal) {
        return storedData;
    }
}

Yes, instead of the above code, I can do as the following where I set bytes to bytes2. Then I can put "0x12", which would output "0x12". But Can I do it without being static?

contract SimpleStorage
{
    bytes2 storedData;
    function set(bytes2 x) {
        storedData = x;
    }
    function get() constant returns (bytes2 retVal) {
        return storedData;
    }
}


texts:
I have used following code to grab transaction hash every time a transfer event is triggered and store them in an array.

contarct1=web3.eth.contract(ABiDefination).at(address);
var arr=[];
var i=0;
function Eventt(){
     contract1.Transfer(function(error,result){
          if(!error){
               arr[i]=result.transactionHash;
               console.log(i);
               console.log(arr[i]);
               document.getElementById('txhash1').innerText="array  is "+ arr ;
               i=i+1;
          }
      })
}

Here Transfer is the event which is declared  in my contract as event Transfer(address indexed from, address indexed to, uint256 value);.

Now in my code I am calling this Eventt() inside transfer(..) function (and inside transfer(..) Transfer event is fired). I am also able to get transaction hashes.
But the issue is when I call transfer(..) function for first time, I get a transaction hash which is corresponding to that transaction, but the second time I call transfer(..) function, I get 3 elements inside my array,first is for the first transaction and 2nd and 3rd are same. And this keeps on going, for third time I get 6 elements inside my array.
I am unable to track why I am getting repeated values. Any solutions, or any alternate way to capture transaction hashes?

I also not sure

whether the line  contract1.Transfer(function(error,result){}) watches changes in event or anything else?
and what is meaning of indexed in line event Transfer(address indexed from, address indexed to, uint256 value);


texts: What is the process called when using e.g a token smart contract in an ICO smart contract? and could someone provide an explanation of the process. I'm not sure that I understand how interaction between multiple contracts works. Thank you very much.


texts: truffle migrate fails with: Error encountered, bailing. Network state unknown

texts:
Could someone point out what is happening with truffle.

"truffle compile" works fine. Please find the below truffle migrate reset output

Ubuntu#truffle version
Truffle v3.1.2
Ubuntu#truffle migrate --reset
Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  Migrations: 0x8ef3810f2dc59ecb37a518d18fab657343d8b281
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying A...
  A: 0x78724b3d9468e1e81e168c4fd3fa7e8c74f41532
Error encountered, bailing. Network state unknown. Review successful transactions manually.
TypeError: Cannot read property 'links' of undefined
    at /usr/lib/node_modules/truffle/node_modules/truffle-migrate/node_modules/truffle-deployer/src/linker.js:30:22
    at Array.forEach (native)
    at Object.link (/usr/lib/node_modules/truffle/node_modules/truffle-migrate/node_modules/truffle-deployer/src/linker.js:28:18)
    at /usr/lib/node_modules/truffle/node_modules/truffle-migrate/node_modules/truffle-deployer/src/actions/link.js:5:12
    at /usr/lib/node_modules/truffle/node_modules/truffle-migrate/node_modules/truffle-deployer/src/deferredchain.js:20:15
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)
Ubuntu#

testrpc output while invoking truffle migrate

HD Wallet
==================
Mnemonic:      ring book bridge orange sick announce original they cross such sudden jar
Base HD Path:  m/44'/60'/0'/0/{account_index}

Listening on localhost:8545
net_version
eth_accounts
net_version
net_version
eth_sendTransaction

  Transaction: 0x4ac810d07f93349a0a15607734138610143cc5a6ab2ebf473969f4a9ad8a98dd
  Contract created: 0x0ecffa76b13841a4d1562d68e651fcbdd2a9c27d
  Gas usage: 0x02c504
  Block Number: 0x01
  Block Time: Thu Feb 23 2017 12:59:28 GMT+0530 (IST)

eth_newBlockFilter
eth_getFilterChanges
eth_getTransactionReceipt
eth_getCode
eth_uninstallFilter
net_version
net_version
eth_sendTransaction

  Transaction: 0x1b1eafe1ed1788ced13a4e9706fba24ef2b156c6211d8aa0328bbb35f5a6d1f5
  Contract created: 0x121a3c3285ba61b88de863013c156fecc23f6d00
  Gas usage: 0x01aad6
  Block Number: 0x02
  Block Time: Thu Feb 23 2017 12:59:29 GMT+0530 (IST)

eth_newBlockFilter
eth_getFilterChanges
eth_getTransactionReceipt
eth_getCode


texts: What is the penalty of having ETH2 validator offline

texts:
i want to do participate in proof of stake.
i have just read https://ethereum.org/en/eth2/staking/ .
under "Risks" the site says

Although you can earn rewards for doing work that benefits the network, you can lose ETH for malicious actions, going offline, and failing to validate."

now i wonder:
what is the issue about going offline exactly?
let's say my server has an uptime of 99%. in the staking-time my server is going offline 2 or 3 times due to a software-crash or a blackout or because my internet-service-provider has problems and it lasts some hours until my server is online and available for proof of stake again. what is the consequence? do i loose some of my staked eth in this case, and if yes: how many?


texts: invalid JUMP after upgrading truffle & testrpc

texts:
I have a contract with a method add() where I read the value msg.value and change the contract informations.

before upgrading, I was calling this method in my test with return contract.add({from: accounts[1], value: 1});.

after upgrading, all the calls create an exception : Uncaught Error: VM Exception while processing transaction: invalid JUMP. To make it work again, I have to remove , value: 1 and just keep return contract.add({from: accounts[1]});.
and I still get the message even if i remove the whole code inside the add method : function add() {}

Is there a new way to send ethers with the transactions ? I read all the documentation and tutorial but it seems everyone is doing like me.

note that it seems that things come from testrpc. Here are the logs i get :

Transaction: 0x7d739e8416775a70a47616347471024feb8fb7da2dc938d3c7a25acf5031d0b8
  Gas usage: 0x47e7c4
  Block Number: 0x13
  Block Time: Sun Oct 16 2016 17:43:33 GMT+0200 (CEST)
  Runtime Error: invalid JUMP

 <   [
 <     {
 <       "id": 61,
 <       "jsonrpc": "2.0",
 <       "result": [
 <         "0x23abbf0929b16b5d905a6cc2735c5d718f598811b5bf4668e64ae91953839571",
 <         "0xd6f5b175fe05dc3b3df1d96d9793468feb9d098290c4b7ab51e034f276376f17"
 <       ]
 <     },
 <     {
 <       "id": 62,
 <       "jsonrpc": "2.0",
 <       "result": [
 <         "0x9f9e54e2c65ef2f0bc73dab9622c33cd726d4e81507a55b37b2d62b01b8bf9b1",
 <         "0xd6f5b175fe05dc3b3df1d96d9793468feb9d098290c4b7ab51e034f276376f17"
 <       ]
 <     },
 <     {
 <       "id": 63,
 <       "jsonrpc": "2.0",
 <       "result": [
 <         "0x0e1a087bec7de89c464714f7e49b9eb46edcf1c540e32111d2d9506bea02a062",
 <         "0xd6f5b175fe05dc3b3df1d96d9793468feb9d098290c4b7ab51e034f276376f17"
 <       ]
 <     }
 <   ]


texts: Estimate gas per line of code while typing

texts: Is it possible and, if yes, does a solidity editor exist that estimates gas per line of code while typing? I haven't found anything like that as yet. Either it is difficult or simply nobody has bothered to build such a tool yet.


texts: As I understand, fast sync has all the security guarantees of a full sync, but is faster. Is that correct? If so, why isn't fast sync the default?


texts: error in the deploying of my first ERC20 tokken

texts:
I'm trying to deploy my first ERC20 token.

When I compile my basic code (that I write based on a guide) there is no problem but when I try to deploy him, there is an error: This contract may be abstract, not implement an abstract parent's methods completely or not invoke an inherited contract's constructor correctly.

I think it's a basic error but I don't understand why it's happening.

Can you please help me?

pragma solidity ^0.5.0;

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

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

contract SafeMath {
    function safeAdd(uint a, uint b) public pure returns (uint c) {
        c = a + b;
        require(c >= a);
    }
    function safeSub(uint a, uint b) public pure returns (uint c) {
        require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
        c = a / b;
    }

}

contract IPES_coin is ERC20Interface, SafeMath {
    string public name;
    string public symbol;
    uint8 public decimals;

    uint256 public _totalSupply;

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

    constructor() public {
        name = "IPES_coin";
        symbol = "IPESC";
        decimals = 18;
        _totalSupply = 100000000000000000000000000;

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

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

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

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

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

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

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


texts: Can Factory Contract Be Used As Parent/Child Function?

texts:
I am attempting to modify the contract below; the way it is set up at the moment is so that the contract can be deployed, and then anytime a user wants to create a campaign, they can do so without redeploying the entire contract.

What I am trying to do is create a scenario whereby a user can create a company(token) and then create campaigns under the banner of that company.

My question is; can I use the Factory function to create a parent/Child type function?

Note: I have attempted to copy and paste a child contract and then import it, however this didn't work and I wasn't really sure what I was supposed to do with the contract.

Thank you, any help greatly appreciated.

pragma solidity ^0.4.17;

    contract CampaignFactory {
    address[] public deployedCampaigns;

    function createCampaign(uint minimum) public {
        address newCampaign = new Campaign(minimum, msg.sender);
        deployedCampaigns.push(newCampaign);
      }

    function getDeployedCampaigns() public view returns (address[]) {
        return deployedCampaigns;
      }
    }

    contract Campaign {
    struct Request {
        string description;
        uint value;
        address recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    mapping(address => bool) public approvers;
    uint approversCount;

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    function Campaign(uint minimum, address creator) public {
        manager = creator;
        minimumContribution = minimum;
    }

    function contribute() public payable {
        require (msg.value > minimumContribution);

       approvers[msg.sender] = true;
       approversCount++;
    }

    function createRequest(string description, uint value, address recipient)
    public restricted
    {
        Request memory newRequest = Request({
           description: description,
           value: value,
           recipient: recipient,
           complete: false,
           approvalCount: 0
        });

        requests.push(newRequest);
    }

    function approveRequest(uint index) public {
        Request storage request = requests[index];

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;

    }

    function finalizeRequest(uint index ) public restricted {
        Request storage request = requests[index];

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
     }
    }


texts: Ecrecover after eth_sign update with preamble

texts:
I've just discovered that with b59c839 geth is now pre-appending the string:

*\x19Ethereum Signed Message:\n<length of message>*

before signing the passed message. I've read here that to use ecrecover on Soldity side it must be pre-appended the same string on the contract.
Do you have any working example on how to correctly manage this pre-appending on a Solidity contract?

Thank you

----- ----- ----- UPDATE

I'm trying to pre-append the signature locally in geth with something like this:

test = web3.sha3("hello")
eth.sign(eth.accounts[0], test)
hash_preamble = web3.sha3("\x19Ethereum Signed Message:\n" + test.length + test)

Then on the contract side I'm trying to test something as simple as this:

function test(bytes32 r, bytes32 s, uint8 v, bytes32 hash_preamble) constant returns (address) {
    address signer = ecrecover(hash_preamble, v, r, s);
    return signer;
}

The bytes32 values passed to the contract are in the form of "0x1234" while the uint8 is 27 or 28. The hash passed to the contract is the composed hash with the preamble, length of my message (which is an hash) and my message.

Unfortunately I'm not able to get the same address as the signing one. Can you see some mistakes in my code?


texts:
Hey there I'm the one who supposed to received the ETH
it seems like the transaction has been pending since 2 Days straight because of the low gas fee
is it possible for me to just wait? or do I need ask the buyer the cancel it and pay it again with higher fee?
https://etherscan.io/tx/0x875e2bff5bf16b829932589a43656d50ce9f0247d7db5b8673456b979615dfca


texts: How to store and load an IPFS hash as bytes32 in contract written in Solidity

texts:
An IPFS hash can be expressed in hexadecimal which is 34 bytes long.
Afaik it is most efficient to store fixed length values in a Ethereum contract, thus a maximum of 32 bytes (bytes32).
Because the first two bytes of the IPFS hex hash describe the hash function and the hash size it could be split and stored with something like this:

  bytes32 hash
  uint8 hash_function
  uint8 size

I tried to do the splitting of the hash in solidity:

function splitHash(bytes source) internal returns(uint8, uint8, bytes32 hash) {
  uint8 tag = uint8(source[0]);
  uint8 len = uint8(source[1]);

  assembly {
    hash := mload(add(source,34))
  }

  return (tag, len, hash);
}

and combining it again using:

function combineHash(uint8 _tag, uint8 _len, bytes32 _hash) internal returns(bytes) {
  bytes memory out = new bytes(34);

  out[0] = byte(_tag);
  out[1] = byte(_len);

  uint8 i;
  for (i = 0; i < 32; i++) {
    out[i+2] = _hash[i];
  }

  return out;
}

This seems to work well but I fail to use it from web3.js and I fail to retrieve the hashes.

Is this approach useful? Does anybody has an example or some best practices on how to store and load IPFS hashes?


texts: How does one move forward with an ethereum application?

texts:
Not sure where to post this, but I've gotten into the ethereum programming space and believe that I have developed an interesting product.

I am unsure how I can take this product further, and ask how I can expand/introduce this token to other people, and/or see if people are interested.

So, my question is, once I have an application, where do I go from there. Where could I ask for advice, etc.?

Any help would be largely appreciated!


texts: Remix is compiling the smart contract but not solc command

texts:
I am able to successfully compile a smart contract in remix IDE. However when I try to do the same with solc npm command, it shows a JSON error when compiling.

Voting.sol

pragma solidity ^0.4.25;
contract Voting{
    mapping(bytes32=>uint8) public votesReceived;

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

    function voteForCandaidate(bytes32 candidate)public{
        votesReceived[candidate]+=1;
    }

 }

compile.js

var fs = require('fs');
var solc = require('solc');
var code = fs.readFileSync('Voting.sol').toString();
console.log(code);
console.log(solc.compile(code));

REMIX IDE is compiling the code without any errors

Compilation error when running the same code with solc

{"errors":[{"component":"general","formattedMessage":"* Line 1, Column 1\n  Syntax error: value, object or array expected.\n* Line 1, Column 2\n  Extra non-whitespace afte
r JSON value.\n","message":"* Line 1, Column 1\n  Syntax error: value, object or array expected.\n* Line 1, Column 2\n  Extra non-whitespace after JSON value.\n","severity
":"error","type":"JSONError"}]}


texts:
I have a cluster with 2 nodes and I would like to create a testnet by connecting them with geth.

I am using the following command:

Node1:
geth --datadir node1 --port 30302 --rpc --rpcport 3003 --rpcaddr 127.0.0.2 --ipcpath node1/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.1 --wsport 3002 --wsorigins "*"

Node2:
geth --datadir node2 --port 30304 --rpc --rpcport 3005 --rpcaddr 127.0.0.2 --ipcpath node2/geth.ipc --rpcapi="db,eth,net,web3,personal" --networkid 15 --rpccorsdomain "*" --ws --wsaddr 127.0.0.1 --wsport 3004 --wsorigins "*"

and both work individually. When I try to add them as peer, if does not work

admin.addPeer("....@127.0.0.1:30304")

Although the exit of this command is true, the peer is not added. Any idea?


texts: How do you set an icon for Metamask "DApp Connect" popup prompt?

texts: For example, here, how would someone get a logo to appear instead of the default "A" logo?


texts: Calling contract functions using only ABI without source code

texts:
I have MyContract.json file of some contract(assume i haven't its source code). In .json file, there is abi and bytecode. If i want to deploy such contract (through web3js), I am facing following problems. However, this question becomes more complex, when there are thousand of contracts, which is my final task. But here i am just limit my self to only one contract for understanding purpose.

If such contract need some arguments in its constructor, then how can i know its parameters with valid values, so that it could be deployed, successfully.
How can I call its different functions (getters, setters)?

For question no. 1; I am sharing here my code for its deployment. It is valid and working if contract has constructor which take owner address in its parameter. This code is tested on some known contract with source code. However, if constructor takes no parameters or different parameters or lot of other parameters, this code will fail to deploy, because i must have to pass valid number of parameters and valid values.

var compiledContract = require('./build/MyContract.json');

async function deployCon() {

const contract = new web3.eth.Contract(compiledContract.abi);
const params = {
    data: '0x' + compiledContract.bytecode,
    arguments: [account1]
};
const transaction = contract.deploy(params);
const options = {
    data: transaction.encodeABI(),
    gas: await transaction.estimateGas({from: account1})
};
// console.log(options)
const signed = await web3.eth.accounts.signTransaction(options, privateKey1);
receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
console.log(`Contract deployed at address: ${receipt.contractAddress}`);
return receipt;

}

For question no. 2; i am totally blind how to call contract's functions shown here as ??????? (which will come to know through abi  of .json file alongwith parameters!).

var  myContAddr = receipt.contractAddress;
    var myContractAbiDefenition = compiledContract.abi;
    var myContractInstance = new web3.eth.Contract(myContractAbiDefenition, myContAddr);
    await myContractInstance.methods.???????.send({from: account1, value: web3.utils.toWei(amount, 'ether')})


texts:
I'm trying to return a dynamic array of structures from a Solidity function to a client. Since I need to build the result, I'm declaring a storage variable and add elements to it:

function conversations(address user) public view returns (Conversation[]){
    Conversation[] userConversations;
    userConversations.push(conversations[0]);
    return userConversations;
}

However, I keep getting an out of gas exception in my Truffle tests. How can it run out of gas when it's a view function? I understand that userConversations is a storage variable (or I won't be able to execute push on it), but does it really modify the state of the contract? If it does, how do you rewrite it so that you can get a dynamic array?


texts: Persons who successfully placed tokens on public exchange: did you shared source code of contract?

texts:
One of my clients created token (standard ERC20) and want to put it to public exchange site. Exchange policy requires reference to Github repository. Client asking whether it safe to share source code of contract (it could contains some code that they treating as "something sensitive" and kinda "our invention") and afraid that it is not safe and somebody could create competitor using they codebase.

Could you please share your experience - would you provided source codes of smart contract that contained something more complex then ordinary ERC20-compliant logic?


texts: Im trying to find a cheap solution in Solidity where a uint256 type caluclation for 1000-1001 results 0. I know that i run into overflow problems here and cant use Safemath.


texts: Solidity store storage pointer in storage variable for accessing it from distinct functions

texts:
In a contract, using Solidity, is it possible to store a pointer to a storage variable in a storage variable (or somewhere else that may be suitable) and access it from distinct functions?

Consider the following example in Solidity pseudo code:

contract AContract {

    struct AStruct {
      uint a_field;
    }

    AStruct variable_a;
    AStruct variable_b;

    AStruct storage pointer_to_either_a_or_b;

    modifier AModifier()
    {
      if (condition_a)
      {
        pointer_to_either_a_or_b = variable_a;
      }
      else
      {
        pointer_to_either_a_or_b = variable_b;
      }
    }

    function AFunctionUsingPointerToAorB100() internal AModifier()
    {
      pointer_to_either_a_or_b.a_field = 100;
    }

    function AFunctionUsingPointerToAorB200() internal AModifier()
    {
      pointer_to_either_a_or_b.a_field = 200;
    }

}

Whenever I try to use the "storage" keyword for a storage variable I get the following compilation error for "AStruct storage pointer_to_either_a_or_b":

  Error: Expected identifier, got 'Storage'

Is there a way to circumvent this, like placing the pointer somewhere else in the code?


texts:
I want to start mining in windows server 2008
( How to Mine Ether and use Ethereum on Windows?)
 everything is going perfectly except ethminer(step 9) says JSON-RPC problem. Probably couldn't connect. Retrying in 1... forever. And geth won't mine

what should I do?


texts:
Is moment of account creation stored in blockchain?
Or only first income or outcome transaction time can estimate it?


texts: Why is my geth node stuck on block 7130891?

texts:
My geth mainnet node (version 1.8.21) has stopped on block 7130891.

Interestingly, eth.syncing returns false and eth.blockNumber constantly returns 7130891. It was working up until ~24 hours ago.

Has my node forked? If so, how did it do this (so I can avoid it in the future)? How do I resync it on the main chain?


texts:
I'm writing my first contract and my withdraw function doesnt work. Eth doesnt move to my _withdrawAddr.

Also can somebody explain why my function getBalanceThis returns 0 instead of amount I send to contract and my other GETTER functions getBalanceOwner, getBalanceBuyer and getBalanceWithdrawAddr all return value..

pragma solidity ^0.5.0;

contract Test{

    address payable owner;
    address payable buyerAddr;
    address payable withdrawAddr;

    mapping(address => uint) balances;

    constructor(address payable _buyerAddr, address payable _withdrawAddr) payable public {
        owner = msg.sender;
        buyerAddr = _buyerAddr;
        withdrawAddr = _withdrawAddr;
    }

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

    modifier onlyBuyer(){
        require(msg.sender == buyerAddr);
        _;
    }

    function Send() payable public onlyBuyer{
        owner.transfer(msg.value);
    }

    function getBalanceOwner() view public returns(uint){
        return owner.balance;
    }

    function getBalanceBuyer() view public returns(uint){
        return buyerAddr.balance;
    }

    function getBalanceWithdrawAddr() view public returns(uint){
        return withdrawAddr.balance;
    }

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

    function Withdraw() onlyOwner public returns(bool success)  {
        uint wd = 5 ether;
        withdrawAddr.transfer(wd);
        return true;
    }

}


texts: How to put some data(hash) in Ethereum blockcahin?

texts:
how to put some data (i want to put in. something like 'ABFFC1244AA')
in Ethereum blockchain ?

as i know there is 'data' variable in transcation .

also if i can, want to know example or link for how to do it.

i make 'geth' network in ubuntu server.

and i can just make account , mining , send transaction ,,,


texts: Why my transactions-private GETH node- take minutes to propagate?  How can I optimize this? Can I broadcast the same transaction to multiple nodes to speed up the propagation?


texts: ERC721 - How is gas worked out with TokenID?

texts:
ERC721 - I have minted a tokenid (tokenid=444) and my account owns it. When I try and transfer it, I get this message stating the gas cost is the normally calculated one and the total cost has the tokenid added (which is arbitrary). How is that worked out?

I am just trying to assign a unique token ID to my wallet address which could then be used to tag rare items (eg rare art). I am using this  ERC721 contract. I did not expect the total cost to be related to the tokenid.


texts:
Lets say an asset is created as a smart contract instance. Now each asset id (i.e. contract address) is stored in a manager contract. Now the status of the asset changes during the course of the workflow.

In this case what is the best way to track the state changes of the asset.

Don't want to have an audit kind of contract to track asset state changes. Rather want to somehow utilize the platform to fetch the previous states of the asset contract instance by providing the asset id (i.e. contract address)


texts: How do I construct a call to contract return string using inline assembly?

texts:
pragma solidity ^0.4.21;
contract Test1 {
    function add(int a, int b) returns(string){  //Simply add the two arguments and return
    return "Qmrwokdkeoiudkeooiskelpdislpeosj;sd[opek;s[pkfe,;soeipsoekf;sodfpsoe,mfoskfesktgfetg";
}
}
contract Test2 {
Test1 test1;

function Test2(){  //Constructor function
    test1 = new Test1();  //Create new "Test1" function
}

function test(string a, string b) constant returns (string c){
    address addr = address(test1);  //Place the test1 address on the stack
     bytes4 sig = bytes4(sha3("add(int256,int256)")); //Function signature

   assembly {
    let x := mload(0x40)   //Find empty storage location using "free memory pointer"
    mstore(x,sig) //Place signature at begining of empty storage
    mstore(add(x,0x04),a) //Place first argument directly next to signature
    mstore(add(x,0x24),b) //Place second argument next to first, padded to 32 bytes

    let success := call(      //This is the critical change (Pop the top stack value)
                        5000, //5k gas
                        addr, //To addr
                        0,    //No value
                        x,    //Inputs are stored at location x
                        0x44, //Inputs are 68 bytes long
                        x,    //Store output over input (saves space)
                        0x20) //Outputs are 32 bytes long

    c := mload(x) //Assign output value to c
    mstore(0x40,add(x,0x44)) // Set storage pointer to empty space
}
 }
}

but c is empty string


texts: How do mrand.Float64() output the same result with same order in reorganisation?

texts:
Recently, I did go deep into the code of reorganisation in blockchain, but I'm confused by the mrand.Float64() in WriteBlockWithState. Here is the code: original code position

// If the total difficulty is higher than our known, add it to the canonical chain
// Second clause in the if statement reduces the vulnerability to selfish mining.
// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
reorg := externTd.Cmp(localTd) > 0
currentBlock = bc.CurrentBlock()
if !reorg && externTd.Cmp(localTd) == 0 {
    // Split same-difficulty blocks by number, then at random
    reorg = block.NumberU64() < currentBlock.NumberU64() || (block.NumberU64() == currentBlock.NumberU64() && mrand.Float64() < 0.5)
}

I know when system receive a block getting the same total difficult and same height, it will use mrand.Float64() to get a "random" number between 0-1 to decide whether reorg or not. My question is how will it ensure different geth client will get the same result by this? I mean, the geth client can start at different time and may execute mrand.Float64() different times, hence get different result and different chain. Am I missing something? Please help!


texts: cannot see event from javascript frontend

texts:
I'm hacking together a frontend for a smart contract for a hackathon (not a frontend developer). An angular page  that someone put together is getting the input parameters for a transactions, which is then sent through web3 to Rinkeby, where the contract is deployed. This works, but I cannot seem to read the corresponding event.

This is the relevant smart contract code:

contract PePaDe {
  event NewShipment(address shipment);

  function createShipment(address _recipient, string _originAddress,
      string _destAddress, int _maxTemp, int _minTemp,
      uint _weightInKg, uint _expirationTime) public  {
    Shipment shipment = new Shipment(msg.sender, _recipient,
       _originAddress, _destAddress, _maxTemp, _minTemp,
       _weightInKg, _expirationTime);
    NewShipment(shipment);
  }
}

(Shipment is another contract defined after the first one)

And this is the relevant javascript in the frontend function called by the press of the button:

let PePaDe = web3.eth.contract(pepadeabi);
var pepadeInstance = PePaDe.at(baseAddress);

function createNewShipment() {
  var recipient = document.getElementById("senderreceivername").value;
  var originAddress = document.getElementById("senderfromaddress").value;
  var destAddress = document.getElementById("sendertoaddress").value;
  var maxTemp = new BigNumber(document.getElementById("sendermaxtemperature").value);
  var minTemp = new BigNumber(document.getElementById("sendermintemperature").value);
  var weightInKg = new BigNumber(document.getElementById("senderparcelweight").value);
  var expirationTime = new BigNumber(document.getElementById("senderdeliverbydate").value);
  const tx = pepadeInstance.createShipment(recipient, originAddress, destAddress,
                            maxTemp, minTemp, weightInKg, expirationTime,
                            {from: web3.eth.accounts[0]});
  console.log(tx);
  // var filter = web3.eth.filter('latest');
  var shipEvent = pepadeInstance.NewShipment({});
  shipEvent.watch(function(error, result){
    if (!error) {
      console.log("New Shipment contract: ", result.args.shipment);
      shipEvent.stopWatching();
    } else {
      console.log(error)
    }
  });
}

The transaction is created, I can see it on Etherscan, the transaction hash is printed on the console, but I never see the event. I have also tried with web3.eth.filter, both with latest or pending, with similar results. Any hint?


texts: Is there a standard name registrar contract?

texts:
In Etherscan's accounts page, some accounts have names affiliated with them. Where are these names saved? I'm thinking of making a name registry for my dapp, but I would like to know if there is a "global" one that I can use instead.

Thanks,


texts: A simple and direct way to buy ethereum without a broker/exchange?

texts: As a starter(day one) I find it very odd there apppears to be no simple direct way to buy ethereum. I dont want to an exchange/broker ' as i have had bad experience that was not resolved(reminds me of early paypal days when they would hold your money for infinity whilst 'so called' security checks were being performed lol. How do we keep the robber barons out of the crypto scene when centralized global banks for example;JP morgan itself is looking at the block chain tech for a centralised purpose. Interesting stuff. Please comment.


texts:
It just doesnt work. I have spent hours looking on the internet and no solution seems to work for me.

root@ewerton-azevedo-blockchainlab-5299615:/home/ubuntu/workspace# npm
install ethereumjs-testrpc web3

> uglifyjs-webpack-plugin@0.4.6 postinstall
/home/ubuntu/workspace/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js

sh: 1: node: Permission denied
npm WARN enoent ENOENT: no such file or directory, open
'/home/ubuntu/workspace/package.json'
npm WARN workspace No description
npm WARN workspace No repository field.
npm WARN workspace No README data
npm WARN workspace No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.2
(node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform f or
fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current:
{"os":"linux","arch":"x64"})

npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! uglifyjs-webpack-plugin@0.4.6 postinstall: `node
lib/post_install.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the uglifyjs-webpack-plugin@0.4.6 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-08-30T13_55_41_153Z-debug.log


texts: Metamask: How to access/call deployed contract's functions using Metamask

texts:
I'm learning Solidity. I've set up Metamask, truffle and testrpc. I can send ether from one account to another via metamask. But I want to Metamask  to access my deployed contract, and call my contract functions.

Question: Can I test and interact with my deployed contract using metamask?


texts: Swarm can't resolve my domain from ENS: 'no contract code at given address'

texts:
I carefully followed the ENS tutorial to register an .eth domain with the auction registrar. However, after pointing my resolver to my swarm content, I receive the following message from my swarm node when accessing the registered domain:

  can't resolve: no contract code at given address

Now, because registering, auctioning and claiming a .eth domain is a process taking several days / weeks, I do not fully remember which steps lead me to this point. Unfortunately, my ~/.ethereum/history file is empty. Here is how I set up the public resolver:

publicResolver.setContent(namehash('5chdfgh.eth'), '0x4fd6994ac8251fc7c6c793d3481353d8757f7e5439f1373e58c3d0b5437fb578', {from: eth.accounts[0], gas: 100000})

The domain in question is 5chdfgh.eth and the content is accessible via bzz://4fd6994ac8251fc7c6c793d3481353d8757f7e5439f1373e58c3d0b5437fb578.
Now my question, finally, is -- why can't this be resolved, which contract code is missing and at which address swarm is looking at exactly. I know I could simply start over again, but I am wondering whether it is possible to go backwards and find out what's wrong.

I think the first step is to find out which resolver is used. Is there any way to check this out?


texts: Why doesn't my private key's public key generate the correct public address?

texts:
Private Key: 9ccbcabf23e271183dbed503b43277f4c6eee9ac918cd6cda75ebb73ceb35c7d

Corresponding Public Address: 0xa73Fb234B1773ed7b115D18A1f0a15579bA2C1e1 (check for yourself on MyCrypto, for example)

One can generate the Public Key from the Private Key: 25b867253fe38ac7ed594f54b4f55fa18c49ced332fc352991e48a77ab7816c759d46cab51a59d9833cd6d958cc752ad95f10bbe469b364db2de5d3535417966

This Public Key, however, does not seem to be produce the Public Address above. Instead, after running it through keccak256, then taking the last 20 bytes, we're left with: 0xaa72e09d258da5496a7e6628e09207ec382e478a

What am I doing wrong?


texts: Modify string in contract (Error: invalid address)

texts:
I'm trying to write a contract that has a string that can be modified/updated by the owner later on.  I tested it in Remix and it works perfectly. But when I deploy it to my private blockchain, I get errors. Any ideas? Or is there at least a reasonable way to debug the code? These errors seem to be useless!

pragma solidity ^0.4.13;

contract c5 {
    uint currentVersion;
    string command;
    address owner;

    //Constructor is automatically executed upon creation:
    function c5(){
            currentVersion = 1;
            command = "test1";
            owner = msg.sender;
    }

    function update(uint input){
            if(msg.sender != owner) return;
            currentVersion = input;
    }

    function query() constant returns (string){
            return command;
    }

    function version() constant returns (uint){
            return currentVersion;
    }
}

This is the error I get in the geth console:

> c5.query()
"test1"
> c5.version()
1
> c5.update("4")
Error: invalid address
at web3.js:3879:15
at web3.js:3705:20
at web3.js:4948:28
at map (<native code>)
at web3.js:4947:12
at web3.js:4973:18
at web3.js:4998:23
at web3.js:4061:16
at apply (<native code>)
at web3.js:4147:16

Are these strings indeed editable? or do I need to submit a new contract with the new string and direct queries to it via an updated address via DELEGATECALL:

Upgradeable smart contracts

Thanks in advance for any ideas!


texts: Low hashrate with Nvidia GeForce GTX 1050 Ti

texts:
I just set up a cheap mining rig running Ubuntu server 18.04 and using Nanominer, which I have been using for Monero.
Now I installed an Asus Nvidia GeForce GTX 1050 Ti using a Riser pci-1X to pci16X adapter to start mining Ethereum, allegedly, with this GPU I should be getting something around 15 MH/s, but I only get roughly 3 MH/s.
Something to note is that the CPU I got in this motherboard is a Intel Celeron J1800 and I wonder if this could be such a dramatic bottleneck that significantly decreases GPU performance, or is it that I need to downgrade the drivers as I've seen as a solution in some other forums.
Thank very much every one!!!!


texts: While retrieving events in web3 js, i am getting "invalid address" error

texts:
Using the following code, i am trying to retrieve events:

var invoiceAbi = invoiceContractAbi;

var invoiceAddress = invoiceContractAddressAddress;

var invoiceInterface = web3.eth.contract(invoiceAbi).at(invoiceAddress);

var invoiceEvent = invoiceInterface.invoiceFinanced({}, { fromBlock: 15971, toBlock: 'latest' });

var i = 0;

invoiceEvent.watch(function (error, result) {
console.log(i++ + ": " + JSON.stringify(result));
});

I ve used actual abi and contract address. Once i run the following command, i get an error:

var invoiceEvent = invoiceInterface.invoiceFinanced({}, { fromBlock: 15971, toBlock: 'latest' });

Error:

invalid address
at web3.js:3887:15
at web3.js:3713:20
at web3.js:4939:28
at web3.js:4938:12
at web3.js:4964:18
at web3.js:4989:23
at web3.js:4055:16
at web3.js:4141:16
at <anonymous>:1:20

What should i do?


texts: How to convert geth arhive to full node without loosing intermediate state

texts:
We have a geth node that runs with --gcmode "archive". However, the recent growth of disk space is unsustainable and we want to change this to a full node. If I stop the node and just re-run it with --gcmode "full":

Will we lose all the intermediate state in the node?
If not lost, will we be able to query old intermediate state?
Will the node start sync again from genesis (depending on --syncmode option) or will continue from where it stopped?

Given the time to resync an archive node if we need to run it again for research purposes, we don't want to lose the intermediate state that's already in our disk.


texts: Why is my rebasing token balance changing over time?

texts:
I bought some tokens for my wallet and noticed the quantity changes very slightly over time. I’ve seen this happen with several tokens, Im not sure why.
Is this related to the way the getbalance function works?
For example i bought some LOGE.
Balance is 2857290319.47672
A few minutes later, it is 2857334061.72867, without any new transaction.
Thanks!


texts: Which function we need to use in truffle for the communication of second Dapp to the contract deployed on blockchain by first Dapp, because contract deployed by truffle is not accessible by geth node. I am trying using contractname.at(contractaddress), but it's not working?


texts: Is it possible to send an extra argument or data when interacting with a contract?

texts:
Take the transfer function of the DAI contract as example.
It allows only two arguments: dst and wad.

This is how the decoded data input looks like on a sample transaction:

Function: transfer(address dst, uint256 wad)

MethodID: 0xa9059cbb
[0]:  0000000000000000000000006262998ced04146fa42253a5c0af90ca02dfd2a3
[1]:  000000000000000000000000000000000000000000000002c3c465ca58ec0000

Is it possible to attach some extra data when calling the transfer function, so that the decoded data input looks as follows:

Function: transfer(address dst, uint256 wad)

MethodID: 0xa9059cbb
[0]:  0000000000000000000000006262998ced04146fa42253a5c0af90ca02dfd2a3
[1]:  000000000000000000000000000000000000000000000002c3c465ca58ec0000
[2]:  000000000000000000000000000000000000000000000000000000000000fede

(obviously without the transaction being reverted or something)

If not possible, is there any other way to attach a message to a transaction that interacts with a contract?


texts: Can the recipient of a block reward spend the funds in the same block?

texts: From my understanding, when a new block is mined, the coinbase address's balance is incremented by the block reward amount. If this address had a zero balance before the block was mined and the block contains a transaction that spends funds from this address, would the block be considered valid?


texts: My Smart contract did not send decimals token

texts:
I have a smart contract with 0.15 Ether = 1 Token
So when user send 0.15 Ether it's fine he receive 1 Token, but if he sent 1 Ether normally should receive 6.66 Token, but the contract sent only 6 Tokens ?

Same case with any decimal number AA.BC it send alwayse A and ignore any number after commas.

USED FUNCTION:

    uint amount = msg.value;

    uint tokentosend = amount / price;
    tokenReward.transfer(msg.sender, tokentosend);

Can you please help ?


texts: How to remove The DAO contract from Ethereum Wallet (Mist) watch list as it is freezing?

texts:
I added The DAO to my Mist watch list, but as many people I experienced freeze of the wallet since. I would like to remove this contract that probably generates too much transactions to watch but as UI freezes when I try to access it, I can't.

Is there another way to remove the watched contact, perhaps by modifying a file manually? Thanks.


texts: How do existing applications on the Ethereum blockchain enforce confidentiality of data?

texts:
How do current applications on the Ethereum blockchain enforce confidentiality of data?

I know that the state of a contract is visible to any node on the network. Does this imply that there are no way of storing and enforcing confidential data on the blockchain?

Is the only way that applications can store and deliver confidential data to encrypt it under the public key of the receiver?


texts: Double voting unit test failing on Election dApp

texts:
I am working through DApp University's election dApp tutorial. I made unit tests for invalid candidate, and double voting. My double voting unit test is failing, saying:

  1) Contract: Election
   throws an exception for double voting:
 AssertionError: error message must contain revert
  at test\election.js:78:7
  at process._tickCallback (internal/process/next_tick.js:68:7)

Here is my dApp's repository. https://github.com/Legitimate/election

This is my code for the double voting unit test. The line that is failing is found in the first unit test I made for invalid candidate. I'm not sure why it is failing for double voting. I would appreciate any consideration from the community. Thank you.

it("throws an exception for invalid candidate", function() {
    return Election.deployed().then(function(instance) {
      electionInstance = instance;
      return electionInstance.vote(99, { from: accounts[1] });
    }).then(assert.fail).catch(function(error) {
      assert(error.message.indexOf('revert') >= 0, "error message must contain revert");
      return electionInstance.candidates(1);
    }).then(function(candidate1) {
      var voteCount = candidate1[2];
      assert.equal(voteCount, 1, "candidate 1 did not receive any votes");
      return electionInstance.candidates(2);
    }).then(function(candidate2) {
      var voteCount = candidate2[2];
      assert.equal(voteCount, 0, "candidate 2 did not receive any votes");
    });
  });

it("throws an exception for double voting", function() {
    return Election.deployed().then(function(instance) {
      electionInstance = instance;
      candidateId = 2;
      electionInstance.vote(candidateId, { from: accounts[1] });
      return electionInstance.candidates(candidateId);
    }).then(function(candidate) {
      var VoteCount = candidate[2];
      assert.equal(voteCount, 1, "accepts first vote");
      // Try to vote again
      return electionInstance.vote(candidateId, { from: accounts[1] });
    }).then(assert.fail).catch(function(error) {
      assert(error.message.indexOf('revert') >= 0, "error message must contain revert");
      return electionInstance.candidates(1);
    }).then(function(candidate1) {
      var voteCount = candidate1[2];
      assert.equal(voteCount, 1, "candidate 1 did not receive any votes");
      return electionInstance.candidates(2);
    }).then(function(candidate2) {
      var voteCount = candidate2[2];
      assert.equal(voteCount, 1, "candidate 2 did not receive any votes");
    });
  });


texts: Will people who buy my newly created erc20 Token also have to buy ETH as well?

texts: I'm currently deciding which crypto platform to go for (Ethereum or Waves). So I'm asking this question because I just wonder if the people, who will buy my newly created token, will HAVE TO buy Ether as well since they need to pay transaction fee in ETH whenever they transfer the bought token forward to other people. Please Help explaining for me in Clear-but-plain English. Thank you in advance!


texts: AWS -KMS sigining using the SIGN-VERIFY method

texts:
The Web3 library provides the function web3.eth.accounts.sign which in return gives the raw RLP encoded signature, using that signature we get the R, S, V values that can be used to recover the signer address.
https://web3js.readthedocs.io/en/v1.2.11/web3-eth-accounts.html#sign
ECDSA signatures in Ethereum consist of three parameters r, s, and v. Solidity provides a globally available method ecrecover that returns an address given these three parameters. If the returned address is the same as the signer’s address, then the signature is valid.
When signing with AWS-KMS it returns signature the value in the required format the returned value is a DER-encoded object.
https://docs.aws.amazon.com/kms/latest/APIReference/API_Sign.html#API_Sign_ResponseSyntax
The cryptographic signature that was generated for the message.
this message contains the R, S but not V.
Is it possible to get the V from the signed transaction anyways??
Understanding Ethereum signatures


texts: How do I get gas used by or price of a single mined transaction like in etherscan through a ethereum node?

texts:
I was using ethers.js to get the transaction receipt of a mined transaction but when I get the cumulative gas used it seems to give me cumulative gas of the block mined and not the transaction itself.
How do I get gas used only by a mined transaction?


texts: net.peerCount is Zero and blockNumber has stuck

texts:
I had a problem that my blockNumber gets stuck. Then I ran geth upgradedb and started geth --rpc --mine console again.

It looked like it was working, had the correct blockNumber for around 30 minutes and had net.peerCount = 1.

And now again, net.peerCount = 0, the blockNumber has stopped updating and it doesn't get synced...


texts: Generating accounts with pyethereum is insanely slow

texts:
I'm trying to debug an app that at some point needs to create a password
protected account. When I reach that point in my code using pycharm's debugger it takes forever to generate an account protected by a four character password.

The code is:

new_account = accounts.Account.new(password, priv_key, path)

where all fields are not None. Is there a way to debug faster?


texts: Process to find out an account's balance in the past

texts:
What would be the process to find out the balance of an account at a specific point in the past?

Is it correct to say that we have to get the balance from the current World State Trie and then roll back every single transaction involving the account from previous blocks until we reach the point in the past (block) that we want?


texts:
Consider this voting contract

contract Voting {
  mapping (bytes32 => uint8) public votesReceived;
  mapping (bytes32 => bool) public candidateList;
  function Voting(bytes32[] candidateNames) {
    for(uint i = 0; i < candidateNames.length; i++) {
      candidateList[candidateNames[i]] = true;
    }
  }
  function totalVotesFor(bytes32 candidate) returns (uint8) {
    require(validCandidate(candidate) == true);
    return votesReceived[candidate];
  }
  function voteForCandidate(bytes32 candidate) {
    require(validCandidate(candidate) == true);
    votesReceived[candidate] += 1;
  }
  function validCandidate(bytes32 candidate) returns (bool) {
    return candidateList[candidate];
  }
}

if I call validCandidate with a valid name (ie. a name included in the array passed to the constructor), it works. But for invalid names, I got a invalid opcode exception. I thought that maps had 0/false by default, is it not the case?


texts: I downloaded the ethereum wallet, and its taken a few days yet its still syncing. Im on block ~701,000 thus far. Is something wrong? Is it supposed to take this long?


texts: Miner not picking pending transactions from pool when TPS is high

texts: I'm running a private testnet with a high block gas limit and low difficulty. When I start pumping in a large volume of transactions (say 150 tx/s), after a certain point of time, I see the miner mining just empty blocks, despite there being a large number of transactions in the miner's tx pool. Any idea about why this might be happening?


texts: Can't understand hashing mechanism for mappings

texts:
I have a contract with function

    function addToBalance () payable {
        userBalances[msg.sender] += msg.value ;
    }

Debugged assembly and stumbled on the code that calculates key for store:

Code:
  => SHA3
Stack:
  0x0, 0x40
Memory:
  0x00: 000000000000000000000000ca35b7d9 // msg.sender
  0x10: 15458ef540ade6068dfe2f44e8fa733c // msg.sender
  0x20: 00000000000000000000000000000000
  0x30: 00000000000000000000000000000000

As far as I understand SHA3 calculatates hash of first 0x40 bytes of memory starting at 0x0. I don't get either the point of hashing 0x40 bytes (when 0x20 bytes would be enough) or what are the arguments of SHA3 instructions.


texts: Can I get a one-to-many(many-to-many) transaction method?

texts:
As we know, geth send eth by sendTransaction, it has from to and amount, it is an one-to-one transaction.
Can I get a way of one-to-many(many-to-many) transaction like sendmany in bitcoin-core? As bitcoin-core can draw bitcoin form all address in the local wallet automatically, it is actually a many-to-many transaction.
Just for saving miner-fee when I have huge transactions.

Thanks.


texts: Iterating over a loop causes out of gas error

texts:
I have an array of json objects, which contain an id and 5 fields. I have a function to register these fields against a unique identifier within a contract.

contract Test {
    struct Product {
        uint p_id,
        uint qty
    }

    mapping(bytes32 => Product) ProdMap;

    function registerProduct (bytes32 id, uint p, uint q) returns (bool) {
        ProdMap[id].p_id = p;
        ProdMap[id].qty = q;
    }
}

I am able to interact with a contract get a transaction hash out of the executed transaction in a contract:

contractInstance.registerProduct.sendTransaction(
    web3.fromAscii("0abc123"),
    items[0].Product_ID,
    items[0].Quantity,
    {
        from:web3.eth.accounts[0],
        gas:470000
    },
    function(err,txid) {
        if(err) { console.log(err); }
        var hash = txid;
        console.log('Transaction registered '+'and transaction hash is: ' + hash);
        callback(null,hash);
    });

Here items is an array if json objects. But when I loop through the entire array, I am getting an out of gas error.

contractInstance.registerProduct.sendTransaction(
    web3.fromAscii(item.Line_Item_ID),
    item.Product_ID,
    item.Quantity,
    {
        from:web3.eth.accounts[0],
        gas:1000000
    },
    function(err,txid) {
        if(err) {console.log(err);}
        var hash = txid;
        console.log('Transaction registered '+'and transaction hash is: ' + hash);
        callback(null,hash);
    });

Here I have listed only 2 attributes, but I have 5 in all while registering the product. I have been using testrpc and when I set the limit to a really high amount 4500000000000, I am able to execute the transactions. But when I see the logs for testrpc, the gas used is 27608. Is it possible to determine the gas needed to execute a transaction? Any suggestions?


texts: Is Solidity being replaced as the de facto standard for smart contract development?

texts: Is Solidity being replaced by languages such as Rust or other programming languages for smart contract development?


texts:
I'm connected to an Ethereum node (running Geth) I manage and I'm able to connect to it using RPC. I can access web3 in the terminal after issuing geth console. I can access and run the RPC function calls as listed in the documentation here. I have to switch between different libraries like webpy and web3.js so an implementation in either should be fine.

Given a transaction hash, I can fetch the transaction details, say using web3.eth.getTransaction(transaction_hash). But all the details I get only includes: hash, input, nonce, from, to, transaction_index, value, v, r, s.

What I'm curious about is how does this website access rest of the rich details as to how many tokens were transferred. More specifically, how can we read (given the sender and contract address involved in a transactions) the value of tokens transferred i.e. the value parameter of the function call?

A snapshot of such details from the above website. (How does one figure out the Token Transfer, shown in the picture below)

Is it from the input field? If so, how does one interpret the hex to actuall values and the function called?


texts: Quorum Private Transactions: Why public key instead of address?

texts: Out of a combination of curiosity and frustration, I'm trying to figure out why Quorum requires a node's public key when using "privateFor". Wouldn't it be easier to use addresses? I am wondering if there is any advantage in using the public key.


texts: Is there any API for ERC20 token balance of an address for a particular contract?


texts: Could not deploy on Ropsten network using Truffle

texts:
I have following truffle-config.js file

const fs = require('fs');
const HDWalletProvider = require("truffle-hdwallet-provider");
const secrets = JSON.parse(
  fs.readFileSync("abc.txt").toString().trim()
);

module.exports = {
  networks: {
    ropsten: {
      provider: () =>
        new HDWalletProvider(
          secrets.seed,
          `https://ropsten.infura.io/v3/${secrets.projectId}`
        ),
      network_id: 3
    }
  }
}

but when i run this command truffle(develop)> migrate --reset --network ropsten, i am facing following error;

Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.

Unknown network "ropsten". See your Truffle configuration file for available networks.

in my abc.txt file i have

{
  "projectId": "7fb0bdc97cbe419fbdf9690......",
  "seed": "affair rally mail snake clever pony also hundred....."
}


texts: In a private blockchain, why do miners keep adding empty blocks to the blockchain?

texts:
I have been working on a private blockchain and observed that a miner, when started, keeps on adding empty blocks with no transactions to the blockchain. Why is this happening? It doesn't make any sense to add empty blocks. This just results in the blockchain occupying more space. Is there a reason behind this? Although unlikely, will the same scenario occur in the Ethereum blockchain if there are no transactions?

P.S: Here's a useful snippet to start mining only when there are transactions.


texts: Why would someone have a fallback function for ^0.6.0?

texts: A receive function allows a contract to accept eth via a send() or transfer(). As someone thought it was a good idea to have both a receive and a fallback function, I was curious what sort of scenario would be helped by having an additional fallback function? I can't think of one so I figure I am missing something.


texts:
It appears ethereum is using plain hexadecimal addresses like 0x0092e965928626f8880629cec353d3fd7ca5974f for now.

I noticed, the ethereum C++ implementation outputs so called ICAP addresses, check this generated by ethkey:

> ethkey new test
Enter a passphrase with which to secure this account (or nothing to use the master passphrase):
Please confirm the passphrase by entering it again:
Enter a hint to help you remember this passphrase: 321 backwards
Created key 055dde03-47ff-dded-8950-0fe39b1fa101
  Name: test
  Password hint: 321 backwards
  ICAP: XE472EVKU3CGMJF2YQ0J9RO1Y90BC0LDFZ
  Raw hex: 0092e965928626f8880629cec353d3fd7ca5974f

What is an ICAP address? Are these to be used in future releases like we are used to in Bitcoin? Do they always start with X? Do they have a checksum?


texts: Why does not this contract send the tokens to the creator?

texts:
I m testing ERC20 token contracts. I could be able to create and get back the tokens in the Ropstan test network.
When I deploy the same contract.sol in the main network my creator address doe not get any tokens back..
when I run the function transferthe transaction says  ERC-20 Token Transfer Failed to complete, check with sender for more information.

This is the contract address: https://etherscan.io/address/0xbda3d86d96eb05a8965d73cb59b12eeeaf2530be

What could be the reason?

I am using remix.


texts:
I have a mapping(string => Person) public map:
struct Person {
        string name;
        string description;
        address primaryAddress;
        string linkToWebsite;
        string linkToPicture;
        address secondaryAddress;
        uint age;
}

, this struct is only made of strings, addresses and uints, but when compiling I get this error.
Internal compiler error: Accessors for mapping with dynamically-sized keys not yet implemented.
BUT,
From Solidity Features:

Strings as Mapping Keys
Strings are allowed as keys for mappings.
contract C {   mapping (string => uint) counter;
function inc(string _s) { counter[_s]++; } }

Any help with it?


texts:
I am creating a contract of storing all the names and address of the users.

Then I returning the array of the names and address.

contract demo{

    address public user;
    uint  public  i=0;

    function demo(){
        user=msg.sender;
    }

    address[10] users;
    bytes32[10] name;

    function add(bytes32 _name){

        users[i]=user;
        name[i]=_name;
        i++;

    }

    function get_names() returns(bytes32[10]){
        return name;
    }

    function get_address() returns(address[10]){
        return users;
    }
  }

when I call the get_names function using web3, it did not returning the names of all the added users.

please help me what to do...

here is the code of web3

mycontract=web3.eth.contract(ABIArray).at(contract_Address);

    console.log(mycontract);
    var defaultAccount = web3.eth.defaultAccount;

    mycontract.get_names(function(err,res){

      console.log("get_names "+res);
      TemplateVar.set(template, "counter", res);

    })

     mycontract.get_address(function(err,res){

      console.log("get_address "+res);
      TemplateVar.set(template, "counter1", res);

    })

      mycontract.i(function(err,res){
        console.log("i "+res);
      TemplateVar.set(template, "counter2", res);

    })

And the returned value is not an array of names or address.


texts: Why install geth beside Mist and why geth use so much CPU?

texts:
I have installed new Mist 0.8.3, frist thing after fresh new instalation of ubuntu 16.4.1. I have run Mist-0.8.3.deb file and clicked install.

How come geth uses so much CPU?

I have i7-6500 processor and geth it is using about 60-70% of CPU just by running Mist, while I'm doing nothing. Just to be clear, all blocks are downloaded.

How come, when I type geth in terminal, it says geth: command not found?

On page https://github.com/ethereum/mist/releases it says Ethereum Wallet and Mist Beta 0.8.3 + Geth 1.4.12. Even better, as I asked in first question, geth is using a lot of my CPU so I have to be able to call geth (I supose). In my previous question someone answered me that I can check geth version by command

  sudo apt-cache policy geth

Probobly that would work before I reinstalled ubuntu because I installed specifically go-ethereum 1.5.0, not just Mist like now. I wouldn't do that if there was no bug at version 1.4.11. So it's clear that I have geth 1.4.12, but how can I check that in terminal?

While I'm asking this, can someone explain why would I install go-ethereum now when I installed Mist? Even better, if I ever have need to upgrade/downgrade geth, while just having only Mist, what is the best way to do that?

Thank you for answers in advance and regards,

Tomo


texts: where are the parity log files in daemon mode

texts:
in parity there is a daemon switch witch is useful but I can not find the logs in this mode.

Where does parity write the logs in daemon mode?


texts:
How can I get contract mapping storage?

Considering this simple contract

contract Currency{
 mapping(address=>uint) public balances;

   function deposit(){
      balances[tx.origin]++;
   }
}

After deploying and calling deposit, I'd like to get contract storage

eth.getStorageAt("0x681afcc842a1a01f34ffb2c091e576aa78175d55",0)

but always getting same result : 0x0000000000000000000000000000000000000000000000000000000000000000

even if currency.balances.call(...) returns correct balance

Is there a way to retrieve entire balances map?


texts:
i was following this nice tutorial to make simple Daap,and at one place i got stuck. I'm really newish to that, so hope someone could explain that. This is the link and the place where i get stuck,if you go thru link, is NodeJS Time  section.

const Web3 = require('web3');
const net = require('net');
const compiledContract = require('./contracts/contractv1');

web3IPC = '/Users/jackschultz/Library/PrivEth/geth.ipc';
let web3 = new Web3(web3IPC, net);

const byteCode = compiledContract.byteCode;
const QuestionContract = new web3.eth.Contract(compiledContract.abi);

web3.eth.getCoinbase(function(err, cba) {
 coinbaseAddress = cba;
 console.log(coinbaseAddress);
});
const coinbasePassphrase = 'passphrase';

app.post('/', (req, res) => {
  const question = req.body.question;
  web3.eth.personal.unlockAccount(coinbaseAddress, coinbasePassphrase, function(err, uares) {
    QuestionContract.deploy({data: byteCode, arguments:
}).send({from: coinbaseAddress, gas: 2000000})
     .on('receipt', function (receipt) {
         console.log("Contract Address: " + receipt.contractAddress);
         res.redirect('/questions?address=' + receipt.contractAddress);
    });
  });
});

So here is a code, but i didn't got what i should do with that, where to save, what format should save. Im using win7 and do not have NodeJs, and what exactly that Path points to(Users/jackschultz/Library/PrivEth/geth.ipc)  cause i did  not find that path on my local machine,instead i have C:\Users\Administrator\AppData\Roaming\Ethereum which has geth and keystore folders ? So need the guide for execution steps.   Unfortunately i couldn't reached out to the authour,so sorry for such a dumb question, but i was working with that tutorial for a long time, don't wanna stop in the middle.


texts: How to calculate the merkle proof for quering the balance of a token holder?

texts:
I know this can be done through accessing the full node of Ethereum, but I want to know, how could I do it technically? Suppose I have an ERC20 token contract having address 0xabc.. and Alice is the token holder having account address 0xqwe.. .I want to query the blockchain for getting the balance of Alice till X block number. As per my research, I can get this by accessing the state trie using the key, state trie hash, Merkle Proof.

I calculate the partial key using this Solidity-Miscellaneous

but still, don't understand how do I map my key related to the ERC20 token contract.

I have the state trie hash but still trying to find out the Merkle proof, How do I do that? Should I need to use the ethereumjs/merkle-patricia-trie or there is an alternate present to calculate the Merkle proof.


texts:
Are there any ways to send simple messages on the Ethereum blockchain without incurring any gas fees at all for the end user?

If this can't be done with Ethereum in solidity or newly created ERC20 tokens, are there any other blockchain options?


texts: Truffle Test: How to test SafeMath Library for overflow

texts:
How can I test if a function is resistant against overflow with truffle test?

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

contract TestSafeMath{
    function test_add_10_and_max_should_return_err() {
          uint256 max = 2**256 - 1;
          uint256 expected = "revert overflow error";
          Assert.errorsEqual(SafeMathExt.add(10, max), expected, "Addition of 10 and max should revert");
    }
}

TestSafeMath
    1) test_add_max_and_10_should_return_err
    No events were emitted
    1 failing

How can I get this test passing?


texts: how to find transaction success or failure programatically?

texts:
I am using geth in linux and sending few transactions, and in out of 100 around 30 are getting errored.

How to find out Whether transactions went though or not with in geth cli.
How to find out what was the issue for rejecting transaction.

Thanks