texts: Where in EthereumJ transaction signature is validated?

texts:
I am having some troubles with finding code responsible for transaction signature verification in EthereumJ. Does anyone can point me somehow ?

I already investigated ethereumj source code but only found validation of components not the real signature against public key.

public static boolean validateComponents(BigInteger r, BigInteger s, byte v) {

        if (v != 27 && v != 28) return false;

        if (isLessThan(r, BigInteger.ONE)) return false;
        if (isLessThan(s, BigInteger.ONE)) return false;

        if (!isLessThan(r, Constants.getSECP256K1N())) return false;
        if (!isLessThan(s, Constants.getSECP256K1N())) return false;

        return true;
    }

Am I missing something ? Does such validation occurs somewhere?


texts: Migrating from TerstRPC to live testnet (Ropsten)

texts:
I have successfully developed my smart contracts in Solidity and the scripts using the web3 API to deploy them on the testRPC. Now, I would like to test on a testnet network: Ropsten.

How can I migrate from testRPC to Ropsten?

I know that I need to create a node and download the entire blockchain. In order to do this, I used:

geth --testnet removedb
geth --testnet --fast --bootnodes "enode://20c9ad97c081d63397d7b685a412227a40e23c8bdc6688c6f37e97cfbc22d2b4d1db1510d8f61e6a8866ad7f0e17c02b14182d37ea7c3c8b9c2683aeb6b733a1@52.169.14.227:30303,enode://6ce05930c72abc632c58e2e4324f7c7ea478cec0ed4fa2528982cf34483094e9cbc9216e7aa349691242576d552a2a56aaeae426c5303ded677ce455ba1acd9d@13.84.180.240:30303"

Once this step is done, I need to create an account and mine a bit to get some Ethers. Then, I can connect to this node and deploy my smart contracts with my JS scripts.

Can someone confirm that I am on the right track?

Thanks in advance


texts: Error: Returned error: invalid opcode: SHR

texts:
I am getting this error while migrating
Contract:
pragma solidity ^0.5.16;
contract Hello {
   string message;

   constructor() public {

   message = "Hello, World";

   }
   function getGreetings() public view returns (string memory)
   {
     return message;
   }
   function setGreetings(string memory _message) public{
     message = _message;
   }

}

2_deploy_contracts.js
var Hello = artifacts.require("./Hello.sol");
module.exports = function(deployer) {
   deployer.deploy(Hello);
};


texts: pytest test_contracts.py error: ImportError: cannot import name state_transition

texts:
I am struggling to set up pyethereum on an old ThinkPad T500 running Ubuntu 16.04 and Python 2.7.11+, following installation instructions here and here.

When I test the installation with:

pyethereum/ethereum/tests$ pytest -m test_contracts.py

I get, for example:

going into /home/pavel/Ethereum/pyethereum/ethereum/tests
============================  test_db.py  ============================

===========================  test_abi.py  ============================
unhandled exception occurred while testing test_abi Traceback (most
recent call last):   File
"/usr/lib/python2.7/dist-packages/logilab/common/pytest.py", line 447,
in testfile
    options=self.options, outstream=sys.stderr)   File "/usr/lib/python2.7/dist-packages/logilab/common/pytest.py", line 763,
in __init__
    testLoader=NonStrictTestLoader())   File "/usr/lib/python2.7/unittest/main.py", line 77, in __init__
    self.module = __import__(module)   File "test_abi.py", line 3, in <module>
    import ethereum.testutils as testutils   File "/home/pavel/.local/lib/python2.7/site-packages/ethereum-1.3.6-py2.7.egg/ethereum/testutils.py",
line 14, in <module>
    from ethereum import state_transition ImportError: cannot import name state_transition

There are at least ten other tests that fail, all with same message:

 ImportError: cannot import name state_transition

I am eager to get started with pyethereum, and would be very grateful for any and all help. Thank you very much!


texts: Is there any good reason in having a stateless contract?

texts:
If I understand correctly, then any stateless contract can be re-declared as a library.

Is there any advantage or benefit in keeping it as a contract?

If there is any, then I guess it would be in terms of runtime (i.e., gas cost).

I cannot see any differences in terms of compile-time.

But I'd be happy to get an answer referring to both aspects.

Thank you!!!


texts: Bytecode on block chain different from the one used when deploying


texts:
I am new to the world of NFTs and I find very hard to understand how the ethereum blockchain enforces their "uniqueness".
As far as I know, smart contracts implementing the ERC721 interface can work with NFTs, basically, for a given ERC721 smart contract tokenIds must be unique and can be assigned to a single address. What I understand by that is that for a given smart contract instance (with its own address), the same tokenId cannot be owned by two different wallets, NFTs are thus unique for that particular instance of a smart contract (Smart contract address + tokenid -> Unique), in other words, the Dapp (a video game for instance) based on that smart contract will be able to keep track of who owns a given game asset (represented by a NFT).
My problem is that, the tokenId (or NFT for this purpose) only means anything to that particular Dapp, it is the Dapp that "knows" what that tokenId actually represents, which is perfect in the context of video games and similar, but is a problem in the context of real-world or even global digital-items (like a tweet) ownership.
What is preventing someone from creating an NFT in two different ERC721 contracts and "attaching" them to the same real world/digital asset? The NFTs would probably have different tokenids in each contract but they would both represent the same item, meaning that the creator could sell that item twice, and none of the buyers could actually prove its unique ownership...


texts: How to get public key from private key in Web3j

texts:
I am developing Dapp by web3j and I attempt to convert private key to public key. I found this question this question that provides a way converting private key to public key in class ECKey, but I need to also add Ethereumj core as dependency.

I am wondering if there is a method in web3j rather than ethereumj to convert private key to public key.

If there is not, why doesn't they add this logic as a function to web3j?


texts: If I try to send to send ether to the standard token contract, the tx is rejected. Even if function() is modified as below. Why?

texts:
/* If I change it like that it still fails */
    function () {
        amount += msg.value;
    }

Is there something like, it's generally not possible to send eth to a token contract?


texts: How BIP 39 tool recovers all my private and public keys which was generated in ledger nano s

texts:
I followed the faq in ledger nano s.

This says that I can retrieve the private and public key. Does it mean that using the 24 word seed we can generate the same set of private and public keys in same order as it was created in my ledger nano s ?


texts: Which is better self-destruct or upgradable smart contract?

texts:
I have a smart contract which I might want to modify in future. Should I use self-destruct to destruct that contract and then deploy a new one?
Or, should I make that contract upgradable to make changes in future?
Which one is most feasible solution in terms of cost and other factors?


texts: How to transfer deployed ERC20 token XZY in solidity?

texts:
In smart contract of solidity,  the following function will transfer _amount ether to a recipient:
function send(address recipient, uint _amount, uint256 _gas) private {
        (bool success, ) = recipient.call{value:_amount, gas: _gas}("");
        require(success, "Transfer failed.");
    }

by default, the value transferred is in ether. If an ERC20 token XYZ was deployed to address _addressERC20, how to transfer the token XYZ instead?


texts: My question is about ICO wallets. when participating in an ICO do i need to download a specific wallet for that new coin?


texts: Why is dynamic array length not updated after addition of new element?

texts:
I created a struct as follows:

struct Node{            //   each node models each device on the network
    address nodeAdress; //   adress of the node
    uint trustValue;    //   trust value assigned to the node
    uint perCentMalware;//   percent probability calculated at the node
}

Then I declared an array Node[] allNodes;.

I have a function addNewNode() in my contract.

function addNewNode(address newNodeAdress) public returns(uint)
{
    addressToIndex[newNodeAdress] = allNodes.length;   //  newNodeAdress added to map
    return allNodes.push(Node(newNodeAdress,50,200));  //  nodes with default values
}

This is the result obtained while testing the code:

  contractInstance.addNewNode.call(0x21f2118a4c7c5fda33d22faa1e2497211e69e935)
  { [String: '1'] s: 1, e: 0, c: [ 1 ] }
  contractInstance.addNewNode.call(0xfb075f799ba2b86599f93a73a34626ade8c237a6)
  { [String: '1'] s: 1, e: 0, c: [ 1 ] }

As it can be observed clearly, I called the addNewNode() function two times, but the return value,i.e., the allNodes.length value remains the same 1. Why is it so? Is there any conceptual misunderstanding here?


texts:
I'm learning about ethereum and smart contracts and I have a simple contract that stores a string. I'm trying to use web3js to change that string. I'm having trouble following the instructions from this answer https://ethereum.stackexchange.com/a/12932. This works fine when I'm in the geth console but when I try to make a js script or use the node console it's like .at doesn't exist. This is my output.

> var contractAbi = new web3.eth.Contract(abi);
> var myContract = contractAbi.at(contractAddress);
TypeError: contractAbi.at is not a function
    at repl:1:30
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:73:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:539:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:232:10)
    at REPLServer.Interface._line (readline.js:583:8)
    at REPLServer.Interface._ttyWrite (readline.js:860:14)
    at REPLServer.self._ttyWrite (repl.js:612:7)
    at ReadStream.onkeypress (readline.js:119:10)
    at emitTwo (events.js:106:13)
    at ReadStream.emit (events.js:191:7)
    at emitKeys (internal/readline.js:389:14)
    at next (native)
    at ReadStream.onData (readline.js:970:36)
    at emitOne (events.js:96:13)
    at ReadStream.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at ReadStream.Readable.push (_stream_readable.js:134:10)
    at TTY.onread (net.js:547:20)

Has anyone had this problem and knows of a fix?


texts: WebSocket connection dropped in Web3.js with Infura

texts:
I know this question have been asked several times and many solutions are being proposed as a workaround but not sure why it is not been working on our case.

In our case we have to listen for contract events like Transfer events on our backend (node js) so that we can update our investor balances and perform other sensitive activities. We can't afford to lose events in our case.

For this, we are using WebSocket provider from infura and web3js library to connect with them. We noticed that if for a few hours we are'nt make any calls then it would close that connection and we would have to restart our app for new connections.
To work around this issue we applied popular community workaround  i.e listen for events like end or error on the provider and if those events occur we would make a call to instantiate a connection but after applying this patch  web3 throws below error instead of connection not open error

'Connection dropped by remote peer.

Here is simplified code of our blockchain module.

const web3  = require('web3');
const ethtx = require('ethereumjs-tx');
const path = require('path');
const fs = require('fs');
const Tx = require('ethereumjs-tx');

const updatebalancedb  = require('../db/Admins/Transactions/updatebalance.js');
const dotenv = require('dotenv');
dotenv.config();

