texts: Looking for help with designing a private Ethereum blockchain to store information

texts:
I would like to be able to store a history of an object on a private chain and have it update-able via a website.It needs to hold public information and some hashed links to an external database. Just a simple proof of concept idea to use in a university project. Is this even possible?

Sorry, I am beginning to learn about Ethereum block-chains.


texts: Calling Smart Contract function returns tx object instead of expected return value in Truffle test

texts:
I have started writing a smart contract for a gift registry.

When I write tests using the Truffle Framework I get unexpected return values.

For example, when calling the offerGift function from within the test it returns a tx object instead of the id.

If I use offerGift.call(...) it returns the id but when I call getGift the gift can't be found, and I get the error

  Error: Returned error: VM Exception while processing transaction: revert Gift not found

I have tried the answers provided in Returns TX Object instead result in Truffle test but they didn't work for me.

Using
  Truffle v5.0.18 (core: 5.0.18)
  Solidity v0.5.0 (solc-js)
  Node v10.15.3
  Web3.js v1.0.0-beta.37
  Ganache v1.3.1
  truffle-assertions 0.9.0

What am I doing wrong?

The Contract Code

pragma solidity >=0.4.21 <0.6.0;

contract GiftRegistry {

  uint256 idCounter = 0;
  enum GiftStatus { Offered }

  struct Gift {
    string description;
    uint256 value;
    GiftStatus status;
    address giftGiver;
    address giftReceiver;
    address giftApprover;
  }

  mapping(uint256 => Gift) public giftMap;

  function doesGiftExist(uint256 _giftId) private view returns(bool){
    Gift memory gift = giftMap[_giftId];
    bytes memory giftAsBytes = bytes(gift.description);

    return giftAsBytes.length > 0;
  }

  function getGift(uint256 _giftId) public view returns(string memory, uint256, GiftStatus, address, address, address){
    require(doesGiftExist(_giftId), 'Gift not found');
    Gift memory gift = giftMap[_giftId];

    return (
      gift.description,
      gift.value,
      gift.status,
      gift.giftGiver,
      gift.giftReceiver,
      gift.giftApprover
    );
  }

  function offerGift(string memory _description, uint256 _value, address _giftReceiver) public returns(uint256) {
    uint256 currentId = idCounter;
    giftMap[currentId] = Gift(_description, _value, GiftStatus.Offered, msg.sender, _giftReceiver, address(0));

    idCounter = idCounter + 1;

    return currentId;
  }
}

The Truffle Test

const GiftRegistry = artifacts.require('GiftRegistry');
const truffleAssert = require('truffle-assertions');

contract('The Gift Registry contract', accounts => {
  let contract;
  const giftGiverAddress = accounts[1];
  const giftReceiverAddress = accounts[2];

  beforeEach(async () => {
    contract = await GiftRegistry.new({from: accounts[0]});
  });

  describe('given offerGift is called', () => {
    const OfferedStatus = 0;

    it('the status should be set to offered', async () => {
      const fiveDollars = 500;
      // Calling like this returns a tx instead of the id, the gift can be found with a hard coded index of 0
      const giftId1 = await contract.offerGift('coffee', fiveDollars, giftReceiverAddress, {from: giftGiverAddress});
      // This call returns the new giftId, however the gift can't be found and the call to getGift throws the error
      // Error: Returned error: VM Exception while processing transaction: revert Gift not found
       const giftId2 = await contract.offerGift.call('coffee', fiveDollars, giftReceiverAddress, {from: giftGiverAddress});

      const gift = await contract.getGift.call(0);

      assert.equal(OfferedStatus, gift[2]);
    });

  });
});


texts: How to build a decentralized bridge between two blockchains?

texts:
I am trying to build my own custom bridge between Ethereum and Binance Smart Chain so that people can transfer tokens and possibly some other assets from one chain to another and vice versa. For this purpose I will need three things:

smart contract in Ethereum blockchain
smart contract in BSC blockchain
some kind of oracle to maintain the communication between contracts in different chains

My question is: how to create a decentralized oracle, that can subscribe to events from one chain and cast them to contract in another chain?
I think I can use Chainlink to achieve this, but for now the only way I see is following:

User executes transaction on contract in Ethereum blockchain.
Smart contract emits event in Ethereum blockchain.
My own custom oracle detects that event was emitted and executes transaction to BSC chain in order to notify the BSC contract about the event.
BSC smart contract verifies that this particular event exists in Ethereum blockchain. For this purpose smart contract executes API request to some known provider (like Etherscan) using Chainlink mechanisms.

The thing is: I don't want to rely on any API-s in my bridge (so no Etherscan and alike). I want to rely only on blockchain events and decentralized oracles that can detect and propagate those events. Are there any existing mechanisms I can use for this matter?


texts:
I am trying to compile my smart contracts using truffle pet-shop. I have the following contract in directory election/contracts/election.sol ;

pragma solidity >=0.4.0 <0.6.0;
contract Election{
    string public candidate;
    constructor() public{
        candidate="Zeeshan";
    }
}

The migration file to deploy contracts in directory election/migrations/2_deploy_contracts1.js is as follows;

var Election1=artifacts.require("election.sol");
module.export=function(deployer){
    deployer.deploy(Election1)
};

I am using the following command to migrate the contracts:

  truffle migrate

And I am getting the following results:

Compiling your contracts...
===========================
> Compiling .\contracts\Election.sol
> Compiling .\contracts\election.sol
> Artifacts written to D:\Notes\BCS\Semester 8\FYP\Practise Coding\dapp university 2 hr video code\election\build\contracts
> Compiled successfully using:
   - solc: 0.5.8+commit.23d335f2.Emscripten.clang

Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 0x6691b7

2_deploy_contracts1.js
======================
Error: Error: Migration D:\Notes\BCS\Semester 8\FYP\Practise Coding\dapp university 2 hr video code\election\migrations\2_deploy_contracts1.js invalid or does not take any parameters
    at Object.run (C:\Users\mk141\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-migrate\index.js:92:1)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Truffle v5.0.30 (core: 5.0.30)
Node v10.16.1

Its also compiling Election.sol because I renamed election.sol to Election.sol and it stores election.sol in cache perhaps.

As you can see above its giving Error:Migration 2_deploy_contracts invalid or does not take any parameters at Object.run() and i don't know how to resolve it.


texts:
I'm considering different designs to implement "configuration options" with Ethereum.

The design should allow me to define arbitrary (= number and type) options, quick access to a list of options, their values, and validated change of options values.

A naive design would be one contract per config option. That would be a lot of contracts.

Right now, I'm wondering about a design where I store JSON and JavaScript code in the contract. The JSON would allow me to define arbitrary options and their values. The JavaScript could be fetched from the contract in web3.js to validate changes to the configuration.

This would, like using normal contracts, allow to share the same code base between all parties. It should be pretty efficient (unless there is a problem with huge strings?).

So far, I'm seeing two drawbacks:

I couldn't use those config options in the smart contracts directly.
A malicious party could to submit illegal values (by simply ignoring the validation)

The first one can be solved by adding extra fields in the contracts and keep the values in sync (with all the problems that brings).

The second could be mitigated by people running the validation before trusting config values.

To make this work, I'd need to use eval(). To make this secure, I need to control who can change the JavaScript fields of a contract.

Am I missing something?


texts: Is it possible to guess the public addresses generated by MetaMask from the same seed?

texts:
If more than one of my public addresses (from same seed) are known, is it possible to guess other addresses generated from the same seed?
If I used 1 seed phrase to generate 10 addresses in MetaMask. If people know 1 or more of my public addresses, is it possible guess my other public addresses from the known ones?
I know this is a similar question to this one but just want to clarify.
Guessing mnemonic phrase based on the first 2 public addresses


texts: Convert a Bitcoin private key into an Ethereum address

texts: I'm currently using the lightwallet.js for ethereum and it seems to only accept a mnemonic seed to generate an ethereum address. I want to be able to use my Bitcoin private key to generate an ethereum address. I'm able to generate a bitcoin private key using bitcoinjs library, but I can't seem to figure out how I can do this with ethereum using a bitcoin private key. Is there a specific library I need to use?


texts: address of deployed RoleManagement contract on Volta

texts: I'm trying to set up my own Origin framework and was wondering if it made sense to reuse the existing RoleManagement contract on the volta network


texts: Is there anyway to seize an account from smart contract?

texts:
I'm creating a smart contract to manage loans, and I'am looking for some way to make me sure when the borrower defaulted pay back the loan, seizing some percentage of ether from the guarantor's account.

Is this possible?

Thanks in advance.


texts: How to access txpool pending transactions using Netherum?

texts:
I want to get list of transactions which are in pending state & queued state in txpool. I can see these transactions in pool using txpool.inspect command.
I tried code given in nethereum sample code but that returns pending transactions in current block.


texts: Ethereum - Can we expect a stable job opportunity?

texts:
I am not sure if this is a right place for this type of questions.

I have done Java development and follow agile methodology. As you know we have sprints in which you would keep on releasing new features/update existing features every sprint which is normal for almost all the programming languages/frameworks we have now.

On the other hand for blockchain technologies, as the contracts are immutable, the very first time when you deploy the contract itself, should have been thoroughly tested and considered all the requirements and deploy it on ethereum network. Once it is deployed in PROD and live for months/years, there is no way to modify later as we might lose the data from the live contract.

So, I feel like we can not have agile development methodology for smart contracts.

From employee perspective, All jobs related to smart contracts development should be short-term related. We can not expect a long-term stable job opportunity!

Is that right?


texts:
I find answer how to make upgradable contract  here

How to call function from currentVersion with fallback function on web3?

    contract Relay {
    address public currentVersion;
    address public owner;

    function Relay(address initAddr){
        currentVersion = initAddr;
        owner = msg.sender;
    }

    function update(address newAddress){
        if(msg.sender != owner) throw;
        currentVersion = newAddress;
    }

    function(){
        if(!currentVersion.delegatecall(msg.data)) throw;
    }
}


texts:
Will nonce increase even when the transaction fail?

For example,

nonce=0 -> tx succeed
nonce=1 -> tx succeed
nonce=2 -> tx fail

Then I want to send a new raw transaction,
should I assign nonce as 2 or nonce as 3?

Thank you


texts: Better ways to test bytes32 type using truffle testing framework

texts:
small quick question, when I store a bytes32 and retrieve it from truffle console, why is it showing in 64 bits?

