texts: Alternatives for Truffle for running and writing tests

texts:
Truffle offers many conveniences for writing tests for Ethereum smart contracts. The benefits include no need for a separate chain process like Ganache, complex automation of linking and deploying of library contracts like SafeMath However, there is an inverse of control and tests must be executed using truffle command and must follow Mocha/Chai pattern.

Are there alternatives for Truffle that would especially

Would use modern and standard test runners like Jest instead of a custom wrapper commands
Play nicely with TypeScript
Set up and tear down in-process blockchain easily
Support automatic compilation, linking and deployment of complex contracts like ones with SafeMath library

I found e.g. this example for Jest, but it is unfinished project. There is another one with Ganache and Jest, but very simplified and does not support linking contracts.


texts: Like Ethereum can you store information on a POS blockchain

texts:
So I know you can store hashed information on the Ethereum blockchain.

Lets say I forked blackcoin a POS version of bitcoin (https://github.com/CoinBlack/blackcoin). Can I also store hashed information on the POS blockchain?


texts:
I'm coding a contract in which I would like some functions to be called only if approved by 2 people (a merchant, and a customer).

Now, I know that I could program a buffer storing pending request and waiting for each part to send a confirm transaction.

I don't want the merchant to act without the approval of the customer, but the problem is that I don't want the customer to pay for the gas.

What I was thinking was to somehow only do one transaction, sent by the merchant (who will thus pay for the gas), but that I could check in my smart contract the transaction was signed by the customer.

Do you have any advice on what's the best way to implement it ?

Thanks for your answers


texts:
I have a function that takes bytes32 _name as a parameter and store it in a struct.

Let's say _name is either Chinese, Korean, or Japanese and from app.js I would convert the _name to hex to pass it to the function.

App.contracts.Test.deployed().then(function(instance) {
            return instance.storeName(web3.toHex(name), { from: account });

Now, when I retrieve the name by calling the function and convert it  using web3.toAscii

App.contracts.Test.deployed().then(function(instance) {
        return instance.getStruct.call();
    }).then(function(result) {

var name = web3.toAscii(result[1]);

the value would look like ÁÁ8È. Is it something that web3.toAscii cannot handle other languages or should I just use string _name?


texts:
I had 0.05 ether in my mist wallet and I just sent some more ether totaling 0.18780179 ethereum in total. You can see on Etherscan that the ether is there, but in mist it says that I have 0.00 ether.

https://etherscan.io/address/0x395dc4ff4afbd361a8351adc5cca3d4c4facc22d

I am only 65 blocks behind and I had Ether in my account all day until now. Why is the mist client showing the incorrect amount?


texts: Issue in understanding MintedCrowdsale in the ICO contract from openzeppelin

texts:
I am trying to understand the openzeppelin code for writing ICO contract.

In MintedCrowdsale, mint() function in ERC20Mintable is called as mentioned below.

ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));

Could you please let me know how this is being called without inheriting it while defining in the contract MintedCrowdsale ?

Also Why address(token()) is used in ERC20Mintable(address(token())) ? I do not see any such type of constructor in ERC20Mintable. Could you please help me to understand this as well ?

MintedCrowdsale

contract MintedCrowdsale is Crowdsale {
constructor() internal {}

/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
}

ERC20Mintable

contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}


texts: Can't connect to Strato instance on Azure

texts: I set up a Blockapps Strato instance on Azure according to these instructions but I can't actually connect to it. The "connect" button is grayed out (despite setting it up with a static public ip address) and there's no DNS name to let me SSH into it. Can anyone help?


texts: What is a good way to put the equivalent of a captcha in a Solidity contract? The objective is to put in a filter to make it difficult for bots to monopolize the contract, allowing regular humans to have access. For example, I could put in a string like 'what is seven times eight' or 'what are the first 5 digits of pi'? and then a user would have to input the answer with his transaction.


texts: How to send ether from a user to another?

texts:
This should be really easy but I can't seem to find the way to do it, thanks to the great documentation. I'm thinking I'm missing something big.

I have a function that buys ownership of something. I want to remove amount ether to msg.sender (user a) and give them to owner (user b) (minus fees).

Can I do it directly? Do I have to first let a send ether to the contract and then send b the same amount, or is there a function to transfer directly?

I assume owner.transfer(amount) (or .send(amount)) sends ether from the contract to the owner, but then how do I get ether from a?

I'm using Solidity by Example as a model, but in the Blind Auction example I can't seem to find what function actually sends ether from the bidder to the contract.


texts:
The interest rates for lending stable-coins on some of these platforms can be extremely high...I'm old enough to know that with returns like this there has to be a catch :) I'm trying to understand what risks of being a lender are. I'm specifically looking lending via fulcrum (which may or may not be relevant). As far as I can understand it:

I don't have counterparty risk in the way I would if I deposited on an exchange and made some capital available to margin traders. The counterparty is the Ethereum network.
There is no leverage involved so I cannot be liquidated...?
For stable-coins, as long as I believe in the peg there is no exchange rate risk.

I understand that the contract itself can be attacked and my capital could potentially be drained that way. What are the other risks involved with DeFi lending that I'm overlooking?


texts: truffle has not been deployed to detected network

texts:
Is it possible to referer to a contract that has been deployed with
Contract.new() with Contract.deployed() ?

When referencing .deployed() in my test it throws :

has not been deployed to detected network (1501794786154)

Obviously the code has been successfully deployed on the network ( in my deploy file i can get access to all the contracts address, can see the sucessfull transaction in Testrpc , etc ) .

Also the network id is the good one.

    module.exports = {
      networks: {
        development: {
          host: "localhost",
          port: 8545,
          network_id: "*" // Match any network id
        }
      }
    };

Lastly :
When i check the contract Build folder json file for the contract that is not recognized as deploy i can find :

"networks": {
    "1501794786154": {

So it is indeed deployed.

I've tried deleting the build folder and recompile again etc. as per

Truffle Webpack starts with error: MetaCoin has not been deployed to detected network

Anybody has a pointer?


texts: How to Include a Lock that will Stop Your Tokens from Being Listed on Exchanges?

texts:
We are working on a security token sale and are aware we may need to be able to "lock" our tokens, not from being transferred from person to person but from being listed on any exchanges decentralized or otherwise (the tokens will be RegA so will be able to be transferred to nonaccredited investors, however it can't be listed on an unregulated exchanges such as Etherdelta).

I am aware that StartEngine offers this code for their projects but we are not with them. Is anyone aware of how this lock can be implemented in our smart contracts or have any publicly available examples?

Thanks in advance.


texts: web3 can't connect to metamask (testnet)

texts:
i'm trying to connect my webiste to testnet using web3 but when i unlock metamask and connect metamask to testnet. web3 cannot connect to metamask.

please help me to solve this problem.

this is my code web3.

    web3 = require('web3');

    if (typeof web3 !== 'undefined') {

     web3 = new Web3(web3.currentProvider);
     console.log("existing web3: provider " + typeof web3);
  }
  else {
        web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/access_token"));
        console.log("new provider " + web3);
    }

Error : Provider not set or invalid


texts: Can an Ether wallet address be traceable to a crypto exchange?

texts: If an ETH wallet address was created upon the opening of a Binance or Coinbase account, is there anything in the address itself, or its activity, that can give clues as to whether it was in fact created on Binance or Coinbase (an exchange)? So that the tracer can approach that exchange and complain about that account's activity?


texts: I've got Norton Antivirus running on my PC and it has been dutifully disabling some files that it detects in the Mist download when I unzip it. In re-enabling these files, I noticed that ffmpeg.dll got detected and disabled. That's an MPEG library, just curious why it was included in Mist. Audio?


texts: Payable function with additional value attached (web3, React)

texts:
I'm making a React frontend for an open-source blockchain protocol for tokenized hedge funds. So the question is how to provide the payable function that requires some other value attached (n this case, it's uint _usdEthBasis)?

The case is the user wants to send ether to a contract by this payable function with the uint _usdEthBasis number attached.

// [INVESTOR METHOD] Issue a subscription request by transferring ether
// into the fund
// Delegates logic to the InvestorActions module
// usdEthBasis is expressed in USD cents.  For example, for a rate of 300.01,
// _usdEthBasis = 30001

function requestSubscription(uint _usdEthBasis)
    whenNotPaused
    payable
    returns (bool success)
  {
    var (_ethPendingSubscription, _totalEthPendingSubscription) =
    investorActions.requestSubscription(msg.sender, msg.value);
    investors[msg.sender].ethPendingSubscription = _ethPendingSubscription;
    totalEthPendingSubscription = _totalEthPendingSubscription;

    LogSubscriptionRequest(msg.sender, msg.value, _usdEthBasis);
    return true;
  }

I tried this one, but I got the error:

  Unhandled Rejection (Error): Invalid number of parameters for
  "requestSubscription". Got 0 expected 1!

    <form onSubmit={this.onSubmit}>

Issue a subscription request by transferring ether into the fund

        Amount of ether to subscribe
        <input
          value={this.state.value}
          onChange={event => this.setState({ value: event.target.value })}
        />

        usdEthBasis
        <input
          value={this.state.usdEthBasis}
          onChange={event => this.setState({ usdEthBasis: event.target.value })}
        />

      <button>Subscribe</button>
    </form>

Here is the onSubmit function:

    onSubmit = async event => {
      event.preventDefault();

      const accounts = await web3.eth.getAccounts();

      this.setState({ message: 'Waiting on transaction success...' });

      await fund.methods.requestSubscription().send({
        from: accounts[0],
        usdEthBasis: this.state.value,
        value: web3.utils.toWei(this.state.value, 'ether')
      });

      this.setState({ message: 'You have been entered!' });
    };


texts: What to try Ether as CLI options on test network to learn

texts:
I'm pretty new for Ether, i have invest a little in it, but now i think its will be fun to learn more about it.

i want to running linux to try out a Ether CLI node so i can developer up to it over REST, first i ofc want the test network to test on before live.

So i will ask you guys and grils about you know somthing about this, and where i shut starting to learn about it?

My idea its ofc to host my own wallet, and later build a applicaion on Ether.


texts:
What is the cheapest way to make your own token at the moment?

ERC-20

I want to create a token as cheaply as possible. Someone made a blog post where it cost 30 USD to launch the token but I'm looking for a cheaper way to do it. Raiden? Any other way?

Vesa


texts: How to overcome the address stored for contract between 2 instances of the same DAPP

texts: I've created an express/nodejs app (Dapp) that interacts with multiple smart contracts. I'm using truffle to migrate the smart contract into geth. Everything works fine when I've one instance of the nodeapp and one instance of geth inside docker. To elaborate, I've 2 docker files, one for geth and the other for nodejs app. When the Dapp docker images is run, it will automatically execute truffle migrate command and updates its build/contract directory with corresponding json files. However, using kubernetes, if I create 2 nodes of the nodejs app (Dapp), the 2 instances of the same dapp gets its own contract address in the json file inside build/contract directory. I know this is the expected behavior. However, I wanted the same artifacts (copy of build/contracts/....json) to be shared with all the instances of the app. How to do this? Please help if you have come across similar situations and solved the same. Appreciate your help on this.


texts: Fetch ETH USD Rate from past using Oracle

texts: Is it possible to fetch the USD rate of ETH at a specific time in the past to a smart contract from an external API using an oracle? i.e. I have a function which tracks whether now > start + 10 days. Now, if this statement is true, then it should fetch the ETH USD value at the exact time of start + 10 days.


texts: Reading most recent blocks without syncing chain

texts:
I would like to be able to read the newly created blocks and list of transactions it included within, without storing the chain on my desktop. Can that be done?
Thanks.


texts: Geth What does the eth.contract(abi).at function do?

texts:
The Javascript-API/geth wiki pages state that the at([address]) function does the following:

// initiate contract for an address
var myContractInstance = MyContract.at('0x78e97bcc5b5dd9ed228fed7a4887c0d7287344a9');

1. What does "instantiate by address" mean here?
 2. What is going on when at is called?
 3. Should the address parameter be from an already deployed contract,
    or a new address?   _
 4. What should be returned?

When I've been using at(..) from a geth console attached to testrpc, it returns undefined. Should this be the case? For example following the example in this question with 'testrpc' set up like this:

testrpc -a 1000
geth attach rpc:http://localhost:8545

EDIT:

Note, I think I've found the source code:

/**
 * Should be called to get access to existing contract on a blockchain
 *
 * @method at
 * @param {Address} contract address (required)
 * @param {Function} callback {optional)
 * @returns {Contract} returns contract if no callback was passed,
 * otherwise calls callback function (err, contract)
 */
ContractFactory.prototype.at = function (address, callback) {
    var contract = new Contract(this.eth, this.abi, address);

    // this functions are not part of prototype,
    // because we dont want to spoil the interface
    addFunctionsToContract(contract);
    addEventsToContract(contract);

    if (callback) {
        callback(null, contract);
    }
    return contract;
};

/**
 * Should be called to create new contract instance
 *
 * @method Contract
 * @param {Array} abi
 * @param {Address} contract address
 */
var Contract = function (eth, abi, address) {
    this._eth = eth;
    this.transactionHash = null;
    this.address = address;
    this.abi = abi;
};


texts: how to send transaction without private key ganache?

texts:
I need access to oracle accounts (whose private keys i do not have) to test my contract. I'm trying to use ganache to fork my local node with the accounts unlocked through the ganache api, but whenever i try to make this web3 call:
web3.eth.personal.unlockAccount("0xf9f62fe6905c8d955f66011f3d86862844fb8084", '', 1000000000000)

or this one:
web3.eth.sendTransaction({from: "0xf9f62fe6905c8d955f66011f3d86862844fb8084", to: userAdr, value: web3.utils.toWei("100")}, '')

i get this error:
 Error: Returned error: Account not found

Here is my ganache setup, I am able to connect to with with geth attach
ganache.server({fork: nodeIpAddr+'@'+blockNum, locked: false, })
I can't find any in depth answers or guides on this anywhere. I thought you could send transactions from any address with ganache? Has anyone been able to figure this out?


texts:
I am trying to sync geth and solc.

which solc # I get the path to my solc
/usr/local/bin/solc

Open the geth console

geth console 2>>geth.log

and now I try to sync

admin.setSolc("/usr/local/bin/solc")

but I get the error

TypeError: 'setSolc' is not a function
at <anonymous>:1:1


texts:
I have a private chain with several nodes. Connecting to only one works fine. However, if this one goes down, I want to connect to one of the other node.

Using web3js 1.0.0 beta 26, according to the documentation, it seems that there is no way to know that you are connected or not to the node unless you try a tx or call and it tells you it fails because a property of web3 is undefined.

So I have been trying to "hack" it and use some trick, but no result so far. Setting a provider will always set your web3 variable to something, even if you could not actually connect to the node.

Here is an example of what I tried:

function getNode() {
    console.log("getting node");
    for (let i = 0; i <= nodeInfo.length - 1; i++) {
        let web3 = new Web3(new Web3.providers.HttpProvider(nodeInfo[i].ip + ':' + nodeInfo[i].port));
        console.log(web3.currentProvider.connected);
        if (web3.currentProvider.connected) {
            console.log("Provider is: " + web3.currentProvider.connect + " at " + i + " loop");
            return web3;
        }
    }
    return null;
}

I also tried using callbacks, checking if eth (or any property of web3) is not undefined or whatever, but I cannot connect to other nodes if the default one if down.

Does someone knows how to check if you actually are really connected to a node or not?


texts: I have some testnet tokens Eth,btc,litecoin,I need to know how can I sell this can we swap this to mainnet any site to do this


texts: Is it possible to seperate token payer from service-consumer with special contract?

texts:
In general, token-payer(=msg.sender) receive service from smartcontract.
Is it possible to seperate token payer from service-consumer with special contract and general smartcontract above?
It means token-payer is user A (or contract) but service-consumer is user B.
Token is erc20.


texts: Coding a smart contract for people to easily start a trustless bet online. How to improve my smart contract?

texts:
so I really want to create a smart contract for the community to use - one where two people can easily and trustlessly make a bet between each other. V1 of the smart contract would be where two people (or more) bet that cryptocurrency pair X will reach the price of Y by a certain date Q. Once the condition is met, the funds are released to the winner.
It is one of my first smart contracts, I appreciate any help I can get.
I know it is far from finished, but maybe someone can point me in the right direction?
Would be greatly appreciated. I have a cool and useful product in mind :)
Once the Betting contract is finished, I will want to hook it up with Chainlink decentralized oracle to provide data to the blockchain. Oh, and I would like the dApp to run on Matic.
Where can I learn to do it? I've been watching videos and trying, but I think I reached a point where I can learn further only by trying to do it myself.
'''
pragma solidity ^0.6.7;

contract Betting {

enum State { Created, Locked, Released }

struct Bet {

string pair;

uint price;

uint date;
}

event BetMade(address bettor, uint amount);

function bet() public payable {

    emit BetMade(msg.sender, msg.value);

}

}

'''


texts:
I would like to get your though about what would be the best way to encapsulate a document in the blockchain.
What i would like to achieve is that 1 token = 1 document, this token isn't divisible, and you can hence transfer the ownership of this document, by sending this token.

Is it possible for a ERC721 token to store a IFPS link ?

Let say i have 1000 documents, and i would like to create a smartcontract, which say if you send ETH in return you get one token which is a link to a unique document (you then own this document), does it sound feasible ?

Thank you for your help


texts: How can I execute deployed contract functions using API?

texts:
Can you please provide me some demo example how can I access contract functions from a PHP Web Application/Mobile application?

For example, if I want to transfer contract funds/ether to owner account then how can I transfer that using API on test or real network? From myetherwallet it is possible by giving private key.

Just want it from other application using API?


texts: Is the Truffle Migrations contract the same as OpenZeppelin's Ownable?

texts:
Please help me to understand what the Migrations contract in the truffle suite does. Are we supposed to inherit from it? What if I'm using OpenZepp's Ownable? Or does this file allow for long term migrations added to the contracts from early on? Thank you.

contracts/Migrations.sol

pragma solidity ^0.4.24;

contract Migrations {
  address public owner;
  uint public last_completed_migration;

  modifier restricted() {
    if (msg.sender == owner) _;
  }

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

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }

  function upgrade(address new_address) public restricted {
    Migrations upgraded = Migrations(new_address);
    upgraded.setCompleted(last_completed_migration);
  }
}


texts: Library gets automatically included in contract

texts:
environment:

all contracts use pragma solidity ^0.4.17;
the compiler is 0.4.18+commit.9cf6e910.Emscripten.clang
OS is MacOS X

My token contract uses a Math library that is defined like so

library Math {...

In the token contract it is imported and then simply used in the functions

import "../Math.sol";
...
data.setBalances(src, Math.sub(data.balances(src), wad));

I compiled the contract with truffle compile and used the resulting bytecode to deploy the contract in parity

The surprising part is that it works and I'd like to understand why. There is no mention of the library in the bytecode. I would expect something like ____Math____ but this is not present.


texts: How to view or transfer initial ethereum smart contract balance?

texts:
I created a new smart contract token with initial supply and deployed it via MetaMask. Then I added this token into MetaMask but token balance is Zero.

Now, My question is when we create a new contract then from where we get the initial balance for an address ?


texts: Can I execute functions within a contract (transact) from multiple accounts?

texts: I have a contract that is deployed on the local test blockchain. I am using testrpc and truffle for testing my contract. However, I wish to execute functions of the contract from multiple accounts (2 at least). Is it possible using truffle console?


texts:
I am trying to test out this sample code:

contract MyContract {

function foo(address a) returns (uint) {

    // send ether with default 21,000 gas
    // likely causes OOG in callee
    a.send(1 ether);

    // send ether with all remaining gas
    // but no success check!
    a.call.value(1 ether)();

    // RECOMMENDED
    // send all remaining gas
    // explicitly handle callee throw
    if(a.call.value(1 ether)()) throw;
    return a.balance;
}

Very simple, just send 1 ether to a specific address, then return address balance, however I always get 0 as output meaning the sending failed:

what's wrong?


texts: get same output as solidity SHA256 in JS

texts: Is there a js function/library which gives same output as sha256 in solidity? I am saving a hash in a mapping and can access it via cli (truffle console) and see what the hash is but I would like to send this same hash as an email. So on the frontend I need to get same hash and send it over via POST request to backend which then handles the email.


texts: Transaction Callback Function Doesn't Run

texts:
I'm running the following code as part of a truffle test:
electionController = ElectionController.new(districtsNo,districtFactory.address,voteTokenFactory.address);

function createVoteToken(electionController, districtNo,x){
        for(let i = 0; i<x; i++){
            let tokenID = web3.utils.randomHex(256);

            electionController.mintVote(tokenID,districtNo,0).then((tx)=>{

                voteTokenIDs[districtNo-1].push(tokenID);

                console.log(districtNo + '\t' + i + ': ' + tokenID + '\n');
            }).catch((err)=>{console.log(err);});
        }
    }

createVoteToken(electionController,i+1,numberOfVotesEachDistrict[i]);

This loop will run about 20,000 times, sending a transaction each time but the call-back function never runs for any of them, whatsmore when examining the blockchain it seems the transactions aren't even being picked up the miner.
At first I thought my contract code must be buggy, or it wasn't sending the transactions to the rpc endpoint, but when I rewrite the test code like so using await/async rather than callbacks:
electionController = ElectionController.new(districtsNo,districtFactory.address,voteTokenFactory.address);

async function createVoteToken(electionController, districtNo,x){
        for(let i = 0; i<x; i++){
            let tokenID = web3.utils.randomHex(256);

            await electionController.mintVote(tokenID,districtNo,0);

            voteTokenIDs[districtNo-1].push(tokenID);

            console.log(districtNo + '\t' + i + ': ' + tokenID + '\n');
        }
    }

await createVoteToken(electionController,i+1,numberOfVotesEachDistrict[i]);

....it works as expected. The transaction is picked up by the node, it succeeds, and I get the expected console output.
I've tried this with both ganache-cli and a local Geth chain (over rpc) and the behaviour appears to be exactly the same.
In both cases I've set the block time to 1 second and the gas limit to 12,500,000. (each transaction appears to average around 250,000 gas, so I'm definitely not hitting the block gas limit)
Is there something I'm doing wrong here ?
I obviously can't use the async/await pattern as this loop is meant to run 13 times with >20,000 iterations each time for a total of over 300,000 transactions, so I naturally cannot afford to wait 1 second for each transaction to confirm.
Not to mention the sheer size of the blockchain on my hard drive since every one of these little transactions would be placed into its own block if I wrote it this way.


texts: How to pass bytes32 value from javascript?

texts:
I am using truffle and Ganache. I wrote the following code in remix and its working. But when I use the same code with javascript I am getting runtime error

pragma solidity ^0.4.17;

contract Delegation {
    //Structure definition to store various roles like IoT_Member.
    //It will store permissions associated to the role.
    struct RoleTypes {
        bytes32[] permTypes;
        uint index;
    }

    //Mapping to map role name to role information for the purpose of indexing
    mapping (bytes32 => RoleTypes) role;
    //Array to check the existance of role
    bytes32[] chkRole;

    //Function to check the existance of role
    function checkRole(bytes32 _roleName) public view returns (bool) {
        return (chkRole[role[_roleName].index] == _roleName);
    }
}

Javascript:

var deleg;
Delegation.deployed().then(function(instance) {
  deleg = instance;
  return deleg.checkRole.call(web3.fromAscii(roleName));
}).then(function(value) {
  //Something
});

Error:

Uncaught (in promise) Error: Invalid JSON RPC response: {"id":2,"jsonrpc":"2.0"}
    at Object.InvalidResponse (app.js:10361)
    at app.js:48396
    at XMLHttpRequest.request.onreadystatechange (app.js:51022)


texts: What's the difference between unlinked_binary and bytecode?

texts:
I have two different projects. In one, the build/token.json file contains an unlinked_binary field. In the other, there's no unlinked_binary, but there's bytecode.

What's the difference between the two?


texts: Have user's reach a consensus regarding a statement in a contract?

texts:
Is there a way for users interacting with the contract to reach a consensus regarding the truthiness of a statement?

For example: has the price gone up since 3 hours ago? True or False

Users will have financial incentives to lie. What is a good way to counter those incentives to lie about the truthiness of the statement? How can I have users successfully reach a consensus even though they have incentives to lie?


texts:
Does the EVM always allocate new memory or can it reuse already allocated, but  unused, memory?

Reading the docs for delete (http://solidity.readthedocs.io/en/develop/types.html), it is mentioned that:

delete a assigns the initial value for the type to a. I.e. for integers it is equivalent to a = 0, but it can also be used on arrays, where it assigns a dynamic array of length zero or a static array of the same length with all elements reset. For structs, it assigns a struct with all members reset.

Does this mean that if a is a dynamic array (uint[]) of, say, length n, then delete a assigns to a an empty array:a = new uint[](0)? Not the original array, of length n, with its contents set to 0?

So, if new and delete are used many times in a Solidity contract, will the EVM keep allocating new memory (expanding memory), or will it reuse already allocated memory when possible?

Consider the loop:

uint[] a;
for (uint i = 0; i < 1000; ++i) {
   a = new uint[](100);
   delete a;
}

Will this allocate 100 or 100000 memory cells?


texts: How to properly use IERC20 interface in a contract using solidity 0.8.0

texts:
Dear Ethereum/Solidity developers,
I have a small solidity contract which should allow the contract to spend the owner's ERC20 tokens.
I currently have the following interface defined
interface IERC20 {
    function totalSupply() external view returns (uint);
    function balanceOf(address account) external view returns (uint);
    function transfer(address recipient, uint amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint);
    function approve(address spender, uint amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint value);
    event Approval(address indexed owner, address indexed spender, uint value);
}

In the contract I use the IERC20 interface as follows:
contract MyContract {
    function myFunction(address _tokenIn, uint256 _amountIn) external {
        IERC20(_tokenIn).approve(msg.sender, _amountIn);
        IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn);
    }
}

When I deploy this contract to the JVM or Injected Web3 provider using the remix compiler the contract throws exceptions on the first call IERC20(_tokenIn).approve(msg.sender, _amountIn);
I tried omitting the .approve() call but according to the documentation I've read the approve is required.
My experience with Solidity is rather limited, I'm afraid I might've wrongly understood the way to implement this. Is there something that i'm doing wrong? Why is the contract not allowed to spend ERC20 tokens from the function caller?
Remix throws a rather obscure error in the sense that the function should be payable, however, adding payable to the function signature does not help.
Maybe not entirely clear but to paraphrase, How do I allow my contract to spend the ERC20 tokens of the function caller?
If any additional information is required or my explanation was not clear enough, please let me know so I can update the original question.


texts: In what version of solidity do I have to write my smart contracts if I want to interact with Web3.js


texts:
I have followed this guide and wrote the same code but instead of getting the latest block, I am getting this,

Subscription Failed =>  The method newBlocks_newBlocks does not exist/is not available

Code :

package main

import (
    "github.com/ethereum/go-ethereum/rpc"
    "time"
    "fmt"
    "context"
)

type Block struct{
    Number string
}

func main(){
    clientSubscription()

}
func clientSubscription(){
    client, err := rpc.Dial("ws://localhost:8546")
    //client, err := rpc.Dial("ws://115.186.176.139:8547")
    if err != nil {
        fmt.Println("Error Connecting to Server",err)

    }
    subch:=make(chan Block)
    go func(){
        for i:=0; ; i++{
            if i>0 {
                time.Sleep(2*time.Second)
            }
            subscribeBlocks(client,subch)
        }
    }()

    for block:=range subch{
        fmt.Println("Latest Block => ",block.Number)
    }

}

func subscribeBlocks(client *rpc.Client, subch chan Block)  {
    ctx,cancel:=context.WithTimeout(context.Background(),10*time.Second)
    defer cancel()

    blockSubscription,err:=client.EthSubscribe(ctx,subch,"newBlocks")
    if err!=nil{
        fmt.Println("Subscription Failed => ",err)
        return
    }

    var latestBlock Block
    if err:=client.CallContext(ctx,&latestBlock,"eth_getBlockByNumber","latest"); err!=nil{
        fmt.Println("Cannot get the latest Block => ",err)
        return
    }

    subch <-latestBlock

    fmt.Println("connection lost",<-blockSubscription.Err())
}

Any idea what is going on?


texts: What can I do with Nethereum TransactionReceipt?

texts:
Refer to this link https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Tutorials/Nethereum.Tutorials.Account/AccountTransfer.cs

Line 55: It mentioned "The transaction receipt polling service is a simple utility service to poll for receipts until mined"

So, what can I do with the transactionReceipt received at line 61? I have checked almost every fields are null.

There is no mention about what to do if success or failed. Hope someone can help. Thanks in advance


texts:
What is meant by Blockhash Minus-256 Problem?

I am reading an article at:

Bad Randomness

It talks about Blockhash Minus-256 problem but does not explain much about it. As a result I can’t understand this problem.

Please guide me.


texts:
Is it possible for an ethereum smart contract to call an external API which then returns a list of value?

Nathan Aw


texts: Do I need to prepare anything for the upcoming homestead release?

texts:
This is a canonical question. What actions should

regular users
miners and pool operators
developers

undertake to prepare for the upcoming homestead release which includes a forking mechanism.


texts:
I'm currently learning how to write smart contracts.
While studying some code, I came across this line:

uint256 a = value.ceil(basePercent);

(with: uint256 public basePercent = 100;)

Then one calculates 1% of the value with:

 uint256 onePercent = a.mul(basePercent).div(10000);

But why was the first line of code necessary or what is it doing?


texts: Set up backup from private Ethereum (Ganache)

texts:
I have created an ethereum application with Ganache and truffle js. i have installed ganache in a server, and th application work. but when i stop the server i lose the the smart contract that i have deployed. How can i set up a backup in case de cut of the server. i have tested

ganche-cli --db /path/

i can recoup my balnces one time and i can't done a transactions any more .
how can i set up a backup


texts: Can I import the account from MyEtherWallet to other wallets?

texts: I generated a password protected Ethereum account on MyEtherWallet with the Create New Wallet button. If MyEtherWallet stops working, will I be able to access this account using another software or other online wallets?


texts: How can I access the address of a contract created by another contract?

texts:
I am having problems in accessing the address of a new contract generated within another contract acting as Factory.
My code:

contract Object {

    string name;
    function Object(String _name) {
        name = _name
    }
}

contract ObjectFactory {
    function createObject(string name) returns (address objectAddress) {
        return address(new Object(name));
    }
}

when I compile and execute the method createObject(''), I expect to be returned the address of the new contract.
Instead, I receive the hash of the transaction.
I use Web3 to execute the function:

var address = web3.eth.contract(objectFactoryAbi)
                  .at(contractFactoryAddress)
                  .createObject("object", { gas: price, from: accountAddress });

I tried also to modify the function to store the address in an array, returning the length of the array, and then retrieve it at a later time, with the same results: always the transaction hash is returned.

Any light on this is welcome.


texts: my solidity airdrop contract don't works

texts:
I works in a last 3 days on solidity airdrop smart contract , i tried it on rinkeby but don't work. i try several time but fail and i dont know why.
Here my last fail TX

A total of 86 steps found.  Contract transaction successfully completed.  Note: REVERT opcode found.

Hope someone can help me?

Here my code on test net

Thanks


texts: Out Of Memory exception when using web3j in Android

texts:
I'm trying to integrate web3j in an android application. But the library gives an Out Of Memory exception when loading the wallet file:

Credentials credentials = WalletUtils.loadCredentials("password", walletFile)

This is the exception:

java.lang.OutOfMemoryError: Failed to allocate a 268435468 byte allocation with 8050708 free bytes and 244MB until OOM

This seems to be the culprit:

//com.lambdaworks.crypto.SCrypt#scryptJ
byte[] V  = new byte[128 * r * N]; // r: 8, N: 262144, V = byte[268435456]

I know that the credentials can be loaded because another project, Ether Wallet, uses web3j and is able to load the same wallet file. Can someone tell me how to solve this?


texts: Usage of web3 provider in multiple processes

texts:
I have web application and background queue that executes long lasting tasks. Both of them using truffle-privatekey-provider with same private key to sign/send transactions.

Now I ma experiencing issue with nonce mismatch - when background worker makes 5 tasks its nonce increases to 5 from zero. Meanwhile web application doesn't knows about it and trying to use old nonce (1) and  failed.

I do not want to calculate nonce before each transaction (moreover - I am using truffle-contract to abstract myself from raw transactions).

Is there any ways to solve it?


texts:
Connecting 2 nodes on different machines on different network from terminal in ethereum.

I have 3 nodes running on my ubuntu machine say A, i have preallocated them with some amount and they can transfer that amount within each other using node addresses.

I want to transfer / communicate from another machine say B which is also running 3 nodes on it. how can nodes on machine A connect to nodes on machine B. I want to setup a private network between A and B without connecting to the main blockchain so as A and B start communicating with each other,

On first node i am running this:

geth --genesis /home/cgen.json --datadir '/home/jedi/Desktop/node1' --networkid 12588 --port 30305 --verbosity 0 console

and on 2nd terminal:

geth --genesis /home/customgen.json --datadir '/home/jedi/Desktop/node1' --networkid 12345 --nodiscover --port 30311 --verbosity 0 console --bootnodes "enode://5675641adc6106447d9741c48ce382aca7becddd6da99881e8c98ef26f73bf4a63252fbe5ec29ddec6960cb78c7d69d39c181c6ca83e38d39670be6742f76d94@1.39.47.145:30311"

Not sure of which geth version.


texts: Web3js shows Contract Address as null after deployment

texts:
I am using web3.js to deploy a contract. I am also using Ganache to mock the network and visualise the accounts.
When the code below executes, the contract gets created, and Ganache shows a successful transaction with the contract address displayed, however the contract.options.address is null, not matter where I try to print it.
web3.eth.getAccounts().then(accounts => {
    const customerAddr = accounts[0];
    let contract = new web3.eth.Contract(ContractConfigs.ABI);
    contract.deploy({ data: ContractConfigs.ByteCode.object })
    .send({
        gas: ContractConfigs.GasFees,
        from: customerAddr,
        value: price
    }, () => {
        console.log(contract.options.address); // null
    });
}).catch(err => { console.log(err); });

Is there anything wrong I am doing? Also, I am okay with any other way to get the address of the contract if any.


texts: Howto check sync with kovan testnet is complete or not?

texts:
I am trying to sync with Kovan testnet,
docker run --name eth -p 8546:8546 -v ~/ws-002-chainlink/ws00-docker-geth-ropsten:/geth -it ethereum/client-go:stable --testnet --syncmode light --ws --wsaddr 0.0.0.0 --wsorigins="*" --datadir /geth

Here is the status after 3 days of running ...

Will there be any print like sync complete ?


texts: Making millions of transactions reliably

texts:
I'll explain the situation :

I want to log Web2 actions onto a blockchain - say, an access log.

On top of that, I'm assuming the content supplied to the browser has passed many hands before reaching the browser, therefore I'd like to send a ping from each member of the chain to "verify" he indeed sent it.

2 key problems arise :

Exposing Web3 features to Web2 users
Making millions of transactions

I've heard of plasma.io and raiden for off-chain solution - but I do not know when it will be released or how to even approach this, how do I implement my logic into the off-chain ?

And exposing Web3 features to Web2, I thought about making an HTTP Gateway to Web3 but that would be "centralizing" the data into one server and streaming it into a smart contract - which isn't the most optimal solution.

What are the current ways of achieving such things over Ethereum ?


texts: When is a clique.proposal known to other nodes?

texts:
I do not really understand how a proposal is communicated to the other nodes.

I have 5 nodes in a PoA private ethereum network. I am trying to add 2 nodes on another server. I get this -

instance: Geth/v1.8.2-stable-b8b9f7f4/linux-amd64/go1.9.4
coinbase: 0x242f75170b0b38917995724bd5aef1aa07d31fff
at block: 14513 (Tue, 17 Apr 2018 11:13:10 UTC)
 datadir: /home/satoshimaca/blockchain3/node1
 modules: admin:1.0 clique:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> clique.proposals()
TypeError: 'proposals' is not a function
    at :1:1

> clique.proposals
{
  0xf39995b718ae7a0075557f9781425b92fd8b28a6: true
}

but when I attach geth to node 2 I get this -

Welcome to the Geth JavaScript console!

instance: Geth/v1.8.2-stable-b8b9f7f4/linux-amd64/go1.9.4
coinbase: 0xc7c776a8b564228ecca00c86d1d80b431aa9f4f3
at block: 14578 (Tue, 17 Apr 2018 11:18:35 UTC)
 datadir: /home/satoshimaca/blockchain3/node2
 modules: admin:1.0 clique:1.0 debug:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

> clique.proposals
{}

When will my proposal be known to node2 or should I manually add to all the nodes?

Also I do not see any reference in my log to the proposal.


texts:
This is a very simple contract that I can't hack and I'm stuck, I need some help to get the concepts right.

pragma solidity ^0.4.10;

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

    function buyToken() payable {
        balances[msg.sender]+=msg.value / 1 ether;
    }

    function sendToken(address _recipient, uint _amount) {
        require(balances[msg.sender]!=0);

        balances[msg.sender]-=_amount;
        balances[_recipient]+=_amount;
    }
}

I'm using truffle to create the project where this and future contracts will be created, tested, deployed and attacked. I want to create a repository with examples of these hacks while I learn how to do them.

What's the vulnerability and why?

We have sendToken(), to call it you just have to have some balance in your account by first calling buyToken(), but then what? reentrancy, overflow/underflow?

Do I need to create a contract to attack it or just call it from an account via web3js?

pragma solidity ^0.4.10;

import '../SimpleToken.sol';

contract SimpleTokenAttack {
    SimpleToken public victim;

    function SimpleTokenAttack(address _addr) public {
        victim =  SimpleToken(_addr);
    }

    function buy() public returns(bool) {
        // How can I call the function victim.buyToken ?
    }

    function send() public returns(bool) {
        // How can I call the function victim.sendToken ?
    }
}

I plan to create attacks by deloying scripts with truffle exec.

const SimpleTokenContract = artifacts.require('SimpleToken')
const SimpleTokenAttack = artifacts.require('SimpleTokenAttack')

async function execute(callback) {

    let contract = await SimpleTokenContract.deployed()
    console.log(contract.address)

    let attack = await SimpleTokenAttack.deployed()
    console.log(attack.address)

    /*
    - Call buy()
    - Call send()
    */

    callback()
}

module.exports = execute


texts: Is there a way to debug live smart contracts on main network?

texts:
Debug button doesn't work on Remix when targeting a live smart contract. What are my other options?

Can I copy the current main Ethereum network snapshot with ganache and then run my own transactions?

I want to copy the current state, so redeploying the contract to a test network is not an option.


texts: Better way to send transaction/call function with web3.py?

texts:
If I'm using a 3rd party provider for my web3.py connection, I have to do a few things to call a function.

I need to get the nonce:

nonce = w3.eth.getTransactionCount(address)

I need to build the transaction

transaction = contract.functions.function_name(function_parameters).buildTransaction(
  {
    'chainId': 1,
    'gasPrice': gas_price,
    'from': address,
    'nonce': nonce
  })

Then I have to sign it:

signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)

Then I can send it:

w3.eth.sendRawTransaction(signed_txn.rawTransaction)

This seems like really bad UX, whereas with brownie (yes, I know brownie heavily depends on web3.py) I can just call it straight up, the transaction automatically registers the nonce, and if I want to I can add some parameters with the transaction. Like so:
contract.function(function_param, {'from': address})

So, is there a better way to do this with web3.py? Ethers.js solved a similar issue on the javascript side. Or should I just use Brownie not in brownie projects?


texts: Why Remix JavaScript VM and Web3 Provider show different behavior at the time CALL is made?

texts:
I'm using Geth evm version 1.8.4-stable to run private network and I see different behavior on CALL between the Remix environment of Javascript VM and Web3 Provider.

On this example, using callHi() makes difference. It works fine with JavaScript VM, but Web3 Provider fails. Web3 Provider needs gas specification to avoid this failure.

According to 0.4.21 release, CALL does not automatically send the remaining gas. Therefore we need to specify the gas amount when using CALL otherwise it fails to run after 0.4.21.

I understand gas specification is needed to avoid reentrancy issue, but why JavaScript VM still allows CALL without gas specification? Is it a bug or evm version difference?

pragma solidity ^0.4.21;
contract Hi {
    event SayHi(string);
    function hi() public { emit SayHi("Hi!");}
    function callHi() public {
        // OK with JavaScript VM,
        // OK with Web3 Provider, compiled with ^0.4.20
        // Not OK with Web3 Provider, compiled with ^0.4.21 and later
        require(address(this).call(bytes4(keccak256("hi()"))));

        // Web3 Provider needs gas specification to fix Error
        // require(address(this).call.gas(2000)(bytes4(keccak256("hi()"))));
    }
}


texts: CPU mining on testnet using geth on ubuntu - eth.hashrate = 0

texts:
I have setup a CPU miner on ropsten testnet but when I run eth.hashrate it always returns zero. Can anyone tell me why this is? I have searched for an answer, but cannot find a satisfactory answer. I am doing this as a self learning exercise, so would really like to get this working on geth rather than using another medium

Exact setup steps were as follows

Sync ropsten blockchain

  $geth --testnet --fast --cache=1024

Once the entire blockchain synced, I verified that the latest blocknumber was correct

  $geth --testnet attach

    eth.blockNumber

This returned the same blockNum as the the latest block number on Ropsten etherscan

I then created my first account i.e the etherbase account

  $geth --testnet account new

and secured with passphrase

I then began mining with

  $geth --testnet --mine

the output I get appears to be mining

However, my hashrate is always zero


texts: How do smart contracts deal with data that fluctuates?

texts: In my limited understanding of smart contracts, I've read that every node on the Ethereum network must execute a smart contract to come to consensus.  I'm guessing that not all these nodes execute the contract at the same time.  If this assumption is true, then what happens if a smart contracts depends on data that fluctuates, e.g. the price of a crypto/currency?  If those execute the contract at different times and the value of the currency is different at each of those times, how is consensus reached?


texts:
I went to myetherwallet.com with iphone, typed in a password and created a ether wallet.  I did not download the keystore because I wanted this to be secured with just the paper print off on its own.
Is this a good idea?  Thanks


texts: eth :: -F and --farm always produce Invalid argument: when attempting to pool mine

texts:
How can I launch a pool mining session using the most recent cpp-ethereum?

According to the ./eth --help, -F or --farm parameters are needed, but they are not recognized when used!

I have a recent successful build and installation of 'eth' on OpenSuSE, and can successfully launch 'eth' as described in the Homestead doc, page 64:

/opt/eth/bin/eth -v 1 -a 0x.MYWALLET --client-name "Oxymoron" -x 50 -m on -t 1
,resulting in a stream of DAG or Block Import messages, and saturated 100% usage of all CPUs.  ethconsole works too.

But no mining pool can be specified, as it immediately returns:
Invalid argument: --farm  or -F as if it was some arbitrary invalid string like -G.

$/opt/eth/bin/eth -V

eth version 1.3.0,
eth network protocol version: 63,
Client database version: 12041,
Build: Linux/g++/Interpreter/.

wwwwwwwwwwwwwwwwwwwwww

edit:  This feels a lot like a programming logic problem, like somebody commented out some switch's 'case' statement.  Does anyone know if v 1.3.0 has been explicitly set to not support pooled mining?


texts:
I've a node that I'm trying to sync with:
--syncomode "full" --gcmode "archive" in order to address this needing Get a balance of an address at a certain block
Unfortunately things became soo slow that probably we never manage to have a synced node.
What can we use to optimize? I'm thinking on a pool of geth working together as a trusted peers cluster, would this work? Can be this created?


texts:
I am learning ethreum dapps development and have developed some dapps. I was  thinking about supply chain dapp which i think , is very good application of blockchain as it ensures all the history of a product is stored immutability in blockchain, But how do we ensure the integrity of data coming from supply chain participants to get stored in blockchain?

for instance in a particular supply chain, every product  has to go through a quality check, how we be sure that the person responsible for that don't put fake data results in chain?

I know it is a very broad question. But I am very curious about to know as I would like to create supply chain dapp.

thanks in advance.


texts: metamask can't connect to local testnet in geth

texts:
I am using geth 1.7.3 stable,  I have tried the following commands.

geth --rinkeby --ws --wsport=8546 --wsorigins="*" --datadir=$HOME/.rinkeby --cache=512 --rpc --rpcapi="personal,eth,network" --rpcport=8545 --fast --bootnodes=enode://a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf@52.169.42.101:30303

in the first begining

INFO [01-01|12:45:07] Initialising Ethereum protocol           versions="[63 62]" network=1
INFO [01-01|12:45:07] Loaded most recent local header          number=1219706 hash=8114e4…01dc09 td=10746707923789321578
INFO [01-01|12:45:07] Loaded most recent local full block      number=0       hash=d4e567…cb8fa3 td=17179869184
INFO [01-01|12:45:07] Loaded most recent local fast block      number=1203408 hash=255f31…0cba4a td=10416051820938618909
INFO [01-01|12:45:07] Upgrading chain index                    type=bloombits percentage=98
INFO [01-01|12:45:07] Loaded local transaction journal         transactions=0 dropped=0
INFO [01-01|12:45:07] Regenerated local transaction journal    transactions=0 accounts=0
INFO [01-01|12:45:07] Starting P2P networking
INFO [01-01|12:45:07] Mapped network port                      proto=udp extport=30303 intport=30303 interface=NAT-PMP(192.168.1.1)
INFO [01-01|12:45:08] UDP listener up                          self=enode://841b29cdefa12ddbcc2569bb61729338100a365cf2f151f966cfd43b757d986b8b7f99d8d55090f00917307a2f713bb8e5d9bbb2fa91f4a18093b0a45e2cf1c2@82.7.211.112:30303
INFO [01-01|12:45:08] WebSocket endpoint opened: ws://127.0.0.1:8546
INFO [01-01|12:45:08] RLPx listener up                         self=enode://841b29cdefa12ddbcc2569bb61729338100a365cf2f151f966cfd43b757d986b8b7f99d8d55090f00917307a2f713bb8e5d9bbb2fa91f4a18093b0a45e2cf1c2@82.7.211.112:30303

it continuously gives me this information

INFO [01-01|12:39:07] Generated ethash verification cache      epoch=2 elapsed=3.111s
INFO [01-01|12:39:07] Imported new block headers               count=2048 elapsed=483.670ms number=37120 hash=a27938…2d697f ignored=0
INFO [01-01|12:39:08] Imported new block headers               count=2048 elapsed=518.097ms number=39168 hash=1a1cd2…514d2d ignored=0
INFO [01-01|12:39:08] Imported new state entries

wondering the continuous message is meaning the node is at the sync?

during the time, i used the metamask to connect the localhost:8545, but it can't connect to it, anything wrong with my commands?


texts: How to know the hex code to use in data to call a specific contract function?

texts:
For instance, on the BAT ico site, you can see the crowdsale contract address, the ABI and also a string to use in the data part of your transaction if you don't want to call the contract function using the ABI.

The data to put in the transaction is 0xb4427263 that corresponds to the createTokens() function.

How did they manage to get this 0xb4427263 hex value ?
Did they have to make a transaction using the ABI first then get the data from the transaction or is there a direct way to get the value without sending a transaction ?


texts: How to add peers to a private blockchain network without using IP address?

texts:
I have created a private blockchain network and added peers to that network using the admin.addPeers() command. But the problem is, in that method I have to give the local IP address of the system which can be changed at any moment and results in peer disconnection.
Can anyone suggest some other method that can be used so the I can have a stable connection between the peers of the network?


texts: Is an Ethereum paper wallet generator considered a dapp?

texts: I made an Ethereum paper wallet generator. Is this considered a dapp as it can be downloaded and run without any central server to generate ethereum addresses? Or does a dapp have to be tied to a specific token of some sort? What are some good examples.


texts: I am not able to capture the web3 Error: Given parameter is not bytes: "0xue"

texts:
//Error: Given parameter is not bytes: "0xue"
//let a = true

myContract.methods.functionName(a).send({
    from: result[0],
    gas: 4700000,
}).then((result) => {
    console.log(result)
})
.catch((error) => {
    console.log(error)
})

my web3 version is 1.0.0.beta.35


texts: why don't popular tokens have payable fallback

texts:
I'm referring to the source of of the most popular tokens on etherscan.

It looks like they don't have any payable functions.
How do they accept ether and transfer the tokens automatically when someone sends ether to the contracts?


texts:
I'm building a service where one can publish a crypted file on the internet which can be accessed and decrypted by people allowed.
I don't want to store any crypted key on a server or something.

For the moment, I have the owner of the file who initializes a key on the blockchain, and the addresses in a list can access this key after a good require statement. But then I realized that when the owner initializes his key, it's being seen over the input which is public.

Is there a known way to solve this issue ?


texts: In web3.js, how do I accurately find total gas cost to deploy a new contract (including constructor)?

texts:
I am using a public node as my web3 privider, so I must sign all transactions manually. This includes transactions that create contracts.

Currently, I use the following method to deploy contracts.

/* I create the contract first. */
var contractAbi = ... (I load this from a file.)
var contractBytecode = ... (I load this from another file.)
var contract = new web3.eth.Contract(contractAbi);

/* Then I get the data encoded with constructor parameters. */
var contractDeployInfo = contract.deploy({
  data: contractBytecode,
  arguments: [constructorParam1, constructorParam2]
});

/* Data field of the transaction. */
var transactionData = contractDeployInfo.encodeABI();

/* Then I estimate the gas, using the provided method. */
contractDeployInfo.estimateGas().then(gas => {
    // Use this gas estimate to create raw transaction,
    // sign it, send it, and so on.
})

The transaction does go through, and the contract is deployed.

However, the gas estimate returned by contract.deploy().estimateGas() only returns gas that is enough to send the contract through to the miners, but not enough to actually execute the contract's constructor.

As a result, I am left with a blank contract with no data in the contract address that is specified in the transaction receipt.

Should I calculate the gas estimate of the contract's constructor, and add that to the gas limit in my transactions?

This(How to estimate gas at contract creation/deployment to private ethereum blockchain) “duplicate” question uses an older version of Web3 library. Also I was referring to the newly introduced deploy function.


texts:
There is a contract with a betting function that calculates a random number and send you back a reward if winning. The betting function looks like:

function bet() public payable
    {
        if ((random()%2==1) && (msg.value == 1 ether))
        {
            if (!msg.sender.call.value(2 ether)())
                throw;
        }
    }

function random() view returns (uint8) {
          return uint8(uint256(keccak256(block.timestamp, block.difficulty))%256);
}

So if you send 1 ether and hit an odd number (50% chance) you will get back 2 ether. Now I want to precalculate the random number and bet if the number is odd.
I am trying that with a contract like this:

BadRandomBetContract private bet_;

function win() public payable onlyOwner {
        uint8 rnd = bet_.random();         // retrieve "random" number

        require(rnd % 2 == 1);             // odd number
        require(msg.value == 1 ether);

        bet_.bet.value(msg.value)();       // send 1 ether

        require(getBalance() == 2 ether);  // make sure we got 2 ether back, else revert
    }

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

When the winning contract sends 1 ether, transaction fails afterwards. Sending 1 ether at least means the requirement require(rnd % 2 == 1); passed. May it fail at this point require(getBalance() == 2 ether); because the balance does not get updated immediately? Shall I check msg.value in contracts fallback function?

The fail tx is from mainnet and the working one is from ropsten


texts: Transaction Order of Execution - Same Gas

texts:
I'm scratching my head here regarding transaction order of execution.  Reference to these posts:
Order of transactions in the same block
What is the default ordering of transactions during mining?

Let's say we have two accounts A and B
Both accounts sends the same kind of transaction with the exact same gas fee
Which transaction gets executed first?
Is it random?
Does the timestamp play a role?
Or something else?


texts: How to interface with a deployed Ethereum smart contract?

texts:
I want to create an interface to interact with my smart contract. I have got an example from the following link.
Counter

Before implementing my contract, I have tried to use the given example.But it throws an error - " Unable to find web3. Please run MetaMask (or something else that injects web ".But I am able to run the dApp from their website - Counter


texts: Make command to send erc20 token with a different paid address

texts: I want to send 100 ERC tokens from address A to address B but in address A there is no eth to pay fees, I want address C to pay for this transaction, how to do, please help, thanks


texts: Any easy php script to sign and send transactions maybe run contract also

texts: Thanks I have JavaScript version but not php version especially for sign and send transaction


texts:
What happens if a function is being passed before { into another function?

Like DetailedERC20(_name, _symbol, TOKEN_DECIMALS) in this example:

function MyToken(Registry _registry, string _name, string _symbol) public
    DetailedERC20(_name, _symbol, TOKEN_DECIMALS)
{
    require(_registry != address(0));

    registry = _registry;
}

Would this be the same as above:

function MyToken(Registry _registry, string _name, string _symbol) public
{
    DetailedERC20(_name, _symbol, TOKEN_DECIMALS)
    require(_registry != address(0));

    registry = _registry;
}


texts: Why the example of Token Contract contains mintToken function?

texts:
I'm examining the token example given on this page https://www.ethereum.org/token

For what cases mintToken function can be included in a token contract? Can someone trust a token that can uncontrollable increase balance of any account?

Can I just delete this function from my contract without having problems with my token in future?


texts: Why would Ganache behave differently depending on geth, web3j, web3js and web3.py?

texts:
I have a smart contract token deployed in a Ganache instance.  My dapp written with React and web3.js shows the same 10 accounts for eth.accounts as running the same command in the geth console.

If I create my token object with the abi and contract address in geth, I get a different balance for accounts[0] than the balance I get with my dapp.  Both create the token object with the same blockchain address.  Both show that eth.accounts[0] is the same address!

I also have an Android app using web3j.  It uses the same contract address and it displays the same values that the React dapp shows.

However, I also have an app in web3.py and it shows the same values that are shown in geth!

Can someone please explain to me how the same token object could display different outputs on .balanceOf("the_same_address") if it's in the same blockchain?  The only difference is if I'm using geth, web3j, web3.js or web3.py

EDIT: added picture ob browser with console (dapp) and terminal console (geth)

It gives me different balances for all accounts.  It feels as if I was connecting to 2 different blockchains.  However, they have the same 10 default accounts and my contracts deployed in the same addresses.


texts: Operator >= not compatible with types tuple() and uint256

texts:
I’m trying to return the balance of msg.sender from an external contract, but when I try to compare pair.balanceOf() to an uint256, it tells me they are not comparable.
I’m using Solidity 0.8.0 on Remix with OpenZeppelin contracts.
interface TokenInterface {
    function balanceOf(address account) view external;
}

contract Contract {
    address public tokenAddress = 0xc5d63121bA479BAeb666a896e84283a1a0AefAe6;

    TokenInterface token = TokenInterface(tokenAddress);

    function stake(uint256 amount) public {
        require(token.balanceOf(msg.sender) >= amount, "Insufficient balance.");

        ...

    }
}

The other contract is an ERC20 built with OpenZeppelin.
Thanks and have a nice day :)


texts: Can a smart contract send the ERC20 token it owns to another address on trigger?

texts:
I know that a smart contract address can accepts a ERC20 token sent to it.

Let’s say there are two smart contracts A and B. A is a deployed smart contract implementing a ERC20 token and B is the contract I want to write.

I would like to know can I write a method in the contract B so that, on trigger by sending a transaction to call its method, it sends a certain amount of the A token owned by the contract B address to another address I specified?

A follow up question: In a manual transaction sender has to sign the raw ERC20 token transaction and send it to network. For smart contract B, is it as simple as calling the target ERC20 smart contract A’s method and it can use the tokens owned by B’s address? Is there any steps needed to "sign" the transfer?

Thank you.


texts:
I am trying to understand what is Hex Prefix as specified in the Yellow Paper(Appendix C), I don't see a similar reference in the whitepaper, but thank's to this awesome medium post I think I got it, but can somebody please correct me if I am stating anything incorrectly or anything I should add, Thanks in advance for the help. My thoughts on HexPrefix and it's relation to the overall picture in Italics below:

Hex Prefix is an encoding of the "Path" to a given value, in Plain English, it means that hey I know a way to get to this house and here is the map. HP enables to efficiently store the path (aka Map). I think of this as the "Key" in the {Key, Value} pair and hence the Ethereum in a very simple way can be looked at an ever-growing list array of tuples of {HP, RLP} where HP is Hex Prefix and RLP Apdx B Yellow Paper, hence:

World State = [ {hp1, rlp1}, {hp2, rlp2}, {hp3, rlp3} ]


texts: Problems with sending eth from multisig wallet to account using geth console

texts:
I'm running simple tests using geth console before making implementation in java project.
I'm using geth 1.5.4 running as one private node with mining. Here is the command I use to start geth:

geth --datadir /home/javauser/geth_dev/data init /home/javauser/geth_dev/genesis_block_test.json
geth --networkid 123456 --identity "TestNode"  --nodiscover --mine --maxpeers 0 --datadir /home/javauser/geth_dev/data --rpc --rpcaddr "0.0.0.0" --rpcapi "admin,debug,miner,shh,txpool,personal,eth,net,web3" --unlock 0,1,2,3

The content of the genesis_block_test.json:

{
  "nonce": "0x0000000000000042",
    "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "difficulty": "0x200",
    "coinbase": "0x0000000000000000000000000000000000000000",
    "nonce"      : "0x0000000000000452",
    "timestamp": "0x00",
    "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "extraData": "",
    "gasLimit": "0xffffffff",
    "alloc": {
        "0x3a5a8f7951f10aeccc331899dcf291e33ea20355": {
          "balance": "1000000000000000000011"
        },
        "0x4aab741837102f5663bfa36fcea844a2bd46be3f": {
          "balance": "1000000000000000000012"
        },
        "0x1d470f694369586005f4eef6ca44b08513ea7bea": {
          "balance": "1000000000000000000013"
        },
        "0xdf2bbb6ce06c9d3962da556ed321ba8ed96e7188": {
          "balance": "1000000000000000000014"
        }
    }
}

I've created 4 accounts which already has some eth.

Also I've created several multisig wallets based on three different solidity contracts.

First wallet : meteor-dapp-wallet
Second wallet: eth-multisig-v2    (based on meteor-dapp-wallet)
Third wallet:    https://github.com/ConsenSys/MultiSigWallet

So the scheme for running tests:

var _owners = [eth.accounts[0],eth.accounts[1]] ;
var _required = 2 ;
var _daylimit = web3.toWei(10, "ether");

Then goes wallet creating, then I'm sending some eth from the accounts[0] to my wallet:

eth.sendTransaction({from: eth.accounts[0], to:  wallet.address, value: web3.toWei(100, "ether")});

Then waiting for transaction mined and checking the result using

web3.fromWei(eth.getBalance(wallet.address), "ether");

At this step I found the the first wallet implementation does not recieve any eth, the second and the third implementations works fine.

Then I'm trying to send some eth to the third account running command for the second wallet implementation:

h = wallet.execute(eth.accounts[2], web3.toWei(5, "ether"), web3.toHex('send some money'), { from: eth.accounts[0]});
wallet.confirm(h , { from: eth.accounts[0] })

and running for the third:

var nonce1 = wallet.getNonce(eth.accounts[1], web3.toWei(50, "ether"), "");
var transHash = wallet.submitTransaction(eth.accounts[1], web3.toWei(50, "ether"), "", nonce1, {from:eth.accounts[0], sender:eth.accounts[0]})

And gets nothing. Transaction mined but balance of the wallet and accounts[2] do not change. I've tried to send eth value less then daily limit, to change requirement, but nothing helps.
What is my mistake?


texts: How to include headers in oraclize GET request

texts:
I need to be able to include an API key as a header within my GET request to an api using oraclize in solidity.

The oraclize documentation states that you can define arguments to send however, you must add them to a second bracket and by doing so, this makes the request a POST request.

When I try to do this, the API responds saying I have not included my key as a header.

Is this possible?


texts: I have token smart contract that is ERC20 compliant. It is now transferable via any software like MyEtherWallet and similar. I wondering is it possible to forbid token transfer and allow it only using my own site/tool?


texts: Created Token, now can't see my tokens in my account

texts:
I followed the basic tutorial to create a new Token, it all seems to have worked correctly, yet I can't see my new tokens in my account (Ethereum Wallet on mac v0.9.3). Also tried via MyEtherWaller.com but also there I can't see my new Token balance.

Any idea how to see them and admin them?


texts:
I am using the following to sign a message

 var str="Trial with signature";
 text=web3.sha3(str);
 var sig=web3.eth.sign(eth.accounts[0],text);

Now after obtaining the hash value from the text and the signature, to verify the same, I use the following contract

contract signature
{
    event ret_addr(address addr);
    function sig_verify(bytes32 hash, bytes sig) returns(address)                       //verifying the signature
    {
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly
        {
                r := mload(add(sig, 32))
                s := mload(add(sig, 64))
                v := byte(0, mload(add(sig, 96)))
            }
        if(v<27)
            v+=27;
        ret_addr(ecrecover(hash, v, r, s));
    }
}

The issue is I am not getting the correct address back. Why is this so? It used to work fine earlier but now it is giving some random addresses.


texts: In Ethereum and Swarm, Difference between Sharding and Chunking

texts:
Understand that in Ethereum further releases sharding will be included for scalability purposes. In swarm, "Chunks are pieces of data of limited size (max 4K), the basic unit of storage and retrieval in the Swarm"

Though in different context, one is for ethereum state and another for file, aren't chunking and sharding the same in concept? i.e., splitting up the files

Are there subtle difference between chunking and sharding then?

http://swarm-guide.readthedocs.io/en/latest/architecture.html
https://github.com/ethereum/wiki/wiki/Releases


texts:
I'm going to publish two contracts: a standard token contract and a crowdsale contract. What is the best practice for this?

Should I publish it in one file? Does it mean only the second contract in the file will be visible?
If I publish first token then crowdsale contract, do I have to hardcode the token's address in the crowdsale contract?
In that case, how do I make the initial token supply owned by the crowdsale contract?


texts: How can I receive a token which is different from my token?

texts:
Lets say I have made a token with symbol ABC and a user wants to send me token of symbol XYZ. How will I receive such tokens ?

In general, do all the tokens have same economical value?

Can I make a token contract that accepts other tokens? How can I go about it?


texts: My Ether has been automatically sent to another address

texts:
I sent 0.04 Ether to my metamask address and within minutes the Ether was resent to another address automatically without my knowledge.  this is my address 0x627306090abab3a6e1400e9345bc60c78a8bef57 and that the address my ether was sent to without my notice is  0xe3a894890459bb8d23418c8b288c225eb4b13a52.
Can anyone tell me whats going.


texts: I intend to trade tokens and coins using MyEtherWallet. Is it possible to use MEW to do Tx's between ALL coins and tokens, or is the wallet limit to a specific list?


texts:
I am using PoA and running geth just from the cli on google cloud. But I found I had the error below. In terms of reliability is there a way to run it without a dependence on ssh (eg something like batch)?

  INFO [04-13|13:41:00] Commit new mining work
  number=2178 txs=0 uncles=0 elapsed=206.317µs INFO [04-13|13:41:00]
  block reached canonical chain          number=2172 hash=f4ced7…b74e50
  INFO [04-13|13:41:05] Successfully sealed new block
  number=2178 hash=43ec93…e99f5a INFO [04-13|13:41:05]  mined
  potential block                  number=2178 hash=43ec93…e99f5a INFO
  [04-13|13:41:05] Commit new mining work                   number=2179
  txs=0 uncles=0 elapsed=2.588ms packet_write_wait: Connection to
  35.195.116.27 port 22: Broken pipe ERROR: (gcloud.compute.ssh) [/usr/bin/ssh] exited with return code [255]. ~/blockchain$


texts: Are gas limit in transaction and block gas limit different?

texts:
What does gas limit mean?
Are there two meanings of gas limit?

gas limit in a transaction
block gas limit


texts: Calling a function to zero out struct data in a mapping costing more gas than other calls, causing out of gas error

texts:
I am working with the following function and state vars:

struct TimeRestriction {
   uint256 fromTime;
   uint256 toTime;
}

mapping (address => TimeRestriction) public whitelist;

function modifyWhitelist(address _investor, uint256 _fromTime, uint256 _toTime) public withPerm(WHITELIST) {

    //Passing a _time == 0 into this function, is equivalent to removing the _investor from the whitelist

    whitelist[_investor] = TimeRestriction(_fromTime, _toTime);
    emit LogModifyWhitelist(_investor, now, msg.sender, _fromTime, _toTime);
}

I can currently call into this function successfully, and write to the blockchain. I can even call into it and update the values to any timestamp. But for some strange reason when I try to pass 0 values to this function, it will fail. I get the following error:

Error: Transaction dry run failed: Invalid JSON RPC response: {"id":470,"jsonrpc":"2.0"} .

Then when I dug into it some more I got this error:

Error:Returned error: base fee exceeds gas limit.

Then by increasing the tx gas amount by 25%, I see:

Error:Returned error: VM Exception while processing transaction: out of gas

And then when I increase the tx gas amount by 100%, it actually works. (note that I am using the web3 estimate gas function from web3 1.0.0-beta.30)

Does anyone know what is going on here? It seems to me like setting these values to zero is costing significantly more gas, but from reading up it seems that setting to zero is supposed to refund gas, and cost you less.

Does it have something to do with it being a struct inside of a mapping? I have hit a dead end here

Here is my environment:
Ganache CLI v6.1.0 (ganache-core: 2.1.0)
Chrome Version 65.0.3325.181
Truffle version 4.1.3^


texts: Can you input decimals number in smart contract?

texts:
I'm having an issue where send 0.1 or 1.1 is saved as 0 and 1 in my contract's storage.

Does anyone knows how to properly pass decimals ?


texts: Using my contract's functions via RPC calls

texts:
I have written a HTML interface which uses web3.js library. For my testing, I dropped web3.js library into the CoinCode directory and import it in HTML file.

<script type="text/javascript" src="bignumber.js/bignumber.min.js"></script>
<script type="text/javascript" src="web3//dist/web3-light.js"></script>
    var Web3 = require('web3');
    var web3 = new Web3();
    web3.setProvider(new web3.providers.HttpProvider("http://localhost:8019"));

Then, I connected to my contract there by using:

var contract1=web3.eth.contract(abiDefination).at(address);

and I was able to use all the functions of my contract by:

contract1.transfer(..)
contract1.checkBalance("0x..")
contract1.sell(..)

But, how can I make rpc calls to my functions.
Like I can use following call to list accounts:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":65}' http://localhost:8019/

Can I use functions of my contract in similar fashion, like:

curl -X POST --data '{"jsonrpc":"2.0","method":"contract1_checkBalance","params":["0x.."],"id":65}' http://localhost:8019/

and get desired output. Currently when I use such post calls I get:

{
    "jsonrpc": "2.0"
    "id": 67
    "error": {
        "code": -32601
        "message": "The method contract1_checkBalance does not exist/is not available"
    }
}


texts: History question: Left and Right padding

texts:
from:

https://solidity.readthedocs.io/en/v0.5.12/abi-spec.html#encoding-of-indexed-event-parameters

  bytesNN types are padded on the right while uintNN / intNN are padded on the left.

I would really love to understand why it was designed this way.


texts: Anything that can be done about slow Parity Sync?

texts:
I've tried resetting the sync and it still comes to a screeching halt around block number 2.4m. I know about the attacks on Ethereum around those blocks, but this is ridiculous:

I've been syncing for 4 days now, the first day I went from #0 to about #2.2m second day I got to ~#2.4m and the last 2 days it hasn't even got half way to #2.5m. Isn't Parity supposed to be significantly faster than this? I tried syncing with Geth first and it got permanently stuck at 141 blocks left in the same time it's taken parity to slow down to a highway parking lot. Now I can't even get Geth to get back to where it was, since I reset it anyway. Is there any other options to get this thing synced faster? Like downloading someone else's block chain copy or something?
This is how I run Parity: parity --min-peers=50 --max-peers=100 --cache 4096 --geth

Update:
By the end of the 6th day, it sped back up because it past the troubled range. Now it's stalled again with less than 200k blocks left. Yay me. Any ideas?


texts: EthOS mining rig stops working after adding RX 560 GPU and only work with one brand of GPU

texts: I have a mining rig with ASUS EV-B250-V7 MB with 6 GPU, initially only with 3 GTX 1050 TI GPU with EthOS 1.2.9 on USB 3.0 flash drive. The rig has been running for about a week without any problem.  But after adding 3 RX 560 cards, there are bunch of I/O error and the rig stops working. However if only 3 RX 560 GPUs or 3 GTX 1050 TI are plugged in, then the rig works fine. The problem happens when mixing both brand together. Is this configuration issue on EthOS? How to make 2 brand GPU work together?


texts: Solidity 'out of gas' exception when trying to transfer Ether

texts:
I try to transfer Ether from the contract to an address but it gives the error that the transaction is out of gas. I think it's a small problem but I can't find it. I have to specifically use solidity version 0.4.24.

The warning from Remix
The balance of the contract
The parameters I use
The error from MetaMask

I have tried different methods, like:

address.transfer(amount);
address.send(amount);
address.call.value(amount)( );

All methods will give the same out of gas exception. and the send and call method will also give a warning that it's outdated and that I should use the transfer method.

I also tried to adjust the gas and it didn't work, I also tried the needed 2,300 for the transfer listed on the docs.

The code:

pragma solidity 0.4.24;

contract TestContract {

    function() external payable { }

    function payContract() public payable {}

    function paySomeone(address _address, uint256 _amount) external {
         _address.transfer(_amount);
    }

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

}

Does anyone know what the problem is here?

Thank you for reading.


texts: Truffle build dont find _mint and _burn -DeclarationError: Undeclared identifier. Did you mean "mint"? _mint(to, amount);

texts:
after some trouble with remix I'm back at a npm/truffle/ganache setup...
The reason why I tried out remix was:
DeclarationError: Undeclared identifier. Did you mean "mint"?
        _mint(to, amount);

And what can I say... stuck at the same place:
pragma solidity >=0.5.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";

contract Testyis IERC20, Ownable {
   using SafeMath for uint256;
   using SafeMath for uint8;

   address _owner;

...

constructor () public {
    _owner = address(msg.sender);
    _decimals = 18;

...

    function mint(address to, uint256 amount) public {
        require((pre == msg.sender), "Caller is not a minter");
        _mint(to, amount);
    }

    function burn(address from, uint256 amount) public {
        require((pre == msg.sender), "Caller is not a burner");
        _burn(from, amount);
    }
}

"pre" is in this case another contract. When I use remix and import ERC20Detailed with a "normal" github path, then it works. Okay the other contract cant mint or burn, but at least I can do it and also set the pre address.
Hope someone can help :)


texts: Why are Ethereum addresses hashes of public keys?

texts:
I understand how Ethereum addresses are generated. This thread has a great explanation: How are ethereum addresses generated?

However, what this explanation is missing is why a hash is used.

There is a related post with no convincing answer:
Relationship between Ethereum Address and public key

Aside from the point that addresses based on hashes are shorter, a commonly given argument is that the hashing provides additional security in case of a compromisation of the elliptic curve cryptography. In case of Bitcoin, I can sort of see the point of that (as it discourages address reuse), but in Ethereum, addresses are designed to be reused and public keys are revealed with every transaction, so "hiding" them using hashes seems rather pointless.

Even in this post by a Bitcoin Core Developer it is argued that hashing is probably unnecessary.

Disregarding the potentially increased usability of shorter addresses, if one were to design a new blockchain, is there any reason to use addresses based on hashes instead of compressed public keys?


texts: How to read the ETH value and other token values from an account?

texts:
Let's say I've created an account using this code as explained in docs:

web3.eth.accounts.create();
> {
    address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
    privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
    signTransaction: function(tx){...},
    sign: function(data){...},
    encrypt: function(password){...}
}

How do I connect (unlock) to that account later and see all the ETH and other tokens it contains?


texts:
How can I create a smart contract that has a function that receives an input ( either eth or another erc20 token ) and sends it to a specified address without revealing who sent it?

Basically making the transaction anonymous?

Is there any implementations of this as a smart contract?


texts: How can the cost of changing 2 state variables and emitting 1 event reach 50K gas units?

texts:
I have this contract:

pragma solidity ^0.4.23;
contract Test {
    event Event(address indexed wallet);

    mapping (address => bool) public authorizedWallets;

    uint256 public authorizedWalletCount;

    function add(address _wallet) external {
        _add(_wallet);
        emit Event(_wallet);
    }

    function _add(address _wallet) private {
        require(!authorizedWallets[_wallet]);
        authorizedWallets[_wallet] = true;
        authorizedWalletCount++;
    }
}

And I am checking the gas cost of function add via web3 v1.0.0-beta.34 on NodeJS:

async function send(transaction) {
    let success = await web3.eth.personal.unlockAccount(OWNER_ADDRESS, OWNER_PASSWORD);
    let gas = await transaction.estimateGas({from: OWNER_ADDRESS, gasPrice: GAS_PRICE});
    console.log(`gas = ${gas}`);
    return await transaction.send({from: OWNER_ADDRESS, gasPrice: GAS_PRICE, gas: gas});
}

for (let i = 1; i < 10; i++) {
    let wallet = `0x5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5${i}`;
    let hash = await send(contract.methods.add(wallet));
}

Note that after I print the gas cost, I execute the transaction so that it will take actual effect on the contract, and subsequently on the gas cost of the next transaction.

On the first iteration, the gas cost is 64827.

On each one of the following iterations, the gas cost is 49827.

This difference by itself makes sense I suppose, since the first transaction probably changes a lot more 0s into 1s than each one of the following transactions (I would guess, in the mapping (address => bool) public authorizedWallets data structure).

What doesn't make much sense to me, is how come each one of these transactions is so costly, as there are only a few operations executed:

_add(_wallet);

require(!authorizedWallets[_wallet]);
authorizedWallets[_wallet] = true;
authorizedWalletCount++;

emit WalletAccepted(_wallet);

I am using Parity and Ropsten for all it matters (I believe that it's not supposed to matter, but maybe I'm wrong here).

Can someone please explain why the cost of these few operations reach 50,000 gas units?

Thank you!


texts: Using Multiple Accounts from a single physical machine

texts:
Hey all,
I was wondering something. I am planning to create a simple Voting Dapp for a closed election, where a number of accounts will be set up ahead of time and pre-authorised to vote. The Voting Contract will contain a Whitelist to know whether or not someone who makes a call to its functions should be allowed to vote. My question is this: the number of PCs that I have (maybe twelve or so) is far less than the number of prospective voters I have. Ideally, I would like to be able to use the PCs in a manner akin to Voting Stations: that is, they would be able to log in and make a vote on an Account, which would be unique to them, but which would be only one of many accounts available on that particular PC. Is this possible? Would it require, say, Metamask accounts? I'm unclear as to what an architecture like this would look like.

Thanks for your help.


texts: Distributing interest to a set amount of tokens

texts:
Consider a contract which manages an unlimited amount of ERC20 tokens. A user can create a token via this contract and give it a name. The contract also acts as exchange for buying and selling tokens it created for Dai:
contract TokenManager {

    function createNewToken(string name) external {
        // Deploy a new ERC20 token with this name
    }

    function buy(string name, uint amount) external {
        // Mint tokens to user, take Dai
    }

    function sell(string name, uint amount) external {
        // Burn tokens from user, send Dai
    }
}

The exact price model of the tokens is not important for this question. The key point is that the price of a token increases the more Dai were spent for it and vice versa.
Now to the question:
The Dai users pay for the tokens can be invested into Compound or similar to generate interest. I want to spread this generated interest across a given amount of the highest ranking tokens. For example the top 100 tokens receive all of the generated interest according to their share of Dai in the top 100 tokens. By receiving the interest their price rises further.
The problem is keeping track which of the tokens are in the top 100. Theoretically it would be possible with a linked-list which contains all tokens ordered by their market cap. However in practice the gas costs would be too high for an unlimited amount of tokens.
Is there a way to do this with constant gas?


texts: How to send Custom tokens ERC20 fromWallet - ethers.js

texts:
I have tried this solution and it worked but only if I use privateKey of the wallet which I used to create custom tokens but what if I want to send from B wallet to C wallet and when I am trying it, the transaction is happening but it's failing.

Failed transaction

var contract = new ethers.Contract(contractAddress, abi, wallet);

var numberOfTokens = ethers.utils.parseUnits('10.0',numberOfDecimals);
var options = { gasLimit: 1500000, gasPrice: ethers.utils.parseUnits('1.0', 'gwei') };

contract.transferFrom(fromAddress, targetAddress,numberOfTokens,options).then(function (tx) { console.log(tx); });

thanks


texts: Where is the bytecode of smart contract stored ? And how to get it executed?

texts:
Well, my question is terse but to the point: Where's the bytecode of smart contract stored?  And how to get it executed ?
From the image and Ethereum Yellow Paper we can see there is codeHash in WorldState ==> Account which is described as:

The hash of the EVM code of this
account—this is the code that gets executed should
this address receive a message call; it is immutable
and thus, unlike all other fields, cannot be changed
after construction. All such code fragments are
contained in the state database under their corresponding
hashes for later retrieval.

So, it only mentions the codeHash but not the code itself. So, it seems I have to read Ethereum's source code to get how it deals with contract bytecode and that's what I'm doing but you know, it's thousands of lines of Golang code. So did anyone have some ideas about that ?


texts: Can I count on this general pattern executing correctly (similarly to C, C++ and probably any other language)?

texts:
Suppose I have something like this:

contract MyToken is ERC20 {
    MyTokenImpl private myTokenImpl;

    constructor(MyTokenImpl _myTokenImpl) public {
        myTokenImpl = _myTokenImpl;
    }

    function transfer(address to, uint256 value) public returns (bool) {
        let status = myTokenImpl.transfer(to, value);
        return status || super.transfer(to, value);
    }
}

In the expression status || super.transfer(to, value), can I count on the right-hand side executing only if the left-hand side is false?

In every language that I know, this is indeed the case.

Can I count on the Solidity compiler to abide the same rules, i.e., jump out of the function without executing the right-hand side if and only if the left-hand side is true?

Is this specified anywhere in the official documentation?

Thanks


texts: Can Ethereum be used to perform computations?

texts:
Can a contract encode a paid request to perform some calculation?

For example, I would like to pay 1 ether to calculate the 100th prime number, and I want the Ethereum blockchain to calculate it for me. In another language, the code might look like this:

boolean function isPrime(int n) {
    if(n < 2)
        return false;

    for (long i = 2; i * i <= n; i++)
        if (n % i == 0)
            return false;
    return true;
}

for(int i = 1; ; i++) {
    if(isPrime(i))
        counter++;

    if(counter == 100) {
        print(i);
        break;
    }
}

The question is not about a contract on doing some work, but about Ethereum's ability to handle computations.


texts: Token balance of all addresses in contract

texts:
How can I retrieve the token balance of all the addresses used to store a spesific ERC20 token in Solidity?

That is, without having a list of addresses, but only relying on the data in the smart contract.


texts:
The hash of a transaction is computed by serializing it and then hashing that.  How are transactions serialized?

Specifically, knowing that this is the data structure of a transaction, what fields are included in the serialized transaction, and in what order?


texts: Why we need "stateMutability" in contract's ABI if we already have "constant" and "payable"?

texts:
stateMutability: a string with one of the following values: pure (specified to not read blockchain state), view (specified to not modify the blockchain state), nonpayable and payable (same as payable above).

constant: true if function is specified to never modify blockchain state;
payable: true if function accepts ether, defaults to false.


texts: Getting "Contract Compilation failed" error

texts:
I am trying  to run my first contract and getting this error "Contract Compilation failed".

pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {

uint storedData;

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

function get() public view returns (uint) {
    return storedData;
}
}

Am i doing any mistake? what should i do?


texts:
I'm designing a dApp where users can submit work they've done (files) to ipfs/swarm. To get credit for the work they then reference the hash of the files when calling a smart contract. What are some ways I might avoid front-running attacks (i.e. someone trolling pending transactions for work submitted, read a file hash, and use more gas to jump to the front of the line, and get credit for someone else's work)?

I'm not very familiar with state channels, but based on my understanding it is one possible solution (although then I'm sacrificing decentralization by having to coordinate the transactions).

There is a reputation component to the app, so maybe some sort of consensus mechanism that burns user reputation/funds if they are deemed fraudulent. Although this requires another layer of approvals/consensus before the work can be considered 'done' and I'm not sure exactly how would be able to could detect fraud.

Is there a simpler solution I'm not seeing? Any thoughts are welcome.

Thanks

EDIT:
I can imagine a two-transaction sequence where someone submits an integer that is the hash modulo their address (or something) followed (once settled) by another transaction with the actual hash, which can now be verified. Not sure if there's anything better.


texts: REVISED: Create a car rental system without the need of a trusted third party on blockchain

texts:
I am working on a project which use Blockchain to develop a car rental system, I have very basic knowledge. Basically, I want people to be able to rent their own car to people who want to rent in a short term period, without needing an intermediary, similar to Airbnb.

Basically, there a few questions I want to ask is:

How can I transfer the access to the vehicle between users on a selected date and return the access back to the owner once rental period ends?

How to transfer money from an account once rental period has begun?

Would be difficult to allow either renter or vehicle owner to cancel a rental agreement?

Have multiple vehicles rentable?

I would really appreciate any advice, especially on a coding perspective.

Thank you,


texts: How to convert from Wei to Ether in React?

texts: In React, I use a Web3js call function to get a value. The returned value is in Wei. However, I want to render it in Ethers. What would be the best way to do it?