var masterwalletpublickey = process.env.daopublicaddress;
var masterwalletprivatekey = Buffer.from(process.env.daoprivatekey, 'hex');
var wsscocketprovider = process.env.infuranode;
var parentcontractaddress = process.env.maincontractaddress;

var provider = new web3.providers.WebsocketProvider(wsscocketprovider);

var web3js = new web3(provider);

provider.on('error', e =>
{
console.log('WS Error', e);
provider = new web3.providers.WebsocketProvider(wsscocketprovider);
});
provider.on('end', e => {
    console.log('WS closed');
    console.log('Attempting to reconnect...');
    provider = new web3.providers.WebsocketProvider(wsscocketprovider);

    provider.on('connect', function () {
        console.log('WSS Reconnected');
    });

    web3js.setProvider(provider);
});

 const rawcontract  = JSON.parse(fs.readFileSync(path.join(__dirname,'../BlockchainModule/build/contracts/ErContract.json')));
 const contractabi = JSON.stringify(rawcontract.abi);

const contract = new web3js.eth.Contract(rawcontract.abi,parentcontractaddress);

contract.events.Transfer()
.on('data', (event) => {
    console.log('data',event);
    var data = event;
    updatebalancedb.updateinvestorbalance(data);
})
.on('error', console.error);

const gettotaltokens = function(){

    return   contract.methods.totaltokens().call()
        .then(function(result){
            return result;

        })
        .catch(function(error){
           throw error;
        })

}

const circulationtokens = function(){

    return contract.methods.circulationsupply().call()
        .then(function(result){
            return result;
        })
        .catch(function(error){
            throw error;
        })
};

module.exports={gettotaltokens,circulationtokens};

When we call functions like gettotaltokens after few hours of connectivity web3 throws such error .

Can anyone give some pointers or some guide of how to solve this messy issue?

The only solution I have in my mind is to move web3 provider code to a functional level and every time we call the function it will start a fresh new connection. That will solve the problem for time being but not very scalable and also wouldn't solve event listener issues.

Tech Environment:

Node js (v10.13.0)
web3.js (1.2.3)
Chain : (Ropsten)
Socket Provider (Infura)


texts: Creating a contract ERC20 and sending a transaction, get balance (web3)

texts:
This is my first time creating a contract. I need to create a TEST contract ERC20.

After researching I understand ERC20 is like an abstract class which tells which methods should be implemented in the contract.

Also I understand I need to create the contract using Solidity and I need to deploy it.

Questions:

Is a Token an instance of a contract?
Is it necessary to deploy a contract for testing purposes?
How do I deploy a contract on a test network and on a main? is it done through web3 API or do I need to do it through a Wallet?
Sender address is the same as the contract address?

Thanks in advance.


texts: How does Ethereum avoid address collision?

texts:
Recently PillarProject reported an issue where there was collision (?) of sort. Apparently their smart contract address on Rinkeby testnet matched with real address on the mainnet.

I am aware that smart contract addresses don't have private key perse. These are generated via a deterministic algorithm that takes into account

address of the creator (sender)
how many transactions the creator has sent
And this is hashed with Keccak-256.

Now theoretically if I were to create a real address on a testnet and assuming that this address matches with a smart contract address on the mainnet. If I were to import my private key to mainnet from any of the ethereum client nodes. Would I have access to the smart contract ether as well?? Is this possible? Or am I talking nonsense??

Lets take the example of Pillarproject itself. If the person having access to the address on the mainnet were to import his address onto rinkeby. What would happen?

Any thoughts?


texts: How to divide and allocate the amount to token holders without loops?

texts:
I have a smart contract that keeps record of the people holding the tokens in form of array of addresses. An owner of the smart contract, whenever, sends some ethers to the contract these ethers shall be divided among all token holders depending on how much they hold the tokens and accordingly these fund will be divided. We will allocate the funds to each holder in a form of mapping and once they want to redeem the pending reward will be sent to them.

My code is currently using a for loop to divide the received deposit among all token holders by iterating over the complete array of holders.Since using loop will eventually goes out of gas limit, so what should be the suggested approach here? How can we divide an amount among all token holders without looping/much gas?


texts: Optimal sync mode for running an ethereum node that can process transactions

texts:
I need to run a local ethereum node, I've downloaded mist wallet but I've had some issues. I have to redownload the whole blockchain again, and I noticed that the problems I had could be related to the sync mode.

Is there a difference in performance when using different type of sync mode for getting balance of accounts and sending transactions?

Or is it once the blockchain is fully downloaded the sync mode doesn't affect the interactions with the network?

Any pointing in the right direction will be greatly appreciated.


texts: Check for error in transaction with web3js

texts:
If you look at this transaction in etherscan.io you can see that it notes that the transaction has an error Warning! Error encountered during contract execution [Bad instruction].  Same status can be found here on ethplorer.io

Does anybody know how I can detect this when processing a transaction via web3js?


texts: NodeSync - Node crashed while syncing? TypeError: Cannot read property 'timestamp' of undefined

texts:
Previously Mist wallet worked. Now it stops at 'Started Swarm' and writes this to console.

I'm using Qubes with Debian-8 template.

I start Mist by ./geth --synchmode "light" in the .config/Ethereum Wallet/binaries/Geth/unpacked folder and after that in other terminal I type  ./mist --light-node


texts: Is there something in front of msg.sender?

texts:
Tx.origin is an old way of utilizing the handling address behind msg.sender. But let's say I, as a user, am calling a contract and that contract calls a contract. Is there a way for contract B... to specifically only receive calls from only contract A, meaning, is there something in front of msg.sender like tx.origin is behind msg.sender.
Example
Me => Contract A => Contract B
Tx.origin => Msg.sender => ???
Is there a way for contract B to specify, "HEY, ONLY CONTRACT A CAN CALL ME" if I am making a call to contract A from the "me" address?


texts: Error compiling OpenZeppelin imported contracts

texts:
I'm running a truffle project and have imported OpenZeppelin contracts.

While running truffle compile I'm facing following error:

github.com/OpenZeppelin/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol:4:1:
ParserError: Source "github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol" not found:
File import callback not supported
import "../math/SafeMath.sol";
^----------------------------^

How can I work around this issue?

It will be great if someone could help me understand what this error says.


texts: How do you delete/remove/hide contracts from Ethereum Wallet (aka mist)?

