texts: TypeError: _getWeb3__WEBPACK_IMPORTED_MODULE_0__.default.eth is undefined

texts:
I'm not familiar with webpack, but after reading this error all I know that I import one module that is undefined by webpack. However, I don't know why export default new web3.eth.Contract(abi, address); this row can cause this problem. Since I already export web3 from my file getWeb3.js and then import it to this error file storehash.js. I can't find any error in my getWeb3.js file since it is created by truffle unbox react and then all I changed in this file is to change the network to rinkby network. Can anybody help me?

storehash.js

import web3 from './getWeb3';

//access our local copy to contract deployed on rinkeby testnet
//use your own contract address
const address = '0xD0e9A858b68cA1981aa524D22B244C3C3A237ad4';//'0x8f388d3a1a4d011eECb3822EE6bDf78902d0F6f1';
//use the ABI from your contract
const abi = [
    {
      "constant": false,
      "inputs": [
        {
          "name": "x",
          "type": "string"
        }
      ],
      "name": "sendHash",
      "outputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [],
      "name": "getHash",
      "outputs": [
        {
          "name": "x",
          "type": "string"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }
]

export default new web3.eth.Contract(abi, address);

getweb3.js

import Web3 from "web3";

const getWeb3 = () =>
  new Promise((resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener("load", async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          // Acccounts now exposed
          resolve(web3);
        } catch (error) {
          reject(error);
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log("Injected web3 detected.");
        resolve(web3);
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider(
          'https://rinkeby.infura.io/v3/172a5e1258804b4d919ded68b1ae1490'
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      }
    });
  });

export default getWeb3;

Below is the error that I got in my browser console.


texts: By what magic ?! : multiswap in 1 block + paradoxal transactions?

texts:
By what magic this is possible ?
https://etherscan.io/tx/0x3f95c3fbddda52c8c07a1b1a0e8ced33a6b71a17cbbd82bf688cd45e23c5f4fd

How to make multiple swap in one block (look section call "Transaction Action" not "Tokens Transferred")
How can you have : swap1 : Token_A -> Token_B, swap2 : Token_B -> Token_C, when user dont have token_B yet ?

Thank you for your answers :)


texts: How to declare a fix bytes type more than bytes32?

texts:
I am facing "UnimplementedFeatureError: Nested dynamic arrays not implemented here.
" when I try to emit an event contains bytes [] data;

I have a fix size of data which is 65bytes but there is no supported type to put it in. so I use a dynamic bytes.

I have this event:

event SkillValidated(
        address indexed user,
        address [] validators,
        bytes [] signatures, //a signature is a 65 bytes
    );

when I emit the event I got the mentionned error.
and when I change it to:

event SkillValidated(
        address indexed user,
        address [] validators,
        bytes32 [] signatures, // I lost part of signature
    );

it works!

How can I resolve the problem, have I to implement a specific type using struct?


texts: What to do about "Block sealing failed" on a new Clique blockchain?

texts:
I've use puppeth to configure a test blockchain. I inited the blockchain and started geth. When I go into the console, this is the output I get:

> miner.start()
INFnOul l[0
6-> 09|00:30:09] Starting mining operation
INFO [06-09|00:30:09] Commit new mining work                   number=1 txs=0 uncles=0 elapsed=0s
WARN [06-09|00:30:09] Block sealing failed                     err=unauthorized

There's an account that's been created with a key in the keystore, and I set it up in puppeth so it would be an authorized sealer. So why is block sealing still unauthorized?


texts: mapping for msg.sender doesn't seem to work

texts:
state Variable is this : mapping(address=>uint) public userVotes;

now i have a function :

function votePresident(uint _id) external {
        presidents[_id-1].voteCount++;
        userVotes[msg.sender] = _id;
        Voter(msg.sender, _id, userVotes[msg.sender]);
    }

the last line is an event. So What happens here is after executing this function, I put an address of the executer in a mapping as a key and value as he passed in. Then I log it.

I have another function where I use this userVotes

function getPresident(uint _index) public view returns (uint, string, uint, string, uint) {
        President storage president = presidents[_index];
   return (president.voteCount, president.hashImage, president.id, president.name, userVotes[msg.sender] );
    }

look at the return line the last parameter, userVotes[msg.sender] . Unfonrtunatelly, it always returns 0. I don't know why it does that. I checked the log after executing the first function and I didn't see 0. i just saw the actual value. Please help . If I call the getPresident funcction in remix, it returns the actual value and not 0.


texts:
I don't want to load the web3 library, I do however want to convert Either to Wei, does anyone have a JavaScript function to share.

I don't mind loading a smaller library


texts: Etherscan shows tx out of gas but completes anyways

texts:
It seems that it is somehow possible to run out of gas but the transaction still completes? This violates my understanding of ethereum. If you run out of gas, it reverts all changes. What does this error from etherscan mean?

Although one or more errors occured [Out of gas] contract execution completed


texts:
I've downloaded the Etash source code and did some test on the PoW algorithm.
In MinerAux.h, if the current.seedHash != newSeedHash, the DAG file needs to be regenerated. And the newSeedHash was set by the rpc-client method getEthashWork (in EthashClient.cpp).
I am confused by the  method getEthashWork. I have some questions below:

How to compute the three parameters “hash without seal, seed hash, target boundary"?
When will the seed hash be different from current one?
Which conditions will lead to the seed hash changing?


texts: Which one is more secure and easier to mange among eth.accounts.create, personal.newAccount & eth.accounts.wallet.add

texts:
Here are what I knew about them:

eth.accounts.create: Generate an address and private key for transaction but did not stored in anywhere.
personal.newAccount: Create an account under node, so that we could get these accounts by eth.getAccounts(). But before transaction, the account need to be unlocked.
eth.accounts.wallet.add: Create an account and private key stored in memory wallet, can get them by eth.accounts.wallet._accounts.

As the topic, which one is more secure, easier to mange in node and recommended to use for erc20 tokens transfer.

Thanks.


texts: Solidity, is it possible to deploy a smart contract that prevents other smart contracts from inheriting from it?

texts: I am new to Ethereum and I was wondering if it is possible to deploy a smart contract such that other smart contracts are not able to inherit from it. In other words once a smart contract is deployed can other smart contracts inherit from it?


texts:
Am I right, that 0xc1384BAFDD139a61998e1f612948da22fD878BD2 and 0xc1384bafdd139a61998e1f612948da22fd878bd2 are the same addresses?

I'm asking, because, for example, in Bitcoin base64 is used, so uppercase and lowercase are not the same.


texts: Is a stand-alone wallet for an ERC20 compatible token a possibility?

texts:
Assuming that there is an ERC20 compatible token deployed on the Ethereum blockchain, is it possible to:
1. Have a stand-alone wallet solely for this token (not an Ether wallet + watching a token, but a dedicated app). Maybe some existing open source solutions?
2. Is it required to download the full Ethereum blockchain in order to be able to send\receive those custom tokens?


texts: Where can I find job listings for companies that use ethereum and are hiring developers that they'll need to train?

texts:
Ethereum is very interesting. I see its potential, but right now I cannot figure out what useful app/service I could implement on my own with my current very limited skills.

It almost reminds me of when 10 years ago I started to learn programming in C++. After a while, I learned how to program, but it was very difficult for me to find any useful applications for my skills.

So, maybe there are already companies which would like to hire some ethereum newbies, to build together great new services. I would like to know where I can find companies that 1) already use ethereum as a development platform and 2) are hiring people that they're willing to train.


texts:
I am trying to convert uint to string in solidity. Is it possible to convert? if so how can I convert it?

Convertion to base 10 is prefered, but in hexadecimal might also be helpful.