Ex: 0x74657374737472696e6700000000000000000000000000000000000000000000

because this is kinda annoying when it comes to using truffle testing framework.

assert.equal(data[1].toUpperCase(), "0x74657374737472696e6700000000000000000000000000000000000000000000".toUpperCase(), "name doesn't match");

When testing bytes32 data, I have to match an exact 64 bits hex value in order to pass. So for assert.equal's second parameter where I would enter in my predicted value, I have to manually convert a string to hex using mostly from this site, and in fact most of the string to hex sites do not show in full 64 bits. They would show it as: 74657374737472696e67.

It is annoying that I have to count the zeros and append them to match 64 bits.
Are there any handy ways to handle this?


texts: How to send transactions to smart contract in batch?

texts:
I have this smart contract function:

 function addOneUser (User memory _user) public {

         bytes32 hash = keccak256(abi.encode(_user.name));

           users[hash] = _user;

    }

Using javascript, I have an array of User, I want to send all of them to smart contract using a batch, is it possible ?


texts: How to nodes maintain when its storage is less then the blockchain ethereum network data.?

texts:
I am new to Ethereum decentralized application.I am exploring how to create decentralized application. There is no single place where is data is store.So every blockchain node has all nodes data.So every day new transaction  data is store in Ethereum blockchain.So my one question is that:-

There is one node in blockchain suppose there storage configuration is 500 gb.And ethereum blockchain transactions data is greater then the node storage configuration. So in this case how to node maintain in blockchain.

And second question is that when my one node is turn off in ethereum blockchain network.In this duration many transactions happen in Ethereum blockchain network.So, how the transaction data sync in network when the node is turn off which is in Ethereum blockchain


texts: Is attaching a name to an Ethereum address a "faux pas?"

texts:
I'm currently working on a DApp right now, and I was curious if it's considered poor design to include a string with the user's name that is mapped to a particular address. A user who has access to that user's address would thereby have access to the user's name.

Does this design serve as a  potential security breach?


texts: Is Ethereum Alarm Clock still alive and well?

texts: Lots of questions here reference Ethereum Alarm Clock as a way to schedule events.  It seems to my eye to no longer be operative.  Is that the case, or am I mistaken?  If it's isn't operative, is there another service that offers similar scheduling functionality?


texts: Convert string of integers separated by a delimiter to integer array in Solidity?

texts:
Using Oraclize, I request a some external data in the form "1 2 3", i.e., space-separated integers (OR any other delimiter).

Indeed, these numbers could be requested one at a time, but this would be EXPENSIVE.

Now, to work with these integers, I need to convert them back to integers and store them inside an array.

I know the parseInt() function for converting a string to a number, but how to I break up the string into "1", "2", "3", such that I can parse the numbers and store them in an array?


texts: Why doesn't Ethereum do double hashing like Bitcoin?  What are the facts or theories on the security of single Keccak-256 hashing like Ethereum, as compared to Bitcoin's double hashing with SHA2-256?  How about Bitcoin's use of a second different hash function (RIPEMD-160) in some cases?


texts:
I git clone the web3j and found in the fold dist there are web3.js , web3.min.js, web3-light.js , web3-light.min.js

Whats the difference between web3.js , web3.min.js, web3-light.js , web3-light.min.js?


texts: Does the term "Ethereum ECDSA signature" have a consistent meaning?

texts:
If you were writing some instructions and one of them was:

Provide the Ethereum ECDSA signature of the file using the person's
Ethereum address.

Would the above instruction have a consistent meaning (i.e. always produces the same output for a given file and address)? I ask because there appears to be subtly different implementations.
If not, what wording could you use to give it a consistent meaning? Perhaps with reference to EIPs...


texts: Does solidity support operator overloading?

texts:
Wondering if solidity supports operator overloading like python does?

Something like:

---WARNING PSEUDOCODE---

overload __+__ {
    if (type(arg1) == string && type(arg2) == string){
        return arg1.append(arg2);
    }
}

I would use this to rewrite the SafeMath library, as SafeMath adding/multiplying/etc. in a long string becomes very unreadable...

Cheers!


texts: Elegant way to detect current provider int web3.js

texts:
I want to know what provider the user is using (Metamaks, Mist...)so I can give better user experience.  E.g. Give tips on how to unlock an account

I'm currently doing this, but is far from elegant. Is there a more correct/reliable way achieve the same?

getProviderName=()=>
{
    let providerName = "UNKNOWN"

    if(window.web3.currentProvider.constructor.name === "MetamaskInpageProvider")
        providerName = "METAMASK"

    else if(window.web3.currentProvider.constructor.name === "EthereumProvider")
        providerName = "MIST"

    else if(window.web3.currentProvider.constructor.name === "o")
        providerName = "PARITY"

    else if(window.web3.currentProvider.host.indexOf("infura")!==-1)
        providerName = "INFURA"

    else if(window.web3.currentProvider.host.indexOf("localhost")!==-1)
        providerName ="LOCALHOST"

    return providerName
}


texts: ERC721 Metadata encrypted by owner's public/private key

texts:
Is there a good way to keep personal data (e.g. name, address , etc.) in the ERC721 metadata JSON, encrpyted with the public key of the owner, so that only the owner can decrypt it with his/her private key on request?
My use case looks as follows:

A user connects his wallet to a Dapp using Wallet Connect
The Dapp requests some personal data from the metadata (ERC721) which is
encrypted by the user's public key
The user confirms the request on his wallet (Wallet Connect)
The personal data can get decrypted by the user's private key


texts: Is there anyway to call Web3js or Contract methods with Non-Ethereum browser so the website could at least show some information to guest/anonymous user? I'm new to this, thanks.


texts:
There is nothing like parity console.

How to open the JavaScript console on Parity?


texts: Why do are the 'type' & 'removed' fields in receipt logs different between Ganache and Geth?

texts:
When I run a particular transaction and log the receipt, I am getting different results depending on if my EVM is Geth or Ganache.  Specifically, Ganache returns receipt.logs[0].type: 'mined' while in Geth, there is no type member of logs[0] and there is instead receipt.logs[0].removed: 'false' (the receipt from Ganache has no removed member.).  The rest of the receipt looks pretty similar between the two EVMs, ignoring member order.

Is there a reliable source about what fields my program should expect to find in an Ethereum transaction receipt?  If so, does one (or both) of these two implementations need a bug report for being inconsistent with that?


texts: Cannot send ether to a payable function in truffle unit test

texts:
I am debugging a bug happened on my truffle solidity test. I can narrow down the problem to an exception happened in the payable modifier.

my contract code:

import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";

contract MyToken is ERC721Token {
  function MyToken() ERC721Token(NAME, SYMB) public payable {
  }
  function purchase(uint256 _tokenId) public payable {
    // all the code in this function is commented out when I do the test
  }
}

my test code:

MyToken myToken = MyToken(contractAddress);
myToken.purchase.value(1000000000000000000).gas(1000000000000000000)(0);

exception:

     Error: VM Exception while processing transaction: revert
  at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
  at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
  at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
  at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
  at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
  at endReadableNT (_stream_readable.js:1101:12)
  at process._tickCallback (internal/process/next_tick.js:114:19)


texts: Invoking internal function with enough gas

texts:
I'm new to ethereum and getting my hands on contracts (in solidity). I think I have a very simple question but I can't for the life of me find the answer.

Simply put: How to I invoke an internal function with enough gas, if it's complex?

Example: Imagine I'm setting up a savings system for my children. They can deposit ether to the contract, and after 10 years their savings will be paid back - but to encourage them, there will be a bonus pool of ether in the contract. The kid who have deposited the most ether will also get the biggest chunk of the bonus pool. They may send from different wallets, so the contract keeps track of their names as well.

Example contract code:

contract Savings
{
    struct Deposit
    {
        string name;
        uint deposit;
    }

    uint        cEnd = now + 10 years;
    address[]   dAddresses;

    mapping(address => Deposit[]) deposits;

    function depositEther(string _name)
    {
        deposits[msg.sender].push(Deposit({
            name: _name,
            deposit: msg.value
        }));
        dAddresses.push(msg.sender);

        if(now >= cEnd){
            distribute(); //CALL THIS WITH ENOUGH GAS
        }
    }

    //complex calculations
    function distribute() internal {
    }
}