texts: I have tons of experimental contracts I created as part of doing tutorials which I no longer need. I know I can kill the contract (from https://www.ethereum.org/greeter tutorial) but that still leaves the contracts grayed out.


texts:
Well, I'm pretty certain I' screwed, but I figured I'd ask for help just in case.

I created one, and only one wallet on MEW. I was meticulous about saving my Private Key and address correctly. I printed them both out immediately, took pictures, and logged them into a notebook.

I transferred TRX to my address: 0xA349Ec964F9814357cA14602870f55BABf44097E

The transaction was successful, as I checked on this initially by entering my address only in MEW.

I just recently to logged into MEW with my Private Key; and to my surprise, no TRX tokens and a completely different address is listed. I'm just not sure how this could have possibly happened. I'm staring at screenprints of my key and address that I used to send the TRX tokens. I'm positive I did not make any key stroke errors as I've reentered multiple times.

Anything I can do to recover my TRX? Or is it a lost cause?


texts: truffle migrate: How to deploy a contract whose constructor takes a parameter

texts:
I'm using Truffle Version 4 to develop a simple smart contract and am stuck on something I think reflects a very basic misunderstanding that I just can't get my head around.

Here's my simple contract, in contracts/BaconSupplier.sol

contract BaconMaker {
    address public pig;
    address public owner;

    function BaconMaker(address _pig) public {
        require(_pig != 0x0);
        owner = msg.sender;
        pig = _pig;
    }
}

And my deployment migration, in migrations/2_deploy_contracts.js

const BaconMaker = artifacts.require('./BaconMaker.sol')

module.exports = (deployer) => {
  deployer.deploy(BaconMaker)
}

I run truffle develop to enter the standard Truffle development environment, then

compile

=> compiles just fine

Compiling ./contracts/BaconMaker.sol...
Compiling ./contracts/Migrations.sol...
Writing artifacts to ./build/contracts

then

migrate

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0x9e8257089a048815b4593a87ae5ae22af7dab80f74c07a98a0cf0a2ba08234a1
  Migrations: 0xee08e5e6643952b3cb22642d2a04a2992141eddd
Saving successful migration to network...
  ... 0x9845c22c3db695912cb4958c9f8071b9a2ac8853b226367c3f969a0f54510fe9
Saving artifacts...
Running migration: 2_deploy_contracts.js
  Deploying BaconMaker...
  ... 0xdcb442cda2621bbcd648813a567f70761746fb583a502746670f63a558a9a5e8
Error encountered, bailing. Network state unknown. Review successful transactions manually.
Error: VM Exception while processing transaction: invalid opcode

If I remove the line require(_pig != 0x0); however then the migration runs fine, which implies to me that the migration process is actually attempting to create an instance of the BaconMaker contract.

I guess I don't really understand what the migrations are doing here or what's actually happening with deployment.

The longer term aim is that there would be a Farm contract that maintains a record of its own pigs and for each pig there is an associated BaconMaker (ignore the logic of this for now, I'm just using pigs and BaconMakers here in place of the actual contracts being developed.)

So the Farm contract would look like

import './BaconMaker.sol';

contract Farm {
    address public owner;
    mapping(address => bool) public pigs;
    BaconMaker[] public baconMakers;

    function Farm() {
        owner = msg.sender;
    }

    function addPig(address pig) external {
        require(pig != 0x0);
        require(msg.sender == owner);
        pigs[pig] = true;
        BaconMaker baconMaker = new BaconMaker(pig);
        baconMakers.push(baconMaker);
    }

}

In this case do I actually need to deploy the BaconMaker contract during the migration, or will it be deployed for me when addPig is called?

If not then how do I deploy the BaconMaker contract in the migration stage?


texts: "liner: function not supported in this terminal" when doing personal.newAccount()

texts:
In the geth console I am trying to add an account :

> personal.newAccount()

but I am getting the following error :

  liner: function not supported in this terminal

What does this mean and how do I fix it.

Note: I am running my node via the docker container


texts: Is it possible to limit the number of ethers sent to a smart contract?

texts:
I'm a newbie in ethereum programming and is playing with an ICO smart contract. I want to know if it is possible to put the below restrictions in the smart contract:

Can I set a maximum amount for ether that can be send to the contract address over a 24-hour period? I want to make sure that a single user doesn't buy all my tokens.
Can I set a maximum amount of ether to be sent to the contract address over a 24-hour period? I want to make sure that only certain amount of my tokens are sold everyday.


texts: Web3 1.3 Contract method call returns empty string

texts:
I am new to solidity and I am facing a strange issue. I have created the following Contract:
pragma solidity >=0.7.0 <=0.8.0;
//SPDX-License-Identifier: UNLICENSED

contract Lottery{

    address public manager;
    address payable [] public players;

    constructor() {
        manager = msg.sender;
    }

    function getManager() public pure returns (string memory)
    {
        return '123';
    }

    function enter() public payable {

        require(msg.value> .001 ether);

        players.push(payable(msg.sender));
    }

    function pickWinner() public restricted {

        uint index = random() % players.length;
        address payable winner = players[index];
        winner.transfer(address(this).balance);

        players = new address payable [](0);
    }

    function random() private view returns (uint) {
       return uint(keccak256(abi.encodePacked(block.difficulty,block.timestamp,players)));
    }

    function getPlayers() public view returns ( address payable[] memory){
        return players;
    }

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

}

I have deployed it to rinkeby network, and I am able to call the method getManager from Remix successfully.
When I try to call the method from my javascript code, it returns an empty string.
ABI and contract address (my lottery.js file):
import myWeb3 from './web3';

const address = '0x96F422C353D6983A0fb2d4a8EC8fe08E188ABaa3';

const abi = [
  {
    inputs: [],
    stateMutability: 'nonpayable',
    type: 'constructor',
    constant: undefined,
    payable: undefined,
    signature: 'constructor'
  },
  {
    inputs: [],
    name: 'enter',
    outputs: [],
    stateMutability: 'payable',
    type: 'function',
    constant: undefined,
    payable: true,
    signature: '0xe97dcb62'
  },
  {
    inputs: [],
    name: 'getManager',
    outputs: [ [Object] ],
    stateMutability: 'pure',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0xd5009584'
  },
  {
    inputs: [],
    name: 'getPlayers',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x8b5b9ccc'
  },
  {
    inputs: [],
    name: 'manager',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x481c6a75'
  },
  {
    inputs: [],
    name: 'pickWinner',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
    constant: undefined,
    payable: undefined,
    signature: '0x5d495aea'
  },
  {
    inputs: [ [Object] ],
    name: 'players',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0xf71d96cb'
  }
];

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

Then I call lottery.methods.getManager().call() and returns empty string [] at my chrome console.
Any advice? I have read similar cases but I could not find a solution for my case.
*Just an update on the issue, the rest of the function i.e. enter or pickWinner work just fine. It seems that I cannot read data from the contract.


texts: I know there is a reg hack that allows you to assign PC memory to Dedicated Video Memory of integrated grahics cards. My question is: Can I in some way use the intel IGPU as a dummy card with enough assigned dedicated video memory so I can continue mining using a 4GB card.


texts:
The address is the last 20 bytes of sha3(publicKey)

In Solidity, using assembly if needed, how could I splice the first 12 bytes from sha3(publicKey) and get the address? What I came up with runs out of gas:

bytes32 b = sha3(publicKey)
address signer;
assembly {
signer := mload(add(b, 0x0c) // skip the first 12 bytes, 0c in hex = 12
}

MLOAD(0XAB) loads the word (32 byte) located at the memory address 0XAB. Does my function fail because it is trying to load 20 byte only? Can MLOAD load only 20 byte?


texts: Solidity "call" function with array as input

texts:
I have a function on contract A for examples :

uint256[] values;
function set(uint256[] _arrayToSet){
    values = _arrayToSet;
}

It works perfectly when called directly, but I would like to call it from contract B, so in B I have something like that :

function set(address _contract, uint256[] _values){
       bool d = _contract.call.gas(50764)( bytes4(sha3("set(uint256[])")),_values);
}

However this does not set values, is there a way to use .call() with array as input ?
Thanks in advance.


texts:
I installed latest Ethereum Wallent and I connected on test network and  I clicked on Start Mining (Testnet only), but nothing is happening. I still have 0 ETH in my account.

I'm not sure if it's bad a design or a bug, I have no idea if it works.

Also I've tried via console
1. geth console
2. in new console geth attach
3. miner.start(2)

I get this error

Error: etherbase missing: etherbase address must be explicitly specified
at web3.js:3104:20
at web3.js:6191:15
at web3.js:5004:36
at <anonymous>:1:1

Not sure how to start miner to get some test ETHs


texts:
Say the makers of a contract all die so no one left has a stake in or knows or cares about that contract. Say the contract never calls self-destruct on itself.

What happens to this old, unused contract? Does it burden the network that it exists? It should never be run or included in future blocks, but doesn't someone somewhere have to store it? Is there a way to reclaim this storage, like requiring all contracts to self destruct after X years?


texts: i would like to create 60GB video NFT, is it possible?

texts:
Is it a matter of price?
I would like to know what is the process to do that.
Thanks a lot


texts: when i call myMethod().send() using web3 state vars aren't updated and there is no transaction cost?

texts:
I am calling a method on my contract like so...

contractInstance.methods.addSchool(result, web3.utils.fromAscii(req.body.schoolName)).send({from: defaultAccount})

The transaction is mined but no state variables are updated. when I look at the transaction details the gas is always 9000 and there is no transaction cost. What am I doing wrong? The method works if I call it from browser solidity.

Thanks!


texts: How to call my contract's function using sendTransaction

texts:
This may be a very basic question, I don't know why but I am unable to find correct solution to how can I call my contract's method using sendTransaction. I have a transfer(address, uint256) function which I want to call using sendTransaction and callTransaction. I have my contract compiled and I have it's abi and address. Now, how can I call different metrhods of the contract using sendTransaction?
I was reading the question Syntax for calling contract state changing methods, and I got explanations for function having single parameter but what if it has more than a parameter of different types, like here transfer() function accepts 2 parameters.


texts: Inheriting from contracts of a different Solidity version

texts: The OpenZeppelin version I'm using is Solidity 0.5.0 but I'm using 0.5.15 in my core contracts. Everything is compiling but I'm having some issues verifying the contract on Etherscan and submitting transactions. Is it kosher to inherit from a different Solidity version like this?


texts: Can a decentralized app know the true identity of its users?

texts: I’ve been thinking about the architecture of decentralized applications.  I know certain applications like Uniswap and Augur don’t know the identity of its users. Would these applications still be decentralized if they know the identity of its users and is this a preferred style of dapps?


texts: Creating contract B from contract A, but address of contract B shows a contract of type A on Remix

texts:
function _createB() public {
    address newB = new B();
    newB(newB); //Event logs the address of contract B
}

When I copy and paste the address that is logged from the newB event into the "load contract at address" on Remix, I get another contract of type A.

How would I be able to create separate contracts of type B?


texts: Smart contract state storage under the hood and scalability

texts: I know smart contract state is being added in block, Does this true always ? When I add or update an array of struct in contract what happens under the hood ? Is there any limit for such data structure ?  Will this not be going to exhausted soon ?  Block size will be very huge after years right ? Is there a scalability issue ?


texts: What exactly would be lost if we had a single, super-powerful centralized node?

texts: That question might sound completely trollish but it is not. Imagine that eventually all nodes are turned off except for a single, centralized supercomputer which did all the contract-executing work. (Mining would still be decentralized.) What would be lost, security-wise, under that scenario?


texts: How to get Ethereum dashboard up and running

texts:
How to get the ethereum dashboard running, I have installed all the dependencies, following steps mentioned in https://github.com/ethereum/go-ethereum/tree/master/dashboard
I followed the steps mentioned,

$ (cd dashboard/assets && npm install)
$ (cd dashboard/assets && ./node_modules/.bin/flow-typed install)

When I do,

go generate ./dashboard

I get the following error,

running "go-bindata": exec: "go-bindata": executable file not found in $PATH

What is it that I am missing?


texts: Solidity - Generate multiple, unpredictable random numbers that do not depend on input

texts:
I know that the "how to generate random number" in solidity is a very common question. However, after reading the great majority of answers I did not find one to fit my case.

A short description of what I want to do is: I have a list of objects that each have a unique id, a number. I need to produce a list that contains 25% of those objects, randomly selected each time the function is called.  The person calling the function cannot be depended on to provide input that will somehow influence predictably the resulting list.

The only answer I found that gives a secure random number was Here. However, it depends on input coming from the participants and it is meant to address a gambling scenario. I cannot use it in my implementation.

All other cases mention that the number generated is going to be predictable, and even some of those depend on a singular input to produce a single random number. Once again, does not help me.

Summarising, I need a function that will give me multiple, non-predictable, random numbers.

Thanks for any help.


texts:
How do I migrate full node from PARITY to GETH ?
So the easy part to tun geth I know, but How do i move all the keys from parity to geth?
I've tried to copy the keystore folder from parity to geth, and re run geth but the balance didn't change and still showing 0 after sync, should I re-sync?


texts: Handling of orphaned/dropped transactions

texts:
I'm curious as to what happens to transactions in orphaned blocks and what happens when a transaction gets dropped.

Transactions in orphaned blocks

They appear when a soft fork happens. All the transactions in the orphaned branch return to the mempool keeping their transaction ID and might eventually be included in some block.

Dropped transactions

A transaction can be dropped if it spends to much time in the mempool without being accepted by any miner (as was the case with some transactions a while ago when the Cryptokittes app congested the network and raised gas price). In that case the transaction needs to be resubmitted and is granted a new transaction ID

Could you comment on my bold statements and correct them if they are wrong? Also, what is the criteria to drop a transaction from the mempool?


texts:
I am new to the development of DApps on ethereum blockchain. I want to make a contract Management System in which users can generate their own tokens and crowdsale using my web application. I am able to interact with an already deployed contract but I don't know

how some one can deploy their crowdsale using my DApp.
I have no idea about how to connect with the Metamask and users account using my application and finally
how to deploy that web application on server and a domain.

Any help will be appreciated. Thanks


texts:
Two contracts (code are for illustrative purposes only. Assume all syntax are correct):

contract CA
{
    function FA() public
    {
        // Invoke CB.FB() multiple times
    }
}

And

contract CB
{
    function FB() public
    {
        // require(now < 12:00pm);
    }

    function FC() public
    {
       // require(now >= 12:00pm);
    }
}

Everything executing smoothly until the following scenario:

11:55am    Invoked FA()

12:10pm    Invoked FC()

12:20pm    FA() invoked FB() multiple times, starting to receive events from FB(). Expecting some of it to fail, since some were processed beyond 12:00pm. But magically all passed

12:20pm    FC() were taken place but failed unexpectedly

Please take note that, I were running all these within a private chain. So it is processed quite fast.


texts:
I have the files from the github repo, which look primarily like client-side files.

I assume there is no backend - the client just interacts with the Etherdelta smart contracts.

The index.html file in the repo redirects to https://etherdelta.com, which is not what I need :)

What are the steps for getting set up locally?

Thanks!


texts: How to get the returned value of a smart contract function when it called by using cacheSend() in drizzle

texts:
I just tried to build a simple DApp using truffle, react and drizzle. My question is how to get the returned value of a smart contract function when it called by using cacheSend() in drizzle? As expected when Calling cacheCall() and cacheSend() functions on a contract, they should send the desired transaction and return a corresponding transaction hash.

In my code, cacheCall() sends the desired transaction and returns the corresponding transaction hash and when I console.log it it shows on the console. so there is no problem with cacheCall()

// this works fine
const dataKey1 = contract.methods.GetNumber.cacheCall();
console.log(dataKey1);

But cacheSend() sends the desired transaction but does not return the corresponding transaction hash !! Instead it returns the value 0 when I console.log the cacheSend() return value

// this does not work
const dataKey2 = contract.methods.setNumber.cacheSend(3);
console.log(dataKey2);

Here is the smart contract:

pragma solidity ^0.5.0;

contract Test {

    uint public number = 10;

    function setNumber(uint _x) public returns (uint)
    {
        number = number+_x;

        return number + 5;
    }

    function GetNumber() public view returns (uint)
    {
        return number;
    }
}

The front end should looks like the following:

The return value of GetNumber function = 13
The return value of setNumber function = 18

This is the code

import React from "react";

class TestDrizzle extends React.Component {
  state = { dataKey1: null, dataKey2: null };

  componentDidMount() {
    const { drizzle, drizzleState } = this.props;
    const contract = drizzle.contracts.Test;

    // let drizzle know we want to call the `GetNumber` method with `value`
    // this works fine
    const dataKey1 = contract.methods.GetNumber.cacheCall();
    console.log(dataKey1);

    // let drizzle know we want to call the `setNumber` method with `value`
    // this does not work
    const dataKey2 = contract.methods.setNumber.cacheSend(3);
    console.log(dataKey2);

    this.setState({ dataKey1, dataKey2 });
  }

  render() {
    // get the contract state from drizzleState
    const { Test } = this.props.drizzleState.contracts;

    // using the saved `dataKey1`, get the return value of GetNumber function
    const result_1 = Test.GetNumber[this.state.dataKey1];

    // using the saved `dataKey2`, get the return value of setNumber function
    const result_2 = Test.setNumber[this.state.dataKey2];

    return (

        The return value of GetNumber function = {result_1 && result_1.value}{" "}
        {
}
        The return value of setNumber function = {result_2 && result_2.value}

    );
  }
}

export default TestDrizzle;

I would be grateful if you could have a look at my project https://github.com/fbalwy/Drizzle-tutorial.git


texts: Deploying Smart Contract On Infura (Kovan Testnet) Using Web3 & Truffle HDWalletProvider

texts:
For better or worse, I'm following a tutorial from late 2018 to help me understand how to deploy a smart contract on Kovan testnet. I'm aware versioning might be an issue, so before I show the deploy.js here is my package.json:
"dependencies": {
    "ganache-cli": "^6.10.2",
    "mocha": "^4.1.0",
    "solc": "^0.4.25",
    "truffle-hdwallet-provider": "0.0.3",
    "web3": "^1.0.0-beta.26"
  },

My .env:
WALLET_SEED="some 12 word seed phrase"
INFURA_ENDPOINT="https://kovan.infura.io/v3/PROJECT_ID"

The deploy.js:
const dotenv = require("dotenv").config();
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');

const provider = new HDWalletProvider(
  process.env.WALLET_SEED,
  process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);

const deploy = async () => {
  const accounts = await web3.eth.getAccounts();

  console.log('Attempting to deploy from account', accounts[0]);
  const result = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({ data: bytecode, arguments: ['Hi there!']})
    .send({ gas: '1000000', from: accounts[0] });

  console.log('Contract deployed to: ', result.options.address);
}

deploy();

The compile works correctly, but when I deploy I get the following error:
UnhandledPromiseRejectionWarning: Error: Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 10000000000000000 and got: 0.
    at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/web3.js:15:44
    at XMLHttpRequest.request.onreadystatechange (/Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/truffle-hdwallet-provider/node_modules/web3/lib/web3/httpprovider.js:118:13)

I definitely have 1 ETH in my Kovan wallet. The interesting thing is this: When I query my wallet in the following code I get the following output:
const balance = await web3.eth.getBalance('0x...............actualaccount');
console.log(balance)
// => 1000000000000 etc.

But when i query the accounts variable generated by the Web3 provider from my mnemonic phrase I get a completely different account:
const provider = new HDWalletProvider(
  process.env.WALLET_SEED,
  process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);

const accounts = await web3.eth.getAccounts();
console.log(accounts)
// [ '0x..............XYZ']

When I check the funds in the account that web3 constructs for me, I confirm that the balance is indeed 0:
const balance = await web3.eth.getBalance('0x...............XYZ');
console.log(balance)
// => 0

But when I hard-code my actual wallet address into the deploy script as such, it tells me the account does not exist!
const result = await new web3.eth.Contract(JSON.parse(interface))
 .deploy({ data: bytecode, arguments: ['Hi there!']})
 .send({ gas: '1000000', from: '0x.................actualaccount' });

(node:93528) UnhandledPromiseRejectionWarning: Error: Unknown address - unable to sign transaction for this address: "0x.....................actualaddress"
    at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:185:35
    at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:207:5


texts: Truffle: how to setup some smart contract's attributes before writing test

texts:
For example I have a smart contract with 2 attributes:

contract SimpleSmartContract {
    uint256 currentPrices;
    mapping(uint8 => uint256) public priceIncrements;
}

When I write test, I want to test some situations (depends on the state of attributes). My question is: How can I setup data for those variables before running tests. (i.e: set currentPrices to 100, and set up map to some data before).

Thanks


texts:
I have deployed contract successfully. I am getting below error when I pass array from JS to contract function.

[JSON RPC 2.0 Error] Message Id: 1, (INTERNAL_ERROR) - Error when transacting: Input out of bounds
[Error: Error when transacting: Input out of bounds]
Error callback from sendTransaction
[Error: Error when transacting: Input out of bounds]

Array in JS is

 data = ['123','4352','54321','76287'];

Array type in solidity is bytes32.

I am clueless why I am getting this error.


texts:
if (typeof window.web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
    } else {
        // set the provider you want from Web3.providers
       window.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/api_key"));
    }
     web3.eth.defaultAccount = "0x37273441D1ecac689220bE6934Cfb8b8B1e85Ca9";
     var StudentContract = web3.eth.contract([{"constant": false, "inputs": [{"name": "Key", "type": "bytes32"}, {"name": "Rollno", "type": "uint256"}, {"name": "Name", "type": "string"}, {"name": "Age", "type": "uint256"}, {"name": "Branch", "type": "string"}, {"name": "Internal_marks", "type": "uint256"}, {"name": "External_marks", "type": "uint256"} ], "name": "StoreDocument", "outputs": [{"name": "success", "type": "bool"} ], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"name": "", "type": "bytes32"} ], "name": "document", "outputs": [{"name": "Rollno", "type": "uint256"}, {"name": "Name", "type": "string"}, {"name": "Age", "type": "uint256"}, {"name": "Branch", "type": "string"}, {"name": "Internal_marks", "type": "uint256"}, {"name": "External_marks", "type": "uint256"}, {"name": "Internalstatus", "type": "string"}, {"name": "Externalstatus", "type": "string"} ], "payable": false, "stateMutability": "view", "type": "function"} ]);
     var Student = StudentContract.at('0x93D030A5e74d8d5e142DF5d3e974dDF8CF1cf3D3');
     console.log(Student);
     $("#button").click(function() {
     var key = $('#key').val();
  var roll_number = $('#roll_number').val();
 var name = $('#name').val();
 var age = $('#age').val();
 var branch = $('#branch').val();
 var internal_marks = $('#inter').val();
 var external_marks = $('#exter').val();
     Student.StoreDocument( key, roll_number, name, age, branch, internal_marks, external_marks, {from: web3.eth.defaultAccount,gas:3000000});
    console.log(Student);
});


texts: Recommendations for setting ERC20 token totalSupply and decimals?

texts:
Looking through the Ethereum.org token tutorials.Any advice or recommendations on setting your total supply and decimals?

Inline comments says:

  18 decimals is the strongly suggested

Any specific reason for this?

uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it

uint256 public totalSupply;

Any thoughts here would be appreciated. Thank you!


texts:
I'm developing an application using smart contracts. I wonder if it is possible to establish different states for a contract, for example:

User 1 determines a condition X, but also determines that user 2 can change this condition.
User 2 finds it necessary to change the conditions of the contract, so it changes condition X from the contract to condition Y.

In order to satisfy this situation I have considered using public key cryptography, where user 1 determines that certain private keys can make changes to the contract condition.


texts: Will be a ring signature scheme possible to implement at Ethereum?

texts:
It's been quite a few days I'm wondering if a Ring Signature Scheme (like Monero (XMR) has) can be implemented on Ethereum blockchains.

As far as I know, that will be so nice in order to increase anonymity (but understanding that it won't be totally anonymous because the signs will be done by groups ob Pub. Key Hashes, not all of them (which will make it totally anonymous).

As I see it, the PoW -> PoS pass will be a nice moment to implement that kind of changes.

If someone knows any paper/article related with that, fill free to share please.

Thanks.


texts:
I am using a string utility library for Solidity with the aim of splitting a string on a specific delimiter. I followed the instructions from the library:

var s = someString.toSlice();
var foo = s.split("-".toSlice());

logString(foo);

However, I'm getting an error with the logString(). The online Solidity IDE says

TypeError: Invalid type for argument in function call. Invalid implicit converstion from struct strings.slice memeory to string memory requested.
    logString(foo);
              ^-^

How can I properly print out the sliced portion of the string?


texts: Will my custom token increase the number of unit after deployed the contract?

texts:
I follow the example here, I can input an initial supply, let say 1,000,000 is my initial supply.

After 1 or 2 years, the miner mine, will the total number of token increased to 1,000,xxx?


texts: How is the Etherscan TokenTracker able to show holder balances?

texts:
How is the Etherscan TokenTracker able to show holder addresses?  The balances mapping of your average ERC20 token cannot be iterated over by index, nor can the length of the mapping be obtained.  So how might holder address information be available to Etherscan?

For example, you can view the Gnosis TokenTracker here and confirm a list of holders.

https://etherscan.io/token/Gnosis#balances

Next, if you view the contract source, you'll see that there's no code that explicitly returns the holder address by way of reference to mapping (address => uint256) balances or anything else.  (At least not that I can see.

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

Many thanks in advance for your help.


texts: Send a proportional amount of ETH to every token holder

texts:
I am creating a token, of which I can mint an unlimited amount. I will sell them to people.
Then I need to send another token, or ETH, to every holder of my token.
The amount sent should be proportional to the amount of token they hold.


texts: filter doesn't trigger events for my contract

texts:
I have a trivial contract and I want to get notification of all events for the contract. But I don't see any events being called for my contract:

contract MainContract{
    event Evt(address indexed _sender,string jsn);
    function deposit(string jsn) returns (int256) {
        Evt(msg.sender, jsn);
    }
}

var contract = web3.eth.contract(abi).at("0xe45866ac5d51067ce292bc656c790e94ddcf0766");
        web3.eth.filter({},function(err,res) {
            console.log("on filter",res.address);
        });
        contract.deposit('hello there',function (res) {
            console.log(arguments)
        });

You can see in console that deposit() worked successfully, but no callback calls matching my address call present in console. Why is this? Is this expected behaviour?


texts:
I see the following error:

TypeError: Type String Memory is not implicitly convertable to
expected type adress while trying to execute

with the following code:
pragma solidity >=0.4.18 <0.5.13;

contract KYC {
   struct Customer {
      string userName;
      string customerData;
      address Bank;
   }
   mapping (address => Customer) customers;
   address[] public customersArray;

 struct Bank {
      string Name;
      address ethAddress;
      string regNumber;
   }
   mapping (address => Bank) bank;
   address[] public banksArray;

    function addCustomer (address _address, string memory _userName, string memory _customerData, address _bank) public {
        Customer storage customer = customers[_address];

        customer.userName=_userName;
        customer.customerData=_customerData;
        customer.Bank=_bank;

        customersArray.push(_address) -1;
    }

   function getCustomer(string memory uName) view public returns (string memory) {
        Customer storage customer = customers[uName];
        return customer.customerData;
    }

}


texts: Encode constructor arguments used when deploying a contract

texts:
How can I encode the constructor arguments when deploying a contract?

Here is my deployment function:

async function deploy(abi, bin, args) {
    let contract = new this.web3.eth.Contract(JSON.parse(abi));
    let transaction = contract.deploy({data: "0x" + bin, arguments: args});
    let handle = await this.send(transaction);
    return new this.web3.eth.Contract(JSON.parse(abi), handle.contractAddress);
}

Inside this function, I can do the following:

console.log(transaction.arguments);
console.log(transaction.encodeABI());

The 1st option just prints the values of the arguments as is.

The second option prints the entire byte-code.

My encoded arguments indeed appear at the end of this byte-code.

But since I don't know the length of this suffix, I cannot easily "cut it" out of the byte-code.

One option I have in mind, is that the length of this suffix is 64 * args.length, since every argument is padded to 256-bits (64 hexadecimal digits).

But I don't think that this will work when some of the arguments are strings or arrays.

Is there any standard solution for this in web3.js?

Thank you!


texts: Should INITIAL_SUPPLY & totalSupply be returned in Wei?

texts:
I was wondering if a token implementing ERC20 should return Values in Wei or Ether. Assuming I'm creating ABC token with a 100000 Token Supply & 500 ABC = 1 ETH.

In the ERC20 protocol, for INITIAL_SUPPLY & totalSupply() should we return a wei value of 100000 that would be 100000e18? Also, after deploying, sending 1 ETH to the contract gives out 500e18 tokens

How will the exchanges & other wallets display this? Is this something to be handled in the code?

Any help appreciated.


texts: How to get amount of token0 and token1 deposited by me using uniswap v2 API?

texts:
Using uniswap, I want to check the amount of token0 and token1 deposited by user.
For instance, user created pair Token0/Token1 in Uniswap.
First, user input amount of Token0 and Token1.
When start trading and used user's token, the remaining amount would be changed.
(I think it seems that the remaining amount is called reserve.
If someone knows about this, please help me.
Thank you


texts:
Ethos rookie problem.

Running ethos 1.2.2.

uname -a
Linux d0c6fe 4.8.17-ethos38 #3 SMP Sun Apr 30 07:16:13 CDT 2017 x86_64 x86_64 x86_64 GNU/Linux

Mining starts but there is a 0.0 hashrate.  Getting this error:

/opt/miners/claymore/claymore: error while loading shared libraries: libOpenCL.so.1: cannot open shared object file: No
such file or directory

Here is the directory.

07:24 PM ethos@d0c6fe 192.168.1.112 [miner started] /opt/miners/claymore # ls
claymore     Data1b1.bin  Data1e1.bin  Data1g2.bin  dpools.txt     History.txt    start.bash
config.txt   Data1c1.bin  Data1e2.bin  Data3.bin    epools.txt     License.txt
Data1a1.bin  Data1d1.bin  Data1g1.bin  Data.bin     ethdcrminer64  Readme!!!.txt

Thanks in advance for any suggestions to get this rig going.


texts: What are the types of nodes in Ethereum?

texts: I have seen the usage of the word full node many times. What exactly is an Ethereum full node? What are bootstrap nodes and light nodes/clients? Are there any other types of nodes?


texts: Is it possible to run the Ethereum Wallet with a remote Blockchain?

texts: To run the Ethereum Wallet on a small computer like a Phone or a Netbook it would useful to have a light client, possibly that connects to a hosted full Ethereum node. Is this currently possible?


texts: No response from live networks except ganache when interacting with truffle-contract

texts:
I am developing a Web3 app for a private Ethereum network. Throughout the development I used ganache-cli and now I wanted to test in the private live network. I can successfully interact with the network at the ganache network.

I deployed the contract successfully to the live network. I see the transaction being mined successfully and my data being written but I don't get any response from the node.

What I do: I add my object first to blockchain and then to DB. However, I don't receive a tx receipt from the live network. I also tested Rinkeby network and don't get any response either.

Here's the code:

export const addReview = (data) => {
  let chainData = {
    // chain data
  };
  return getCurrentAccount().then((address) => {
    let dbData = {
      address: address,
      // db data
    };
    return connection.addReview(chainData) // connection.addReview code below
    .then((tx) => {
      console.log(tx);
      return post(`/reviews/${address}`, dbData) // Write to DB through backend
        .then(dbResponse => dbResponse.json())
        .then((dbJson) => {
         // return response
        });
    })
    .catch((err) => console.log('Error adding to the blockchain\n', err));

Calling the function I get tx response when writing to ganache network and see console.log(tx) output. Using live network or Rinkeby I don't see console.log(tx) output or the error output. The Promise seems to be hanging.

Here's the contract call code connection.addReview

import TruffleContract from '@truffle/contract';
import ReviewStorageArtifact from '../contracts/ReviewStorage.json';

export const addReview = async (review) => {
  let [instance, accounts] = await init();
  return instance.addReview( //review data
    ,{ from: accounts[0] });
};

async function init() {
  const web3 = await getWeb3();
  const ReviewStorage = TruffleContract(ReviewStorageArtifact);
  ReviewStorage.setProvider(web3.currentProvider);
  let instance;
  let accounts;
  try {
    instance = await ReviewStorage.deployed();
    accounts = await web3.eth.getAccounts();
    return [instance, accounts];
  } catch (e) {
    console.log('Error in deploying contract');
    console.error(e);
  }
}

The contract code, compilers, and EVM versions are exactly the same. I use @truffle/contract to interact with the contract. I suspect this to be the issue.

Edit: I tried at home and now it works for the live and Rinkeby network.


texts: How to do an air drop to all ETH token holders?

texts: Say I have an ERC20 token and I want to distribute it 1:1 to all ETH token holders at a given block. Is there a straight forward way to make a smart contract that anyone could call in order to receive their tokens?


texts: Creating new proxy using Zeppelin OS always use the same amount of gas

texts:
I'm building upgradeable infrastructure for the project and noticed that creation of proxy using Zeppelin OS always uses the same amount of gas.

How I understand, during the setting implementation to a proxy, it copies all storage of contract with the implementation. Logically, a different amount of gas should be used because of the different size of the data, but it always uses 592.000 of gas

Could anybody explain this?

Thanks!


texts: How to connect another node to my own private network?

texts:
i have followed this guide and set up my own private blockchain. Now the only node that mines and sets smart contracts is my own computer, but I want to connect another computer to my network. How do I do that? And not just for mining, but to be seen in Mist, too (to participate in smart contracts).

Also a "bonus" simple question - the guide says to download the entire Ethereum blockchain and then set up a private network, but i don't understand why download the entire blockchain, when youre in the end setting up your private network anyway? Isn't the guide wrong?


texts: Working with 0.4.4 version of solidity, still got error, "Member 'transfer' not found or not visible after argument-dependent lookup in address."

texts:
According to some resources, this well known error occur because of versions 0.4.X to 0.5.X change.

Previously I compiled contract with ^0.5.1, to solve this error currently I'm using 0.4.4. But still the error is there.

  fundsWallet.transfer(msg.value);

Error:

  Error: Member "transfer" not found or not visible after argument-dependent lookup in address
          fundsWallet.transfer(msg.value);
          ^------------------^

I have also changed my declaration,
from:

address public fundsWallet;

to

address public payable fundsWallet;

still error is:

  Error: Expected identifier, got 'Payable'

How can I fix this issue in version ^0.4.4 as well as ^0.5.1?


texts:
I just found out about the token swapping function of MyEtherWallet: https://kb.myetherwallet.com/en/swap/swapping-via-kyber-bity-changelly/

Now, let's say I have a lot of ERC20 tokens that I want to swap for ETH. Is there an upper limit to the amount from which I can swap? If someone obtained a massive stash of ERC20 tokens (for example, tokens that are worth billions in total), can he or she swap them directly for ETH?

EDIT: I'm asking this question because I've heard that a lot of scam token developers assign a lot of their newly created tokens for themselves, and then dump them on the market. Sometimes, the dev can dump billions or trillions of these scam tokens for profit. I'm wondering if these people can just insta-dump trillions of tokens by simply swapping them on MyEtherWallet, or is there an upper limit to the amount which they can swap?


texts: How to avoid using tx.origin when we really need it?

texts:
It's been recommended that we should avoid using tx.origin.

However, there're some cases it's really needed, like the following case.

Assume we have two smart contracts: Sc1 and Sc2, both of which are created by the same owner. It first  deployes Sc1 that maintains a token balance. Then, the owner creates another smart contract Sc2, deploys it and allows users to interact with Sc2, and transfer some of their tokens from Sc1 to Sc2 (so assume some users have tokens in Sc1). But only the token owners should be able to do that not anybody else (not even the contracts owner).

As you can see below I have to use tx.origin. I'm aware that if the contracts owner creates another invalid contract and make the user (token owners) call it then it will be able to decrement their token_bsalance in Sc1. Below is the code for the above case (the attack is excluded).

   contract Sc1{
      mapping (address => uint) token_balance;
      mapping (address => bool) valid_caller_contracts;// keeps track
                                                      //of those contract that can call this contract
      address owner;
      function Sc1(){
        owner = msg.sender;
      }
       // only owner must be able to register.
      function register_valid_contract() external {
          require(tx.origin==owner);
          valid_caller_contracts[msg.sender] = true;
      }
      function decrement_token(uint val) external{
        require(token_balance[tx.origin] >= val);
        token_balance[tx.origin] -=val;
      }
   }

   contract Sc2{
     mapping (address => uint) token_balance2;
     address owner;
     function SC2(){
        owner = msg.sender;
      }
      function register() external{
       Sc1 c1=Sc1(0x22);//Let's assum the address of Sc1 after it's
                        //deployed is 0x22
       c1.register_valid_contract();
      }
      // only those who have tokens in Sc1 must be able to tranfer
      //tokens to Sc2.
      function fetch_tokens(uint val) external{
       Sc1 c1=Sc1(0x22);//Let's assum the address of Sc1 after it's
                        //deployed is 0x22
      c1.decrement_token(val);
      token_balance2[msg.sender] += val;
      }
    }

Question: In the above case, can we avoid using tx.origin?


texts: what type of encoding is used by the abi specification in solidity

texts: the abi specification of solidity which provides functions like abi.encodePacked() using a certain type of encoding (eg: for functions, a 4 byte function signature hash followed  by encoding of parameters). My question is, is there a name for such a particular encoding format? Are we using RLP encoding? If not, why can't RLP type encoding be used for abi specification? From what I understand RLP is more "self describing" and might possibly not require an abi file as a descriptor.


texts: "onlyOwner" Function restrict the call from child contract

texts:
I have a basic knowledge of solidity. I am trying to create an upgradable ERC20 Token. For that, I create TokenStorage contract and Logic contract and trying to write the Proxy contract.

In the Logic contract:

pragma solidity ^0.4.24;
import "./TokenStorage.sol";
import "./SafeMath.sol";
import './Ownable.sol';

In the TokenStorage contract:

function addTotalSupply(uint256 _value) public onlyOwner {
    totalSupply = totalSupply.add(_value);
}

When I call balances.addTotalSupply(_amount) from Logic.mint(), I get error.

If I remove onlyOwner in addTotalSupply, it executes correctly.

Note All contracts are deployed using the same account.

Please help me to understand why this happens.

Please Share me a proper guide to creating an upgradeable ERC20 Token is much appreciable

Thank you.
Sorry for my bad English


texts: How to store data in the ethereum blockchain?

texts: In my application, I need to store my data in the blockchain so that the data is transparent and everyone can see the data. How to store the data so that everyone can see the data? Could anyone help?


texts: Under the hood, what happens in an unbounded loop? let's say I'm trying to send tokens to an infinite amount of addresses and end up with an out of gas error. Will the function which executes the transfers complete transfers successfully until it runs out of gas, or will it 'build-up' and revert all of them at once.


texts:
So, I am new to the entire crypto currency idea although, I am a software developer and I have been planning for years to create a CRM that is fully autonomous and exceptionally secure. Ether's code will allow me to do just that through blockchain.
This is something I have been working for the past 2 years and once I have a demo. I will be more than happy to share it with you when the demo is ready.

Although, I have been introduced to the idea of POS and although it does add a layer of security I was thinking.... that many miners might abandon the daily mining hence, the CRM app that I am planning might stop performing if there is no miners to handle the request.

As I said, I am new to the whole idea of BlockChain and I might have misunderstood the whole “POS” concept when it comes to the miners.

Try to give me some insight. Thank you in advance.


texts: Seems that my EtherWallet Private Key takes me to a different account that doesn't show my correct Etherscan/Private EtherWallet address in Acct. Info. It instead shows my AION address (happened when I tried to use the AION Bridge two days ago) as my unencrypted Private Key address. I can still access my Etherscan using a URL address I stored and it has my correct "public address". How do I now transfer my Etherscan coins to a different EtherWallet or gain access to my original EtherWallet?


texts:
I'm compiling a contract with solc and I'm getting something like this (I replaced most of the hexadecimal digits with three dots to make it shorter):

608060405234801561001057600080fd5b5060008054600...152905173__whitelist.sol:AddressSet______________91637ab6b0b491604480830192...0029

The thing that seems to be causing troubles is __whitelist.sol:AddressSet______________ because when I deployed the contract in Ethereum, when I check the transaction, only the code up to that string is taken. Everything else is discarded.

When I deploy the contract using Remix, the binary looks good, without those strings in the middle.

Here is the command I'm using to compile the code:

solc --optimize --pretty-json --combined-json bin,abi whitelist.sol

Do I need to use a special flag to avoid that?


texts: Testnet blockchain inconsistencies - geth diverged from original blockchain?

texts:
I'm using go-ethereum instance: Geth/v1.5.9-unstable-fa999861/linux/go1.7.4. I cloned it from github (commit: fa99986143fe3dec08cdffcff9185e3700719edd).

On Feb, 6th I synchronized with testnet via ./build/bin/geth —-testnet —-fast —-cache 1024 -—rpc -—ws. After successful sync, eth.syncing started to return false. I created a new account via web3 API calls. I used the faucet twice to fund the account.

The transactions/balances were not visible in testnet.etherscan.io, though after some time, the balance of the account (visible via eth.getBalance(eth.account[0])) increased from 0 to 2 ethers.

On Feb, 7th I ran ./build/bin/geth -—testnet --cache 1024 —-rpc —-ws to start geth. Via another console (geth attach) I created a second account. I used the faucet again and funded both accounts with 1 ether each. Now, the transactions showed up in testnet.etherscan.io, but I could not see the balance increase via eth.getBalance. I even made a transaction between the accounts, which is reflected both in the blockchain explorer and also via eth.getBalance calls.

The weird thing is that, compared to etherscan, I'm lagging behind in terms of number of blocks. I'm connected to 1 peer only, plus I see:

I0207 23:37:00.459143 eth/downloader/downloader.go:723] Peer 2335d4125a0c5f6f [hs 0.00/s, bs 0.00/s, rs 0.00/s, ss 0.00/s, miss    0, rtt 20s]: potential rewrite attack: #394279 [00000000…] <= #394279 limit

I0207 23:40:04.500520 eth/downloader/downloader.go:723] Peer 995c53d7b78fcf82 [hs 0.00/s, bs 0.00/s, rs 0.00/s, ss 0.00/s, miss    0, rtt 20s]: potential rewrite attack: #394279 [00000000…] <= #394279 limit

[...]

I0208 00:58:21.335954 eth/downloader/downloader.go:623] Peer 16ab7523de2c0967 [hs 0.00/s, bs 0.00/s, rs 0.00/s, ss 0.00/s, miss    0, rtt 20s]: head header set (item 0) broke chain ordering: requested 484431, got 484446

in the logs. While checking example blocks, I have the feeling that I diverged from the original blockchain:

eth.getBlock(484634).hash
“0xc8016bca08924e45d5aa4a2f58ef824e8c1a4238be22ce4eaa16411c102f10cb"

vs.

https://testnet.etherscan.io/block/484634
0x79a96fcaddfd584e3f5b1b4057a1af53418234bc662a4297599487af01e34277

In summary:

+=================================+================================+=====================================+
|          Time, Action           |              geth              |              etherscan              |
+=================================+================================+=====================================+
| Feb, 6th - Testnet fastsync     | -                              | -                                   |
+---------------------------------+--------------------------------+-------------------------------------+
| Feb, 6th - Account creation     | -                              | -                                   |
+---------------------------------+--------------------------------+-------------------------------------+
| Feb, 6th - 2x faucet            | 2 ether                        | 0 ether                             |
+---------------------------------+--------------------------------+-------------------------------------+
| Feb, 7th - 2nd account creation | [2 ether, 0 ether]             | [0 ether, 0 ether]                  |
+---------------------------------+--------------------------------+-------------------------------------+
| Feb, 7th - 2x faucet            | [2 ether, 0 ether]             | [1 ether, 1 ether]                  |
+---------------------------------+--------------------------------+-------------------------------------+
| Feb, 7th - tx                   | [1.99957999, 0.00000001 ether] | [0.99957999 ether, 1.00000001 ether |
+---------------------------------+--------------------------------+-------------------------------------+

Where do the inconsistencies come from? Why is my transaction visible locally via geth, though I'm not synchronized with the correct blockchain anymore?


texts: What is the max possible supply for a new cryptocurrency on the Ethereum blockchain?

texts: Would it theoretically be the Javascript Max Safe Integer?


texts: what is the difference between hard cap and soft cap in ethereum ICO

texts: Please someone provide me details about the hard cap and soft cap in ICO. I have to build an ICO with an hard cap. How do I implement it in a smart contract using solidity? Provide me concept behind the hard cap so I will implement the same in a smart contract.


texts: Watching the transaction of an external account using smart contract

texts: Is their any way to execute a function of smart contract whenever a transaction to a predefined external account occurs? I mean if someone transfers some ethers to account A, a function of a smart contract can store some values of that transaction. I want to do it using smart contract only not using any wrapper around this. Please suggest.


texts: Promise pending while calling a function from contract using web3

texts:
I have deployed a contract for producing hash :

Contract Hash
{
  function sethash(string id)public pure returns(bytes32)
  {
    return(keccak256(id));
  }
}

Now I am calling this function using web3js

    var Web3 = require('web3')
var web3 = new Web3('https://rinkeby.infura.io/infura_key')
var contract = new web3.eth.Contract(HashABI, 'HashAddress')
var number
number = contract.methods.sethash("123456789").call()
console.log(number)

But instead of giving me hash it is showing :

     Promise { <pending> }


texts: Do nodes lose connectivity if no network activity is happening?

texts:
I have a private blockchain that seems to work great, but over 18 hours, the nodes stop talking to each other, no matter how many I start with.  So they go from 25/25 connections to 0.

Something I don't have is any real work being done on the network.  There are miners, but nothing substantial to mine since I'm not deploying any contracts.

Could this lack of real work be the reason the nodes lose connectivity?  It's not a networking problem.  The boxes can ping each other.

If it matters, I'm using Parity.


texts: 'authentication needed: password or unlock' Error when trying to call smart contract method via web3

texts:
I am trying to call the smart contract method (deployed on remote ethereum account) from my nodejs DAPP, and getting the following error-

Error: authentication needed: password or unlock
    at Object.InvalidResponse (D:\dapp\node_modules\web3\lib\web3\errors.js:38:16)

My web3 DAPP code looks like this-

var ABI = [abiinterface];
var contract = web3.eth.contract(ABI);
var contractInstance = contract.at(accAddress);

I have run the unlock code on my geth console using-
personal.unlockAccount("address") which returned true, but still getting the 'authentication needed: password or unlock' error in the dapp.
Any help or pointers are much appreciated. Thanks.


texts:
Are the dynamic arrays of type memory fixed sized. I have read that the arrays of type memory are fixed sixed.

Thanks


texts: What percentage of Ethereum addresses that currently have an ETH balance, also have DAO Tokens?

texts:
I read a comment elsewhere that insinuated that the population of DAO Token Holders was a tiny subset of the Ethereum community. My impression is that this isn't the case, but I have no way of knowing. I also have no idea of how to figure this out.

Ideally, data from ~June 1st (after creation period, before everything went down) to determine this, but I'll take whatever you can give me.


texts: Is it feasible to perform signing with a private key inside a smart contract?

texts:
Is it possible/feasible to have a private key stored inside a smart contract and sign transactions with it or would the calculations be to pricey in gas?
For example a smart contract should create signed transactions and the costs should be not much more than the transaction cost itself


texts: Is there any way of creating ERC-1155 or ERC-721 tokens always earn transaction fees?

texts:
I have a rather interesting but challenging question. I want to create ERC-1155 and ERC-721 tokens that will be primarily traded using a Decentralized Exchange (DEX) implemented for a newly created protocol. However, I want to allow those tokens to be traded on external DEXes such as OpenSea. That is possible, no question about, but my question relates to protocol fees earned on transactions.
Is there a way of accruing protocol fees on transactions (trades) even if they are not on the native DEX? It would seem to me it should be possible by programming the smart contract such the protocol fee is always collected, but I am not clear on how that would work practically.
Any ideas? Is there something obvious that I am not thinking about?
Possible solution
Could I implement the solution suggested by @porton as follows? This is now slightly updated to include a percentage.
contract myNFT {
    address public immutable feeAddress;
    uint256 public immutable feePercentage;

    // Set address to receive fees
    constructor (address feeAddress, feePercentage) public {
        feeAddress = _feeAddress;
        feePercentage = _feePercentage;
        }

    //******************
    // Some other stuff
    //******************

    function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable {

        uint256 private _feeAmount;
        _feeAmount = (getLastTradePrice()*feePercentage/10^18);

// This only works if sufficient funds have been provided for the fees. Otherwise the trade will fail

        address(feeAddress).transfer(feeAmount);

        //******************
        // Some other stuff
        //******************
        }
    }

getLastTradePrice() will access an Oracle managed by the protocol to track trades made on external trading platforms.
Could this work?


texts: Connecting Metamask to private Blockchain created via Puppeth (go-ethereum)

texts:
I am using Puppeth provided as part of go-ethereum. It is able to create the containers with geth, all working fine. How to send transaction into this private blockchain via Metamask. I don't see either --rpc flag or rpc port mapping to host. Can someone help connecting metamask to private blockchain created via puppeth. Thanks.

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                                                                           NAMES
6a370053beb5        Hello/bootnode      "/bin/sh geth.sh"   4 hours ago         Up 4 hours          8545-8546/tcp, 0.0.0.0:30303->30303/tcp, 0.0.0.0:30303-30304->30303-30304/udp   Hello_bootnode_1


texts:
I have a following simple contract that stores file details:

pragma solidity ^0.4.17;

contract FileDetail {
    uint fileSize;
    string fileName;
    string fileType;

 function set(uint fileS,string fileN, string fileT) {
        fileSize = fileS;
        fileName = fileN;
        fileType = fileT;
    }
}

How do I access the set method from web3 js and pass the needed parameters ?


texts: nethermind node stuck at syncing states 96.5%

texts:
I have started syncing an eth node using nethermind, and initially, the state sync process was increasing by 1% every 10 minutes (in average) and it was downloading 1200kb/s of states data. Now that the syncing is 96.5% done the node syncing process has slowed down significantly. Now it takes 24 hours per percentage, and it is downloading an average of 10kb/s of data.
Anyone knows the reason?


texts:
I've seen some suggestions from the community about managing throws in transactions using some different methods:

Don't use a throw - use events for error checking
Check using eth_getTransactionReceipt that the gas used in the transaction was equal to the gas sent (this works except when the gas used was exactly the gas sent)
Use eth_estimateGas on the transaction before sending it and checking that it doesn't return a value above some high limit (as used by chriseth in browser-solidity).

Assuming we want the state revert that comes with a throw, (1) is out.
(2) and (3) will present problems when dealing with multiple transactions sent in a short period.
For option (2), there is the problem that some transaction fails, and then all subsequent transactions are then buffered in a queue due to the nonce ordering requirements, and some filler transaction will need to be sent to plug the nonce gap.
For option (3), we get the foresight of early detection, but with a drawback. EstimateGas, when used on a transaction that calls a contract method, will run in the current state (i.e. the last mined block). Consider the following:

Tx1 updates state to state B
Tx2 requires state B, otherwise throws

If we do the following in a short period (less than the time it takes for Tx1 to be mined):

EstimateGas on Tx1, send Tx1
EstimateGas on Tx2, send Tx2

Step (2) will result in the estimateGas throwing, where in reality Tx2 would not throw when it gets mined, because it would be executed after Tx1 (due to nonce ordering) and by then the state would have been updated.

Any ideas on how to manage this?

EDIT - just noticed the JSON RPC docs do specify that estimateGas can take a block param, so assuming we pass "pending", it should mitigate some of the problems with state updates, assuming transactions relevant are available to the node.

EDIT2 - the actual code for geth in api.go only actually takes one argument:

// EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
func (s *PublicBlockChainAPI) EstimateGas(args CallArgs) (*rpc.HexNumber, error) {
    _, gas, err := s.doCall(args, rpc.PendingBlockNumber)
    return rpc.NewHexNumber(gas), err
}

This is confirmed by the error returned when attempting to send the pending block as a parameter to the eth_estimateGas RPC endpoint "too many params, want 1 got 2". It looks like the go code actually injects the pending block as the block parameter argument.


texts: What is "selector" in ChainLink API call?

texts:
I am using the example from chainlink to call an API; however, I am not sure it does.
function checkProof(string memory JobLocation, int job_id) public {
   Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOBID), address(this), this.fulfill.selector);

   req.add("get",JobLocation);

   req.add("path", "proof");

   sendChainlinkRequestTo(ORACLE_ADDRESS, req, ORACLE_PAYMENT);
}

I know it calls the following function
 function fulfill(bytes32 _requestId, bool _isProofCorrect, unit val) public recordChainlinkFulfillment(_requestId){
        customers[1].proof = _isProofCorrect;
 }

But, what does selector do in the above code (this.fulfill.selecor)?


texts: any web3 event callback to notify the account balance change

texts:
The app below is to send the eth value to the account and refresh the account balance. however the balance doesn't show immediately.

   // send the eth to the contract
   contract.methods.create(model)
                     .send({from: account,value:value })
                     .on('transactionHash', function(hash){
                               console.log('hash',hash);
                      })

   // refresh the account to see the balance
    web3.eth.getBalance(address, function (error, result) {
      if (error) {
      } else {

        }
    })

I am just wondering is there a event callback on web3 to notify the account balance change?


texts:
I have a private blockchain using Parity.  One of the bootnodes may have to change the IP.  What is the correct way to do this and what are the implications of this?

This question implies questions like these:

Is it as simple as distributing a new chain specification?

Would this be considered a fork?

What things should I look for and worry about?


texts:
I'm new to the blockchain but I'm reading every day consistently and since I am a coder I'm sure it will be a really interesting venture for me :)

Nevertheless, the whole thing started with the ideea of mining ETH. It's going to be a hobby mining (at least at the beginning).

I know how to set up my rig to mine with a pool, but I need a really safe wallet (not web-based), I found Mist should be good, but any other recommendations are welcome, and also I need to know that there exists a way for me to cash out my earned ETH from mining, in USD let's say, and then into my bank account or VISA.

How is this accomplished ? (the sending ETH from very secure wallet to a place where you can actually cash out the ETH).

thanks!


texts:
Is there any possibility for one token (e.g. Augur's REP) to
become more valuable than the total Ether market cap? If so, how would that be possible?

In Security of PoS if/when Assets (Tracked or Native) to Ethereum exceed the total Value of Ether, the security of the asset(s) whose total value is greater than Ethereum's is discussed, but not the mechanism through which such a scenario could arise.


texts:
When I request https://etherchain.org/api/difficulty using python 3.6 I get HTTPError: Forbidden. Does anyone know the solution?

import json
from urllib.request import urlopen
from pandas.io.json import json_normalize

r_difficulty_eth =
urlopen('https://etherchain.org/api/difficulty').read().decode('UTF-8')

difficulty_eth_data = json.loads(r_difficulty_eth)


texts: Ethereum - How does the smart contract get deployed via web3?

texts:
I am trying create an application using NodeJS, web3, ganache and write a smart contract with solidity on
Ethereum as a part of my final year project. Reading the documentations, I still have a few questions which I could not understand -

1) When we deploy the smart contract via web3 (server code), where does the smart contract actually get deployed? Because the JSON contract build file is still on the server, right?

2) Does every user need to have their own deployed version of smart contract?

3) If we are deploying smart contract via server for each user, wouldn't it create a bottleneck on the server? Because all the requests are going to the server first, then how is the application decentralized?

4) Do users need to install ganache, metamask, etc. if they want to connect to the application running on a private Ethereum blockchain network?