texts:
When I execute a python script to deploy smart contracts, it throws the following exceptions:
Traceback (most recent call last):
  File "contrCompDeploy.py", line 7, in <module>
    from web3 import Web3, HTTPProvider
  File "/home/fabric/.local/lib/python3.6/site-packages/web3/__init__.py", line 7, in <module>
    from eth_account import Account  # noqa: E402
  File "/home/fabric/.local/lib/python3.6/site-packages/eth_account/__init__.py", line 1, in <module>
    from eth_account.account import Account  # noqa: F401
  File "/home/fabric/.local/lib/python3.6/site-packages/eth_account/account.py", line 40, in <module>
    from eth_account.signing import (
  File "/home/fabric/.local/lib/python3.6/site-packages/eth_account/signing.py", line 9, in <module>
    from eth_account.transactions import (
  File "/home/fabric/.local/lib/python3.6/site-packages/eth_account/transactions.py", line 101, in <module>
    UnsignedTransaction = Transaction.exclude(['v', 'r', 's'])
AttributeError: type object 'Transaction' has no attribute 'exclude'

and the related python codes are:
import _pysha3
from web3 import Web3, HTTPProvider


texts: What is the best practice to store and retreive large data in solidity smart contracts?

texts:
Assume, I have an event creation page with some form fields in UI. And I have a smart contract to store the event in events mapping or the public array in some struct format.

struct event{
      bytes32 name;
      uint time;
}

event[] public events;

or

mapping(uint=>event) public events;

I'm submitting the UI and data is stored in the contract.

I have a list events page, which will display all the events created in the contract.

After searching many forums, I got some info, can someone validate this.

Approach 1:

For every submits or save in contract, an event is called and UI is having the watcher and stored in the local storage and displays in the UI. The events data can be a mapping or array here.

I don't want to have any intermediate storage for the application, so whenever the UI refresh the event watcher will receive all the state data and again update the local storage and display in the UI.

Approach 2:

For event submit new event object is created and pushed into the events array.

And writing the get events method, to iterate the events array and returns the list of string elements for each key in the object and then again concatenating and destructure the strings in an array of objects in UI to bind with the UI.

I think the computation for the second approach will be high because of the iteration. Since we are developing the Dapp I don't want to have any intermediate database again which become as a centralised system.

Can someone explain the various possibilities of storing and retrieving data from the smart contract which is a preferable way so far.

It will help me a lot. Thanks in advance.


texts: Proof of Stake - Let's get down to brass tacks and understand it

texts:
I have read six different articles now trying to understand this fully and completely and have been unable to get to that point.

I get that you are giving the validator/forger chosen with the privilege of forging the block the fees for that block. But what exactly is preventing them from including tx's that favour them?

I hear that you have to put up some stake/bet in Ether prior to forging, but how EXACTLY is this enforced? When do you lose your stake/bet? Who ensures it?

I have alot of questions here that just seem to be totally unanswered.


texts:
Following this answer, I'm running

$ geth --dev

to start a testnet, which works as expected, returning INFO [08-01|14:32:29] IPC endpoint opened: /Users/mcansado/Users/Desktop/private/datadir/geth.ipc
. When I run

$ geth --dev attach

from another console though, I get back

Fatal: Unable to attach to remote geth: dial unix /Users/mcansado/Library/Ethereum/geth.ipc: connect: no such file or directory

After googling, I found this issue here but the solution doesn't work either. I tried starting geth with

$ geth --datadir ~/Users/Desktop/private/datadir --dev

to go to a file I have in my desktop and then attaching with

$ geth attach --datadir ~/Users/Desktop/private/datadir or

$ geth attach --datadir ~/Users/Desktop/private/datadir/geth.ipc or

$ geth attach --datadir ~/Users/Desktop/private/datadir/geth.ipc or

$ geth attach ipc: ~/Users/Desktop/private/datadir/geth.ipc (as mentioned here)

For the last one, I just get Fatal: Unable to attach to remote geth: dial unix: missing address back.

Nothing works and I'm really running out of ideas. Could anyone please explain what I'm doing wrong?

EDIT: Just including the structure of the directory I'm passing in geth

├── geth
│   ├── LOCK
│   ├── chaindata
│   │   ├── 000027.ldb
│   │   ├── 000028.ldb
│   │   ├── 000031.ldb
│   │   ├── 000032.log
│   │   ├── CURRENT
│   │   ├── LOCK
│   │   ├── LOG
│   │   └── MANIFEST-000033
│   ├── lightchaindata
│   │   ├── 000002.ldb
│   │   ├── 000003.log
│   │   ├── CURRENT
│   │   ├── LOCK
│   │   ├── LOG
│   │   └── MANIFEST-000004
│   ├── nodekey
│   └── nodes
│       ├── 000006.log
│       ├── 000008.ldb
│       ├── CURRENT
│       ├── LOCK
│       ├── LOG
│       └── MANIFEST-000007
├── geth.ipc
├── history
└── keystore
    ├── UTC--2017-07-31T16-52-20.478037541Z--7ca3a0da3345506f15c603eba011c8f354155ee9
    ├── UTC--2017-07-31T18-17-31.814205896Z--f0a63da28af8a8aece135d8c5a268ffc261e2d36
    └── UTC--2017-07-31T21-46-55.452893142Z--1918ced27804f6b83acf0587a81e9f56020620d1

where there is clearly a geth.ipc file.


texts: Geth LES Client. Only synchronize the last 50 headers?

texts:
Using a LES client, is it possible to only synchronize only some of the last headers on first run ?

I am not interested in the chain history.

I understand the security implications of not validating the full chain, but I believe that getting, say, the last 50 continuous headers from 5 different LES server nodes is good enough to assume that the chain I got is valid.


texts: Likelihood of malicious nodes in a shard

texts:
in his post https://vitalik.ca/general/2021/04/07/sharding.html, V. Buterin said:
“Certainly, they can wait until they get lucky and get 51% in a single shard by random chance despite having less than 50% of the total stake, but this gets exponentially harder for attackers that have much less than 51%. If an attacker has less than ~30%, it's virtually impossible.“
Now I tried to calculate the exact likelihood of the event e that in at least one shard more than 50 % the shard’s nodes are malicious depending on:

the total number of nodes N,
the number of malicious nodes M,
the number of shards S.

The nodes are assigned randomly to each shard and each shard contains the same number of nodes.
I discussed this with colleagues, but we couldn’t find a solution, and I hope to find an answer here.
Our approach was to calculate the total number of all outcomes / number of e = likelihood.
But we got stuck with number of e.
Thank you


texts: How to get events result using web3 1.0.0 version

texts:
function depositToEscrow(bytes32 _id) public payable returns(uint) {
    DepositToEscrow(msg.sender,orderdata[_id].buyer,msg.value,orderdata[_id].amount);
}

suppose this is my function in a smart contract. How to get the result of the event "DepositToEscrow" using web3


texts: Parity: Is it possible to copy-paste/migrate Parity database into new node instead of syncing? Sync operation is very slow on 1 GiB RAM

texts:
I am using Amazon Web Services (AWS)'s 1 GiB RAM free instance. I have private Ethereum network, which has around 1,500,000 blocks, but most blocks are empty. There is not much transactions exist and chain is around 1 GiB size.

First I was syncing without using --warp flag. Based on suggestions, I used --warp and it get much much slower. Now it is almost 5 hours and I am still on 300,000 th block.

The way I run parity node:

parity --warp --geth --chain /home/ubuntu/EBloc/parity.json --network-id 23422 --reserved-peers /home/ubuntu/EBloc/myPrivateNetwork.txt --jsonrpc-apis web3,eth,net,parity,parity_accounts,traces,rpc,parity_set --author $COINBASE --rpccorsdomain=* --mode active --tracing off --pruning fast --db-compaction ssd --cache-size 1024

[Q] Why migh Parity sycn that slow? --warp did not make any speed-up instead it make syncing operation much slow.

[Q] I have up-to-date chain on my server machine. Would it be possible to copy-paste/migrate the Parity's chain database (/home/ubuntu/.local/share/io.parity.ethereum) I already have into AWS instance, since copy-paste operation is much faster than the syncing operation?

ubuntu@space:~/.local/share/io.parity.ethereum$ ls
chains  dapps  keys  network  signer

Thank you for your valuable time and help.


texts:
I am trying monitoring pending transactions using my local node. I mentioned that my app does not consume all pending transactions.
I compared transaction from my app with etherscan.com or dextools.io. Most amount of transactions were not consumed by my app.
I am using web3js lib with subscription on pending transactions. Also, I have geth as local node.
So, do I have some issues with my local node or it is expected behavior?
I tried to increase  txpool.globalslots parameter but it did not help me. I still have the same problem


texts:
How do I update my balance on a contract?

I created a function that receives an address as a parameter, I can visualize the balance:

address.balance.

But I want to transfer the balance to an account and update the value, but I can not do:

address.balance = + value;

What do I do?


texts: How to get signed transaction hash before mining? [Ethereum]

texts: Is it possible to get transaction hash before send transaction to node? How  transactionHash is calculated?


texts: Say that my wallet is connected to a malicious miner. Of course this miner can DoS me and ignore all my transactions, but can they withhold it and release it to the network in the future? Or is the transaction only valid for the current block ID?


texts:
I'm looking at the multisig wallet implementation here and I see the usage of sha3(msg.data,block.number) being used as an identifier.

What exactly is inside the msg.data and why is it unique enough to be used to make the identifier? Doesn't it only contain info on how the contract was called? Meaning will it be same if I call the contract with the same parameters?


texts:
I hava a function in a contract:

  function getLastBidding() public view returns (Bidding) {
    return biddings[biddings.length-1];
  }

The problem is when the biddings array is empty, it doesn't work, because I can't access index -1. So, I would like to return some sort of null when the array is empty. What can I return instead?


texts:
I really hope this is not a dumb question.

I am trying to call the constructors of the inherited contracts in a structure like this:

contract A{
    uint a;

    constructor (uint _a) public {
        a = _a;
    }
}

contract B is A{
    uint b;

    constructor (uint _a, uint _b) public{
        A(_a);
        b = _b;
    }
}

contract C is B{
    uint c;

    constructor(uint _a, uint _b, uint _c) public {
        B(_a, _b);
        c = _c;
    }
}

If I try to compile it in Remix I get the following error:

TypeError: Exactly one argument expected for explicit type conversion B(_a, _b);

Why can't I call the constructor of B with two variables?


texts: How to fix: Warning! Error encountered during contract execution [Out of gas]

texts:
I have sent ETH to a contract address, and it "failed" the transaction saying it is: Warning! Error encountered during contract execution [Reverted]
contract address and transaction failure here: https://etherscan.io/tx/0x0fba0c8e21a3c9f123fc8667a08cd4b1c495178285e9dbff9730b9e1918d455b
Even though I tried to set the gas higher, it still failed. Can someone help and explain, please?


texts: Transfer ERC20 Tokens from my wallet to another wallet

texts:
before I start just wanted to say that I started a few time ago with solidity and I'm still noob, but I've been reading and researching about this and can't get it working.

I'm using ethereum wallet with ropsten network.

Let's say I have X tokens from a standar ERC20 token already deployed, I know its contract address. I want to create a contract to transfer that to another account. I want to do this so in the future I could send to multiple accounts at once, but wanted to go step by step.

Should something like this work?

    pragma solidity ^0.4.18;

contract Token {
    function totalSupply() constant public returns (uint256 supply);
    function balanceOf(address _owner) constant public returns (uint256 balance);
    function transfer(address _to, uint256 _value) public returns (bool success) ;
    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) ;
    function approve(address _spender, uint256 _value) public returns (bool success) ;
    function allowance(address _owner, address _spender) constant public returns (uint256 remaining) ;
}

contract Envio{

    function Envio() public{
         Token miToken = Token(0x87458903eB3A37775A9CC097f80eb703D1cd0231); //Contract address
         uint8   decimals = 18;
         uint256   decimalFactor = 10 ** uint256(decimals);
        miToken.transfer(0xD49E71da9b64088BA1Ea1535c97f2985F9D3B1Bb,5000*decimalFactor);
    }
}

The result I'm getting after the transaction completes is: no tokens are transferred and it says gas used = 0. Also tried using transferFrom, same results.

I know that what I'm doing might be completely wrong, just looking for some guidance.


texts: Solidity Smart Contract not executing - Written in Remix

texts:
Ia m newbie to smart contract world. Not able to execute smal smart contract written in solidity within Ethereum remix dev environment. I am simply using get set to return name, but while I supply name input no output is getting returned. Below is code.

Environment is: Javascript VM

pragma solidity ^0.4.0;

contract myHWSC
{
    string private name;
    uint private age;

    function setName (string newName)
    {
        name=newName;
    }

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

}


texts: Sending ether from transaction to contract in Pyethereum using Solidity

texts:
I want to transfer some ethers from a user account to a contract account in Solidity. I tried using the following syntax:

contract_code = """
contract bug {
    function load_money() returns (uint32) {

       if(msg.value != 10) {
          return(0);
       }
    }
}
"""

# Create the contract
contract = s.abi_contract(contract_code, language='solidity')

# Transfer money
contract.load_money(value=5, sender=tester.k0)

I get a transaction failure when I try this. Any ideas why?

Thanks.


texts: Is there another purpose for ether besides buying gas?

texts:
Were ether coins invented only in order to buy gas? Or can I trade it too (like in bitcoin) ?

thank you


texts: How to know if the token is ERC20 or ERC233?

texts: as I stated on the title because I am very confuse on how to know if the token is ERC20 or ERC233. I bought Thore Cash on Mercatox and I didnt know if it is ERC20 or ERC233 but they said they supported the swap but i just want to make sure.


texts:
in the web3 version 1.x docs:
https://web3js.readthedocs.io/en/1.0/getting-started.html
it says to install web 3 using

> npm install web3

but this installs version 0.2x.00.

so what should I do?


texts: How do I set from address in embark tests

texts:
In my embark tests, I have the following tests:

it("should allow setting new beneficiary by owner to valid address", async function () {
        //await UTO.setBeneficiary(0x0, {from: owner}).should.be.rejectedWith(EVMInvalid);
        await UTO.setBeneficiary(owner, {from: customer});
        (await UTO.beneficiary()).should.deep.equal(owner);
     });

'customer' maps to a valid address. The contract is:

pragma solidity >=0.6.0 <0.7.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

contract UTO is ERC20, Ownable, Pausable {

    string private _name = "UnlimitedToken";
    string private _symbol = "UTO";

    uint256 public tokensPerEth;            //Number of tokens per ETH
    uint256 public tokenValue;              //Value of 1 Token (in ETH)
    uint256 public percentForBeneficiary;   //Percentage of tokens generated to be assigned to beneficiary
    address public beneficiary;             //The address of the beneficiary of the held tokens

    constructor(address _beneficiary, uint256 _tokensPerEth, uint256 _percentForBeneficiary) ERC20(_name, _symbol) public {
        tokensPerEth = _tokensPerEth;
        tokenValue = 1 wei;    //initial value, dynamic once contract is deployed
        beneficiary = _beneficiary;
        percentForBeneficiary = _percentForBeneficiary;
    }

    /**
     * @dev Allows the current owner to change the beneficiary.
     * @param newBeneficiary The address of the new beneficiary.
     */
    function setBeneficiary(address newBeneficiary) public onlyOwner {
        require(newBeneficiary != address(0), "Invalid address for beneficiary");
        beneficiary = newBeneficiary;
    }

}

So the function call to setBeneficiary should only be allowed to be called by the owner of the contraact. However, the from address is ignored and the test passes. I have replaced the from address with invalid data as well with the same result. So, it seems that setting {from: 0xaddress} is ignored.. any idea?

Thanks


texts: Custom difficulty consensus in a private network.

texts: Suppose in a private network setup , one node runs a standard geth client, and then we add another node to the network using a modified geth, where only the difficulty has been made static. Can this node be added successfully as a peer to the existing node in the network ? If yes , how will the consensus algorithm work if a differential difficulty exists in the network (I don't think its possible , but have doubts) . If no , what are the exact reasons for such a set up not working ?


texts: How do I transfer balance to another address? w/o syncing with network

texts: I have a single ethereum address that has ether in it from 2015 when I was playing around with Geth and the CLI. I have removed the blockchain and associated homebrew files from my computer. How can I transfer that balance from that ether account into something else? Is there a way to do it without syncing with the network? Could I just somehow import the address into a wallet like Jaxx? Thanks for the help.


texts: What logic controls Proof of Stake voting?

texts:
NOTICE: This question is now outdated; it refers to one of the older plans for the Casper Proof of Stake validation concept (including validators voting on multiple heights at once). The updated (hybrid Proof-of-Stake and Proof-of-Work) model can be seen detailed here

I understand from the Casper Proof of Stake FAQ that the roadmap for Ethereum is to implement a BFT-style (Byzantine Fault Tolerant) Proof of Stake block-creation scheme, where all users who have a stake can vote on individual block proposals to help them become finalized.

For Proof of Work, it's very clear what blocks should be "voted" upon by honest peers (ones whose hash is below the difficulty threshold, and whose timestamp is less than any other block that also meets the difficulty threshold). But how does that work for Proof of Stake; what criteria should honest peers/miners/stake-holders use to vote for blocks?

It seems to me if anyone with a stake can create a new proposed block, won't they all craft a block that grabs the highest gas-paying transactions out of the mempool and create a coinbase that pays it all to themselves? What incentive is there for stake-holders to vote for someone else's block (giving the coinbase to someone else) rather than for their own?

If those with a larger portion of coins get a larger vote, won't they be able to just outvote everyone else so their blocks (which pay themselves) get finalized more frequently, and lead to an ever-increasing split in wealth (the wealthy get more wealthy faster than those with less)?


texts: How to access test accounts created by TestRPC from a Solidity test with Truffle?

texts:
With Javascript tests, it is possible to access the accounts which TestRPC creates using:

contract('MetaCoin', function(accounts) {
   // tests here can access accounts[n] to get the public keys
}

But how can I use those addresses from a test written in Solidity?


texts: How can I call contract's function from the Jaxx wallet?

texts:
As I know, at this date there is no Ethereum's light wallets, which supports contracts. But in Jaxx wallet, it's possible to send some Custom Data to the contract.

So, the question is: if I have a simple contact like greeter (source), how can I call greet function from the Jaxx?


texts: How do I find my DBET tokens in MyEtherWallet?

texts: I mistakenly bought DBET tokens directly from my Exodus wallet. I used the public key of Decent.bet (DBET). I assume I should be able to find/see my DBET tokens in MyEtherWallet, but I do not know which steps to take. Hopefully, someone in here can clarify this for me.


texts: How does cryptokitties work with smart contracts and is there a random element to it?

texts:
I'm totally new to cryptokitties, but my understanding of cryptokitties so far is:

It's a smart contract that generates new kitties according to your ethereum address.

My questions are:

If you are breeding kitties, how does it handle randomness to "breed" different attributes of kitties?
Can we see how the kitties smart contract is made?
Can the crypto kitties website run as a standalone app (dapp) to interact with the ethereum blockchain?


texts:
Cannot compile the "contract Auction". Got this error for Miscellaneous methods.

//Miscellaneous methods: Below methods are used to assist Grading. Please DONOT CHANGE THEM
function getPersonDetails(uint id) public constant returns(uint,uint,address){
    return (bidders[id].remainingTokens,bidders[id].personId,bidders[id].addr);
}

https://i.stack.imgur.com/igtp1.png

EDIT

Complete code:

pragma solidity ^0.4.17;

contract Auction {
    // Data
    //Structure to hold details of the item
    struct Item {
        uint itemId;          // id of the item
        uint[] itemTokens;    //tokens bid in favor of the item
    }

    //Structure to hold the details of a persons
    struct Person {
        uint remainingTokens; //tokens remaining with bidder
        uint personId;        //it serves as tokenId as well
        address addr;         //address of the bidder
    }

    mapping(address => Person) tokenDetails; //address to person
    Person [4] bidders;//Array containing 4 person objects

    Item [3] public items;       //Array containing 3 item objects
    address[3] public winners;   //Array for address of winners
    address public beneficiary;  //owner of the smart contract
    uint bidderCount=0;          //counter

    //functions
    function Auction() public payable{                     //constructor
        beneficiary = msg.sender;                          //Part 1 Task 1 – 1 line
        uint[] memory emptyArray;
        items[0] = Item({itemId:0,itemTokens:emptyArray});
        items[1] = Item({itemId:1,itemTokens:emptyArray}); //Part 1 Task 2 – line 1
        items[2] = Item({itemId:2,itemTokens:emptyArray}); //Part 1 Task 2 – line 2
    }

    function register() public payable{
        bidders[bidderCount].personId = bidderCount;
        bidders[bidderCount].addr = addr;                  //Part 1 Task 3 – 1 line
        bidders[bidderCount].remainingTokens = 5;          // only 5 tokens
        tokenDetails[msg.sender]=bidders[bidderCount];
        bidderCount++;
    }

    function bid(uint _itemId, uint _count) public payable{
        if (tokenDetails[msg.sender].remainingTokens < _count) return; //Part 1 Task 4 – line 1
        if (_itemId > 2) return;                                       //Part 1 Task 4 – line 2
        (tokenDetails[msg.sender].remainingTokens - _count);           //Part 1 Task 5 – 1 line
        bidders[tokenDetails[msg.sender].personId].remainingTokens= tokenDetails[msg.sender].remainingTokens; //updating the same balance in bidders map.
        Item storage bidItem = items[_itemId];
        for(uint i=0; i<_count;i++) {
            bidItem.itemTokens.push(tokenDetails[msg.sender].personId);
        }
    }

    function revealWinners() public {
         for (uint id = 0; id < 3; id++) {
             Item storage currentItem=items[id];
             If (currentItem.itemTokens.length != 0);
                 uint randomIndex = (block.number / currentItem.itemTokens.length)% currentItem.itemTokens.length;
                 uint winnerId = currentItem.itemTokens[randomIndex];
                 return winnerId;                                      //Part 1 Task 6 – 1 line
            }
        }
    }

    //Miscellaneous methods: Below methods are used to assist Grading. Please DONOT CHANGE THEM
    function getPersonDetails(uint id) public constant returns(uint,uint,address){
      return (bidders[id].remainingTokens,bidders[id].personId,bidders[id].addr);
    }
}


texts:
Currently, Ethereum developers are developing Casper Algorithm for Ethereum 2.0.
According to their proposal, some validator are chosen randomly but validators has permanently authority to verify transactions as long as they do not put down their validator's authority.

There are some other strange points and I would like to ask about them.

How many period they has the qualification that can verify some transactions and earn reward?
Assume that validators are chosen totally 1000 people, how they divide the reward for verification transaction which is in checkpoint block? for example, assume block reward is 3ETH so, Can each person earn the reward 3ETH/1000?
The time that validator do work is checkpoint time, generated in every 100 blocks. I THINK THIS IS CONTRADICTION because current Casper algorithm is based on PoW, which takes Nakamoto consensus. Each miner in the world can't synchronize their chain(ledger database) due to Nakamoto Consensus but how validators can verify in checkpoint? at that time, it absolutely cannot convinced that each miner has checkpoint. for example, some miner's block height is 189, some miner's block height is 195 due to async network. It can't convinced that all miners have 200 of block height. How think about it?

Sorry for my English.


texts: Has an exchange ever voted with a users tokens?

texts:
If a token allows tokenholders to vote on some issue/proposal/action or whatever, it is conceivable that a token-exchange that holds its customers' tokens could covertly, or perhaps openly, vote on their behalf.  It seems unlikely to me that an exchange would ever do this, risking their reputation, and I'm skeptical it could be done covertly.  However, vitalik recently warned about this issue (4 months ago at the time of this question) on reddit, quoted below:

  [tokens with voting] have the following problems: .... situations like everyone putting their coins on exchanges and exchanges voting on users' behalf, with users not really caring how exchanges vote with their money, are likely to happen.

My main objection is that the exchange's token holding contract would need a special function to call the voting function of any tokens that had a voting function.  Their token holding contract would need a generic function that could execute arbitrary function calls.  Wouldn't this raise a lot of red flags?


texts:
Can you tell me what this piece of solidity code means please?
uint number = uint(block.blockhash(block.number - 1)) % 37;
Thank you
Take care
Pierre


texts: Is there a dynamic pruning in geth --fast?

texts: Once i've downloaded the blockchain with geth --fast , is there a dynamic pruning on the up-comings blocks, or will I archive all the blocks from where I stand?


texts: How did the "state clearing" transactions run Out of Gas?

texts:
"Failing to revert empty account deletions when the transaction causing the deletions of empty accounts ended with an out-of-gas exception" caused issues with consensus on November 24 2016.

Usually, a transaction provides a comfortable cushion of gas so that it doesn't reach an out-of-gas exception.  For example, if one thinks their transaction might consume 500K gas, specifying 1M gas for it seems reasonable since all unused gas will be refunded.

Testing a transaction for Out of Gas (OOG) must also have been performed (because transactions either complete or OOG), so what are the details?

How did the "state clearing" transactions run OOG?
Were there several primary ways that they ran OOG?  If so, how can they be classified so that the community keeps them in mind for their own testing?


texts: what does that 'No state variables' restriction in Libraries?

texts:
I read some about Libraries restriction that 'No state variables'

but, some solidity code's Libraries have struct type.

As far as I know that(may be wrong) struct type is 'storage' and 'state variables' are values which are permanently stored in contract 'storage'.

so, struct type is 'state variable'?

I'm confused.


texts: How do i see my records stored in the ethereum blockchain

texts:
So I have a smart contract, in my code, I have an array and i am pushing to it using a particular method call addToUser, from the code below
Contract Example{
string[] users;
function addToUser(_user) public {
users.push(_user);
}
}
from my understanding when I call the addToUser method above and I push records to it. users is stored in the contract storage(which I am thinking of, as a database). my confusion is, how do I see all the users. like how do I access the database to see all the records and what happens when I redeploy the contract?


texts:
Why do some ethereum related websites (for example regis.nu, there are many others) tell me they cannot find a node running at http://localhost:8545 and what can I do about that?

Regis.nu allowed me to create a "light-wallet" and then I had to put some ether in there, but I didn't really want to do that. I wanted to use my own wallet. I tried starting 'geth' but now I'm going into deep water and I can't swim.

So question: How can I start a node at http://localhost:8545?


texts: How to call a state changing function with web3.js (browser) and remote node?

texts:
Solidity Contract:

contract MyContract {
    bytes32 public product;
    uint public amount;

    function setOrder(bytes32 _product, uint _reorderAmount,) public returns (bool success);
}

Javascript web3js (without node.js):

<script src="./web3.min.js"></script>
<script>
web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/key"));
web3.eth.defaultAccount = "0x...address of my account...";
var myContract = web3.eth.contract([...abi...]);
var contractInstance = myContract.at('0x...contract address...');
contractInstance.setOrder(web3.toHex('ProductName'),3000);
</script>

This works when I have ganache-cli running, but not on a testnet (e.g. Ropsten). On a testnet I can only getter functions, but how do I call a setter function? What am I missing here?


texts:
I saw the following : what does `deploy.link` exactly do in `truffle`
I have safe.sol
library safe {

    function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        } else {
            uint256 c = a * b;
            assert(c / a == b);
            return c;
        }
    }

}