(I keep running into c.sendTransaction({from: to: gas: }) but I can not get that working.

If anyone could explain this to me in a simple way, I would be very happy.


texts:
I have two contracts (A and B) in the same smart contract. When I access from B to a A's variable the value is different that I can see from A.

For instance, when I access from A to that variable has a length equal to 2 If I have inserted two values but when I access from B the lenght of that variable has a different value.

Why?


texts: I am new to all this. I didn't know that MEW could not access my password protected excel file! I deleted my UTC address because didn't like it sitting there in my folders in WINDOWS 10 FILE EXPLORER. So now I cannot repaste the UTC address in any folder. Does anyone know how to save it again  in my folder? It has an 890z extension. Thanks! somehow in my searching i came across a manual for it but now i cannot find that info. Appreciate any help here! THanks!!


texts: How to run a dapp with a backend server on Rinkeby Network

texts:
I have created a dapp which has a front end as well as a backend server.
The role of back end server is to listen to events triggered by the smart contract and execute related piece of code. So far I have tested the functionality on local Ganache only which is working fine. Now I want to deploy my entire dapp to Rinkeby Testnet. I am able to deploy the smart contract via Remix to Rinkeby but cannot figure out how to connect my backend server to Rinkeby Testnet.

Please suggest..


texts: How is verification of transformation of raw values done on the blockchain

texts:
Is there a solution to verifying a transformation of raw values on the blockchain available?

Example: You have a (private, permissioned) blockchain solution to verify how many apples you have in your storage. New apples arrive randomly every 1 to 5 minutes. Same is for outgoing apples.

After every hour that passed you want to calculate the apples that have arrived within the last hour. After every day you want to calculate the average apples that arrived per hour.

Does Ethereum (and others) solve this with Smart Contracts? What are alternative approaches?

To make it a bit more complex: let's assume the transformation itself is very complex and cannot be stored in a smart contract - like using a neuronal network that can not be replicated across all nodes. How can the other nodes confirm the transformation was done correctly and is trustworthy and store the result only on the blockchain?


texts: Ethereum contracts problems sync appdata token (ETHEREUM WALLET)

texts:
please help I have created contract and tokens with my account. After 2 days I couldn't sync and I deleted all my appdata and started resync. After it resynced I put my old keystore and my ether does show but my contract and "contract admin page" doesnt show. How do I restore this? Thank you

UPDATE
I am using Ethereum official wallet downloaded from www.ethereum.org


texts: How will I determine the number of nodes required to run my private Blockchain Network stable?

texts: I am designing a use case where millions of users will be using it and is expecting a  transaction rate of 50 per second.  I am looking forward to have it on Azure.


texts: Why account creation using CALL or SUICIDE costs 25000 gas?

texts:
CALL and SUICIDE both have additional cost of 25000 gas if it leads to account creation.
At the same time, sending 1 wei in separate transaction costs only 21000 gas.
Thereby if I am about to create account using CALL or SUICIDE, I'd better send 1 wei in separate transaction to that account and only after that do my CALL/SUICIDE stuff.
These two transactions will cost me 4000 gas less, however they will for sure generate more waste for blockchain to store.

Is there any reason for account creation pricing to be designed in such contradictory way?


texts:
I am trying to send ether to an account but the transaction is sent to my contract address. Here is the code

function send(address _account, uint amount) payable {
    _account.transfer(amount);
 }

I mined but the balance of the account does not change. I am using geth 1.5.9


texts: Error:new bignumber() not a base 16 number

texts:
I have built a private chain with two node on two computer. The smart contract was successfully deployed on node1,and i can call the method on node1 ,but when i call the same method on node2,it occur the error new BigNumber not a base 16 number

BTW,the two node have the same block number!


texts: How to use a contract address to find block/transaction hashes of block where contract was deployed using web3.py

texts:
I am new to the Ethereum blockchain and web3.py, and I'm interested in finding a way to work with a contract address to return the block and transaction hashes for the block where the contract was deployed.

I've been working with the getCode() method that's part of web3.py, but have ran into a wall. My idea is to use the block_identifier argument in some way to improve upon a sequential search of all blocks in the chain, but don't quite know the best approach.

Is there any way to utilize the getCode() method to accomplish my overall goal of returning the block and transaction hashes?

Any help or hints would be greatly appreciated. This is an assignment, therefore I'm not looking for the complete answer, just some help to get moving again.


texts: Create and sign OFFLINE raw transactions?

texts:
I'm looking to create a raw transaction, sign it, and broadcast it using the eth.sendRawTransaction RPC method.

I would like to do this offline using code or an open-source library OR online but without the need of using an specific wallet or software.

There is neither a RPC method to create/sign the raw transaction, nor can I find any libraries to do this (offline).

Any help or guidance on how this could be achieved would be most thanked. If there is a python implementation that would be awesome.


texts:
I am a beginner of solidity and rewriting a Casino DApp code based on the following link:

https://itnext.io/create-your-first-ethereum-dapp-with-web3-and-vue-js-c7221af1ed82

Now I am testing solidity code in remix and getting an error in the second require function in bet function since msg.value is 0.

How should I fix this?

This is my current code.

pragma solidity ^0.4.10;
contract Ownable {
  address public owner;

  function Ownable() public {
    owner = msg.sender;
  }

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

contract Mortal is Ownable {
  function kill() public Owned {
    selfdestruct(owner);
  }
}

contract Casino is Mortal{
  uint minBet;
  uint houseEdge;

  event Won(bool _status, uint _amount);
  event Log(uint _value);

  function Casino(uint _minBet, uint _houseEdge) payable public {
    require(_minBet > 0);
    require(_houseEdge <= 100);
    minBet = _minBet;
    houseEdge = _houseEdge;
  }

  function() public {
    revert();
  }

  function bet(uint _number) payable public {
    require(_number > 0 && _number <= 10);
    require(msg.value >= minBet);

    uint winningNumber = block.number % 10 + 1;

    if (_number == winningNumber) {
      uint amountWon = msg.value * (100 - houseEdge)/10;
      if(!msg.sender.send(amountWon)) revert();
      emit Won(true, amountWon);
    } else {
      emit Won(false, 0);
    }
  }

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

}

Updates;
I gave 20 eth and values to Casino contract when I deploy it.


texts: Confusion regarding total number of ERC-721 Tokens

texts:
I have two questions:

1) I want to retrieve the list of all ERC-721 tokens. The main block explorer for Ethereum which is Etherscan shows 2,883 ERC-721 tokens on its website https://etherscan.io/tokens-nft, whereas the number of ERC-721 tokens which I received using Bloxy's api (https://bloxy.info/api_methods) was a lot more than that when I kept the result limit of 100000. Upon filtering for only ERC721 by calling bloxy's "List Tokens" method, it returned 76,216 erc721 tokens. So I am confused as to why there is this huge difference in the count of tokens.

2) The NFT list on Etherscan contains many repeating tokens. E.g. Gods Unchained Cards have multiple occurrences and each has a different address. Is this because these are totally separate tokens with copied names or same token with different versions?


texts: Please send me some faucet ETH of ropsten network

texts:
My  adress of metamask wallet is 0x7E279990b12980d37C87abF402f1356b1Dc6F05f

Please soem one can provide me some ETH faucets to test my application?


texts: IPFS versioning - How to get all files from the IPFS key?

texts:
Based on the below code, im able to add a file**(dataobj.txt --QmUUHKjR5ZdrrYmxpXyPrYP3eMyhv9FnRKo1Duv9stzmmw)** and publish a file and then assign to the key "myIPFSKey".

Step 1: ipfs add -r ipfs/dataobj.txt
Step 2: ipfs name publish QmUUHKjR5ZdrrYmxpXyPrYP3eMyhv9FnRKo1Duv9stzmmw
Result: Published to QmVHUPh6TJKZpXjQ4gL2rZU5YYi7Eb3cUsh4xvSfMrZfhU: /ipfs/QmUUHKjR5ZdrrYmxpXyPrYP3eMyhv9FnRKo1Duv9stzmmw
Step 3: ipfs name publish --key=myIPFSKey QmVHUPh6TJKZpXjQ4gL2rZU5YYi7Eb3cUsh4xvSfMrZfhU
http://localhost:8080/ipns/QmVHUPh6TJKZpXjQ4gL2rZU5YYi7Eb3cUsh4xvSfMrZfhU

Now i want to update some text on the file(dataobj.txt) and uploaded to the IPFS again. it has returned the new IPFS hash**(QmfKtQh2apaM9eQM3ohwgfrr3zfSSXd1wsQhMJtvXTurUg)**. So again i have published the new hash to the IPFS key "myIPFSKey". so far everything goes well.

Here i want to get the list of all the files published to the particular key(myIPFSKey) like versioning. Is it possible to achieve it?

Command:   ipfs key list myIPFSKey
Expected O/P:  QmUUHKjR5ZdrrYmxpXyPrYP3eMyhv9FnRKo1Duv9stzmmw dataObj.txt
               QmfKtQh2apaM9eQM3ohwgfrr3zfSSXd1wsQhMJtvXTurUg dataObj.txt

Here I'm trying to get both versions of the files from IPFS key(myIPFSKey)

Regards
Mani


texts: How can I know a hash mined and confirmed by ethers.js

texts: In ethers.js is there any way I can check whether a hash is mined and confirmed so that I know it is not reverted and valid?


texts:
I have a contract that sends a small fee to the owner. It works perfectly fine but when I change the owner to an address which contains another contract it always causes an error when viewed on the block chain explorer (that and the balance is never received by the receiving contract).

The bug seems to have been recognized on Github but I'm having trouble with the work around suggested:

address.call.value(_value)(_data)

My implementation looks like:

owner.call.value(fee);

It compiles fine but the fee is never sent. Am I doing it wrong or is this a current limitation of the platform?


texts: What's the fastest way to mine a transaction so I can test contracts quickly?

texts:
I am developing a solidity automated test framework in nodejs that uses events/logging extensively.  The use of events eliminates (I believe) all the RPC simulators out there.  It's also frustrating to chase down simulator problems, I'd rather use a real server that's modified to go faster.

I've hacked up geth to mine transactions every 4 seconds instead of 15-20 seconds, but it's still too slow.  I'd like to run as fast as the VM can execute code.

I'm going to post my patch to geth to do this, but I and others would really like a better answer to this question.   It really slows down development to have to wait multiple seconds for each transaction to complete.  My test suite of about 60 transactions takes about 4-5 minutes to run, and my test suite keeps getting longer...

Please advise on making this geth mine even faster than the answer I propose, or an alternative suggestion as well.


texts:
Hi I am trying to deploy a contract but keep getting this error. I am new to solidity.
I am running the cmd node deploy.js
error message
const interface = JSON.parse(compile).contracts["lottery.sol"].Lottery.abi;
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at Object. (C:\Users\LG\OneDrive\Desktop\Solidity\lottery\truffle-smart-contract\deploy.js:5:24)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
pragma solidity ^0.5.16;

contract Lottery {
    address public manager;
    address payable [] public players;

    function Start_Lottery() public {
        manager = msg.sender;
    }

    function enter() public payable {
        require(msg.value > .01 ether);

        players.push(msg.sender);
    }

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

    function pickWinner() public restricted {
        address payable winner = players[random() % players.length];

        winner.transfer(address(this).balance);
        players = new address payable[](0);
    }

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

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

}

Deploy.js
const HDWalletProvider = require('@truffle/hdwallet-provider');
const Web3 = require('web3');
const compile = require('./compile');
const interface = JSON.parse(compile).contracts["lottery.sol"].Lottery.abi;
const bytecode = JSON.parse(compile).contracts["Inbox.sol"].Lottery.evm.bytecode.object;

const provider = new HDWalletProvider(
    '<mnemonic phrases>',
    'https://rinkeby.infura.io/v3/<xxxxxxxxx>'
);

const web3 = new Web3(provider);

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

    console.log('Attempting to deploy from accounts', accounts[0]);

    const result = await new web3.eth.Contract(interface)
        .deploy({data: '0x' + bytecode})
        .send({from: accounts[0]});

    console.log(interface);
    console.log('Contract deployed to', results.options.address);
};

compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');

const lotteryPath = path.resolve(__dirname, 'contracts', 'lottery.sol');
const source = fs.readFileSync(lotteryPath, 'UTF-8');

var input = {
    language: 'Solidity',
    sources: {
        'lottery.sol' : {
            content: source
        }
    },
    settings: {
        outputSelection: {
            '*': {
                '*': [ '*' ]
            }
        }
    }
};