Please clarify my doubts and correct my understanding if I am wrong.


texts:
When a contributor transfers fund to my smart contract the default balance is automatically increased. Is it possible to control this default property within  our contract.

Also, will a method executed with a payable keyword effect the current balance property of that smart contract in any way?


texts: Parse contract to retrieve declared identifiers

texts:
Node.js Solidity compiler parses contract and returns its ABI, is there any library to retrieve all declared identifiers in a contract?

For example, the following contract:

contract Person {
    uint id;
    bytes firstName;
    bytes lastName;
}

Should be parsed to:

identifiers: [
  {
    type: "uint",
    name: "id"
  },
  {
    type: "bytes",
    name: "firstName"
  },
  {
    type: "bytes",
    name: "lastName"
  }
]


texts: Architecture for a simple payment system - Wallet + Infura

texts:
I'm fiddling with Ethereum a bit.
I'm trying to create a payment system using an external node provider such as Infura.
Now, of course I wouldn't leave for an external provider to hold my private keys, so I'm managing them locally on my own protected server.. But. I need a wallet software to generate and keep addresses (with a layer of encryption, of course).
I'm looking for something very simple, such as this one https://github.com/openethereum/openethereum/tree/main/accounts/ethkey
It seems simple enough to do the job. But I'm starting to wonder if I'm not taking this too far on simplicity. Is there something else I'd need to worry about? Is this tool the right one for the job or should I be considering a much more "feature-rich" wallet.