In my contract, I have this:
import "../libraries/safe.sol";

contract TokenSale {

  function test() public view returns (uint256){

        return safe.safeMultiply(5, 10);

    }

}

Now, when deploying contract, I just have deployer.deploy(myContract) , It deploys the contract successfully and , test function works as expected. There was no need to use deployer.link from truffle.
So , why does the stackoverflow question above I linked or even truffle's website explain like this that deployer.link is needed to make this work ?


texts:
Currently I'm using 1 r9 380 card with 20 MH. I've only been mining for 3 days straight (72hours). I used the Mining Calculators from Etherscan and Cryptocompare. While these sites calculate it will take me approximately 1 month to solve a block for  5 Ether on this single card, with the exponential rate of difficulty increasing is it futile to mine solo? Should I just jump into the adult swim (mining pool) for at minimum some payout  in finney? Or should I expect some finney payout in my 20 mh solo mining efforts at least once a week if not daily?

Basically I'll never see a single amount in my wallet , not even a penny ('finney') because the pools collectively out pace a 20 mh card (or even a 45mh rate for that matter if I added crossfire).

To answer my question please also include the 'reward' process for solo mining. These calculators are not descriptive enough and I have yet to find a Q&A to this delimma.


texts: From an account's address is it possible to tell whether the account is a contract account or externally owned contract?