module.exports = JSON.parse(solc.compile(JSON.stringify(input)));


texts: Is there a distinguishing characteristic of a 'contract creation' transaction?

texts:
Look at this transaction:

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

In geth's console, if I enter:

  eth.getTransaction('0x37c4...')

It returns the transaction with a to value of null.  I'm pretty sure this is because this transaction is a contract deployment.

If I look at:

  eth.getTransactionReceipt('0x37c4...')

with the same transaction id, the contract address field is non-empty.

My question: is to being null enough to distinguish a transaction as one that deployed a contract? And secondly, is looking at the receipt the only way to get the address of the contract?


texts: Testrpc installation on Ubuntu 14.04 is failing

texts:
I'm trying to install testrpc using the command

sudo npm install -g ethereumjs-testrpc

It's failing with the below error message. Can someone please help?

  sudo npm install -g ethereumjs-testrpc
  npm WARN npm npm does not support Node.js v0.10.28
  npm WARN npm You should probably upgrade to a newer version of node as we
  npm WARN npm can't make any promises that npm will work with this version.
  npm WARN npm You can find the latest version at https://nodejs.org/

  /usr/local/lib/node_modules/npm/lib/install.js:298
          [this, (next) => { computeMetadata(this.idealTree); next() }],
                         ^
  npm ERR! Unexpected token >

  npm ERR! A complete log of this run can be found in:
  npm ERR!     /home/kumard/.npm/_logs/2017-06-25T18_34_19_267Z-debug.log

This is happening inspite of having a higher version of node

kumard@kumard-Lenovo-G580:~/.npm/_git-remotes$ node -v
v5.12.0


texts: How do you pass an array as an argument to a contract *constructor* using Truffle deployment script

texts:
I need to pass array as argument to contract constructor using truffle deployment script.

My contract code looks like this:

pragma solidity ^0.5.0;

contract ArrayArgument {
    uint[] public arrsv;

    constructor(uint[] memory arr) public {
        for(uint i=0; i< arr.length; i++)
        {
            arrsv[i] = arr[i];
        }
    }

    function fetcharrayindexvalue(uint index) public view returns (uint)
    {
        return arrsv[index];
    }
}

My deployment script looks like this:

var ArrayArgument = artifacts.require("ArrayArgument");

module.exports = function (deployer) {
    deployer.deploy(ArrayArgument, [10, 12, 35]);
};

But when I try to migrate my contract, I get the following error:

Error:  *** Deployment Failed ***

"ArrayArgument" hit an invalid opcode while deploying. Try:
   * Verifying that your constructor params satisfy all assert conditions.
   * Verifying your constructor code doesn't access an array out of bounds.
   * Adding reason strings to your assert statements.

  at C:\Users\Saurab Marjara\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deployment.js:364:1
  at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)
Truffle v5.0.8 (core: 5.0.8)
Node v8.10.0

How do I pass an array argument to a contract constructor from the deployment script ?


texts: Is it possible to put the initial ERC20 supply into a contract holding address that is not the token creators address?

texts:
With the standard open zeppelin ERC20 contracts, a fixed supply can be created by minting all of the new tokens to the contract creator. But this does not 'look good' and has the risk of the contract creator taking all the available balance. Is there a way to have a neutral address generated by the contract to hold the unallocated tokens? With functions then distributing the tokens as they are earned?
What is best practice for handling the risk of owner holding all the funds on contract initiation? Is it to create a fixed supply limit in the contract and _mint tokens within functions until that max level is hit? Or is there a better way to do it?
    constructor(uint256 initialSupply) public ERC20("SimpleToken", "SIM") {
        _mint(msg.sender, initialSupply);
    }


texts:
I've been following this wiki as a reference. The code has this snippet:

// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
    return ERC20Interface(tokenAddress).transfer(owner, tokens);
}

Can someone explain the syntax and purpose of this method? Does this allow the owner to take back tokens from any stakeholders?


texts:
What would help speed up synchronization?

I'm not sure if it's a bandwidth issue or a CPU issue?

If I were to upgrade my processor would that help make it move faster or do I need to upgrade my download/up speed?


texts: When trying to perform sendSignedTransaction iteratively on wallets in an array, an undefined error is returned

texts:
I'm trying to write a script that takes as input a JSON array where each element of the array has an address and a corresponding private key. I'd like to have a function that iterates through this array, checking the balance of each account and subsequently emptying it into an arbitrary external account.

However, when I run this function below, an error with no contents (undefined error) is returned. How can I figure out what's going wrong?

Here's my code, including sample input:

var Tx = require('ethereumjs-tx');

var wallets = [
  { _id: 5b898c5cda06f4c58c8aa59c,
    address: '0x107396c9f484666d0C43F227FEd9f3d258576F37',
    key:
     '0x4482be4e4e36d5521d70dafa57818eed38a4d0c69562bffebf24901c3199b271' },
  { _id: 5b89a45918f5dbce22e9115f,
    address: '0xB6125B6F5854547da1CF3B2CDe831cBEB7Ea31c0',
    key:
     '0x62305fc1c775f69603b1f378b5cd72815c102fb77d549d3364df7c9b53a0b444' } ]

var counter = 0;
var to = "0xa1cc63e76dc8dde54abf848810abd2680617b900";
var updatedBalance = 0;
var txHashes = [];

 function iterateAndEmptyWallets(counter, wallets, updatedBalance, txHashes, to) {

  if (counter >= wallets.length) {
    return [updatedBalance, txHashes]
  }

  var addr = wallets[counter].address;
  var key = wallets[counter].key;

  web3.eth.getBalance(addr).then( (result) => {
    result = parseInt(result, 10);
    var gasLimit = 25000;

    web3.eth.getGasPrice()
    .then((gasPrice) => {
      web3.eth.getTransactionCount(addr).then( (nonce) => {
        var nonce = nonce.toString();
        var valAfterGas = result - (gasPrice * gasLimit)

        key = key.slice(2);

        var rawTransaction = {
          "from": addr,
          "nonce": web3.utils.toHex(nonce),
          "gasPrice": web3.utils.toHex(gasPrice),
          "gasLimit": web3.utils.toHex(gasLimit),
          "to": to,
          "value": valAfterGas,
        };

        var privKey = Buffer.from(key, 'hex');

        var tx = new Tx(rawTransaction);

        tx.sign(privKey);
        var serializedTx = tx.serialize();
        updatedBalance += valAfterGas;
        var transaction = web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));

        transaction.on('receipt', receipt => {
          txHashes.push(receipt.transactionHash);
          counter++;
          iterateAndEmptyWallets(counter, wallets, updatedBalance, txHashes, to);
        });
        transaction.on('error', error => {
          return error
        });
      });
    });
  });
}


texts: Any good recommendations on online courses for learning how to build decentralized apps?

texts:
There's one called DappUniversity, but wondering if there are any other courses. And where did you learn how to build dapps?

Thank you!


texts:
I've started three Ethereum nodes using Geth, and they happen to be on the same node. I've specified the ports (30401, 30402, 30403) and used the --nodiscover options.

On each of the nodes, I've added the peers using the enodes (using static-nodes.json) using the external IPs:

enode1@18.222.108.246:30401
enode2@18.222.108.246:30402
enode2@18.222.108.246:30403

However, when I attach into the console and observe the peers, I notice that the port number has changed in the enode specification. Also, the local addresses are correct, the remote address have port numbers changed.

enode://enode2@18.222.108.246:30402
    network: {
      inbound: true,
      localAddress: "192.168.144.4:52594",
      remoteAddress: "18.222.108.246:30402",
      static: false,
      trusted: false
    },

enode://enode1@18.222.106.246:46636
    network: {
      inbound: true,
      localAddress: "192.168.144.4:30401",
      remoteAddress: "18.222.108.246:46636",
      static: false,
      trusted: false
    },

Does anyone know why the remote port numbers are different? Are the local and remote addresses two ends of a TCP connection?


texts: How to Download source code of existing smart contracts on ethereum block chain

texts:
We are working on a project which requires smart contract source codes for analysis in ethereum blockchain.

Can anyone suggest us how to download the source codes of various smart contracts already existing on the blockchain?
Thanks.


texts: What's the difference between the `testnet` and the production network technically?

texts: In principle I'm asking, what makes ether on the testnet worthless and ether on the production net valuable. On both nets, contracts and transactions are included in blocks which are mined, so electricity is spent on both.


texts: How exactly smart contracts guarantee an action?

texts: One of the most common pros of blockchains/smart contract that I see is the guarantee of certain action (most commonly money transfers). However, I don't quite understand how it is guaranteed? Smart contracts are basically pieces of code where the author can write them in anyway they want, so how is it different from standard applications?


texts: "Error: gas required exceeds allowance or always failing transaction" for simple AirDropper contract

texts:
I try to use simple AirDrop contract taken from https://github.com/omisego/airdrop/blob/master/contracts/Airdropper.sol -
https://gist.github.com/Gim6626/083d556e0a41da5172de0c49ffd64577 .

It deployes successfully using Remix, but when I try to use it and call multisend function I get error "gas required exceeds allowance or always failing transaction".

Here is data that I pass to function:

"0x955fe846c726d5e4aa0a9eea65417dc7394e8dbf"
["0x4fB302f34b3bD02E742B532f266D8853258567cd", "0x4fB302f34b3bD02E742B532f266D8853258567cd"]
[1, 1]

Could anybody help me?


texts: Private Network on restart balance and transaction is gone?

texts:
I am running a private ethereum node with a single node.
and it creates a folder for the keystore and chaindata But on restart, all the data is gone even the balance as well.

init genesis.json is occurred only once and later only this:

  geth --gcmode archive --port 3000 --networkid 15 --nodiscover --datadir=./block-data --maxpeers=2  --rpc  --rpcaddr 0.0.0.0 --rpcport 8545 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner" --allow-insecure-unlock


texts: I apply all commands (i.e.  sudo apt-get --purge autoremove solc)  to remove solc from my Ubuntu bash (WSL)... but after removing, when i type solc --version (it print version 0.4.24) and when i type solcjs --version it print 0.5.14... I just want to remove all my solc or just upgrade it to new version... is there any solution.. i searched a lot and couldn't found any solution to upgrade or remove solc...


texts:
I want to set limit on erc20 token that owner will not transfer after the set limit.

Lets totallSupply =1000 tokens
But transfer function could not be able to transfer more than 500 tokens.

Please suggest!!.