texts: Sending contract's source code to deployed contract in order to deploy it

texts:
I am writing a factory contract in solidity.
I want to be able to add some more contracts to be deployed by the factory after it has been deployed.

I thought sending the contract's source code to my factory. Stock it in a mapping with a custom key.
Then using a contract's function with the key in order to deploy a new contract from the new type.
Is it only possible please ?


texts: using private key to prove the you own this account

texts: How do I ensure that the function is performed by the owner of the account using web3.js whose instance is used to call the function, I am using ganache and I have my private keys for account .


texts:
transferFrom method from ERC20 contract interface:

function transferFrom(address _from, address _to, uint _value) public;

transferFrom function from my contract :

function transferFrom(address _from, address _to, uint _value) public returns (bool) {
  token.transferFrom(_from, _to, _value);
  return true;
}

transferFromOneToMany function with for loop transferFrom function

function transferFromOneToMany(address _from, address[] memory _receivers, uint[] memory _values) public onlyOwner returns (bool) {
  require(_receivers.length == _values.length && _receivers.length >= 1);
  for (uint j = 0; j < _receivers.length; j++) {
    token.transferFrom(_from, _receivers[j], _values[j]);
  }
  return true;
}

transferFrom function working good, I received confirmation of the transaction ( event Transfer )

transferFromOneToMany doesn't working good, I received success but transaction don't have events of transfer
e.g 0x501d19e013defcc6cc1808f75ea0cca575ab8bfb26d96a1869b4671da743e44b