texts:
I am trying to visualise transactions for Ethereum, currently, I know there are blockchain explorers such as Etherscan.io and Etherchain.org, however I don't want to keep calling their API to get data, rather use my own full node to get all the data I require since it give me greater control.

So I set up a full node and use the Web3JS library to get blocks and transactions. However, the Web3JS doesn't have the option to get an account via given address (unless I am mistaken). So, once I have the transaction object, I can figure out who the sender and receiver are, but I also want to know whether the sender or receiver is a contract or an account. I know on etherchain's API we can get accounts using the address, is it possible to do the same using geth and Web3Js?

Ethereum's yellow paper mentions that each account has a nonce, balance, storageHash and codeHash, so I thought it would be possible to get an account using addresses from the blockchain. Please help we figure out how to determine whether a given address is a contract or an account, without using blockchain explorers mentioned above?


texts: Is it impossible to empty an Ethereum wallet?

texts:
When you send a transaction, you specify a gas price and gas limit. If it doesn't use the entire gas limit, then you get some of the money back. So it would seem to be impossible to know beforehand what the total used gas will be, leaving spare change in every wallet.

I tried to empty my MetaMask wallet. I looked up a reasonable gas price on https://ethgasstation.info/ (7). I entered the total balance to send, MetaMask of course said 'not enough balance' due to the fee. I changed the gas price to 7, copied the maximum fee, rejected the transaction, entered a new transaction with the amount equal to (total balance - maximum fee), and again changed the gas price to 7. After it was sent (a few hours), I was left with $0.09 in my MetaMask wallet! Even though I tried to carefully calculate the exact amount, it seems like would be impossible to empty a wallet.

MetaMask help says MyEtherWallet has a 'send max' feature, but how would that work?

https://support.metamask.io/kb/article/14-sending-max-balance

  An easy way to send your full balance in the meanwhile is to export your MetaMask account to MyEtherWallet, which has a "send max" feature, and send to the exchange from there.

Isn't it true that you cannot know the actual gas used ahead of time? If you try to calculate the gas limit exactly, then you risk that it uses up all your gas and your transaction still fails! (I've had that happen before.)


texts: Are liquidity pools the decentralized exchange equivalent of storing assets on centralized exchanges?

texts:
We'd think that decentralized exchanges are just the same as centralized exchanges in terms of functional purposes which are

trading
storing crypto assets

However, the second item is not readily apparent on decentralized exchanges. Uniswap, for example, doesn't act as custodian of your crypto to just hold it there on the Uniswap exchange. Or does it?
All I could think is that the decentralized equivalent of storing assets on centralized exchanges are the liquidity pools made by decentralized exchange participants. Is this the correct analogy to explain how the second item is represented in DeFi?
If so, how to properly cement the analogy, given that liquidity pools are in many ways a cloud representation of many participants' holdings floating in thin air, in many ways very abstract and loosely defined. The concept still doesn't square up with the metaphysical act of storing holdings as would be done on centralized exchanges


texts:
Can somebody explain what are the fixed and ufixed data types in Solidity. Can you give me some examples?

I expected that these are the representations of decimal numbers, but this is not a case?

Thank you for your answers!


texts: Smart contracts and blocks in the blockchain

texts:
I am trying to understand how smart contracts interact with each other and the blockchain.
So, let's say that I have a smart contract SC1 which asks a node A in my peer to peer network to send some information to another node B. When B receives the request it will run another smart contract SC2 to generate some data to publish on the blockchain. Now the two Smart Contracts depend on each other so does it mean they will always be mined in two different blocks?


texts: Is it possible to have a struct within an Event?

texts:
I have something like this in solidity:

struct Bid {
   ...
}
event BidEvent(Bid bid)

but when I try to read this event in Javascript, there's no data inside that I can access — no bid variable, none of the things inside it, nothing at all really.

Does this mean structs can't be put inside events?


texts:
Is there a way to stop the Geth console from printing syncing information?

I start Geth with geth console.

Actually, I do not want to see all that syncing information constantly. Can I turn it off somehow without using geth attach?


texts: Issue in comparing token contract address and address(0) in Solidity 0.5.0

texts:
I am trying to compare the token contract address with the address(0). This was working fine in older version of truffle and solidity compiler (0.4.24). When I upgraded truffle and started using the latest truffle and compiler version (0.5.0) I am unable to compare the token contract address and address(0).

Could you please assist me to resolve this ?


texts: I installed ethereum miner and I wonder how to transfer from ballance

texts:
I seem to have 40 ether in my wallet in Alethzero frontier. how do I transfer this to my ethereum wallet?

when I click transaction I can only submit contracts...

However , Are my Ether legitimate mined as they might be mined before I synced and properly installed my geth.


texts: Use smartcontract's ENUM in test scenarios in truffle