texts:
The update is scheduled to last year, but it is delayed.

Does anyone know the exact reasons?

Where is a related website?

Thank you.


texts: Detecting ETH and Token deposits on an address and/or multiple contract addresses

texts:
Many questions have been asked here but mostly they have been vague questions and/or answers so before marking as duplicate please read this one as its completely specific.

I have an ether account that deploys multiple forwarder contracts to be used as unique deposit addresses for the public, just like an exchange.
I need to detect all the deposits made to these contract addresses or to the one main ether address.

Possible solution was to use web3 subscriptions as documented web3.eth.subscribe but the code(below) given as example doesn't log any deposits/transactions made to the account address to be honest it doesn't log any relevant information when it comes to logging the data with the contract address and/or account address. I tried removing all the filters and seeing all the logs, made a deposit to contract address but it never logged anything related to my account or contract address or the sender address for that matter.

var subscription = web3.eth.subscribe('logs', {
    address: '0x123456..',
    topics: ['0x12345...']
}, function(error, result){
    if (!error)
        console.log(result);
});

// unsubscribes the subscription
subscription.unsubscribe(function(error, success){
    if(success)
        console.log('Successfully unsubscribed!');
});

References:

https://github.com/ethereum/web3.js/issues/1752
How to programmatically detect and accept ETH and ERC20 deposits
How to detect ETH deposits into an Ether address?

I believe it was quite simple when it was web3.eth.filter but since web3 1.0 this is no more an option.

So what is the current recommended method for listening to the deposits?


texts: Read state from smart contract deployed to azure proof of authority ethereum network

texts:
I deployed a smart contract to an azure proof of authority network(ethereum). Following the instructions here https://docs.microsoft.com/en-us/azure/blockchain/templates/ethereum-poa-deployment#tutorials, I was also able to send a signed transaction to the contract which i believe succeeds since i get back a transaction hash. But I cannot successfully query state in the contract. Im not sure what I’m missing or doing wrong. But here’s sample code to describe better.

contract MyContract {
struct Account {
    address owner;
    boolean active;
}

mapping( address => Account) allAccounts;

function AddAccount(address newAddress) public returns (bool success ) {
    allAccounts[newAddress].owner = newAddress;
    allAccounts[newAddress].active = true;
    return true;
}

function GetAccount(address _address) public view returns( address owner, boolean active) {
    return (allAccounts[_address].owner, allAccounts[_address].active);
}
}

I executed the AddAccount method.above by sending a signed transaction as follows