texts: Get deployed contract dynamically in node JS

texts:
I am using Node JS and ethereum smart-contract. Every time contract gets deployed new addresses generated.
Is there a way that node JS always gets an updated address of a contract? Any API so that I don't have to go and update in node to connect contract through new address every time I deploy.


texts: How to split bytes32 into multiples of 8 in solidity

texts:
I want to split bytes32 into multiples of 8 (in assembly).
I have the following code(After referring here):

function testAssembly(bytes32 _msg) public pure returns (bytes8 i, bytes8 j, bytes8 k, uint256 m, bytes memory size){
      assembly {
        let i_ptr := mload(0x40)
        let j_ptr := mload(0x62)
        let k_ptr := mload(0x92)

        m := calldataload(4)
        //size := msize
        calldatacopy(i_ptr,0x4,8)
        calldatacopy(j_ptr,0x9,8)
        calldatacopy(k_ptr,0x11,8)

        i := mload(i_ptr)
        j := mload(j_ptr)
        k := mload(k_ptr)
      }
      return (i,j,k,m,size);
    }

 function testAssemblyArr(bytes32 _msg) public pure returns (bytes8 i, bytes8 j, bytes8 k, uint256 m, bytes memory size){

      bytes8[3] memory y = [bytes8(0), 0,0];

      assembly {

        m := calldataload(4)
        //size := msize         //(*)
        mstore(y,_msg)
        mstore(add(y,0x8),_msg)
        mstore(add(y,0x10),_msg)
      }
      return (y[0],y[1],y[2],m,size);
    }