texts:
I have create a truffle project with this command:
truffle unbox react

Here is my smartcontract contracts/SimpleStorage.sol :
contract SimpleStorage {

   enum MyEnum {
      step1,
      step2,
      step3,
      step4
   }

   MyEnum private var1 = MyEnum.step3;

   function myfunction() external view returns (MyEnum) {
      return var1;
   }
}

Here is my test file: test/simplestorage.js
const SimpleStorage = artifacts.require("./SimpleStorage.sol");

contract("SimpleStorage", accounts => {

  it("my test", async () => {
    const simpleStorageInstance = await SimpleStorage.deployed();

    const ret = await simpleStorageInstance.myfunction();
    assert.equal(ret, 2);
  });

});

My question is: Is there a way to access to Enum Structure in the test file.
I would like to write something like that:
assert.equal(ret, MyEnum.step3);

Thanks


texts:
I'm using web3.jp 1.0

How to connect (log in) my existing account (for example, created through myetherwallet) to make a transaction or call contract?

As I understand it, the list of accounts is provided by the RPC node, because when using testerpc in the Web3.eth.accounts, test accounts were available, but new ones were not added.

const Web3 = require('web3');
console.log(web3.eth.getAccounts()) // []

thank you!


texts: should I stop geth for copying /chaindata to another machine?

texts:
Since I've made stats from geth full node by calling rpc api, it is burdensome for me to stop geth a few hours.

Nowadays my local machine uses about 95% disk, so I want to migrate my /chaindata to another machine.

But after I copied original /chaindata to another machine while running original geth, running new full geth on another machine failed with error message.

Fatal: Error starting protocol stack: gap (#8952595) in the chain between ancients and leveldb

What I have to do?
Should I have to stop geth and copy /chaindata?


texts:
everything is in the title :

are the ERC721 smart contracts compatible with Zk-SNARKs?

since Zk-SNARKs is being used "grosso modo" to make transactions "private", can we use it with the ERC721 type of smart contracts to create a non fungible private transactions/token? or should we wait until the erc721 get normalized and Zk-SNARKs gets implemented?

My understanding is that current token contracts do not make use of zkSNARKs to hide balances or sender/receiver information. Contracts wishing to do so need to have zkSNARKs functionality explicitly coded into them for them to hide things.

Right now zkSNARKs code is not easy to write, nor is it easy for users to interact with. It is also very expensive. I think these are the reasons why it is currently possible, but not done, at the moment.

Can someone confirm all this?


texts: Function consumes all gas using TestRPC, but is fine in JS VM

texts:
So here's the function that's causing trouble:

function init() {
    require(! isInitialized);
    isInitialized = true;

    bytes32[] storage votableGroups;
    bytes32 fullTimeHash = keccak256('full_time');
    votableGroups.push(fullTimeHash);

    //Initialize voting types
    votingTypeList.push(VotingType({
        name: "Default",
        description: "For initializing",
        quorumPercent: 100,
        minForPercent: 100,
        activeTimeInBlocks: 25,
        goodRepWeight: 1,
        badRepWeight: 1,
        votableGroups: votableGroups
    }));
    votingTypeList[votingTypeList.length - 1].isEligible[fullTimeHash] = true;
}

It always consumes all gas when I'm testing it using Truffle and TestRPC, but it works just fine when I'm using the JavaScript VM in Remix. The function runs fine when I commented out the last two statements.

I can't see anything wrong with my code, so is this caused by a bug in TestRPC?


texts: Will ᴇɪᴘ86 be implemented for Constantinople?

texts: ᴇɪᴘ86 is said to be implemented on Metropolis hard fork. Does it means it will be implemented in the Constantinople hard fork planned next October ?


texts: Given only a raw transaction, how can I determine the from address that signed it?


texts: Retrieve data from smart contract using sendTransaction

texts:
Lets take a very basic smart contract that has one function in which you send a number and it will return the square. It has another function that returns a fixed string.

contract MyContract {
  uint public version;
  address public previousPublishedVersion;

  function ping() returns (string param){
    param = "pong";
  }

  function squareNumber(uint num) returns (uint256 numSqr) {
    numSqr = (num * num);
  }
}

Now to deploy the contract I use

myContract.new({
  data: MyContract.compiled_code,
  gas: gasNeeded * ethConfig.gas_factor,
  from: ethConfig.primary_address
}, (err, myContract) => {
    if(!err) {
     if(!myContract.address) {
         console.log('contract trasnaction hash ' + myContract.transactionHash)
     } else {
        console.log('contract address ' + myContract.address)
        resolve({
         primary_address: ethConfig.primary_address,
         contract_address: myContract.address,
         gas_estimate: gasNeeded
        })
     }
  } else {
    reject(err)
  }
});

This fires two callbacks, one with the transaction hash and one with the address once its mined. However this method is not there for sendTransaction. I have read that using getTransactionReceipt or checking block numbers is a good way to check whether the transaction has been mined or not.

  myContract.ping.call(null, (err, data) => {
    if (err) {
      reject(err)
    } else {
      resolve({
        primary_address: ethConfig.primary_address,
        returnValue: data
      })
    }
  })

But for squaring the number I use

  myContract.squareNumber.estimateGas(10, (err, gasNeeded) => {
    if (err) reject(err)
    myContract.squareNumber.sendTransaction(
      10,
      {
        gas: gasNeeded * config.ethConfig.gas_factor,
        from: config.ethConfig.primary_address
      }, (err, data) => {
      if (err) reject(err)
      resolve({
        primary_address: config.ethConfig.primary_address,
        numSquare : data
      })
    })
  })

Now for a call function, I can get the data directly without any mining to be done, however the docs say that the value returned from sendTransaction() is the hash of it, and then we are to use getTransactionReceipt() to actually confirm when the block was mined.

My question is simply this, how exactly do I structure my web3js code, to get the value returned (10*10) from the solidity function squareNumber().

I have wrapped all APIs shown above in promises but just skipped that part as its long and not related to web3js in any way.


texts: Should I include all public and view functions under contract ERC20Interface?

texts: Should I include all public and view functions under  contract ERC20Interface, why or why not ?


texts: Where is the geth.exe in the Ethereum mist?

texts:
I'm running Ethereum Mist on Windows 7. Mist Version is 0.8.6.

I can't find the geth.exe in the Mist github.

https://github.com/ethereum/mist

In the version 0.8.2, the geth path was "mist\nodes\geth\win32-x64\geth.exe".

Anyone help me.


texts: Does go-ethereum encrypt new wallets by default?

texts:
And if so, is it considered safe to store and encrypted wallet on a unencrypted drive?

I know there is a process to lock and unlock accounts with a password, but how difficult is it to brute force the unlocking process?


texts: How much C++ is needed to write smart contracts?

texts: Solidity seems to be written in C++ so does that mean that smart contracts require some level of C++ programming skills to get by? How much background knowledge is required for writing a simple one or two-condition contract compared to tokenizing stocks?


texts: web3 error - web3.eth.Contract is not a constructor

texts:
i try to get the contract balance and im using this

var Web3 = require('web3')
var web3 = new Web3('ropsten.infura.io/v3/123456789')
var abi = abi is here ;

var contractAddress = '0x31111.....';
var contract = new web3.eth.Contract(abi, contractAddress);
//var address = '0x31111......';

web3.eth.getBalance(contract.address, function (e, r) {
   $('contractBalanceAgi').text(convertWeiToEth(r).toFixed(4))
 })

and when running this i get following error in my console
 web3.eth.Contract is not a constructor

when i googled for it some said its because of the new web3 js version
but the new web3 version requires this
var contract = new web3.eth.Contract(abi, contractAddress)
new and capital C


texts: How to fill section "Read Smart Contract" on Etherscan without publishing source code?

texts:
I see a lot of tokens (like GNO or QRL) has tab "Read Smart Contract" tab populated with standard ERC20 tokens members and functions but in the same time haven't "Contract Source" tab. I'd like to have the same for my token but cannot find how to do it.

I know how to verify source and it actually make tab "Read Smart Contract" filled but how to avoid publishing of my contract source code?


texts: Can we use openzeppelin library to make contracts upgrade-able in ETC test net?

texts:
I am trying to develop smart contracts to run in the ETC test-net. Beforehand, I am doing some background research and need to know if openzeppelin library is compatible to make things work in ETC  as well.
What solidity version is compatible in the ETC network and is it possible to use openzeppelin to make contracts upgrade-able?


texts: Sending Signed Transaction returns pending and event:undefined

texts:
I am trying to send a signed transaction using web3 1.0 and Infura.io through the browser. When I run it I dont get any errors but the transaction never hits the blockchain so I am confused on whats happening.

*See the log below to see the details

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>
<script src="https://cdn.rawgit.com/ethereumjs/browser-builds/2fb69a714afe092b06645286f14b94f41e5c062c/dist/ethereumjs-tx.js"></script>

Here is the script -

var web3 = new Web3();

if(web3.setProvider(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/API KEY'))){
web3.eth.net.isListening();
}

// Get Contract ABI
var abi = JSON.parse('MY ABI')

// Define Variable for Contract ABI
var AK = new web3.eth.Contract(abi);

// Set Contract Address
AK.options.address = "CONTRACT ADDRESS";

// Set amount
var amountToSend = 100;
var weiAmount = amountToSend * 1e18;

// create transaction - to address, amount
var data = AK.methods.transfer("SEND TO ADDRESS", weiAmount).encodeABI();

// object to hold the transaction data From Address
web3.eth.getTransactionCount("SEND FROM ADDRESS").then(count => {

// Set transaction params

let privateKey = new EthJS.Buffer.Buffer("FROM ADDRESS PRIVATE KEY", "hex")

web3.eth.getGasPrice().then(gasPrice => {

let txParams = {

nonce: web3.utils.toHex(count),

gasLimit: web3.utils.toHex(250000),

value: web3.utils.toHex(0),

gas: web3.utils.toHex(1000000),

gasPrice: web3.utils.toHex(web3.eth.gasPrice),

to: "TO ADDRESS",

from: "FROM ADDRESS",

data: data

}

// Sign Transaction
let tx = new EthJS.Tx(txParams)

tx.sign(privateKey)

let serializedTx = tx.serialize().toString('hex')

var receipt = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));

console.log('serializedTx:', serializedTx)
console.log('Receipt:', receipt)

});
});