web3.eth.getTransactionCount(accountAddress, (err, nonce) => {
const data = MyContract.methods.AddAccount(
  newAddress ).encodeABI();

const rawTx = {
  nonce,
  gasPrice: '0x00',
  gasLimit: '0x2FAF080',
  to: contractAddress,
  value: '0x00',
  data,
};

const tx = new ethereumjs(rawTx);
tx.sign(privateKey);

// var serializedTx = tx.serialize();
const raw = '0x' + tx.serialize().toString('hex');

web3.eth.sendSignedTransaction(raw, (txErr, transactionHash) => {
  console.log("TX Hash: " + transactionHash);
  console.log("Error: " + txErr);})

Then I try to query the account like so

MyContract.methods.GetAccount(newAddress).call({
    from: accountAddress,
  }, (error, result) => {
    if (error) {
      logger.error(`${errors}`);
    }
    logger.info(`${result}`);
  });

However the result of this query always returns wrong values. Like im not able to get the initial values I sent in the first call. Pls what im I doing wrong or how can I make this work?


texts: how do you handle token value data type in database?

texts:
Ones who do exchange / Investment platforms development, all ERC20 tokens has its atomic unit and only moved by specifying value in its atomic form.

for eg: 1 BuritoToken with unit decimals as 18, to move 63.33 BuritoToken we need to place 63,331,344,345,123,500,000 atomic units in tx params as hex string. it's convenient to keep it as number type in db to say sum a list of records. But we run out of column size to keep it as numbers.

Solution here seems to be to store values as hex strings in db. I wonder if thats the approach to go with.

ideas are appreciated.


texts: Can we reuse the values stored in the ganache test network which is running in the local machine, even if the terminal which is running ganache test network is closed or what are the possible ways to make the ganache network up & running all the time?


texts: I accidentally sent all my tokens to a token contract. Can I get them back?

texts:
I accidentally sent my tokens to this token contract, is it possible to get them back?
0x33E6Ad33255890e79cE1431FE142e1F3bC1fbEc3
Thanks!


texts:
What does the "indexed" keyword do in the below line of code?  I'm guessing it just tells the event object that the following input should be logged?  Can we use it other places ie outside of events?

event Transfer(address indexed from, address indexed to, uint256 value);


texts: How to be sure "ethereumjs" is installed?

texts:
I installed ethereumjs library using following command:

npm i ethereumjs-testrpc

And here is the output:

And then I tried to run an html example which uses ethereumjs-vm. The example is here :
https://github.com/ethereumjs/browser-builds/blob/master/examples/vm.html

However, when I open this html file, there is an error message :

  ethereumjs is not defined.

Here is screen shot:

Does it mean that I need to modigy following directory in the html file ?

<script src="../dist/ethereumjs-vm/ethereumjs-vm-2.3.1.js"></script>

Note:  My main purpose is to run successfully JavaScript code presented HERE . When I run it using node I receive some errors. What is the best way of running this JavaScript code? Do I need to create an html file and run it with browser? or it's better to create a JavaScript file and run it using node filename.js ? The problem with running this code that is for signature verification is explained in details HERE . Eventually, I had to change some part of JavaScript code (I precised which parts have been changed in my question HERE ). However, eventually, when I call the function of Solidity contract (i.e. function close) to verify signature, the transaction is reverted as I mentioned the details of error HERE.


texts: Wallets and etherscan can track ERC20 tokens an account owns, but are there plans for them to track ERC721 ownership?


texts: how does a lightweight node interact with smart contracts?

texts:
In my current understanding, (1) smart contracts are code stored in the blockchain network, and access the data in the blockchain network. (When we deploy contracts, we'll get the storage address)

(2) Lightweight nodes are those that do not download all the chaindata from network.

Correct me if I'm getting it wrong, but I believe that lightweight node can interact with smart contracts (Metamask?)
It simply doesn't have to ability to fully verify the data it downloaded.

My problems are as follow:
(1) Since the lightweight node doesn't have all data, how does it interact with the smart contract? Is the chaindata downloaded upon each request?

(2) While the code of smart contract may remain the same, the data will change with each update. How does the node know where to look for the updated data?

(3) Are code or data downloaded with other data that are useless for the smart contract?

I figured this is possible since the code and data are stored in blocks with other transactions, and if downloads are in the unit of "blocks" then it will include other data

(4) Any suggestions on how can I monitor these network usages?

Thanks!


texts: Why is Fallback function not being executed?

texts:
I have a fallback function for receive ether on my contract and I have a function for send ether to my contract, also in my contract, I have withdrawal function.

Why is the fallback function not executed when I executed paybaleFunction()?
I detected this case with help withdraw function, which sends ether from contract this.balance to my address.

contract Some {
   function () payable {
      withdraw();
   }
   function withdraw(){}

   function paybaleFunction() payable{
      withdraw();
   }
}


texts: Alternative solution for loops in subscription smart contract design

texts:
I am a new developer, working on a smart contract mostly for my own learning. I am developing a Smart Contract to handle subscriptions. The contract has the below features.

Subscribers can subscribe to other public addresses and deposit ether into their account.
Producers (people you subscribe to) can execute a charge function, which will loop though all of their subscriptions, calculate the payout, deduct the payout from subscriber accounts and send the ether to the person calling the function.

Here is a snippet of my code:

function charge() external {
uint payout;
uint service;

Producer storage producer = producers[msg.sender];

// calculate payout
for (uint i = 0; i < producer.subscribers.length; i++) {
  // get subscriber
  address subscriberAddress = producer.subscribers[i].account;
  Subscriber storage subscriber = subscribers[subscriberAddress];
  //check balance
  if (subscriber.balance >= weeklyCharge) {
    subscriber.balance -= weeklyCharge + serviceCharge;
    payout += weeklyCharge;
    service += serviceCharge;
  }
}
// send total ETH to producer address
producer.lastPayment = now;
msg.sender.transfer(payout);
serviceAddress.transfer(serviceCharge);
Charged(msg.sender, payout, service);
}

I am leaving out some details for simplicity's sake. The full code is here: https://github.com/cseale/patrecoin/blob/master/smart-contracts/contracts/Subscriptions.sol.

This charge function seems to me to potentially be a very expensive function, if someone had, let's say, 1M subscribers.

Can anyone advise me on how I might make this function more efficient, or design my smart contracts in a better way?

EDIT: One restriction. I want to put the control for charging into the hands of the person calling the charge function. If I invert the payment control to the subscribers, there is no point in the contract. I want to set up this accounting system to track payments and ensure a certain revenue flow for what I call the "Producer"


texts:
I am (totally new to DApp) currently involved in a research project that regarding the Front-end side (Js Libraries and Frameworks) of the DApp. I read many articles but still confused.

My question is, could help me to clarify this with e.g a graph that shows/describes the tools/technologies/libraries etc (Like HTML5, CSS, React web3, etc..) that must be used and the interaction between all of them ?

A simple brief/detailed documentation for each tool/technology/library would great :)


texts: Is it possible to allow users to withdraw certain amount of tokens if we sign that transaction somehow?

texts:
Let's say I create a token. Supply is some determined amount. I distribute that token like Brave browser let's say. I want the user to withdraw that token to their address. How could I do it?
I am thinking if I could do something like "{message: sendTokenToAddress(user_address_added_in_account), amount: amount, signature: signature}" and somehow verify it in the contract, and if verification is successful, allow the withdrawal to take place.
The thing is I want people to have tokens in their addresses without sending it myself (because in that case I would need to pay gas).


texts: What is a stale block and how does it work

texts: What is stale block and how does it impact the performance of the ethereum blockchain?


texts:
I am checking in web3 if it is listening to a port using

var web3 = new Web3();
if(web3.setProvider(new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8545')))){
    web3.eth.net.isListening()
    .then(() => console.log('is connected'))
    .catch(e => console.log('Wow. Something went wrong'));
}

but it giving type error:

  TypeError: this.provider[(intermediate value)(intermediate value)(intermediate value)] is not a function


texts:
I am reading this article to understand the storage in Solidity/EVM https://programtheblockchain.com/posts/2018/03/09/understanding-ethereum-smart-contract-storage/

It says that each smart contract has an (independent?) storage and "This storage can be thought of as a very large array, initially full of zeros. Each value in the array is 32-bytes wide, and there are $2^{256}$ such values". Since $2^{256}$ is an enormously high number and each (I suppose only "full") node has to store the same data for each deployed contract I assume only nonzero values are stored. Then how does EVM searches for a needed value in the storage? Are the non-zero values ordered increasingly and EVM uses binary search? I probably need a deeper understanding of how computer memory works in low level. If that is the case is there any accessible article on this topic?


texts: truffle always says ".my_function is not a function"

texts:
I'm trying to do my first basic smart contract, following this popular HelloWorld tutorial.

However whenever I get to the part where I run a function in the truffle console, it is always telling me ".function_name is not a function".

For example, calling the default truffle MetaCoin getBalance function :

truffle(development)> MetaCoin.deployed().getBalance( web3.eth.accounts[0] )
TypeError: MetaCoin.deployed(...).getBalance is not a function

Am I calling the function incorrectly?
How should I be calling the .getBalance function in the MetaCoin example?


texts: Deploy many instances of configured base contracts or track multiple agreements on one contract?

texts:
I am playing around with solidity, truffle, and node and i was wondering if I am trying to make a game that allows players to browse a list of games and join the ones they want.

Would it be best to deploy many instances of a base contract for each game instance or perhaps use one contract that tracks all game instances in a linked list of structs and identifiers? I have experimented with both but right now I am writing one contract, that can handle different configurations, and be deployed many times. However, I am wondering how does web-3 track these contract instances? Can I store a contract address and use that to interact with each instance? If not, is there any other way?

// one contract to rule them all?
Contract A {
 struct GameInstance {
   // state variables here
 }
 mapping(bytes32 => uint256) idToIndex;
 GameInstance[] activeGames;

 // logic here
}

// many instances
Contract B {
  // state variables here

  // logic here
}

If A (one contract with an Instance struct, ...etc), could/should A inherit B? If it did would the functions in B need to be modified to return values instead of interact within contract state variables? That way they can pass the value to a function in A that interact with a GameInstance struct's state variables?

Contract A is B {

  Contract A {
   struct GameInstance {
     // state variables here
   }

  mapping(bytes32 => uint256) idToIndex;
  GameInstance[] activeGames;

  function ex(bytes32 instanceId) {
    uint256 index = idToIndex[instanceId];
    activeGames[index].example = super.ex(activeGames[index]) ;
  }
}


texts: Difference between Geth POA Clique and Parity POA Aura

texts: I am creating my own private blockchain with a POA consensus. What is the difference between POA networks created by Geth (Clique) and by Parity (Aura), and are there scenarios that favor one over the other?


texts: Transaction fees in ether transfer from coinbase to bittrex?

texts:
I have transferred 0.1 ether from Coinbase to biitex and was charged 0.00042 ETH as transaction fee so ended up paying 0.10042 ETH.

Just now I have checked my balance in bittrex and found that I have only received 0.09308775 ether. Are there any other transaction fees that I am not aware of ?


texts: What is the purpose of solidity Address operators?

texts:
According to solidity docs the type address has the following operators:

  <=, <, ==, !=, >= and >

Besides checking for equality - Why would I want to check if an address is greater or smaller than another one? What is the usecase?


texts: Cannot import Ethereum web3.js in React Native application

texts:
I'm trying to import the Ethereum web3.js library into a React Native project.

I've followed the React Linking Libraries instructions, installing the web3.js package and linking it with the commands:

$ npm install web3 --save
$ react-native link

My index.ios.js file looks as follows:

import { default as Web3 } from 'web3';

import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';

class ReactProject extends Component {
  render() {
    return (
      <Text>Hello world!</Text>
    );
  }
}

AppRegistry.registerComponent('ReactProject', () => ReactProject);

The error message I receive in the simulator when I run the app  {"type":"InternalError","message":"react-packager has encountered an internal error, please check your terminal error output for more details"} is not very helpful as the terminal shows only the same message.

How do I go about importing this library, into other projects such as React-Native?


texts:
I know it has been asked a lot of times but the newest post about this I could find was about 1 year old. To me it seems quite possible that things have changed since then. So my question: Is there an easy way to convert bytes8/16/32 to a String value?

Here is the problem I face right now. Contract A takes one user-input per transaction as a bytes8/16/32 variable. The contract passes it to Contract B and stores it there. My getter function in Contract B returns this Bytes8/16/32 variable. So Contract A calls the getter-function of B if needed and successfully gets the bytes variable back. Now I simply want to turn it back to a readable string and put it on screen in a decoded way :)
Somebody has an idea? Many thanks!


texts: Get smartcontract token balance via JSON RPC

texts:
Via Geth commandline I can get my smartcontract token balance with:

var mytest = eth.contract([{interface}]).at(contract address);
mytest.balanceOf(eth.accounts[0])
>998

I want to present the token balance on my website.  How can I do that?

I tried JSON-RPC and several methods like eth_getTransactionByHash, but can't find out how to get the balance.


texts: Is there any working provider for Ethereum Classic APIs?

texts:
Provider used for Ethereum is Infura, but there is no any provider for Ethereum Classic.

Previously tested Ethercluster endpoint to access APIs for Ethereum Classic, not able to connect with Kotti endpoint.


texts: What replay attack protections does Ropsten provide?

texts:
I understand the Ropsten testnet was partly necessary because of some broken replay-protection measures on Morden.  So what's different for Ropsten?

Is the nonce simply incremented by a smaller number than Morden was?

Looking at the genesis block, it looks like the nonce value is set to 0x42, is that the nonce offset?  So after a mainnet account has more than 66 transactions, its testnet transactions are replayable on the mainnet?

This doesn't sound ideal, but if that's the answer, please let me know!


texts: Ethercamp. Could not start sandbox: Sandbox is not available

texts:
I somehow managed to break my ether-camp IDE. The sandbox wont' start. When clicking "Run All Contracts" it fails with Could not start sandbox: Sandbox is not available.

When browsing the filesystem, /root/ethereum-sandbox is still there and I didn't tamper with it.

How can this be fixed?


texts:
Is the value of a contract's method's parameter visible on blockchain?
On Etherscan, in the tx information there is an Input Data field, which details says

  The binary data that formed the input of the transaction, either the input data if it was a message call or the contract initialisation if it was a contract creation

Is this what I am looking for?


texts: How to pass the whole array from one contract to another when working with different solidity files?

texts: For example, I am taking one function function transferAddresses() in my contract contract one{} from where I am taking number of addresses in array. Now I want to transfer the whole data of the array to another solidity file's contract. What should I do?


texts: Ethereum Wallet Version 0.7.6 Couldn't connect to node

texts:
Hello,
Sometimes Ethereum Wallet gets this error when I want to start up. I have Windows 7 x64. What is the problem?
Thanks


texts: Deploy Contract that Imports Other Contracts in Mist

texts:
I have a main smart contract that Imports two other contracts by their file path. Inside the contract I have:

Import "/test/files/test.sol"
Import  "/test/files/testimport.sol"

So I have three contracts in total. The main contract uses modifiers and mappings from the other two contracts.

How do I deploy these contracts in Mist while allowing the main contract to communicate with the other two imported contracts?

If this cannot be done in Mist, what is the best way to deploy these contracts so they can communicate?


texts: Copying a mapping from Contract A to contract B

texts:
Is there any way at the moment that I can copy a mapping from one contract to the other?

mapping (address => uint256) public balanceOf;

function importFrom(address _from) onlyOwner {
    Token s = Token(_from);
    balanceOf = s.balanceOf;
}

I want to allow this feature to enable smart contract upgrades. If this is not possible, I know that it is possible to use a delegatecall from one contract to the other; but then the problem is: how do I see the interface of the contract that is being called from the Ethereum wallet? I don't want to call directly the functions in that contract, but rather through the intermediary contract that then makes the call.


texts: How to connect to a peer in ethereum and then run contract on ethereum?

texts:
I have developed a smart contract and run it with remix in cases of javascript vm and web3 provider.
Now, I want to run it such that my computer to be connected to real ethereum network.
I think in case of using web3 provider in remix, I am not connected really to ethereum and it's like a simulation, isn't it?


texts: Says Transaction not executed but the funds still went through

texts:
Mac Ethereum wallet says "transaction not executed" but the funds still went through:

https://ropsten.etherscan.io/tx/0x11ac91b6aac99eb02afe078b8786a9f1672929f65c73ee68e51b9e0ccc91036a

But my everything was transferred..
From account has a 0 balance: https://ropsten.etherscan.io/address/0x3a98a87557dbd81d94153188d83251513890bb5d
To account has a increased balance:
https://ropsten.etherscan.io/address/0x48cbde71d09ba63b768d94b50cb7160cf1188705

Any thoughts?


texts:
Is there a way to print the values of an array in my contract to a console (using truffle or geth for example)?

Suppose this is my contract:

contract MetaCoin {

    uint256[] public someNumbers;

    function writeNumber(uint256 num) public {
      someNumbers.push(num);
    }
...

Now, I managed to get one value of someNumbers, but not all of them through

> meta.someNumbers.call(0)
> BigNumber { s: 1, e: 2, c: [ 123 ] }

Note that I made an instance of the MetaCoin contract first with MetaCoin.deployed().then(a => {meta = a})


texts: How to read past events from the blockchain?

texts:
I can read events as they happen with:

const eventsWatch = myContract.allEvents();
    eventsWatch.watch((err, res) => {
      if (err) return;
      console.log("Event:", res.event, res.args);
    });

This even shows the last event after I refresh the page, but I would like a list of all the past events.

Anyone know how to get this?

I've tried changing watch to get but then i get undefined objects back...

Thanks!


texts: Why remix account is empty when select "Injected Web3"?


texts: Is there any way to see the txpool with infura and web3?

texts:
I'd like to get pending transactions information without running my own node. Is there any way to do that?

Something like this would work too, but they only seem to provide a fraction of the pending transactions they see.


texts: Why `array[array.length] = elem;` fails for appending to a dynamic storage array in Solidity?

texts:
Consider the following contract:
pragma solidity ^0.8.0;

// SPDX-License-Identifier: WTFPL

contract Demo {
    uint256[] public numbers;

    function append(uint256 num) public {
        numbers[numbers.length] = num;
    }
}

When trying to execute append(..), the execution reverts. As in the following tx:
https://dashboard.tenderly.co/tx/kovan/0x919d409ba863c640181af55db3b1576e7c6bb8367a4472f554499d9510029e07
After doing some digging, I found out the error was somehow related to using numbers.length as the index. I finally discovered array.push(..) that ended up working just fine:
pragma solidity ^0.8.0;

// SPDX-License-Identifier: WTFPL

contract Demo {
    uint256[] public numbers;

    function append(uint256 num) public {
        numbers.push(num);
    }
}

I'm still curious why the first code block fails, while the second one works just fine.


texts: How does the network decide where data is stored and contracts executed?

texts:
What I'm trying to figure out (and various internet and specific searches here have failed to answer) is where the data is stored and contracts executed.

Optimally, I figure, all "data" (transactions, contracts, anything at all really) should be stored on every node, and all contracts should be run by every node in order to form the best consensus of what is accurate to maintain the "decentralized consensus" nature of Ethereum.
Realistically, however, I'm aware that storing every bit of data on every node could become very expensive (in physical data storage hardware costs) very rapidly. So I figure the network has some system that decides to store a contract and associated data on a certain number of nodes and periodically (each time a new block is generated (possibly)) decides if that data needs to be stored on different nodes (because current ones are no longer available or the data is being accessed more frequently).

If it helps, here's the best I can do for an example:
I have a contract (hypothetically) that simply waits for activation and then spits out some small amount of data, such as "Hello World".
Does every single node on the network have a copy of the contract?
Will every single node execute the contract and send the result across the network for comparison to determine a consensus result that will be recorded in the blockchain?
When (if ever) does any of aforementioned data get determined "no longer useful" and ceases to exist?

To clarify some of my assumptions (in case they're inaccurate) I did read somewhere in the Ethereum documentation something that gave me the impression that not every single node will run a contract, which to me meant that either they don't all store the data or they simply don't all process every single contract execution.
Also, I'm sure this has been asked before and there even appears to be a question for it in the official FAQ, but I can't find a definitive answer online and the FAQ answer just says "TODO".


texts: Unable to synchronise with a remote peer

texts:
I am running a private network with two geth instances one on my machine and other on an AWS server using the same Genesis file. I am also using a networkid flag to differentiate my private network.

I have successfully added the two nodes as PEERS using a static-nodes.json file - which I confirm through the admin.peers function.

Now i started mining on the remote node and mined some blocks and then stopped the miner. Now, my local geth instance starts to synchronise and just as it does, I get the following error

  ########## BAD BLOCK #########
  Chain config: {ChainID: 0 Homestead:  DAO:  DAOSupport: false EIP150:  EIP155:  EIP158: }

  Number: 1
  Hash: 0xfc5d907f90c021e55b4ffceb27413992e722cbfa63cc77aed9274938a903f22d

  Error: invalid merkle root (remote: 70d1206c41e2508d61a0b6e605e5d26a93b94fdf48ea6e781d410ea269bf6b44 local: 08c6e61d54f29af09d3f063157f75dbdc3121b311d471ef19523a86c80b51e09)

I have been getting this issue for a day , even when i have previously been able to synchronise some peers on a private network.

Is there something wrong with the Chain config object ?
I have even tried removing the chaindata folder and this issue still persists.


texts: What happens when you submit the same transaction to multiple providers?

texts:
Suppose I sign a transaction locally using eth_sendRawTransaction of an implementation (web3js, web3py etc.), and then send the same signed transaction to multiple providers like Infura, Alchemy and a node of my own. My questions as follows:

Does it have any side effects?
Could it increase the propagation chance of the transaction through mempools (assuming every node has a slightly different mempool state at a given time).
Do the nodes just discard the second coming signed transaction, if they already have the same transaction? Or do they add it to the queue and there is a chance that it will go into another block, different than the first one they have?


texts: What can we tell from a contract's public address?

texts:
This is asked differently around but I haven't found an explanation as direct as I wanted to.

I've read that all state variables in a contract are publicly visible (solidity docs). It's stated there: "Note that you can never restrict any human or computer from reading the content of your transactions or your contract’s state".

I understand it conceptually but I wonder what steps would be required in order to get the state variables from a contract. Specifically, I've deployed a contract to address 0x8325ba5B0A67745FC6F21DC9A9Cb43f5E8d9c5Df in the Rinkeby test chain. What are the steps required for someone to see the state of my contract? And follow-up, can someone see the functions that contract implements?


texts: How to create signer for Trezor hardware wallet?

texts:
I'm trying to create a signer for Trezor hardware wallet.

I'm using library ethers.js

In case of Metamask wallet, this is how I created the signer:

export const createMetamaskSigner = async () => {
  let networkId = Number(window.web3.version.network)
  let provider = new providers.Web3Provider(window.web3.currentProvider, { chainId: networkId })
  let signer = provider.getSigner()
  addMethodsToSigner(signer)

  let address = await signer.getAddress()
  window.signer = { instance: signer, type: 'metamask' }

  return { address, networkId }
}

How can I do this in case of Trezor hardware wallet?

Thanks


texts: How do I serialize an array of strings in Solidity?

texts:
Since I can't seem to get my contract to return a string array in any of its methods, I'm just going to serialize the array and return it as a string or bytes.

I've tried various for loop methods to do this but I can't seem to concatenate strings either.

What's the best way to serialize an array of strings in Solidity?

I have a function like this that isn't working:

/* inside my contract */

string[] myArray;

function serializeArray() returns (string serializedArray) {
  uint arrayLength = myArray.length;
  string serialized = '[';

  for (uint i = 0; i < arrayLength; i++) {
    serialized += '"';
    serialized += inbox[i];
    serialized += '"';

    if (i < arrayLength) {
      serialized += ',';
    }
  }
  serialized += ']';

  return serialized;
}


texts: geth websocket connection stuck open. ethers and web3

texts:
on my bsc geth node I have 2 bizarre issues.

connecting to the jsonrpc over http through a script fails with network errors. same code through node shell works. /shrug
web socket connection never closes/terminates. this causes my async functions to NEVER finish.

Assuming that I will never solve #1, I figure the easiest solution is figure out a way to close the web socket. I cannot find any docs on close() or disconnect() in either web3 or ethers.
any suggestions? thanks so much!


texts: what is the size of the web3.eth.sign() result?

texts:
I am looking for a solution to emit a dynamique array of signature using event.
I thought that signature is a byte32 and it works, but I think is a 65 bytes.

so what is the exact size and how could I emit an event that contains an array of signatures ?


texts: Decrypting an account from keystore generates the error - Cannot read property 'kdf' of undefined

texts:
I need to sign a transaction and send to infura using a keystore. I ran into the following error while calling the decrypt function.

if (json.crypto.kdf === 'scrypt') {
                ^
TypeError: Cannot read property 'kdf' of undefined
at Accounts.decrypt

I am using web3 v1.0.0-beta.36

This is my code, any help is appreciated

const Web3 = require('web3');
const Tx = require('ethereumjs-tx')
const web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/f..."));
var fs = require('fs');

const contractAddress = "0x...";
const sendingAccount = "0x...";
const password = "...";

var abiArray = JSON.parse(getAbi());
var contract = new web3.eth.Contract(abiArray,contractAddress);

const keystore = fs.readFileSync("UTC--...", 'utf8');
const decryptedAccount =
web3.eth.accounts.decrypt(JSON.parse(keystore), password);


texts: Geth syncing gets close to latest block and then stops

texts:
I have a new node that gets close to the latest block and then stops syncing.  Each time I stop and then restart geth, it will sync back up to about 75 to 100 blocks away from the latest block and then stop.  The only way to get it close to the latest block again is to stop and start geth.

my geth command:

sudo geth --datadir "/data/.ethereum" --rpc --rpcaddr 127.0.0.1 --rpcport 8545 --rpccorsdomain * --rpcapi admin,db,eth,debug,miner,net,shh,txpool,personal,web3

Examining my chaindata shows that it is about 32G, which seems small but I don't know how large it should be.

du -sh /data/.ethereum/geth/chaindata/

32G     /data/.ethereum/geth/chaindata/

I've also ensured that my time is synced up with:

timedatectl

shows

      Local time: Mon 2017-11-06 17:14:48 UTC
  Universal time: Mon 2017-11-06 17:14:48 UTC
        RTC time: Mon 2017-11-06 17:14:48
       Time zone: Etc/UTC (UTC, +0000)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no


texts: How do I add Ether to Browser Solidity for Testing?

texts:
I am unable to perform any transaction in Browser Solidity as there is no ether in the account.

The contract is being created, but now ether is needed to test the functions.

I have tried using the "value" field under the airplane toggle, but executing any function with a non-zero value here throws the following error:

VM Exception: invalid JUMP

How should I add ether to my test accounts?

Thanks in advance!


texts: Whose blockchain is selected for a transaction?

texts: When a transaction is initited (for example  transfer of ethers across accounts), does it first happen on the local copy of the blockchain and then synced over the network to other nodes? Or does the transaction look for the destination account on the blockchain of some other node (randomly) on the network?


texts: Call method of another contract from one contract in upgradable smartcontract

texts:
I have two contracts Vase and Box
contract Vase {
    uint256 public vase1;
    event VaseValueChanged(uint256 newValue);

    function createVase(uint256 newValue) public {
        vase1 = newValue;
        emit VaseValueChanged(newValue);
    }

    // Reads the last stored value
    function retrieveVase() external view returns (uint256) {
        return vase1;
    }
}

contract Box {
    uint256 private value;

    // Stores a new value in the contract
    function store(uint256 newValue, uint256 breadth) public {
        value = newValue;
    }

}

Both are upgradable smartcontracts and I am using the openzeppelin library and using its CLI for upgrading these  contracts.
How can I call retrieveVase() method of Vase contract from Box contract. I don't want to inherit Vase in Box contract.


texts: What’s the block reward for smart contract miners?

texts:
Maybe this is a basic question, but I can’t figure out what are the block rewards and/or transaction fees for miners of smart contracts .
When talking about a cryptocurrency, the block rewards are new coins given to the miner, right?

Then, I guessed that the reward for miners of smart contracts are the native tokens (or ether) used as fuel for the smart contracts, but I’ve read an article that says that they are not the same thing.
Can you help me understand? Thanks


texts: Can someone please explain,  How can we configure SQL database for e.g. MySQL using Embark framework and How do we configure this in application.


texts: How to process transactions that are in txpool with status pending and queued?

texts:
I'm running a private chain and facing issue while doing transactions. All my transactions going to pending status.
Hence I have increased gasprice, and now new transaction going to queue.
Is there any way to determine why transaction stuck into txpool?
And how to process existing transaction that are in txpool?
I know that deleting transactions.rlp file would work, but I want to process it, not remove it.


texts: ERC 721 Transfer Event vs. Sale Event Detection

texts:
When it comes to working with ERC721 Tokens, is there a way to figure out if a Transfer event was emitted due to the actual sale of a Token as opposed to the mere transferring of one?
To be clear: it's fairly commonplace for owners of ERC721 Tokens to transfer their tokens from one of their Ethereum accounts to another one of their accounts - or say to a friend's Ethereum account, as a gift for example.
This sort of "free" transfer obviously causes the emitting of the Transfer event - but so does the for-profit sale of any ERC721 Token.
Given that this exact same Transfer event gets emitted in both cases, how can I tell if it was emitted as a result of a straight "free" transfer between two "friendly" accounts, or as a result of the actual selling of a token by one account to another?
I can see that the only arguments returned by the Transfer event are: from, to, and tokenId, but those aren't sufficient to differentiate between the two situations.
I also know I can use the transactionHash - which also comes back with the Transfer event's payload, to make another query into the nature of the Tx, but that obviously requires a whole other transaction.
I'm thinking maybe I can add a 4th argument to the Transfer event, say one called TxType,
so that I have from, to, tokenId, and TxType - but wouldn't this changing of the Transfer event make my contract non-conformant with IERC721 standard?
What's the best way to handle this then?


texts:
I am currently building a project where the users can referr other persons.
Now let's say I have a user who has only 2 referrals but those 2 also have another 2, then again 2 etc. and that for much more. Now I want to output those referrals/users and their users. To get a users referrals, the function getUser(uint _userId) is called. It returns some values and an array _referrals that contains the IDs of the users that specific user has referred. Now it's required to again call getUser for the 2 users until at one point it returns that a user has no referrals.

I currently am doing this via

struct User {
    mapping(uint => uint) directReferrals; // Referrals
    mapping(uint => uint) index; // ReferralId => ID in above
    uint directReferralsAmount;
}

User[] users;

function getUser(uint _userId) [...] public view returns(uint[] directReferrals) { [...] }

The problem is, that when for example a user has 100 levels of referrals (referrals of him, referrals of the referrals of him, etc.), it will call getUser (view only) 100 times (in the web interface through javascript and an ethereum node connection / MetaMask) which can result in a long waiting time.

Are there alternative ways of storing and getting of referrals?
Or wouldn't 100 view-calls take that long?

What would be the best way to
1) Programm this in the solidity code and
2) Output this via javascript?
3) Is it possible to show those data in one page without a too long waiting time?


texts:
Is it possible to fire up event handlers upon transaction creation/confirmation? In this tutorial two event handlers are used on_start() and on_block().

Is it possible to have a finer level of granularity; handlers that manage transaction creation and confirmation?

Following, this this example it also seems possible to execute code outside of the blockchain.

Would it be possible to create a handler that invokes a system call upon transaction confirmation?


texts: Remix: Bytecode isn't working, when deploying it with myetherwallet

texts: The bytecode from Remix isn't just working, it isn't deploying the contract. As far what I've known, there's something to do with the code that I've to minimize. Is there something that I has to do? I tried to run the contract on remix but it said " This contract does not implement all functions and thus cannot be created." Might think it have to do with


texts: Is it possible for a contract to hold multiple versions of ERC20 tokens? Also in extension this, what if one does not know which versions of ERC20 token(s) is to be sold in advance of deployment of the contract, is it possible to define and initiate the token(s) through the constructor?


texts:
I was trying to share my local folder of contracts to remix-ide using RemixD.
I followed the tutorial here. I ran the code below which is how you setup the connection for remixd and remix-ide now.

remixd -s D:\remix-contract --remix-ide https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.25+commit.59dbf8f1.js

After that it shows

setup notifications for D:\remix-contract
Thu Nov 08 2018 11:40:24 GMT+0800 (China Standard Time) Remixd is listening on 127.0.0.1:65520

But when I click on the link icon on remix-ide, it won't connect.

And prompts Connection from origin https://remix.ethereum.org rejected. in my cmd. Am I missing some setup/configuration that I need to do to succefully connect my local folder to remix-ide using remixd?


texts: Ethereum Solidity how to deploy a contract from another contract with constructor function

texts:
The old way: constructor function is the same as the contract name:

contract CtrtFactory {
  function makeCtrt() {
    address ctrtAddress = new Ctrt(...);
  }
}
contract Ctrt() {
  function Ctrt(..) {}
}

-----------------==
But now the new Solidity syntax is saying to use "constructor" as the function name for constructors...:  Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.

contract CtrtFactory {
  Ctrt ctrt;
  function makeCtrt() {
    address ctrtAddress = Ctrt.constructor(...);// This gives me ERROR...
  //but I don't know how to fix this.. adding "new" keyword does not help...
  }
}
contract Ctrt() {
  function constructor(..) {}
}

-----------------==
Please help me. Thank you.


texts: React returns Error 'TypeError: ETHEREUM_CLIENT.eth.contract is not a function' when I trying to connect to my ethereum contract

texts:
I declared the variables as follows

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Web3 from 'web3';

  var ETHEREUM_CLIENT = new Web3(new Web3.providers.HttpProvider("http://localhost:9545"));
  var contractABI = [{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Candidates","outputs":[{"name":"firstName","type":"bytes32"},{"name":"lastName","type":"bytes32"},{"name":"age","type":"uint256"},{"name":"group","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCandidate","outputs":[{"name":"","type":"bytes32[]"},{"name":"","type":"bytes32[]"},{"name":"","type":"uint256[]"},{"name":"","type":"bytes32[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_firstName","type":"bytes32"},{"name":"_lastName","type":"bytes32"},{"name":"_age","type":"uint256"},{"name":"_group","type":"bytes32"}],"name":"createCandidate","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]
  var contractAddress = '0x345ca3e014aaf5dca488057592ee47305d9b3e10';
  var CandidatesContract = ETHEREUM_CLIENT.eth.contract(contractABI).at(contractAddress)

But React returns a Type error as 'TypeError: ETHEREUM_CLIENT.eth.contract is not a function'

The same function working properly in Browser console, when i declare the variables directly put into the console?

can you please fix it?


texts: Is it possible to limit a blockchain to a single token/contract?

texts:
I want to create blockchain that will have only my token in that chain(eg: a fork on ethereum).

How can I achieve this?


texts: Cannot call function even though it is present in the jsonInteface

texts:
I have a simple contract with a simple test-function:

pragma solidity ^0.5.0;

contract TestContract{
  uint public a;
  uint public b;

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

function TestFunc(uint c, uint d) public view returns(bool success){
  if (c == d){
    return false;
  }
  else{
      return true;
  }
}}

I want to deploy this contract on my local instance of Ganache and call the TestFunc function through a javascript file, using web3js functionality. My javascript file is as follows:

const Web3 = require('web3')
const fs = require('fs');

const options = {
    transactionConfirmationBlocks: 1,
}

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"), null, options);

const contract_Abi = [...] //Copied from Truffle's TestContract.json file
bytecode = ... // This is the bytecode (not the deployedBytecode) from the TestContract.json file

const contract = new web3.eth.Contract(contract_Abi);

async function call_TestFunc(){
  accounts = await web3.eth.getAccounts();
  const gas = await contract.deploy({data: bytecode, arguments:[1,1]}).estimateGas();
  const response = await contract.deploy({data:bytecode, arguments: [1,1]}).send({
    from: accounts[0],
    gas: gas + 1
  });
  console.log(response.jsonInterface);
  const txHash = await response.TestFunc.sendTransaction([1,2], {from:accounts[0]});
  console.log(txHash);
}

call_TestFunc();

Now when I run this script, the response.jsonInterface shows the following:

AbiModel {
  abi:
   { methods:
      { a: [Object],
        '0x0dbe671f': [Object],
        'a()': [Object],
        b: [Object],
        '0x4df7e3d0': [Object],
        'b()': [Object],
        contractConstructor: [Object],
        TestFunc: [Object],
        '0x3ff9143f': [Object],

        'TestFunc(uint256,uint256)': [Object] },
     events: {} } }

but when reaching the part where TestFunc is called it gives the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sendTransaction' of undefined

How can I call the TestFunc method properly?


texts: Transaction out of gas despite much higher gas price than almost identical transaction at same time that is fully mined

texts:
Two Uniswap txns calling swapExactETHForTokens that are almost identical (even same timestamp) except for the value and gas price, but the one with higher value and gas price runs out of gas and uses much more gas than the other one. The only other difference is of course a proportionally different amountOutMin.
Given the value on the failing swap is less than x2 of the other one while its gas price is x10, why is it failing?
I've linked above, but these are the txns:

✔ https://etherscan.io/tx/0xcf3e9d50afae4076db3469438e1baddd0da77dac499ae527d6eabf55e0c97ad9
❌ https://etherscan.io/tx/0xe1640ab307910ecf639790f272ef7b1e0f64b41bba03c75e9012eb5f1c6b17ae

This has happened to me twice now. The other time was a lot less value but still x10 gas price over the txn that was fully mined (although that txn failed for a different reason - insufficient output amount).

✔ https://etherscan.io/tx/0x435bbc9963c3ef9a4e384b589b08938f8b266f4c53a0e06fd078b9b5f3f6b6ac
❌ https://etherscan.io/tx/0x621c5d7dcb7765e2d9c187f17691ae0ea3337bc6fe912ab9c277331cd2998e06

Any idea what could be causing the failing txns to run out of gas (and even use much more gas) given that they're virtually identical to a successful swap at the same time, but with much higher gas price?
The internal txns are also identical between the txns in each case.


texts: fraction**veryLargeNumber type math in EVM

texts: A fraction like 0.5**1/31556926, raised to an exponent in the range of 10^9. What are the best ways to do that in a smart contract?


texts:
Is there a tool like the subject for Solidity. Let's say I have a contract with import and that import has three imports etc. I'd like to combine all of them into one file and play with it in Remix, for example.

I know how to make it manually.