I have following input (Remix): "0x1212121212121212343434343434343456565656565656567878787878787878"

Expected output(for both):

0: bytes8: i 0x1212121212121212
1: bytes8: j 0x3434343434343434
2: bytes8: k 0x5656565656565656

Observed output:

testAssembly:
0: bytes8: i 0x1212121212121212
1: bytes8: j 0x3434345656565656
2: bytes8: k 0x3434345656565656
3: uint256: m 8173559240281143207206663486900115636630769273905500857318033424334900983928
4: bytes: size 0x

testAssemblyArr:
0: bytes8: i 0x1212121212121212
1: bytes8: j 0x5656565656565656
2: bytes8: k 0x0000000000000000
3: uint256: m 8173559240281143207206663486900115636630769273905500857318033424334900983928
4: bytes: size 0x

If i change function parameter of testAssemblyArr to bytes then it gives the following output:

0: bytes8: i 0x0000000000000000
1: bytes8: j 0x0000000000000000
2: bytes8: k 0x0000000000000000
3: uint256: m 32
4: bytes: size 0x

In the above output, (Ignore m, it gives correct output if its return type is changed to bytes32). For calldatacopy() function, I used both integer and hexadecimal values but it gives incorrect values. How should i go about this to get expected results?

Also when you uncomment line *(msize), it gives "out of gas" error in ganache and crashes the browser(tab) in Remix.