When i run the script it logs -

Promise {<pending>, _events: undefined, emit: ƒ, on: ƒ, once: ƒ, off: ƒ, …}
addListener: ƒ (t,e,r)
emit: ƒ (t,e,r,i,o,a)
listeners: ƒ (t,e)
off: ƒ (t,e,r,i)
on: ƒ (t,e,r)
once: ƒ (t,e,r)
removeAllListeners: ƒ (t)
removeListener: ƒ (t,e,r,i)
_events: undefined
__proto__: Promise
[[PromiseStatus]]: "pending"
[[PromiseValue]]: undefined


texts: Error: failed to unlock developer account on using list

texts:
I am following this video from youtube to learn about blockchain.
I am getting error while trying to list the account using command "geth -datadir /media/privatechain -dev account list". But i got error.
Below i have pasted the executed command and output :
(base) aaa@aaa:/media/Osiris geth -datadir /media/privatechain  -dev account new
INFO [09-08|11:48:54.876] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-08|11:48:54.876] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:

Your new key was generated

Public address of the key:   0xFd0850dfd36728B652f5352a560044C3bbC944a7
Path of the secret key file:/media/privatechain/keystore/UTC--2020-09-08T09-49-25.404829295Z--fd0850dfd36728b652f5352a560044c3bbc944a7

- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it's impossible to access account funds!
- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!

(base) aaa@aaa:/media/Osiris$ geth -datadir /media/privatechain -dev account list
INFO [09-08|11:50:28.645] Maximum peer count                       ETH=50 LES=0 total=50
INFO [09-08|11:50:28.645] Smartcard socket not found, disabling    err="stat /run/pcscd/pcscd.comm: no such file or directory"
INFO [09-08|11:50:28.649] Set global gas cap                       cap=25000000
Fatal: Failed to unlock developer account: could not decrypt key with given password

Can someone guide on whats wrong here?


texts: Ethereum client build that only listens to new transaction and blocks

texts:
I want to configure Ethereum client to only maintain a transaction pool:

Receive incoming transactions
Receive incoming blocks

I want a minimal functionality: I don't need to validate blocks, I don't care about the state or synching with the chain and waiting for it to catch up.
What is the easiest way to achieve this?
I can modify existing client if needed (e.g. Go Ethereum), but I'm not sure if nodes in the network will ban my node because they expect some of the functionality that was disabled.
I didn't find a way to achieve this via configuration files of some of the popular clients.


texts: "SSO-style" Login into app with web3.eth.accounts[0]

texts:
On top of the data exchanged through the Ethereum network, my app stores some extra user data in a classic DB (E.g. thumbnails, display preferences, newsletter management etc.).

Doing that has led me to use a double account system: an Ethereum account—I get it from web3.eth.accounts[0]—and a classic login/PW account. While you can make all sort of links between the two, it still requires to type 2 different PW and manage two accounts.

So I wonder if it is possible to login into the app using just the Ethereum PW (in Mist, MetaMask etc.):

Is safe to login into a classic account with just the web3.eth.accounts[0] and no PW?
Is it possible to ask for the user permission (like the "accept" prompt with Metamask) but without mining a transaction (too long for a login)?
Is there another way to enable single-click login?

The use case is a Meteor app used with MetaMask, but I guess it's a more general question.


texts:
I am not too understanding this equation. Do any one know it? Especially what is m stand for since I cannot get it from the paper.

Thanks


texts: What percentage of total Ether was held by TheDAO?

texts: Recent news of someone stealing from TheDAO suggest that it had a lot of Ether. How much of the total amount of Ether did it control?


texts: What do I do about my Ether since the 2019 Constantinople upgrade has been postponed?

texts: With the last minute postponement of the 2019 Constantinople upgrade. What do I do about my stored Ether? And what software do I need to upgrade to if I am running Geth or Parity?


texts: Event cannot trigger when the transaction is done

texts:
My contract location is here

pragma solidity ^0.4.18;

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() view public returns (string, uint) {
       return (fName, age);
   }

}

MY JS script

window.addEventListener('load', function() {
    if (typeof web3 !== 'undefined') {
        console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
        window.web3 = new Web3(web3.currentProvider);
    } else {
        //console.log('No Web3 Detected... using HTTP Provider')
        window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
        //TO-DO
        //Pop Up Model And Ask User download MetaMask
        console.log('No web3? You should consider trying MetaMask!');
    }
    startApp();
});

function startApp() {
    var CoursetroContract = web3.eth.contract(
        [{ "constant": false, "inputs": [{ "name": "_fName", "type": "string" }, { "name": "_age", "type": "uint256" }], "name": "setInstructor", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "getInstructor", "outputs": [{ "name": "", "type": "string" }, { "name": "", "type": "uint256" }], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [{ "indexed": false, "name": "name", "type": "string" }, { "indexed": false, "name": "age", "type": "uint256" }], "name": "Instructor", "type": "event" }]
    );

    var Coursetro = CoursetroContract.at('0x96d2a2978d52287c2DffF0e2A40D12181223303C');

    var instructorEvent = Coursetro.Instructor({ fromBlock: 0, toBlock: 'latest' });

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

    $("#button").click(function() {
        $("#loader").show();
        Coursetro.setInstructor($("#name").val(), $("#age").val(), function(error, result) {
            if (!error) {

            } else
                console.log(error);
        });
    });
}

When I click the button to call setInstructor function and then the transaction is done, the Event is not triggered. Please Help.


texts: Serpent Vulnerabilities, Migrate to Solidity?

texts:
With recent high profile bugs discovered in the core Serpent Language, would it be wise to henceforth make Solidity the deFacto Dapp Language?

https://medium.com/@AugurProject/serpent-compiler-vulnerability-rep-solidity-migration-5d91e4ae90dd


texts:
I have a directed multigraph of courts "trusting" each other:

    struct TrustedCourt {
        uint256 courtId;
        mapping (uint256 => uint256) limits; // intercourt token => amount
    }

    // truster => trustee
    mapping (uint256 => TrustedCourt[]) internal trustedCourts;

I used a mapping in the struct because I want checking the limit for a given intercourt token to be efficient.

Now it would be desirable to be able also to enumerate all "intercourt tokens" for a given truster and trustee.

We know that Solidity mapping does not support enumeration.

What is the best solution of this problem?

Keep the list of all such intercourt tokens in an additional array struct field?
"Outsource" a solution of this problem to external means like to another contract that would control my contract? (Note that in many cases it would be not necessary to keep a list of such tokens for a particular external controlling contract, so we would implement it only sometimes, when necessary, so saving gas.)
Don't solve it inside the blockchain at all, but allow external software to enumerate such tokens?


texts: How to determine if a block is on minority fork from geth console?

texts: So right now my current blocknumber is 600,000+ , Is there anyway to check if a particular block number is on the forked chain ?


texts:
So I have this setup : truffle and ganache-cli

I'm sending some ether to my contract, here is the related part of my contract:

    mapping(address => uint256) public balanceOf;

    function () payable public {
              uint amount = msg.value;
              balanceOf[msg.sender] += amount;
        }

In truffle this is how I send the ether.

it("Test if can be payed", function(){
    return web3.eth.sendTransaction({
           from:fromAddr,
           to:MyContract.address,
           value:amountToSend
    }).then(function(res){
           expect(res).to.not.be.an("error"); // test passed
    });
 });

it("Test if contract received ether", function(){
        return web3.eth.getBalance(MyContract.address,
               function(err, res){
                        expect(parseInt(res)).to.be.at.least(1000000000000000000); // test passed
                });
});

it("Catch if balanceOf "+fromAddr, function(){
        return sale.balanceOf.call(fromAddr).then(function(res){
                        expect(parseInt(res)).to.be.at.least(1); // fails the test
               });
});

Am I doing it right? What could be the reason for failed test?
truffle test output :

AssertionError: expected 0 to be at least 1
      + expected - actual

      -0
      +1

I can provide more info if needed.


texts:
Preconditions

I'm running a private network with Geth, having custom smart contracts deployed by Truffle and a simple frontend which using Metamask as a provider to connect the network.

Versions

Geth: 1.8.12-stable
Truffle: v4.1.13 (core: 4.1.13)
Solidity: v0.4.24 (solc-js)

Genesis Block

{
    "config": {
        "chainId": 331788,
        "homesteadBlock": 0,
        "eip155Block": 331788,
        "eip158Block": 0
    },
    "nonce": "0x0000000000000000",
    "timestamp": "0x00",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "0x00",
    "gasLimit": "10000100000",
    "difficulty": "20",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "coinbase": "0x0d33f764b19d03df4daa283859577378a01c5cad",
    "alloc": {
        "0x0d33f764b19d03df4daa283859577378a01c5cad": { "balance": "1000000" }
    }
}

Initing the private network

geth --identity "node" --rpc --rpcport "8545" --rpccorsdomain "*" --datadir=/ethereum/data --ethash.dagdir=/ethereum/ethash --port "30303" --nodiscover --rpcapi "db,eth,net,admin,web3,debug" --networkid 331788 init /ethereum/genesis.json
geth --identity "node" --rpc --rpcaddr="0.0.0.0" --rpcport "8545" --rpccorsdomain "*" --datadir=/ethereum/data --ethash.dagdir=/ethereum/ethash --port "30303" --nodiscover --verbosity=9 --rpcapi "admin,db,eth,net,web3,miner,personal,debug" --networkid 331788

Preparation

Once the private network is up, I connect to it via geth attach and then run the following:

personal.unlockAccount(web3.eth.coinbase, "123123", 150000);
miner.setGasPrice(1); miner.setEtherbase(personal.listAccounts[0]); miner.start(5);

So I unlock my coinbase account and start 5 miners with gas price value 1. After some time, I'm able to deploy my contracts which I do next. So they take the first three nonce values for my coinbase account. When contract is deploying txpool.inspect shows me the following:

pending: {
  0x0D33f764b19d03DF4DAa283859577378a01C5Cad: {
    2: "contract creation: 0 wei + 10010000 gas × 32 wei"
  }
},
queued: {}

Contracts are deployed okay.

Sending transactions

On the frontend, I have the following code to send transaction to my custom contract using truffle-contract abstraction:

sampleNameContract().use(function (instance) {
        return instance.addRecord(recordId, address, recordId, address, { gas: "0x10000", from: address })
    }).then(function (value) {
        console.log(`Tx: ${value}`)
    })

Executing this snippet, Metamask asks me to approve transaction and I do it. As a result, I have the following info in txpool.inspect:

pending: {
      0x0D33f764b19d03DF4DAa283859577378a01C5Cad: {
        3: "0x440C9c5DBC21cedcAfF1a98ac7A48b5c6930cd0c: 0 wei + 10010000 gas × 32000000000 wei"
      }
    },
    queued: {}

This transaction is never mined and applied and leaves in the tx pool as a pending one forever.

Issue

The transaction I send to my custom contract from the frontend is never mined and applied. Can you please help me figure this out?


texts:
I am currently researching about the formal verification of smart contracts.
I am surprised that I did not manage to find a paper about the (shape) analysis of the storage of a contract.

Is there in the literature or in github a tool to perform shape analysis (on the storage and/or memory) of Ethereum?
If not, it is so, because this problem is not a concern or why nobody studied this problem?


texts: Converting Log Topics to int64 correctly in Go

texts:
I currently use the code below to extract the ERC721 Token ID from Transfer Event Logs:

txHash := newLog.TxHash.Hex()
hexString := common.BytesToAddress(newLog.Topics[3].Bytes()).Hex()
flowerNum, _ := strconv.ParseUint(hexString, 0, 10)
flowerNumInt := int64(flowerNum)

flowerNumInt is 1023, even though txHash linked below references FLOWER #1133. Moreso, FLOWER #1023 has no transfer events at all, and does not appear in the tx linked below.

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

Am I doing something wrong during the conversion?


texts: Branch a Truffle test into various Ganache blockchain states

texts:
I am currently testing a contract that can evolve in different ways, depending on the interaction between parties. But all these possible scenarios share the same initialization.

So, the question I have is the following. When I am writing a test for this contract in Truffle/Ganache, is it possible to run a single chain until the decision point, then create several copies of the test blockchain state, one for each possible scenario?

I know that Ganache offers the evm_snapshot and evm_revert RPC calls. But it is not clear to me how to use them and how it interacts with Truffle and Mocha.

Also, can I use nested contract directives, as we can nest describe in Mocha?

Ideally I would like to do something like this:

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