texts: 12/30/17 ERC20 Sample Fixed Supply Token Contract totalSupply function

texts:
The latest Sample Fixed Supply Token Contract in the 30 December 2017 revision of the ERC20 Token Standard has some great improvements that our team was wanting to add to our contract in test. It is now 224 lines long. However, there is one function that spans across lines 126-131 in the FixedSupplyToken contract that makes no sense to us.

    // ------------------------------------------------------------------------
127     // Total supply
128     // ------------------------------------------------------------------------
129     function totalSupply() public constant returns (uint) {
130         return _totalSupply  - balances[address(0)];
131     }

Above this function, there is

uint public _totalSupply;

which provides an automatic getter function for total supply. So I don't see why this function is needed, AND the

- balances[address(0)];

makes no sense to us whatsoever. There would never be a balance to a zero address - correct?

We ask this, because we are afraid that we may be missing something - thanks!


texts: Difference between `0x01` and `0x1` status code?

texts: Sometimes when running Ganache I receive status code 0x01, sometimes 0x1. Should I treat both as successful executions?


texts: Sending value to a solidity contract method from web3 results in `Invalid Tuple Value` error

texts:
I'm sending values to a solidity 0.5.1 method using web3 and keep getting an invalid Tuple value error.

Here's the relevant contract code:

struct mystruct {
    bytes32 id;
    string str;
}

mapping (bytes32 => mystruct) structs;

function creatMyStruct(bytes32 id, string memory str) public {
    mystruct memory newStruct = mystruct(id, str);
    structs[id] = newStruct;
}

I'm calling this from node.js:

contract.methods.creatMyStruct(someId, someString).send({from: fromAccount, gas: gasEstimate})
    .then(receipt => {
       var txhash = receipt.transactionHash;
       resolve(txhash);
    },
    (error) => {
        reject(error);
    }).catch((err) => {
         reject(err);
    });

I tried sending a string, a number, and converting the string to hex. The same error: invalid tuple value. What am I missing?

EDIT: here are some of the values I tried for id, which is the one that causes the problem. The string values below were tried when the id value was defined as a string in the contract, and the numeric ones when it was defined as bytes32. I can use both, so a solution for either one would be great.

let id = '123';
id = "hello";
id = '0xabca00000000000000000000000000';
id = 0xabca00000000000000000000000000;
id = 1;
id = 12300000000000000000000000000000;
id = 'hello';

I tried both as is, or by converting to hex:

userId = web3.utils.asciiToHex(userId);

The same error is generated for all of them. Here's a bit more description in the error:

reason: 'invalid tuple value',
code: 'INVALID_ARGUMENT',
coderType: 'tuple',
value: '0x68656c6c6f'


texts:
I want to get the customers last name but i get the following error any idea how to fix that ?

And is there a way to modify my current get function so that it returns the first name and last name at once ?

  Unhandled Rejection (TypeError): _this.contarct.getLastName(...).call is not a function

React:

changeLastName(e){
e.preventDefault();
let id = e.target.dataset.somefield;
this.contarct.getLastName(id).call().then((lastName)=>{

this.setState({lastName:lastName});

}
);
}

<form data-somefield={this.id} onSubmit={this.changeLastName}>
<input type="text" name="id"/>
<input type="text"/>
</form>
<p>{this.state.lastName}</p>

solidity:

struct {
string lastName;

}
getLastName(unit256 _id)public view returns (string){
unit256 id = customersIndex[_id];
return customers[id].lastName;

}


texts: sendTransaction results in double send with arbitrary library call

texts:
I have a situation I have isolated that seems very bizarre to me and I cannot figure out. I am running truffle v1.0.2 (not latest) and testrpc v2.0.5.

When I send ETH from an account to a contract with a fallback function that calls a library function, the sending account is reduced by twice as much as the send value. When I remove the library call, it sends the expected amount. It should all be clear from the below code. What's going on?

You can clone and test it for yourself at: https://github.com/raineorshine/double-send.

Contract.sol:

import "MyLib.sol";

contract Contract {
  function() {
    // The test is showing that the balance of account[1] is decremented
    // by 200 instead of the expected 100.
    // If I remove this line, the balance of account[1] is decremented
    // by 100.
    MyLib.doNothing();
  }
}

MyLib.sol:

library MyLib {
  function doNothing() {
  }
}

test/spec.js:

describe('test', () => {
  contract('Contract', () => {
    it('send to deployed address', () => {
      const contract = Contract.deployed()
      const initialBalance = web3.eth.getBalance(web3.eth.accounts[1])
      console.log(web3.fromWei(initialBalance).toString())
      web3.eth.sendTransaction({ from: web3.eth.accounts[1], to: contract.address, value: web3.toWei(100) })

      const finalBalance = web3.eth.getBalance(web3.eth.accounts[1])
      console.log(web3.fromWei(finalBalance).toString())

      const diff = web3.fromWei(initialBalance.minus(finalBalance))
      console.log('initialBalance - finalBalance == ' + diff)

      assert(diff > 99 && diff < 101, 'Balance after is not ~100 less than balance before.')
    })
  })
})

Here is the test output:

  test
    Contract: Contract
21267647932558650071.31300778513203191
21267647932558649871.313007785132010657
initialBalance - finalBalance == 200.000000000000021253
      1) send to deployed address
    > No events were emitted

  0 passing (2s)
  1 failing

  1) test Contract: Contract send to deployed address:
     AssertionError: Balance after is not ~100 less than balance before.