contract('Contract', function(accounts) {
  beforeEach(async function() {
    // launch contract
    let contract = await Contract
        .new({ from: accounts[2], gas: 2000000 });

    // let users interact here
    // ...
  });

  contract('Agreement', function(accounts) {
    it('Payment is processed', async function() {
      // test that payment was processed
    });
  });

  contract('Disagreement, see who is right', function(accounts) {

    contract('Alice right', function(accounts) {
      it('Punish Bob', async function() {
        // show that Alice is right and punish Bob
      });
    });
    contract('Alice right', function(accounts) {
      it('Punish Alice', async function() {
        // show that Bob is right and punish Alice
      });
    });
  });
}

You see that we are testing three different outcomes, but they share the same initialization. I would like to avoid starting three fresh chains, one for each test. Is it possible and how one does it?


texts: Library/Framework for generating Contract Forms

texts:
Based on ABI, Mist is able to automatically generate forms for contracts for read/write access.

Does someone know if there is a JS framework/library for this task? For the prototyping/demonstration purpose, it’s extremely useful to be able to quickly generate corresponding forms.


texts: "Difficulty" opcode pushes always 0x0 to stack


texts: Smart Contract for Ethereum Blockchain On Azure - Automatic Execution on Coin Transfer Event

texts:
I am new to both Blockchain and Smart Contracts. My use case is to design a contract which can be mined in a way so that, if any user of blockchain sends ether to another user using any type of wallet, contract should be triggered automatically and perform some action - say sending part of ethers to other user or owner.

Basically I am looking for some documentation , or help for designing a smart contract which should be executed automatically on the even happening on blockchain - transfer of ethers in this case. User should not need to interact with contract, instead contract should identify event to act upon.


texts: geth keeps opening & re-opening in background (OSX 10.10.5)

texts:
Issue started after installing cpp-ethereum & updating geth to 1.3.3. Geth continually re-opens in the background after being forced to shut down. When I try and run geth in terminal, I receive the following error:

  Fatal: Error starting Ethereum: listen udp :30303: bind: address already >in use (possibly another instance of geth is using the same port)

Tried a hard re-start, after which geth re-opened in the background again. Tried uninstalling cpp-ethereum and uninstalling geth (both 1.3.3 and the previous 1.2.2). As soon as it is reinstalled, geth opens up in the background.

Open to any and all suggestions!


texts: Events firing but bool variable not changing in value

texts:
Given a contract with an event as follows

contract test {
    event LogEvent(
        address a,
        bool result
    );

    function testInputs(some parameters) public (){

        ....

        //set it to pass the if condition
        bool[2] a = [true,true];

        //set it to fail the if condition
        //bool[2] a = [false,true];

        if(a[1] && a[2])
            LogEvent(msg.sender,true);
        else
            LogEvent(msg.sender,false);
    }
}

I initially transact and set the parameters so that the if condition is satisfied and the event fires true.

I then transact again and set the parameters so that the if condition does not pass. I expect a new event to be fired setting the value to false.

However, the value remains true when I check the log. I believe that each event fired should permanently store the value with the transaction. Is that incorrect?

I also tried testing this the other way around. I started with a transaction that fires the event setting it to false. That works. Then I transact again, setting it to true. Again, that works. However, if I try transacting with incorrect parameters once more, it does not set back to false when I check the log.

Can someone provide an explanation and how to work around that issue?


texts: Deploying contract with no cost (gasPrice 0) on private network

texts:
In order to achieve a no-coin bootstrapping of my private network I'm trying to deploy a first special contract having zero funds in owner wallet (every wallet of this private network should have zero balance) and to do so with truffle, gasPrice was set to 0 on truffle.js config file.

Nevertheless, when deploying truffle Migrations contract the following error is thrown:

"Migrations" could not deploy due to insufficient funds
* Account:  0x5FBF29a8Ad77EA087275858d874AcD55526cFbDF
* Balance:  0 wei
* Message:  sender doesn't have enough funds to send tx. The upfront cost is: 9400000000000000 and the sender's account only has: 0

The question is: how can be 9400000000000000 the expected cost while gasPrice being 0. Shouldn't cost be 0 too?

Some tests on the node console show that even setting flag gasPrice to 0 on the miner simple transactions having gasPrice=0 are not mined. So probably the problem is not on deploying contracts but simply transacting with zero cost.

truffle.js:

var HDWalletProvider = require("truffle-hdwallet-provider");
var mnemonic = "...";

module.exports = {
    networks: {
    development: {
        gas : 4700000,
        gasPrice : 0,
        provider: function() {
        return new HDWalletProvider(mnemonic, "http://127.0.0.1:port...", 0, 10)
        },
        network_id: "*" // Match any network id
    },
    ropsten: {
        gas : 4700000,
        gasPrice : 10000000000,
        provider: function() {
        return new HDWalletProvider(mnemonic, "https://ropsten.infura.io/...", 0, 10)
        },
        network_id: "*" // Match any network id
    }
    },

    compilers: {
    solc: {
        version: "0.4.24",
        docker: false,
        settings: {
        optimizer: {
            enabled: true,
        }
        }
    }
    }
};


texts: How do I determine the network within a truffle exec script?

texts:
I'm writing a script to be executed with truffle exec and I need to add some logic conditional on the network we're calling truffle exec with.

This is (roughly) what I want in my script:

const contract = artifacts.require("./MyContract.sol");
module.exports = function(callback) {
  // TODO: Do some conditional thing based on network!

  contract.callMethod();
}

I'm hoping to call this script in the following way:

truffle exec script.js --network ropsten


texts: What happens if the Ethereum network is separated?

texts:
Say China's internet suddenly is separated from the rest of the World (by accident or government action).
Miners in China keep mining Ethereum blocks, all other miners, as well.

Then after a couple of days the firewall is loosened and the networks rejoin.

What would be the consequences?


texts: Can someone explain me this part of White Paper?

texts:
I want to know what this para means, more clearly and with more detail.
"
Theoretically, Ethereum-based token systems acting as sub-currencies can potentially include another important feature that on-chain Bitcoin-based meta-currencies lack: the ability to pay transaction fees directly in that currency. The way this would be implemented is that the contract would maintain an ether balance with which it would refund ether used to pay fees to the sender, and it would refill this balance by collecting the internal currency units that it takes in fees and reselling them in a constant running auction.
"

To whom does it refund the ether?

To whom is the txn fee paid?

Please explain that para using plain and easy english so that I & even a 10 year old kid can understand.


texts: Ethereum Classic (ETC) And The DAO Holders - Will The White Hat Hackers Return The DAO Funds?

texts:
As a DAO token holder I'm wondering if the DAO White Hat Hackers will return the funds to the DAO token holders on the Ethereum Classic chain?

I'm 100% for the Ethereum forked chain, but I can't turn my back on free money...

Thanks


texts:
event transfer(address indexed from, address indexed to, uint value);
    event Approval (address indexed owner, address indexed spender, uint value);

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

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

    function transfer(address to, uint value) public  returns(bool) {
        require(balanceOf(msg.sender) >= value, 'balance too low');
        balances[to] +=value;
        balances[msg.sender] -=value;
        emit transfer(msg.sender, to, value);
        return true;
    }

I get this error when trying to compile a contract in remix:
DeclarationError: Identifier already declared. --> Token.sol:23:5: | 23 |
function transfer(address to, uint value) public returns(bool) { | ^ (Relevant source part starts here and spans across multiple lines). Note: The previous declaration is here: --> Token.sol:12:5: | 12 | event transfer(address indexed from, address indexed to, uint value); |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


texts: approve-transferfrom pattern between contracts

texts:
What is the general process-flow of approving contract a to spend tokens on behalf of contract b and how would  a sufficient function implementation look like which successfully achieves this?

For example let's consider following scenario. I created a standard ERC20 token and minted the token supply to contract a. Now I want to allow contract b to spend the minted ERC20 tokens on behalf contract a


texts:
I tried to understand what a DAO token is that you can buy for Ether, but I can't.

And because my OSX Ether wallet has issues, I can't try to buy DAO tokens, so I hope you could explain me what it is.

Thanks a lot for your patience.


texts: Solidity Split Comma-Delimited String into Individual words

texts:
Since Solidity functions can't accept String Arrays as arguments, I'm trying instead to pass in a long comma-delimited string, and then convert it to an array of strings on the fly.
I'm close - but the one line in the else statement towards the bottom - which I've pointed out in a comment - keeps crashing the contract.
Here's my code:
function splitString(string calldata stringToSplit) external pure returns(string memory) {
    // 1. Declare a string array to hold all the individual words I'm able to tease
    //    out of the passed-in string:
    string[] memory finalWordsArray;

    // 2. Declare a word-counter var to keep track of how many words I've gotten:
    uint256 wordCounter = 0;

    // 3. Convert and store the passed-in String argument into a Bytes Array so
    //    I can iterate through it one character at a time:
    bytes memory stringAsBytesArray = bytes(stringToSplit);

    // 4. Declare another bytes array to contain all the characters that will be
    //    in my next full individual Word:
    string memory tmp = new string(stringAsBytesArray.length);
    bytes memory tempWord = bytes(tmp);

    // 5. Iterate through the "stringAsBytesArray" one Char at a time:
    // ["Hello,here,we,are,today"]
    for(uint i = 0; i < stringAsBytesArray.length; i++) {
        // if current char is NOT a comma, append it to my "tempWord":
        if (stringAsBytesArray[i] != ",") {
            tempWord[i] = stringAsBytesArray[i];
        }
        else {
            // We found a Comma, which means we've reached the end of a word. So
            // let's convert our "tempWord" from a bytes Array to a String:
            string memory newWord = string(tempWord);

            // And then add that word to our "finalWordsArray":
            // -->this next line causes a crash!
            // finalWordsArray[wordCounter] = newWord;

            // Iterate our wordCounter:
             wordCounter++;

            // And reset/blank-out our "tempWord" for the next go-around:
            tempWord = bytes(tmp);

            // This next statement DOES work: it returns the first word it
            // found before hitting that first comma. I put this in just to
            // see that I am getting at least SOMETHING out of this:
            return newWord;
        }
    }

    return "no Commas found!!!";

    // return string(finalWordsArray[2]);
}


texts: BlockCypher Account nonce too far behind transaction

texts:
I'm currently working on a DApp that involves sending transactions. I'm using BlockCypher to send the transactions since the API is fairly straight forward. One issue I'm finding is that when I run my API locally and call the send transaction method I receive the transaction hash and I'm able to check it on Etherscan and the transaction does goes ahead.

The next step of course is deploying the API and then testing it, when I do this and hit the API endpoint with the exact same parameters. I receive the following error: Error validating transaction: Account nonce 68 too far behind transaction 0xad50ba948fc3fe266fb19c4aa3f3a81928ff114b3fadf597a620ec86eada7cf0:. It doesn't appear that the transaction in question even exists (from searching for it on Etherscan) and so it seems that my Nonce for this account is out of sync with what it should be. Is that even possible? And what is the way to overcome this issue?

As it turns out, what I've found out is that the account should have a nonce of over 200, and the function web3.eth.getTransactionCount(ADDR) seems to only be returning 68.
Here is how I construct the transaction:

 var count = web3.eth.getTransactionCount(FROM_ADDR);

 var data = myContractInstance.transfer.getData(to, value, { from: FROM_ADDR });

 var gasPrice = "2000000000";
 var gasLimit = 90000;

 var rawTransaction = {
     "from": FROM_ADDR,
     "nonce": web3.toHex(count),
     "gasPrice": web3.toHex(gasPrice),
     "gasLimit": web3.toHex(gasLimit),
     "to": to,
     "data": data,
     "chainId": 0x01
 };

Strangely, when I changed the address the transactions are correctly sending again on both my local machine and the server. I've left a email for BlockCypher to see if they are able to help with this.

Thanks in advance,


texts: How can I stop the block gas limit on a private chain dropping to the public chain default?

texts:
I've got a little private chain running which occasionally runs some rather labour-intensive transactions.

I was able to set the initial block gas limit using the "gasLimit" parameter in genesis.json but that seems to get automatically adjusted down over time back to the public chain default.

Short of feeding the chain intentionally labour-intensive transactions every single block to keep the average up, is there anything I can do to stop it adjusting downwards?


texts:
How to call a function with data location as parameter using web interface designed in sublime?  Please find the Solidity code below:

contract Demo{
  string public name;

  function setName(string memory  _name) public{
    name= _name;
  }
  function getName()view public returns (string memory){
    return name;
  }
}

The Function call is made in .html file:

web3.eth.defaultAccount = web3.eth.accounts[0];
var new_contract= new web3.eth.Contract([
{
    "constant": false,
    "inputs": [
        {
            "name": "_name",
            "type": "string"
        }
    ],
    "name": "setName",
    "outputs": [],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
},
{
    "constant": true,
    "inputs": [],
    "name": "getName",
    "outputs": [
        {
            "name": "",
            "type": "string"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
},
{
    "constant": true,
    "inputs": [],
    "name": "name",
    "outputs": [
        {
            "name": "",
            "type": "string"
        }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
}
],"0x0df91edadefbf4dd5ae655d1e7db48f4623863f3");

var contract= new_contract;
var pre=document.getElementById("output");
var input=document.getElementById("input");
var button=document.getElementById("button");
button.addEventListener("click",function(){
  contract.setName(input.value);
  output.innerHTML=contract.getName();
})

But I am getting an error on wepage which says:

  Uncaught TypeError: contract.setName is not a function at HTMLButtonElement.

Thanks :)


texts:
I have an error whenever I add the event line
for EVM logging and to notify anyone listening that this transfer took place.

function sendCoin(address receiver, uint amount) returns (bool sufficient) {     //receiver 160 bit public address of receipient
                                                                                //amount # of coins to be sent

            if (balances[msg.sender] < amount || balances[receiver] + amount < balances[receiver]) throw;             //Check current balance of msg.sender is less than amount to send if yes, then dont execute

            balances[msg.sender] -= amount;

                 //If msg.sender is greater than amount then subtract the # of coins from sender account
        balances[receiver] += amount;                                           // and add the # of coins to receiver account
        return true;

    //event sendCoin(address indexed sender, address indexed receiver, uint256 amount);
    //sendCoin(msg.sender, receiver, amount)

How do I fix this?


texts:
-I am trying to transfer ether from one account to another using smart contract which is deployed on azure.

-when I call receiverAddress.send(amount)
in the function in my contract it returns the transaction receipt/ acknowledgement in json format.

-My account get debited by amount I specified but the receivers account is not credited.
the receipt shows from :myAddress ie. sender address
and               to:contract address

-I don't understand why the to field has a contract address when I am calling receiverAddress.send(amount)

-Is there any thing I am missing or I need to transfer that ether from contact to the receivers account??

-Bellow is the snippet of transaction receipt:-

-function from contract

function sendPayment(address beneficiary,uint amount){
     coin-=amount;
     if (beneficiary.send(amount))
     throw;
}

this is code of contract:

`pragma solidity ^0.4.4;

import "./strings.sol";

contract SDFFinance {
    using strings for *;
    address addr;
    address public driver1;
    address public driver2;
    address public driver3;
    string statusOf;
    uint coin;

function SDFFinance(uint balance) {
    coin=balance;
    driver1=0x1b7207197717fe2114d3d22f38c81d980e74e13a;
    driver2=0x1b7207197717fe2114d3d22f38c81d980e74e13a;
    driver3=0x1b7207197717fe2114d3d22f38c81d980e74e13a;
    statusOf='OPN';
  }

function changeShipmentStatus(string shipmentId,string st){
            statusOf=st;
        processPayment();
}

function processPayment(){
    if(statusOf.toSlice().equals('RAP'.toSlice())){
        sendPayment(driver1);
    }
    else if(statusOf.toSlice().equals('DAL'.toSlice())){
        sendPayment(driver2);
    }

    else
    if(statusOf.toSlice().equals('ATD'.toSlice())){
        sendPayment(driver3);
    }
}

function sendPayment(address beneficiary) payable returns(bool success) {
  if(msg.value==0) throw;
  if(!beneficiary.send(msg.value)) throw;
  return true;
}

function getBalance() returns(uint){
    return coin;
}

function getStatus() returns(string){
    return statusOf;
}

function getAddress() returns(address){
    return addr;
}

}`


texts: How can I connect my static page (Dapp) to my ipfs node?

texts:
The very naive way I'm going about it is:

const node = new Ipfs({ host: "xxx.ip.address.xxx"});

When I save an image from the static page, it does give me an ipfs hash back and save it to the local browser cache,  but when I run on my ipfs node:

ipfs dht findpeer QmVLRBHgCvFhPbxenyPpM1UnoLMY9kPhB6vyU2JmenaLYv

My node can't find the file.

PS: I'm running the IPFS node on Digital Ocean.


texts: Paying for a transaction that will happen later

texts: I have a voting contract that opens and closes every 5 minutes. I don't want the owner to have two transactions for open and close. Is there a way I can have the owner pay for the close transaction when the vote is opened?


texts: Etherscan api not showing internal transactions

texts:
For example:

https://etherscan.io/address/0x4e646a576917a6a47d5b0896c3e207693870869d#internaltx

If I make an api call for the same address as:

  http://api.etherscan.io/api?module=account&action=txlistinternal&address=0x4e646a576917a6a47d5b0896c3e207693870869d&startblock=0&endblock=2702578&sort=asc&apikey=YourApiKeyToken

and got the below response:

{"status":"0","message":"No transactions found","result":[]}

This contains some internal transactions but etherscan api is not showing them. What is the reason?

Thanks in advance.


texts:
I'm building an application that is a mix of the blockchain and a centralized app.
I need some way for the systems to communicate with each other, for example.
Let's say you can buy some digital asset in my app. you pay for this digital asset using the blockchain and after the transaction succeded, my system needs to see that you really paid for it and only then give you the asset.
because I can't use custom data in a transaction, what I was thinking to do is to create a transaction id in my DB and send it to a costume function that will log this id and the amount paid, then my system will be able to search(in case the system was down and the subscribe didn't fire) for that event by the id and check if the user really paid for the asset.
is it the right approach for a case like this? can I trust the events for a case like that?


texts: Re-setting file permissions on IPC file on Parity re-start?

texts: Can anyone think of a clever way to re-set the IPC file permissions on a Parity re-start?  I'm using systemd to control Parity.