texts: When using array.push in solidity contract the logs is empty (using truffle-contract)

texts:
When I run the below solidity function:

function startAuction(string name, uint timeLimit) public returns (uint[]) {
    uint auctionID = totalAuctions++;
    AuctionStruct a = Auctions[auctionID];
    a.recipient = msg.sender; // the person who starts the auction is the recipient
    a.name = name;
    uint array = auctionList.length;
    auctionList.push(13);
    Update(a.name, a.highestBid, a.highestBidder, a.recipient, auctionID, array);
    return auctionList;
}

Using the below request from javascript:

contractInstance.startAuction(auctionname, duration, { from: buyerAddress }).then(function(result) {...

I receive a response with an empty logs array.

But when I remove the below line from the above solidity function:

auctionList.push(13);

And add the below Solidity function I receive a filled logs array from the first function and an auctionList from the below function including the pushed 12:

function listAuctions() public returns (uint[]) {
    auctionList.push(12);
    return auctionList;

}

Which is called using the below request in javacsript (next to the prior script to request the solidity function):

contractInstance.listAuctions.call().then(function(v) {...

I am using truffle-contract to access the contracts, which is activated using the below code:

var Auction = contract(auction_artifacts);
console.log(Auction);
Auction.setProvider(web3.currentProvider);

The contract is included using browserify:

global.contract = require('truffle-contract');
global.auction_artifacts = require('../build/contracts/Auction.json');

When I run the above functions from the truffle console all seems to be working fine.

Could anyone explain this?


texts:
I have tried running programs with oraclize on the ethereum testnet (Morden). My program fails to compile due to import "dev.oraclize.it/api.sol" error.

I have therefore tried to manually download api.sol. I guess I have to store this file somewhere specific in order for my contract to work, but where? I cannot save it directly in the contract folder since I am writing my contract directly in the ethereum wallet.


texts: Insurance platform's and Ethereum smart contracts

texts:
I am trying to create a proof of concept for an insurance platform, a one that deals with risk and selling promises of coverage. A similar idea will be the car insurance platform's where you pay each month for 5 times coverage a year.

What I want to ask is how would ethereum and the smart contracts built on top of ethereum be useful in this case? Would it be just a paper contract integrity checking mechanism (like digital certification)?

Thanks.


texts: Balance does not match incoming transactions

texts:
In my akasha account - I currently have a balance of ~40(test)ETH:

https://rinkeby.etherscan.io/address/0x925770eee9e66e7f628fbf9244f2888fb0a5d36f

But I only see one incoming transaction of 4.2(test)ETH

https://rinkeby.etherscan.io/txs?a=0x925770eee9e66e7f628fbf9244f2888fb0a5d36f

Can someone explain what is going on there?


texts: Solidity event function not appearing in web3

texts:
I have a contract with the following event (using 0.4.24):

event UpdateProgress(bool _gameInProgress);

I am registering the contract like this:

import Web3 from 'web3';
import address from './address';

const web3 = new Web3(window.web3.currentProvider);
const abi = [{...}}

// Access to our contract that exists on the blockchain.
export default new web3.eth.Contract(abi, address);

When I call the events object in my JS:

// Contract
import leaderboard from './leaderboard';

console.log(leaderboard.events.allEvents());

All events is empty. What am I doing incorrect here?


texts: transaction pending but now showing on MEW

texts:
I wanted to transfer ERC20 tokens to transfer from metamask to exchange. However I accidentally set 2 gwei, which was very low. Now my transaction is pending and it doesn't showing up in myetherwallet as a pending status. Can this transaction be automatically cancelled or I have to do something? (transaction is not showing up, so I am not able to replace or cancel it)

TRANSACTION SHOWING HERE https://etherscan.io/address/0x3cef0911c527cfd6bdc8cf9045f38c2da29787dd

SAME TRANSACTION NOT SHOWING HERE (using TXHASH on MEW)
Go to: https://www.myetherwallet.com/#check-tx-status

& paste TxHash: 0x113d0136b7286ca8cc1fdd03d82c9e52e9e23e8bb88eecc081d2e45a57e46ac1

MY QUESTION
this transaction will ever be executed or not? What should I do to get rid of this?


texts: While using MEW Error encountered during contract execution [Bad instruction]

texts:
I am facing some issue with the token transfer , when I am using REMIX with Metamask , the transfer of the tokens from a non owner account to another account works fine . However when using MEW or MIST the transaction fails .

  function transfer(address _to, uint _value) returns (bool success){
      require( balances[msg.sender] >= _value &&
          _value > 0 );
          _value     = _value.mul(1000000000000000000);
          balances[msg.sender]  = balances[msg.sender].sub(_value);
          balances[_to]  = balances[_to].add(_value);
          Transfer(msg.sender,_to,_value);
          return true;
  }

  function transferFrom(address _from, address _to, uint _value) returns (bool success){
      require( balances[_from] >= _value && _value > 0 );
    _value     = _value.mul(1000000000000000000);
    balances[_from]  = balances[_from].sub(_value);
    balances[_to]    = balances[_to].add(_value);
    Transfer(_from,_to,_value);
    return true;
  }


texts:
From: https://medium.com/blockchannel/life-cycle-of-an-ethereum-transaction-e5c66bae0f6e

"Eventually your local node will receive this new block and syncs it’s local copy of the blockchain. Upon receiving the new block, the local node executes all the transactions in the block."

What happens if the local node while executing all transaction in the newly monted block found out that one transaction does not yield the correct results? Different execution results from other nodes


texts: Missing trie node only on some blocks > is it possible to resync a specific Block?

texts:
I'm trying to trace some transactions and I'm getting the
"Missing trie node" warning only on some specific blocks, but not on others

I've read a solution that suggests to delete the chaindata folder
but I wouldn't want to do that as it took forever to download in the first place.

Is there a way, though a low level API, to force the resync / re-download ONLY of the specific blocks that cause the Missing trie node problem?


texts: What's the difference between Nakamoto consensus vs Proof-of-Authority vs BFT

texts:
Documentations all around the internet are filled with these terms to categorise consensus protocols. What is the difference between them.

For example: many call parity's tendermint as a BFT type whereas official docs say it's a PoA protocol.

Can we have proper definition to them and also what are the other categories?


texts:
Follow up on: Web3J: TypeError: MyContract is not a constructor

Here is how my contract looks like:

contract OrganisationsFactory {
    mapping(string => OrganisationObject[]) organisations;
    event CreatedOrg(address indexed hsAddr);

    function add(string name, string vat, string headquaterAddress) public returns(address) {
        OrganisationObject newOrg = new OrganisationObject(name, vat, headquaterAddress);
        organisations[name].push(newOrg);
        CreatedOrg(newOrg);
        return newOrg;
    }

    function get(string name) public returns(OrganisationObject[]){
        return organisations[name];
    }
}

contract OrganisationObject {
    struct organisationDetails {
        string name;
        string vat;
        string headquaterAddress;
    }

    organisationDetails public details;

    address[] public staff;

    function OrganisationObject (string name, string vat, string headquaterAddress){
        details.name = name;
        details.vat = vat;
        details.headquaterAddress = headquaterAddress;
    }

    function addStaff(address x){
        staff.push(x);
    }
}

My aim is to create a contract on the chain containing the details of an organisation, to then be retrieve in the future. Basically just like a database.
If I follow your approach I will compile a new contract every time, I will therefore never know where is my "organisation" kept unless I keep a reference to it contract in a conventional database.

Is there a better way then my approach to deal with this ?


texts: Error calling web3.eth.Contract send() function gives error: Method not found

texts:
I just deployed a contract and wants to access it using web3 to read and write data.
I have web3 working, passed the contract Address and ABI and I can access the contract and Read Data using:
contract.methods.getPrice().call()
This returns the correct value from the contract.
However, If i want to write something using send() like:
contract.methods.setTestString("Test").send( {from: account }, function(error, transactionHash){
alert(error);
});
I get the error "Method not found". But the method is there and it is also public available.
Any ideas?
Thx


texts: I want to use a decentralized btc wallet which I can create btc address and export private key safely. Which wallet I can use? I mean the reliable decentralized btc wallet? Some wallet does not support private key export function.


texts: Using a solidity smart contract, what's the best proof that A can provide B showing that A acted in good faith towards paying C?

texts:
Let's say that applicant (A) has applied for a lease that's managed by some landlord (B), and that during the screening process, B has discovered that A owes money to his old landlord (C).
In B's lease agreement, applicants must be debt-free with all previous landlords. Given proof of settlement between A and C, B will sign the agreement with A.
A has the money to pay C, but C hasn't responded to any of A's voicemails or emails that show A's willingness to pay off his debt. Without cooperation from C, A doesn't have the information needed to send money using traditional electronic methods.
Is there an existing solidity smart contract that would allow A to prove to B that he has acted in the best faith possible towards paying back C? If not, would creating one be possible and/or be a good solution?


texts: Migrating from paper wallet to Ledger Nano S with private key ONLY

texts:
I recently purchased a Ledger Nano S, and I'm wanting to transfer my Ether from my paper wallet to the new ledger device. Please forgive my ignorance, but I have no idea how I can transfer my Ether using ONLY my private key for my paper wallet. Unfortunately, I no longer have access to the original JSON file that was created for my paper wallet which I had created on "My Ether Wallet .com" some time ago, so my private key is all that I have :[

If someone could take the time to simplify the process, I would be INCREDIBLY grateful, and would also be willing to donate some Ether to you upon my successful migration from paper to ledger.

Thanks.


texts: truffle unbox react - front end is unable to read / set state of the contract

texts:
I am experiencing problems with the Truffle React boilerplate code that the front end is unable to read / set state of the contract. Here are the details:

I unboxed the React boilerplate using truffle unbox react. I updated the development host and port details in the truffle-config.js to match the Ganache configurations, while Ganache running in the background. I successfully truffle compile and truffle migrate the SimpleStorage contract to Ganache. I opened another terminal and cd into the client folder, npm install the latest "web3": "^1.0.0-beta.55" and other dependencies in the client folder. I then logged in my MetaMask with the same Mnemonic generated by Ganache, so then I can access all the wallet accounts. I npm start the client and the app appears to be working on the localhost:3000. Everything runs except the front end is unable to read / set state of the contract. The stored value is 0 as opposed to be 5. What has gone wrong?

Github repo:
https://github.com/hugo2soo/react

Best,
Hugo


texts: How to clean up geth data directory, perhaps moving more into freezer?

texts:
I am running full geth 1.10.1 node; there is quite a large amount of data in active database and not nearly enough is moved into freezer db:
Filesystem      Size  Used Avail Use% Mounted on
/dev/vdc        314G  255G   44G  86% /var/lib/geth/data
/dev/vdd        472G  197G  251G  44% /var/lib/geth/data/geth/chaindata/ancient

Questions are:

is there any way I could migrate more data from active set into freezer?
is there another way to safely prune the active database to reduce amount of data?


texts: Web3 Websocket Connection To Infura Rinkeby Ropsten

texts:
This is my Javascript code. I keep getting an error that states

  (node:30062) UnhandledPromiseRejectionWarning: TypeError:
  privateKey.startsWith is not a function

I am using node 12.1.0 & web3^1.0.0-beta.55

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

   web3.eth.accounts.wallet.add({
        address:_publicKey,
        privateKey: _privateKey
    });
    const contract_Instance = await contract.deploy({
        data: _bytecode,
        arguments: _constructor_args})
        .send({
        from: _adminAddress,
        gas: 1500000,
        gasPrice: '20000000000'
    });

What am I doing wrong here?


texts:
The solidity wiki explains that standalone assembly is also possible. However, I cannot compile it. For example:

{
  mstore(0x40, 0x60) // store the "free memory pointer"
  // function dispatcher
  switch div(calldataload(0), exp(2, 226))
  case 0xb3de648b {
    let r := f(calldataload(4))
    let ret := $allocate(0x20)
    mstore(ret, r)
    return(ret, 0x20)
  }
  default { revert(0, 0) }
  // memory allocator
  function $allocate(size) -> pos {
    pos := mload(0x40)
    mstore(0x40, add(pos, size))
  }
  // the contract function
  function f(x) -> y {
    y := 1
    for { let i := 0 } lt(i, x) { i := add(i, 1) } {
      y := mul(2, y)
    }
  }
}

(Taken from solidity docs).

How do I compile this? I'm pretty sure I have to add some flag in solc. Is it possible to compile this in remix?


texts: How can I connect to a local geth node from docker container?

texts: In this case, I run a geth node in local env, and A app in docker,  How can I connect to geth from docker?


texts: getting error error TypeError: Member "isContract" not found or not visible after argument-dependent lookup in address payable

texts:
Using Solidity 0.4.17, I have defined a simple library at ./Addresses.sol

     function isContract(address _base) external pure returns(bool) {
    assembly {
        _r := gt(extcodesize(_base), 0)
     }
   }
 }

Now I am trying to use it in a contract at ./AddressesTests.sol

pragma solidity >=0.4.21 <0.6.0;

import "./Addresses.sol";

contract AddressesTests {
using Addresses for address;

function testIsContract() public {
    //error  TypeError: Member "isContract" not found or not visible
  //after argument-dependent lookup in address payable.
    assert(address(this).isContract());
    assert(!msg.sender.isContract());
   }
 }

I get the error

   TypeError: Member "isContract" not found or not visible after
   argument-dependent lookup in address payable.
    assert(!msg.sender.isContract());
            ^-------------------^

What am I doing wrong?


texts:
I have some confusions regarding Token and Coin.

Form my understanding, Token are built top on some blockchains like Ethereum for crowdfunding. That Token has a name itself let say "" (A to Z token). Lets assume that crowdfunding is successful.

Now that team build their project and create their own Coin on their own real blockchain. Lets say that coin name is "ZAT" (Z to A token).

Now my question is how can the AZT(in Ethereum)and ZAT(own blockchain) can be exchanged? What can investor do with the AZT token(From ethereum) when there is actual  coin ZAT (blockchain) from that team.

What are the similarities and dissimilarities between Crypto token and coin.

NB: Pardon me if I have been asked a very silly question.


texts:
I am a neophyte(noob) in cryptocurrencies so I'm here at stackexchange with this question, what is the difference between blockchain size and dag file size? Because what actually confused me was the values of it, the blockchain size of Ethereum is 670 gigs and that of the DAG file size is only 2.6 gigs.
So what exact values are they storing of and can also someone explain me in brief about the contents of both the things or at least help me by referring a link in the reply?ASAP pls....

Thanks a lot


texts:
Can you tell me the differences between

--rpcaddr 127.0.0.1

--rpcaddr 0.0.0.0

--rpcaddr my_public_ip

--rpcaddr my_private_ip

during a private network config?

Thank you


texts: POA - Always pending transaction in txPool

texts:
Always when I send transactions (I tried several accounts) it gets stack in the txpool (pending) so they are not mined, I am using POA, I checked gas and nonce and they are good.
What are the possible reasons for this issue? I think it is related to the mining mechanism (I am using clique) I am not yet sure though, Thanks in advance.


texts: Getting exchange address 0x0000000000000000000000000000000000000000 by using factoryContract.methods.getExchange(tokenAddress)

texts:
I am using UNISWAP API to automate a swapping transaction, by using UNISWAP_FACTORY_ABI and UNISWAP_FACTORY_ADDRESS i have created uniswapFactoryContract as follows:
const uniswapFactoryContract = new web3.eth.Contract(UNISWAP_FACTORY_ABI, process.env.UNISWAP_FACTORY_ADDRESS)

when i am trying to get exchange address by using:
const exchangeAddress = await uniswapFactoryContract.methods.getExchange(BuyTokenAddress).call()

i am getting a value 0x0000000000000000000000000000000000000000 that means the token does not yet have an exchange.
What should i do to make a swap?


texts: I created my own liquidity pool on Uniswap V3. Now I'm trying to add liquidity to my pool with my smart contract. Which Uniswap contract including addLiquidity() or increaseLiquidity() methods? What are the differences between of them? How can I call that method from my contract?


texts:
I don't understand how ABI encoding with tuples work:

f(uint8[], uint) with arguments [3], 4 accordingly https://abi.hashex.org produces:

479587820000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003

In arguments the value 3 goes before 4, but in the encoded 4 is before 3. In some reason, the value 3 is at the very end despite it is in the first element. Why?!
First go all the heads, then all the tails, right? Each head is a 32 bytes offset to the corresponding tail from the beginning of the tuple, right?


texts:
I tried to create a smart contract (Token ERC20) with this web IDE : https://remix.ethereum.org
Everything was good.
I taked te same contract and i tried to deploy it with node application by using web3 and solc (for the compiler). When i send the transaction to create the contract, i recieve an error who tell :  "Warning! Error encountered during contract execution [Out of gas] "

Can you help me please to fix this problem ?


texts: Simulating the passage of time with testrpc

texts:
Any tips on how to simulate real network conditions on the testrpc testing client using truffle?  I have some functions that look at blocknumber and try to deal with passing time.  Has anyone come up with a good way to test these kind of things?

I'm wondering if just calling some null transactions in a loop with increase the block number accordingly.  Any info on the inner workings of these things would be appreciated.


texts: Geth 1.9.11 (and JSON-RPC) are still using a old version of web3?

texts:
Geth console by default is using web3  0.20.1, even in the very last geth version (1.9.11). Is it possible to use web3 1.0+?

{
  api: "0.20.1",
  ethereum: "0x41",
  network: "3",
  node: "Geth/v1.9.12-unstable-2a5ed1a1-20200225/linux-amd64/go1.13.8",
  whisper: undefined,
  getEthereum: function(callback),
  getNetwork: function(callback),
  getNode: function(callback),
  getWhisper: function(callback)
}


texts: Sent transaction between ETH and ETC accounts

texts: Halp! I sent a transaction between an ETH account and an ETC account by accident! How can I recover the ether?


texts: Is there a certification process or agency for ERC-20 tokens?

texts:
The EMV site claims that their token contracts are officialy ERC-20 certified and is listed here (then they give their EtherScan address).

My question is whether there is a certification agency or process.
I realize ERC-20 is a standard that can be followed, but is there some way to certify or validate that it actually followed?


texts:
I'm just trying to return the multiple value in the loop. How this can be done, if I wish to return the last 20 value of x and y. here is the code:

contract Bar{

    struct Foo{
        uint x;
        uint y;
    }
    mapping(uint => Foo[]) foo;

    function add(uint id, uint x , uint y)  {
        foo[id].push(Foo(x, y));
    }

    function get(uint id, uint index) public returns(uint, uint){
      //  return foo[id][index].x;
      {
      var a = foo[id][index].x;
      var b = foo[id][index].y;
      }
      return (a,b);
    }

    function get_last_ten(uint id) constant returns(uint[20]){
    uint[20] memory lastItems;
    for(uint i=0;i<20;i++){
        if(foo[id].length>i){
            lastItems[i] = foo[id][foo[id].length-i-1].x;
        }
    }
    return lastItems;
}
}


texts: What is Calldata tag needed when a function has a string parameter?

texts:
I'm using:

 pragma solidity ^0.5.0;

I have a function as below in my contract:

function test(string a) external{
  a="apple";
}

An error shows up saying I need to add "calldata" to the parameter. So, if I do the following the error disappears:

function test(string calldata a) external{
  a="apple";
}

Question: Why do I need to add "calldata" when I use string type as a parameter?


texts:
Codius is one of smart contract platforms by Ripple which project is unfortunately suspended.

What did they try to do with Codius?
How does it differ from Ethereum?


texts: Javascript web3 calls Solidity contract function with extra parameter?

texts:
In the http://truffleframework.com/tutorials/pet-shop example, there is the following contract, and the function adopt(uint petId) has only one parameter.

contract Adoption {
    address[16] public adopters;

    function adopt(uint petId) public returns (uint) {
        require(petId >= 0 && petId <= 15);
        adopters[petId] = msg.sender;
        return petId;
    }

    function getAdopters() public returns (address[16]) {
        return adopters;
    }
}

However, in the javascript code app.js, the handleAdopt function call the contract function using the following code.

  App.contracts.Adoption.deployed().then(function(instance) {
    adoptionInstance = instance;
    return adoptionInstance.adopt(petId, {from: account});
  })

The function is called with the extra object {from: account}. Why? And is this parameter discarded in the solidity code?

BTW, there is an undefined global variable web3? Is the value be assigned by the MetaMask extension?


texts: Will contracts on Frontier be wiped before the move to Homestead?

texts:
The Frontier Guide contains instructions on how to create a Greeter contract. Those instructions contain details about how to kill a contract, and why we'd want to do that. Part of those instructions read:

  If you don't add any kill clause it could potentially live forever
  (or at least until the frontier contracts are all wiped)
  independently of you and any earthly borders, so before you put it
  live check what your local laws say about it....

I'm assuming this isn't going to be the case, and the instructions just need to be updated (right?), but was this actually the original plan, and if so, why? And how would this have been achieved without destroying non-contract data? (i.e. transaction/account details).


texts: I want to connect Ganache to Ropsten such that i can see Ropsten's ledger with Ganache. Is this possible? if yes, what settings do I need to do on Ganache?


texts: How are encrypted Oraclize queries protected against replay attacks, precisely?

texts:
The Oraclize API allows users to encrypt a query or part of a query using their public key "to protect data from public scrutiny," to quote their documentation.

The documentation has this to say about replay attacks: "In order to prevent other users from using your exact encrypted query ('replay attacks'), the first contract querying Oraclize with a given encrypted query becomes its rightful 'owner.' Any other contract using that exact same string will receive an empty result."

A few points of clarification:

If I send a computation query where an encrypted API token is one of the arguments, and the other arguments are not encrypted, will an attacker be able to use my API token to make computation queries with different plaintext arguments? The documentation refers to "that exact same string" but it's not clear to me whether that refers to a single argument, or the entire query.
If an attacker does attempt a replay attack using "that exact same string," and Oraclize returns an "empty result" to that user, what exactly has happened behind the scenes? Has Oraclize actually executed the query and then just hidden the result to the caller? If so, that is a problem, because most APIs have a request limit, and an attacker could use this to spam the external API and exceed the token request limit, thereby breaking the smart contract. My specific external API has a limit of 5 requests per second and 1000 requests per day, so this isn't too hard to abuse, especially since each computation query will make multiple requests to the external API.
Does the replay attack protection apply to all the networks, or just mainnet? That is, can someone take my encrypted API token from mainnet and use it on Rinkeby to spam the external API and break my smart contract? Or is the "rightful owner" feature consistent across all the networks?


texts: Etherscan "Write" buttons not interacting with Metamask

texts: For some reason, I cannot get any of the "Write" buttons on Etherscan to intereact with my metamask. I made sure to "connect to Web3" before I proceed to click on the "Write" button, but it's not responding. I thought there was a problem with my computer so I just re-formatted my PC and it's still not responding. I checked my Laptop and it's working fine. This problem is driving me nuts. Does anyone what is going on with my PC?


texts: Way to import library in a solidity smartcontract

texts:
I am studying smart contracts and I have looked at some popular projects on GithHub.
I have seen imports like this:
 import "@openzeppelin/contracts/math/SafeMath.sol";

and like that:
import "openzeppelin-solidity/contracts/math/SafeMath.sol";

I do not understand the difference between these 2 methods for importing the SafeMath library.
Thanks


texts: How to get multiple blocks timestamps with a single JSON RPC call?

texts:
Is there a way to get data similar to the ones provided by web3.eth.getBlock(blockNumber) but with multiple blocks at once?

The goal is to get the timestamps for 100 blocks in a row without performing 100 http calls to Infura. Thank you.


texts: Using Smart contract with web3- Not able to send transaction sucessfully

texts:
I tried to send ether from multiaddress, for that I have created one contract. Contract is deployed successfully in ropsten testnet.

I have started service in background using this command.

parity --warp --chain ropsten --rpcapi 'eth,net,web3,personal'

Contract Code:

pragma solidity ^0.4.20;

contract ERC20 {
  function transfer(address _recipient, uint256 _value) public returns (bool success);
}

contract Airdrop {
  function drop(ERC20 token, address[] recipients, uint256[] values) public {
    for (uint256 i = 0; i < recipients.length; i++) {
      token.transfer(recipients[i], values[i]);
    }
  }
}

Contract Deployed URL: https://ropsten.etherscan.io/address/0x84265173B2386D674ABA59b35D8C2A77C8A88181

Tried to apply send_transaction using Web3Js but Not able to success.

const Web3 = require('web3')
const abi = require('human-standard-token-abi')

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

// Define the contract addresses and the contract instance
const contractAddress = '0x84265173B2386D674ABA59b35D8C2A77C8A88181'
//const contract = new web3.eth.contract(abi, contractAddress)

var contractAbi = web3.eth.contract(abi);
var contract = contractAbi.at(contractAddress);
// suppose you want to call a function named myFunction of myContract

/*console.log(web3.eth.accounts[0]);
return false;*/

contract.drop.sendTransaction('0x627306090abaB3A6e1400e9345bC60c78a8BEf57',["0x2885f9904f3d1790ba53009bc9e0baae377d67df","0x7b7cd7d5cee9fb36b7995a3d81df0122a0b1af4a"],[100,200],{
    from:web3.eth.accounts[0],
    gas:4000000},function (error, result){ //get callback from function which is your transaction key
    if(!error){
        console.log(result);
    } else{
        console.log(error);
    }
})

Please let me know what is wrong in this steps. What I missed from my side. I am not able to send my transaction to multiaddress using contract.

Currently I am getting this error:

TypeError: name.match is not a function
    at SolidityTypeAddress.isType (/var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/address.js:23:19)
    at /var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/coder.js:57:18
    at Array.filter (<anonymous>)
    at SolidityCoder._requireType (/var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/coder.js:56:36)
    at /var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/coder.js:231:21
    at Array.map (<anonymous>)
    at SolidityCoder.getSolidityTypes (/var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/coder.js:230:18)
    at SolidityCoder.encodeParams (/var/www/html/BlockChain/parity/node_modules/web3/lib/solidity/coder.js:88:30)
    at SolidityFunction.toPayload (/var/www/html/BlockChain/parity/node_modules/web3/lib/web3/function.js:92:52)
    at SolidityFunction.sendTransaction (/var/www/html/BlockChain/parity/node_modules/web3/lib/web3/function.js:163:24)

But I don't think it is related to contract. I am missing something or going in wrong way?

Please help me urgent so, I can continue my work based on it.


texts: not able to access metamask account, even if i manually connect website

texts:
I am trying to connect my website to metamask manually, still, I'm not able to access the account.enter image description here
I'm able to read data from the smart contract but when I call a function which changes the state it gives an error

enter code here
<!doctype html>
<html>
    <meta charset="UTF-8">
    <body>
       <input type="text" id= "i1">
        <button id ="b1">set</button>
        <button id="b2">show</button>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.js" integrity="sha256-DrT5NfxfbHvMHux31Lkhxg42LY6of8TaYyK50jnxRnM=" crossorigin="anonymous"></script>

<script src="https://unpkg.com/@metamask/detect-provider/dist/detect-provider.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.2.7/dist/web3.min.js"></script>

<script type="text/javascript">

window.addEventListener('load', async () => {

  let abi = [
    {
        "inputs": [
            {
                "internalType": "uint256",
                "name": "_data",
                "type": "uint256"
            }
        ],
        "name": "w",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "r",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
];
  let add = "0x73FaC9D61321EB3E68F20846bD35644B0D997e10"

/// var  web3 = new Web3();
 //web3 = new Web3( Web3.currentProvider);

 web3 = new Web3('https://rpc-mumbai.matic.today')

  const mycontract = new web3.eth.Contract(abi, add);

   console.log(mycontract);
   const acc = await web3.eth.getAccounts()
   console.log(acc);

   $("#b1").click( async function(){
        var str = $("#i1").val();
      await mycontract.methods.w(str).send({from: "0x70aF29f754988473fcAbA6E01AbfbafF871046d1"});

    });

    $("#b2").click( async function(){

       var x = await mycontract.methods.r().call();
       alert(x);

    });

})
</script>
    </body>
</html>


texts:
How can I run ethkey under Parity?

I cloned the Parity repo, built everything, and Parity is running, but I can't figure out how to run ethkey.


texts: Examples to clarify Storage vs Memory assignments / return parameters

texts:
Is there a mistake in funcB? I do not understand why/when to mention the variable name of the return parameter in the function signature.

contract Foo {

    // State variables go to Storage
    uint[] public foo;

    function funcA(uint[] x) public returns (uint) { // x is in memory
        foo = x  // x is copied to storage now

        uint a = 100  // a is in storage
        return a
    }

    function funcB(uint[] x) public returns (uint a) { // x is in memory
        a = 100  // a is in memory? because `returns (uint a)`
        return a
    }
}

Also, I suppose funcA is incorrect but funcB is okay in the following example?

contract Foo {

    uint[] public foo;

    function funcA() public returns (uint[]) {
        uint a[];
        // push stuff to a
        return a
    }

    function funcB() public returns (uint a[]) {
        // push stuff to a
        return a
    }
}


texts:
I have a mobile app that has users who generate transactions. Basically if a user wants to turn on their TV, they press a button in the app, and that should

1) Run code in a smart contract to verify that the user is authorized to control this TV

2) If the user is authorized, store the "turn on TV" command on the blockchain.

However, I don't want my users to have to pay for this activity. I would like for the company to be in charge of paying for the gas. This way I can just refill / send more gas to 1 source (my company's smart contract), as opposed to having to send gas to a ton of sources (a ton of user smart contracts).

Is there a way to centralize gas payment like this? I want to generate the transaction on the user side for security purposes, but I want the company to take the burden of paying gas. I'm thinking of sending the raw transaction from my mobile app to my backend server, and then sending the transaction from there? Would that work?


texts: Handling the String msg returned from revert() in solidity

texts:
This is my sample contract..

pragma solidity ^ 0.4.15;

contract Sample{

  struct Info
  {
    address pubKey;        //key
    bytes32 Id;
  }

  mapping(address => Info) public userMap;

  // Registration
  function register(bytes32 orgId, address pubKey) public returns(bool){
    if (pubKey == 0x0 || orgId == 0x0 ) {
        revert("Pub Key & Org Id are mandatory");
    }
    if (userMap[pubKey].pubKey == pubKey) {
        revert("User already exists");
    }
    userMap[pubKey].pubKey = pubKey;
    userMap[pubKey].orgId = orgId;
    return true;
  }
  //getting the given Details
  function getUser(address pubKey) public returns(bytes32 orgId){
    orgId = userMap[pubKey].orgId;
  }
}

I have to handle the message returning from the revert() in the api (node.js). Whether will I get this message in the transactionReceipt of the corresponding transaction like web3.eth.getTransaction(txhash) or where can I read the above message?


texts: How to use orbit-db visualization in dapp created using Embark Framework?

texts:
This is the contract code:-

pragma solidity ^0.4.7;

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

Index.html code

     <title>Embark - SimpleStorage Demo</title>
     <link rel="stylesheet" href="css/app.css">

Embark - SimpleStorage Demo

 1. Set the string in the blockchain

          <input type="text" class="text form-control">
          <button class="set btn btn-primary">Set String</button>

 2. Get the current value

              current value is

       <button class="get btn btn-primary">Get String</button>

File Uploading

 1. Set the file in the blockchain

             <input type="file">
             <button class="setfile btn btn-primary">Set File</button>

 2. Get the current value

                    current value is

                  <button class="getfile btn btn-primary">Get File</button>

Index.js file

 EmbarkJS.Messages.setProvider('orbit',{server: 'localhost', port: '5001'});
 $(document).ready(function() {
           $("button.set").click(function() {
                    var value = $("input.text").val();
                    EmbarkJS.Storage.saveText(value).then(function(hash) {
                    SimpleStorage.set(hash);
                    });
           });
         $("button.get").click(function() {
                   SimpleStorage.get().then(function(hash) {
                   EmbarkJS.Storage.get(hash).then(function(content) {
                           $(".value").html(content);
                   });
                   });
        });

        $("button.setfile").click(function() {
                            var input = $("input[type=file]");
                     console.log(input);

                   EmbarkJS.Storage.uploadFile(input).then(function(hash) {
                             SimpleStorage.set(hash);
                              console.log(hash);
                   });
           });
           $("button.getfile").click(function() {
                   SimpleStorage.get().then(function(hash) {
                             console.log("get");
                              console.log(hash);
                             EmbarkJS.Storage.getUrl(hash);
                            $(".valuefile").html("https://ipfs.io/ipfs/"+hash);
                              console.log("https://ipfs.io/ipfs/"+hash);

                            });
                    });
        });

I have created a dapp which saves the hash of text and file in orbit-db and retrieves it back.
I have used orbit-db for storing data.How can i visualize the data stored in orbit-db?


texts: How do nodes find peers without bootnodes?

texts:
I know once a peer is added, it also communicates its own peers. But how is the first peer added? Do the nodes (Geth & Parity) have built-in bootnodes? Or is there a scanning method of some kind?

Thanks,


texts: gift card - private key - how to redeem?

texts:
Someone gave me a gift card with an address - 0X ... - and a private key - list of words.

I have used various wallets but I am unsure what I an meant to do with this. How from the address alone and the key can I move the money to one of my wallets? I have used myetherwallet before.

Thanks


texts: Cannot send ERC20 tokens because user has no ethereum

texts:
I have 1 wallet server but have many account address for each user, so when user want to transfer erc-20 token say OMG to another address(user) in the same wallet server, the system said can not because no fee(user don't have ETH.

Has someone had this problem or have any idea on how to manage this?


texts: Is it possible to regenerate the private key file?

texts:
I have created an account in testnet which I know the address and the password of, but I did not backup the private key file. Can I somehow create the key file again using the password? Or is my account locked inside forever?

Thanks,


texts: Eth.getTransactionReceipt sometimes shows 'root' value in response instead of 'status'. why?

texts:
I am using Geth 1.9.0. While fetching the value for eth.getTransactionreceipt, I am  not getting 'status' in response. Instead i am getting 'Root' field in response.
Why status is not getting displayed?


texts: When a bonded node loses a bet who gets the ETH?

texts:
In Casper Proof-of-Stake, a validator needs to be a bonded node: it puts up a security deposit that can be lost if the validator misbehaves.

When a bonded node misbehaves, who receives the lost ETH?


texts: Error: The called function should be payable

texts:
This is a common error and there are quite a few posts related to the error. However none of the solution seems working here when deploying a  solidity 0.7 contract. Here is the constructor:
uint256 public value;  //in FYX
uint256 public feePercent; //ex, 125 is 1.25% as 125/10000
string public itemName;
uint256 public itemId;
address payable public seller;
address payable private feeAddress;  //address to take payment for transaction
address private contractDude;  //a address of contract keeping a list of user addresses
address private contractFEX;   //a ERC20 contract address

event itemForSale(address _seller, string _item, uint256 _id);

constructor (uint256 _value, string memory _itemName, uint256 _itemId, address _dudes, address _erc20, address payable _feeAdd, uint256 _feePercent) {  //seller deploys the contract
    bytes memory temp = bytes(_itemName);

    contractDude = _dudes;
    contractFEX = _erc20;
    feeAddress = _feeAdd;  //address receiving commission
    feePercent = _feePercent;
    require(mustBeDude(msg.sender), "Seller must be on chain"); //behind the address
    itemName = _itemName;
    itemId = _itemId;
    seller = msg.sender;
    value = SafeMath.add(0, _value);
    state = State.ForSale;

    emit itemForSale(msg.sender, _itemName, _itemId);

}

function mustBeDude(address _add) view private returns (bool) {
    DudeOnChain _dudes = DudeOnChain(contractDude);
    return _dudes.isDude(_add);
}

Here is the error message when deploying:
VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance.

The balance of the seller is zero when the contract is deployed. Tried to add payable to constructor and  add payable to address of contractFEX. Both didn't work.


texts: Unable to override web3.eth.transactionBlockTimeout using web3js when using with Truffle Contract instance

texts:
I want to override the default transactionBlockTimeout from 50 Blocks to 5 Blocks. However, it appears not to have any affect when using web3js with Truffle Contract.
A high level overview of my code looks like this:
// Initialize web3js and set transactionBlockTimeout property
const Web3 = require('web3');
web3 = new Web3(provider); // provider already set elsewhere
web3.eth.transactionBlockTimeout = 5

// Initialize contract
const MyContractArtifact = require("../build/contracts/MyContract.json")
MyContract = contract(MyContractArtifact)
MyContract.setProvider(web3._provider)
myContractInstance = await MyContract.deployed()

// Call contract function
tx = await myContractInstance.someFunctionThatICall()

Let's say I send this transaction to ropsten testnet with a very low gas to ensure it is not mined right away the transaction does not timeout after 5 blocks but will still only timeout after the default 50 blocks.
Interestingly, it appears that sending a transaction using web3js library directly like in the example below does pick up the updated value for transactionBlockTimeout.
web3.eth.sendTransaction({from: accounts[0], to: accounts[0], value: 1e18, gasPrice: 100}) // sending with very low gas to trigger a block timeout

So this would appear to be an issue with Truffle Contract. Has anyone come across this situation and do you have a solution on how to control the block timeout in this case, perhaps directly using the Truffle Contract API?
The version of web3js and Truffle Contract are as follows:
├─┬ @openzeppelin/test-helpers@0.5.6
│ ├─┬ @truffle/contract@4.2.1
│ │ └── web3@1.2.1
│ └── web3@1.2.11  deduped
├─┬ @truffle/contract@4.2.22
│ ├─┬ @truffle/interface-adapter@0.4.16
│ │ └── web3@1.2.1
│ ├─┬ ethereum-ens@0.8.0
│ │ └── web3@1.2.11  deduped
│ └── web3@1.2.1
├─┬ @truffle/hdwallet-provider@1.0.43
│ └─┬ @types/web3@1.2.2
│   └── web3@1.2.11  deduped
└── web3@1.2.11

Many thanks!


texts:
For some time I have been writing my own tooken. I call it COIN
I come across the last three problems:
my fallback function does not work
code:
function () payable {
        createTookens ();

he gives an error message to the createTookens

then I want my initial supply to be different than my total supply.
For example, I want total supply 100 and the initial supply at the crowdsale 75. which still leaves 25 COINS.
Is it true that the 3 now stand for 1000 COINS for 1 ETH?
code:
totalSupply = initialSupply * 10 ** 3 uint256 (decimals);
er is a error with the uint256 and the initialSupply

and my last question
can I also accept 0.1 eth with a crowdsale for payment?
I know that solidity does not work with decimals. So how can I put that in a code ?


texts: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '1545042106' for column 'test123' at row 1

texts:
web3.eth.getBlock(12345).then(res => {
connection.query(`INSERT INTO blockdata(bnumber,btimestamp) VALUES ("${res.number}","${res.timestamp}");`)
});

I got timestamp already.

I wanna insert data to mysql but got an

  Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value:
  '1545042106' for column 'btimestamp' at row 1


texts: Geth error: fatal: could not list accounts: index 0 higher than number of accounts 0

texts:
I'm trying to run the following command:

geth --datadir mychaindata --nodiscover --unlock 0 --mine 1

and getting the above error.

When I enter geth account list, I see two accounts.

What gives?


texts:
I am working with the basic truffle framework. The MetaCoin.sol file which is installed automatically has the following

contract MetaCoin {
    mapping (address => uint) balances;

    function MetaCoin() {
        balances[tx.origin] = 10000;
    }...

What this accomplishes is adding 10000 MetaCoin into account 0. What I want to do is access account 1, 2, 3, perhaps to add MetaCoin or do something else. But I don't know how to do this. I can do it by explicitly including the address (e.g. balances[0x90afa53bce...]) but this is bad because truffle addresses are not static between sessions.

I know that truffle tests starts out with all accounts in a list, but I want to access them within the contract first, and then test.


texts:
I want to know something about GAS...can you please explain...

What is the relationship between Gas and Wei / Ether? Can you please give an example of how much the execution of a contract will cost?
What is maximum GAS amount for a contract. I want to mean is there any restriction for the the amount of GAS in a contract?
How much will the execution of a contract cost in real world (just estimation)?


texts:
In PoW, in the case of a chain fork, the client will continue on the chain with the most work on it.

In Geth PoA Clique, forks still can ocur, since Sealers are racing against each other in sealing blocks. If a fork is detected, how to the node decided on which chain to continue? On the deepest chain?


texts: How to generate the right genesis file, using puppeth?

texts:
I tried to generate genesis block (POA), and genesis.json don't contain these strings

{
    "sealEngine": "BasicAuthority",
    "options": {
        "authorities": [
            "0xfa0c706a1410c8785baa7498325cf7461b325583",
            "0x7766d151b2c63cb096f624daa091ccb27a2c693f"
        ]
    },

What i did wrong?

What would you like to do? (default = stats)
 1. Show network stats
 2. Configure new genesis
 3. Track new remote server
 4. Deploy network components
> 2

Which consensus engine to use? (default = clique)
 1. Ethash - proof-of-work
 2. Clique - proof-of-authority
> 2

How many seconds should blocks take? (default = 15)
> 2

Which accounts are allowed to seal? (mandatory at least one)
> 0x38e12f4d9713c4c4a86cafba370b43f46e3b4885
> 0x

Which accounts should be pre-funded? (advisable at least one)
> 0xcb367d317496d36b9f3a673b3ba006f4110d57ec
> 0x

Specify your chain/network ID if you want an explicit one (default = random)
> 123

Anything fun to embed into the genesis block? (max 32 bytes)
> TEST

What would you like to do? (default = stats)
 1. Show network stats
 2. Save existing genesis
 3. Track new remote server
 4. Deploy network components
> 2

And genesis.json is:

  "config": {
    "chainId": 123,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "clique": {
      "period": 2,
      "epoch": 30000
    }
  },
  "nonce": "0x0",
  "timestamp": "0x59e8ce29",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "extraData": "0x544553540000000000000000000000000000000000000000000000000000000038e12f4d9713c4c4a86cafba370b43f46e3b48850000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0x47b760",
  "difficulty": "0x1",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    "0000000000000000000000000000000000000000": {
      "balance": "0x1"
    },
    "0000000000000000000000000000000000000001": {
      "balance": "0x1"
    },
    "0000000000000000000000000000000000000002": {
      "balance": "0x1"
    },

Why puppeth put some unknown addresses in genesis file..


texts: How to call the precompiled contracts from my contract?

texts:
I am trying to call one of the precompiled contracts from my contract. In this case, it is the ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) function with the address 0x0..01.

pragma solidity ^0.4.3;

contract Precompile {
  function foo (bytes32, uint8, bytes32, bytes32) returns (address);
}

contract Testcontract {
  address last = 0x0;

  event Debug(string message, address res);

  Precompile prec = Precompile(0x0000000000000000000000000000000000000001);

  function testMe () {
    last = prec.foo("\x00", uint8(0), "\x00", "\x00");
    Debug("testMe()", last);
  }

}

When commenting out the line last = prec.foo("\x00", uint8(0), "\x00", "\x00"); everything works fine and the Debug event is fired.

But when using the code as is, strange things happen.
The transaction is send and mined! BUT the Debug event is NOT fired.
Web3 also returns the transaction hash. Example Parity mining:

2016-11-02 16:24:28  Imported #176 ffbe…53cd (1 txs, 0.94 Mgas, 6.53 ms, 0.65 KiB)

I am using Parity and a private chain with the following genesis block: https://gist.github.com/Kyroy/741a275a7af7b60ae66dc59d27089dcd

I compiled the contract with the online compiler https://ethereum.github.io/browser-solidity/
and use a slightly modified version.
(Adding the myContract variable and the starting 0x to the data field)

var testcontractContract = web3.eth.contract([{"constant":false,"inputs":[],"name":"testMe","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"message","type":"string"},{"indexed":false,"name":"res","type":"address"}],"name":"Debug","type":"event"}]);
var testcontract = testcontractContract.new(
   {
     from: web3.eth.accounts[0],
     data: '0x60606040526000600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055506001600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055506102068061008e6000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063524158401461003c57610037565b610002565b346100025761004e6004805050610050565b005b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663debc39516000600060405160200152604051827c0100000000000000000000000000000000000000000000000000000000028152600401808060008152602001506020018260ff168152602001806000815260200150602001806000815260200150602001915050602060405180830381600087803b156100025760325a03f1156100025750505060405180519060200150600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690836c010000000000000000000000009081020402179055507f14186b8ac9c91f14b0f16f9e886356157442bb899be26513dfe1d4d5929a5bac600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660405180806020018373ffffffffffffffffffffffffffffffffffffffff168152602001828103825260088152602001807f746573744d6528290000000000000000000000000000000000000000000000008152602001506020019250505060405180910390a15b56',
     gas: 4700000
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
         myContract = contract;
    }
 })

After the contract is mined, I use the following commands to listen for the event and call the function:

var evt = myContract.Debug(function (err, data) { console.log('Debug', err, data); });
myContract.testMe({from: web3.eth.accounts[1]});

I also tried to:

Build Parity myself with println! in the precompiled functions to test if they are called. They are not.
But when using sha256(..) my outputs appear on the console.

Use sha256(..) before and after last = prec.foo("\x00", uint8(0), "\x00", "\x00");.
The first line is executed and I see the output on the console.
But the line after the precompiled contract call is NOT executed.


texts:
I'm setting up a proof of work contract. When a solution is found, the contract emits a Transfer event and the number that gets hashed with future solutions changes. I need to set up a listener so that the miner knows when this number has updated.

I've written my contract in web3py so far, so help going about this in web3py would be awesome.


texts: Can Solidity constant functions be arbitrarily complex?

texts: Non-constant functions are limited in computational complexity by the block gas limit. I assume, but am not sure, that this does not apply to constant functions. Are constant functions in any way limited in computational complexity other than the fact that I'd have to wait for quite a while until e.g. a long loop is executed?


texts: Pros and Cons of smart contract upgradable patterns

texts:
There have been quite many arguments around how to achieve smart contract updates like Upgradeable smart contracts.
I feel Proxycontract with Delegate-call is currently the most famous one. But aside from that, there are also other patterns.
So, I list the summary of some of the most known patterns and compare each pattern.

1. Delegatecall-based proxies pattern
The most known one. also led by OpenZeppelin which distributes great tools and development kits. the proxy pattern splits a contract in two: one contract holding the logic and a proxy contract holding the data. In this pattern, the proxy contract calls the logic contract with delegatecall. Data returned by the logic contract will be stored in the proxy contract.

Pros: Most flexible that developer team can alter the contract completely. This enables unpredictable bug fix in the future and smooth update without any needs of user participation.

Cons: As mentioned in the trailofbits blog This pattern is most complicated that may cause serious damage to contracts. Implementing this requires a deep understanding of EVM. Thanks to OpenZeppelin, they check those complicated tasks.
But, it's doubtful that a fully upgradable contract remains "Decentralized".

2. Data separation pattern

Also introduced in trailofbits blog.
This pattern also separates data and logic. But, they don't use delegate-call, so an upgrade can be achieved by calling the new logic contract which stores data on the same contract.

Pros: Doesn't use complicated delegate-call function and doesn't require a deep understanding of EVM and can upgrade flexibly.

Cons: it still makes contract complicate and also it's doubtful that fully upgradable contract remains "Decentralized".

3. Registery pattern
This pattern was introduced in Consensys blog

Pros: Simple, easy to audit.

Cons: You will need to think carefully about how to deal with the contract data when you replace the contract

4. Updates through functions
This pattern is not standardized. Each project considers their upgradability before deployment and makes some of the contract(e,g, variables like the owner) upgradable through functions. I think Compound finance is using this pattern.

Pros: Simple, easy to audit, can reduce vulnerability by minimalizing upgradability.

Cons: Cannot deal with unexpected errors or bugs.

Thanks for reading so far.
So, my questions are

If there is something wrong with my explanations, please give me feedback
Do you know any of active projects using one of those patterns?
Do you think of any other pros and cons, or other patterns?


texts:
I am trying to create an ethereum wallet app using Ionic. I have tried to import bip39 node module directly in the angular project but it gives me error. Please help

import { Injectable } from '@angular/core';
import * as bip39 from 'bip39';

@Injectable({
  providedIn: 'root'
})
export class EthereumService {
  mnemonic = 'hello world';
  constructor() {
    this.mnemonic = bip39.generateMnemonic();
  }
}

Error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'prototype' of undefined
TypeError: Cannot read property 'prototype' of undefined
    at inherits (inherits_browser.js:5)
    at Object../node_modules/hash-base/index.js (index.js:23)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/md5.js/index.js (index.js:3)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/create-hash/browser.js (browser.js:3)
    at __webpack_require__ (bootstrap:83)
    at Object../node_modules/bip39/src/index.js (index.js:3)
    at __webpack_require__ (bootstrap:83)
    at Module../src/app/ethereum.service.ts (signup.page.ts:15)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)


texts:
for example,

contract A{

}
contract B{

}

but here contract B will call contract A, I use solidity to compile and get two source code, how can I deployed it? deploy two times on myetherwallet since i have two codes? if I deploy two times, there will be no way to tell B where A is so B cannot find A?


texts:
How can I upload a smart contract to the Ethereum blockchain directly from a Raspbian Terminal without Parity, Geth, etc installed?

Hello,

I primarily use a Raspberry Pi 3B with Raspbian OS installed as my main computer.

I would like to upload my smart contracts directly from the terminal to the Ethereum blockchain without using a browser OR parity OR geth etc.

Is it possible and if so how?

Vesa


texts: Change contract transaction payer from initiator to contract

texts: I have smartcontract that creates some internal structures in external call. Now, when calling this creator function transaction paid by initiator. Is it possible to make contract paying for this tx?


texts: What is the safest way to generate an ethereum wallet for cold storage?

texts:
I am currently making a DIY cold storage using a desktop computer. I cannot find any good desktop wallet for ethereum cold storage. Something like electrum for BTC.
So, I can only found these 3 ways to generate a new ethereum wallet address.

Using geth account

This will create a keystore .json file. I need to keep safe the account password and keystore json file
geth account new

using web3js

This will give an output of address and privateKey. What I need to keep safe is the privateKey.
const Web3 = require("web3");
const web3 = new Web3();
const wallet = web3.eth.accounts.create();
console.log(wallet);

Using ethereumjs-wallet

This will give an output of address and privateKey. What I need to keep safe is the privateKey.
const Wallet = require('ethereumjs-wallet')
const ethWallet = Wallet.default.generate();
console.log(`address: ${ethWallet.getAddressString()}`);
console.log(`privateKey: ${ethWallet.getPrivateKeyString()}`);

Are these methods safe to generate a new address for cold storage?
Please let me know if you have any other method.


texts: How can I import Ethereum Account(s) into my own DApp? - iOS

texts:
I'm currently building an iOS Ethereum DApp/Wallet, and my biggest challenge so far has been finding information about how to import Accounts from the Ethereum Network into my DApp.

When I look at Mist for example, I can scan a QR Code of a given account's address, and that of course will allow me to get the Account's address into my iOS DApp, but what about the private key? (or the account's password?)

My iOS client communicates with a Node.js Server, which in turn performs the calls to my deployed Contract(s) via Web3.js, but in order to call state-changing functions I need the account's password to unlock it first. So, in this scenario, Do I need to ask the user the account's password for each Transaction? (Just like MIST does) Or... am I supposed to use the Private Key in this case? and If so, How can I import it?

As you can tell, I'm very confused about the importing procedures in general.

Note. For this Scenario assume I can send password(s) to my Node.js server securely, encrypted, etc.


texts: Initialize a big fixed length array in Solidity

texts:
I'm building a game on ethereum as my first project and I'm facing with the storage and gas limits. I would like to store a storage smart contract on the blockchain to be queried after the deployment. I really need to initialize a fixed length array with constant values I insert manually. My situation is the following:

contract A {

...some states variables/modifiers and events......

uint[] public vector = new uint[](162);

vector = [.......1, 2, 3,......];

function A () {

....some code....

ContractB contract = new ContractB(vector);

}

....functions....

}

This code doesn't deploy. Apparently I exceed gas limits on remix. I tried the following:

I split the vector in 10 different vectors and then pass just one of them to the constructor. With this the deploy works.
I really need to have just one single vector because it represents the edges set of a graph where ContractB is the data structure to build a graph. Vectors elements are ordered like this:

vector = [edge1From, edge1To, edge2From, edge2To,.......]

and I got 81 edges (162 entries in the vector).

I tought I can create a setData function that push the values in the vector one by one calling this function after the deployment but this is not my case because I need to have the vector filled before the call

ContractB contract = new ContractB(vector);

Now I can see I have two doubts:

1) Am I wrong trying to pass a vector as parameter in a function call inside the A constructor ?

2) I can see that I can create a double mapping for the edges. Something like

mapping (bool => mapping(uint => uint))

but then I will need multi-key valued mappings (more edges starting from the same point) and I will have the problem to initialize all the mappings at once like I do with the vector?


texts: gasCost of opcode "STATICCALL" in Geth VM Trace

texts:
{
    "pc": 4765,
    "op": "STATICCALL",
    "gas": 222711,
    "gasCost": 219243,
    "depth": 1,
    ...
  }

As above, Geth VM Trace (https://etherscan.io/vmtrace?txhash=0x457c267f3acea528fdf0159a05d0794270a858fed9ad71b96d6ad66b44975eec) shows that gas cost of "STATICCALL" is 219243, which seems impossible because it's even larger than the entire gas consumption of the transaction.

So, how to interpret this?


texts: What is the difference between Pegged token and Wrapped tokens?

texts: As the question in the title: is the pegged token and wrapped token the same thing? From my understanding - it is? Both are tied to a particular cryptocurrency in order to maintain its value across blockchains. Or maybe its the same thing?


texts:
From the example here, I could split bytes32 to bytes16. But I am unable to use a similar approach to split bytes9 into three parts. Can someone help me understand what am I doing wrong?

//working
    function split2(bytes32 source) constant returns (bytes16, bytes16){
        bytes16[2] memory y = [bytes16(0), 0];
        assembly {
            mstore(y, source)
            mstore(add(y, 16), source)
        }
        return (y[0], y[1]);
    }

//not working
    function split3(bytes9 source) constant returns (bytes3, bytes3, bytes3){
        bytes3[3] memory y = [bytes3(0), 0, 0];
        assembly {
            mstore(y, source)
            mstore(add(y, 3), source)
            mstore(add(y, 6), source)
        }
        return (y[0], y[1], y[2]);
    }


texts: Do miners or validators have to pay LINK fees for oracle service?

texts:
I will try to ask a question based on the use case.
Assume I only use 1 oracle (ignoring the fact decentralization of chainlink oracles) to execute GET call to an API which returns bool information (GET > bool) for 0.01 LINK.
This is happening with the following line of code. See the documentation for more information.
 function checkProof(string memory JobLocation, int customerId) public {
        Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOBID), address(this), this.fulfill.selector);

        req.add("get",JobLocation);

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

        bytes32 requestId = sendChainlinkRequestTo(ORACLE_ADDRESS, req, ORACLE_PAYMENT);

        requestMapping[requestId] = customers[customerId].id;

}

Which calls the following function once the API GET result is ready.
    function fulfill(bytes32 _requestId, bool _isProofCorrect) public recordChainlinkFulfillment(_requestId){
         int value = requestMapping[_requestId];
         customers[value]._proof = _isProofCorrect;
     }

When as an EOA I trigger this function checkProof, this triggers chainlink oracle (Please stop if I am wrong).
Since calling the checkProof function is state changing function (non-pure), it will need to be mined to include in the next block. Each miner executed the transaction (which is calling the API).
Does every miner pay the LINK for the oracle service? or only the miner node (winner miner) pays the LINK to the oracle?
Once the block mined, all the transactions of the block need to be executed.
Does each validator need to pay LINK to trigger the API GET call again to match the result?


texts:
I have created a ProductFactory contract which creates instances of another Product contract.
Now I change code in the Product contract which is imported into the ProductFactory and run

truffle migrate

When I create a new Product instance using ProductFactory the new Product does not reflect changes (new methods, new variables) in the Product contract.
The migration file only deploys the ProductFactory like below:

 var ProductFactory = artifacts.require("./ProductFactory.sol");
    module.exports = function(deployer) {
      deployer.deploy(ProductFactory, {gas:4555000});
    };

What should I do to get the Product contract code updated?
Do I need to deploy the Product contract also separately?


texts: What is actually Ropsten? What is a new "network"?

texts: Where can we read about what exactly is Ropsten and it's influence to the Etherium in general?


texts: how to get the hash address of previous block while adding a block into blockchain?

texts:
In blockchain every block is having three things,

Hash address of the previous block
Hash of the all the
    transactions those are part of the current block
Nonce, a random value which can be got using hit and trial method. It is a
    predermined value and once a right value for the block is found then
    this block can be added into the blockchain.

Please confirm my understanding and correct me if I am wrong.

Now I have a question about the hash address of the previous block.

How do we get the hash address of the previous block while adding a block into block chain?

Thanks for reply.


texts: how to call "selfdestruct" if not written in contract, as documentation says its possible

texts: as mentioned in documentation "Even if a contract’s code does not contain a call to selfdestruct, it can still perform that operation using delegatecall or callcode." so my question is how does it possible , my purpose is to release Eth which stuck in a contract due to code mistake, and there is no way to withdraw now


texts: Unable to load Solidity contract using `compile_files` function with web3.py

texts:
I am new to ethereum block-chain. I created a ERC20 smart-contract with help of open-zeppelin framework. I used py-solc package for solidity compilation with python. I imported compile_files function form solc. And use the function to compile solidity files. I got error when I intelize solidity file to compile.

So, my source code of python files is:-

import json
from web3 import Web3, HTTPProvider,TestRPCProvider
from solc import compile_source, compile_files
from web3.contract import ConciseContract

#Intelize solidity files to compile
compiled_sol = compile_files(["/home/anupam/Documents/workspace/DjangoProject/ico_application/users/contracts/old_type_contracts/DappToken.sol"])
print(compiled_sol.keys())

# Compiled solidity code
contract_interface = compiled_sol['/home/anupam/Documents/workspace/DjangoProject/ico_application/users/contracts/old_type_contracts/DappToken.sol:DappToken']

# web3.py instance
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545"))

# Instantiate and deploy contract
contract = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
print(contract)

# Get transaction hash from deployed contract
tx_hash =  contract.transact({'from': w3.eth.accounts[0]})
print(tx_hash)

Source Code of ERC20 Solidity file is:-

  pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol";
/**
 * The contractName contract does this and that...
 */
contract DappToken is MintableToken,PausableToken,DetailedERC20 {
            constructor(string _name, string _symbol, uint8 _decimals)
                    DetailedERC20(_name, _symbol, _decimals)
                    public
            {

                }

 }

I got error like this:-

Traceback (most recent call last):
  File "/home/anupam/Documents/workspace/DjangoProject/ico_application/users/common/ERC20.py", line 7, in <module>
    compiled_sol = compile_files(["/home/anupam/Documents/workspace/DjangoProject/ico_application/users/contracts/old_type_contracts/DappToken.sol"])
  File "/home/anupam/Documents/envs/py_eth/lib/python3.7/site-packages/solc/main.py", line 135, in compile_files
    stdoutdata, stderrdata, command, proc = solc_wrapper(**compiler_kwargs)
  File "/home/anupam/Documents/envs/py_eth/lib/python3.7/site-packages/solc/utils/string.py", line 85, in inner
    return force_obj_to_text(fn(*args, **kwargs))
  File "/home/anupam/Documents/envs/py_eth/lib/python3.7/site-packages/solc/wrapper.py", line 169, in solc_wrapper
    stderr_data=stderrdata,
solc.exceptions.SolcError: An error occurred during execution
> command: `solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc /home/anupam/Documents/workspace/DjangoProject/ico_application/users/contracts/old_type_contracts/DappToken.sol`
> return code: `1`
> stderr:

> stdout:
Invalid option to --combined-json: clone-bin

Query 1:- Why this error came??

Quary 2:- Where I do mistakes in a code??

Please resolve my query as soon as.


texts:
I want to setup a proxy contract that my users can interact with. The proxy contract is a store contract with stores the user's age for now. When I call writeData to update my age, I expect it to call my logic contract to run the update there.

When I run the code below in Remix, I am unable to update the userData mapping. When I enter an age of 30, it returns 0 for BOTH contracts so I assume the call is failing. However, if I call writeData on the logic contract, it writes just fine. I assume there is something wrong with my delegatecall.

I am following https://blog.trailofbits.com/2018/09/05/contract-upgrade-anti-patterns/ (under Delegatecall-based proxy pattern
) and I have my state variables ordered correctly so I don't expect it to write to my proxy address by accident.

What am I doing wrong here?

Storage/Proxy Contract:

pragma solidity ^0.4.23;

// Storage contract
contract HealthcareStorage  {

  mapping (address => uint8) public userData;

  address public logicContract;
  address public owner;

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

  function updateContract(address _newAddress) public returns (bool) {
    require(msg.sender == owner);
    logicContract = _newAddress;

    return true;
  }

  function writeData(uint8 _age) public {
   logicContract.delegatecall(bytes4(keccak256("writeData(uint8)",_age)));
  }
}

Logic Contract:

pragma solidity ^0.4.23;

import { HealthcareStorage } from "./HealthcareStorage.sol";

// Logic contract - Upgradeable
contract HealthcareLogic{

  mapping (address => uint8) public userData;

  function writeData(uint8 _age) public returns (bool) {
    userData[msg.sender] = _age;

    return true;
  }

}


texts: "Public DNS" v.s. "Public IP" of AWS for running geth RPC

texts:
In my AWS ec2 instance, I run geth and specify --rpcport and --rpcaddr using "Public DNS" like this:

geth --datadir "./signer1/data" --networkid 55661 --port 2000 --rpc --rpcport 5566 --rpcaddr "ec2-13-114-49-66.ap-northeast-1.compute.amazonaws.com" --rpcapi "eth,personal,web3,net,db" --mine

It will work fine, but if I specify --rpcaddr as "Public IP":

geth --datadir "./signer1/data" --networkid 55661 --port 2000 --rpc --rpcport 5566 --rpcaddr "13.114.49.66" --rpcapi "eth,personal,web3,net,db" --mine

I will get Error: Invalid JSON RPC response: "" when I try to deploy the contract through web3.

What's the reason causes this different behavior?


texts: How to share TypeScript code between truffle tests?

texts:
I have some code in my TypeScript tests, say:

function foo() {
    return 'bar';
}

which I'd like to share with all my tests. The simple solution is to copy the function into each *_test.ts file.

How can I "import" this code from foo_test_helper.ts in a truffle test?

If possible, I'd like to avoid adding Babel to my build. It should work with a project created by npx truffle init. If you suggest Babel, then please include (pointers to) the instructions necessary to set this up.


texts: How to make a Docker container talk to geth.ipc on local host

texts:
from web3 import Web3

web3 = Web3(Web3.IPCProvider("/Ethereum/geth.ipc"))
print(f'IPC connected: {web3.isConnected()}')  # want to return True

I have the above script Dockerized and I'm trying to connect to geth.ipc on local host and I can't seem to connect to it.

Here is how I run Docker:

docker run --mount type=bind,source=$HOME/Library/Ethereum,target=/Ethereum container1

I've verified that geth.ipc exists in /Ethereum directory but cannot seem to connect to it. Is there a way to do it?

The question might be related to this and here is my original question
https://stackoverflow.com/questions/52715141/how-to-make-a-docker-container-talk-to-geth-on-local-host


texts: If I am fast syncing Ropsten, and i close the command prompt or Mist and reopen Mist, will it continue to fast sync?

texts: Just wondering since I was trying to fast sync Ropsten with Mist and it came to a block number around 600,000 and stopped, so I closed Mist and reopened it and it only got to the "started swarm" part. Then I closed the command prompt and reopened Mist and now it has a ton more blocks and its back to 1%.


texts:
I want to test a sale contract, that also takes ERC20 tokens and mint/burn another IERC20 token.
In this excample I try to implement USDT:
pragma solidity >=0.5.0 <0.8.0;

import "@openzeppelin/contracts/payment/PullPayment.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./test.sol";

interface ERC20 {
    function balanceOf(address tokenOwner) external returns (uint balance);
    function allowance(address tokenOwner, address spender) external returns (uint remaining);
    function transfer(address to, uint tokens) external returns (bool success);
    function approve(address spender, uint tokens) external returns (bool success);
    function transferFrom(address from, address to, uint tokens) external returns (bool success);
    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

contract AutomatedMarketMakerUSDT is PullPayment, Ownable{
    using SafeMath for uint256;
    // address _inToken; // ContractA Address
    mapping ( address => uint256 ) public balances;

    ERC20 private _inToken;
    TestToken private testToken;
    uint256 public _reserve;

    constructor() public {
    }

    receive () external payable {
    }

    function setInToken(address payable token) public onlyOwner{
        _inToken = ERC20(token);
    }

    function setToken(address payable token) public onlyOwner{
        testToken= TestToken(token);
    }

    function buy(uint256 amount) public payable{
        ERC20(_inToken).transferFrom(msg.sender, address(this), amount);
        testToken.mint(msg.sender, amount);
    }

    function sell(uint256 tokenAmount, uint256 usdtAmount) external{
        require(tokenAmount == usdtAmount.mul(10**12), 'The exchange ratio is 1:1');
        require(_inToken.balanceOf(address(this)) <= usdtAmount && testToken.totalSupply() <= usdtAmount, "Thats too much");
        uint256 newDecimalAmount = usdtAmount.div(10**6);
        ERC20(_inToken).transfer(msg.sender, newDecimalAmount);
        testToken.burn(msg.sender, tokenAmount);
    }

    function withdrawPayments(address payable payee) public override {
        // Do nothing
    }
}

So the sale contract should make it possible to swap USDT for the TestToken (the testToken has 18 decimals). Now when I call buy with 100 robsten USDT token metamask try to send 100 test ETH...
But I set with setInToken() the address of the inToken variable to the address of testnet USDT (0xFf48Ea739AeD20f3111042B38eCed6D999736fd3)
So how and why ERC20(_inToken).transferFrom(msg.sender, address(this), amount); is an call on ETH?
And how can I make it run?
Thanks for them who knows the answere :) (and write it)


texts: Getting errors when sending ETH to a contract on testnet

texts:
I am trying to send ETH to a contract I have just created and I am getting errors

pragma solidity ^0.4.6;
contract Owned {
    modifier only_owner {
        if (msg.sender != owner) return; _;
    }

    event NewOwner(address indexed old, address indexed current);

    function setOwner(address _new) only_owner { NewOwner(owner, _new); owner = _new; }

    address public owner = msg.sender;
}

Anyone have any ideas what is going on?


texts: Execute programming statement on Geth console

texts: Can I write if statements in geth console - for example if I would like to check that allowance for a ERC20 token is greater than the amount to be transferred , then execute the transferFrom else not or do I have to load and execute a js file for this?


texts:
I create a contract and implement a cleanup function like this

modifier ownerOnly {
    if(msg.sender != owner) revert();
    _;
}

function cleanup() public ownerOnly {
    if(!canDelete()) { //perform validations
        SelfDestructError("Invalid state. Cannot destruct");
        revert();
    }
    selfdestruct(owner);
}

Now my question is since my contract does not implement selfdestruct/suicide/kill method. Can someone still call the "selfdestruct" and take away any balance from this contract using delegateCall,
I did see this and I think its not possible for some other contract to just call a selfdestruct on mine.
I would like to know if what I understand is correct?


texts: MetaMask - RPC Error: Error: [ethjs-rpc] rpc error with payload

texts:
I have created a DApp. In all my functions where I have used send() function of web3, I am facing above error.

I have a function in which I used call() and it worked fine but all send() using functions are failing with above error.

I have seen all possible answers online but no help, can someone please help me? I have very quick submission please

Moreover, the read functions are working fine on DAPP, so Im sure contract is initialized correctly and contract functions works fine as well without Dapp, so metamask is correct too.

web3 version in DApp = 1.0
Please someone help.

This is my failing transaction:

Contract.methods.AuctionInfo(deadline, maxBids).send({from: accounts[0], gas: '21000', value: (0.1*maxBids) * 1000000000000000000}, (error, result) => {
                    if (result) console.log(result);
                    if (error) console.log(error);
                });


texts: How to catch JSON RPC exception in front end web3

texts:
I have a transaction in contract which "requires" only owner can call. In front end when I call this with accounts other than owner of the contract I want to display an error.  Code below doesn't work. It says

:Uncaught (in promise) Error: Invalid JSON RPC response: {"id":6,"jsonrpc":"2.0"}

      this.state.web3.eth.getAccounts((error, accounts) => {
        TalioInterview.deployed().then((instance) => {
          try {
            return instance.isTalioOwner.call({from:accounts[1]})

          }catch(err){
            alert("You are not authorized to run this.");
          }

My contract looks as below

 function isTalioOwner()
    public onlyIfTalioOwner()
    constant
    returns(bool)
    {
        return true;
    }

Found a similar question here, but without any answer. What is the best solution here other than changing contract to return false for non-owner accounts ?


texts: Remix now force to use https, how can i continue to use http://remix.ethereum.org?

texts:
Recently I was able to both use http://remix.ethereum.org or https://remix.ethereum.org, but today I was not able to direct by browser to the unsecure version of remix. The reason I need to do so is because I have many contracts there and I would like to access them and eventually transfer them to the "secure" version.

I checked the request sent to remix with http and the response is a 301 Moved Permanently to https. I also receive the error message: "You are using an https connection. Please switch to http if you are using Remix against an http Web3 provider or allow Mixed Content in your browser.", but this doesn't give me a clue on how to solve the problem.

Is there a way to force remix to use http instead of https?
I'm using a Chrome browser on a Mac.


texts: Allow access to private ethereum network from certain IP only

texts:
I have a question regarding restriction access to private etehreum network.

I created my Private Etehreum network using Geth(for now just only with one node) on the Ubuntu 16.04 virtual machine.

And I have the App which is communicated with private network by Web3, this app is hosted on the different virtual machine.

I ran my node from the console with this command:

geth --datadir=/ethereum-private/chaindata/ --rpcapi admin,personal,web3,eth,miner --networkid 11 --rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpccorsdomain "*"

And after that I'm able to connect by geth attach http://56.120.4.46:8545 or throug web3
web3.setProvider(new web3.providers.HttpProvider(host)); from any server or computer.

So what I want to do it's to allow access to my ethereum network only for that server where my App is located and restrict it for any other servers/ips

Can you please tell me how can I do it?


texts: account unlock with HTTP access is forbidden

texts:
I am using in the geth console and there is a similar error.

Do I add "--allow-insecure-unlock" when I "init a node"?

personal.unlockAccount(eth.accounts1)

Any suggestion would be helpful. Thank you.

-I'm sorry :( I'm not good at English.-


texts: How to implement Ethereum mixing (or coin tumbling) to preserve anonymity in smart contracts?

texts:
According to this answer: (https://ethereum.stackexchange.com/a/62694/23024) one of the approaches to anonymize users in smart contracts is:

  "writing a smart contract which accepts Ether transactions and stores
  the received Ethers inside the contract. After enough such Ether
  transactions have been received (or after a time interval, or
  something else), it sends out corresponding Ether transactions to the
  intended receivers."

Is there an example of such smart contract as an instance?


texts: Are Speed Bumps safe to delay contract action?

texts:
In the Ethereum Wiki it is stated that you can delay a smart contract's action in this defined way :

struct RequestedWithdrawal {
    uint amount;
    uint time;
}

mapping (address => uint) private balances;
mapping (address => RequestedWithdrawal) private requestedWithdrawals;
uint constant withdrawalWaitPeriod = 28 days; // 4 weeks

function requestWithdrawal() public {
    if (balances[msg.sender] > 0) {
        uint amountToWithdraw = balances[msg.sender];
        balances[msg.sender] = 0; // for simplicity, we withdraw everything;
        // presumably, the deposit function prevents new deposits when withdrawals are in progress

        requestedWithdrawals[msg.sender] = RequestedWithdrawal({
            amount: amountToWithdraw,
            time: now
        });
    }
}

function withdraw() public {
    if(requestedWithdrawals[msg.sender].amount > 0 && now > requestedWithdrawals[msg.sender].time + withdrawalWaitPeriod) {
        uint amountToWithdraw = requestedWithdrawals[msg.sender].amount;
        requestedWithdrawals[msg.sender].amount = 0;

        if(!msg.sender.send(amountToWithdraw)) {
            throw;
        }
    }
}

Using "now", though it is stated here that :

  The timestamp of the block can be manipulated by the miner, and so should not be used for critical components of the contract.

It is quite confusing, and I wonder both how one can safely delay a contract's action and how one can get trusted time from within a smart contract.


texts: Is it possible to accept erc-20 tokens in ico smart contract?

texts: Let's say Im having an ICO, and want to accept ETH and OMG as means of payment. Is it possible to create a smart contract that instantly sends my tokens to people that send Ether or OmiseGo (erc-20) to the contract address?


texts: How deploy a smart contract with meteor and metamask?

texts:
I will deploy a smart contract with meteor and matamask.
My code in main.js :

var inactivityTime = 1000;
var continuityContract = web3.eth.contract(Continuity.abi);
var continuity = continuityContract.new(
   inactivityTime,
   {
     from: web3.eth.accounts[0],
     data: Continuity.bytecode,
     gas: 4700000
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

but I have this error

  Uncaught Error: The MetaMask Web3 object does not support synchronous
  methods like eth_uninstallFilter without a callback parameter.

Any idea ?

Code is on github: https://github.com/n1c01a5/etherlife.co


texts:
Reading the whitepaper of Ethereum I came up with the following questions on forks. Let me explain:
 Lets say that I send 1 ETHER to an address A1 to buy something and this transaction gets logged on block 100. After a few hours more blocks have been added to the blockchain and they indirectly confirm block 100 though the PreviousHash information each  block contains.
If ETH gets forked at block 99 I would have my 1 ETH back and I could spend it again. I guess this would be double-spending and this is not how forks work.

How do forks happen/ how is the block that will separate the two new blockchains chosen?
What is the point of separating a blockchain? I mean there is already a common consensus that the current state of the network is right, due to proof of work. Why fork it?


texts: Truffle test error: Cannot create instance of Vault; no code at address

texts:
I'm trying to make a simple test in Truffle using Ganache where I call a function from a smart contract instance. This component will create a Vault and return me its address.

My truffle test does the following:

const VaultFactory = artifacts.require("./VaultFactory");
const Vault = artifacts.require("./Vault");

contract('VaultFactory', async () => {
    it("Should create a new Vault", async () => {
        let VaultFactoryInstance = await VaultFactory.deploy();
        let VaultAddress = await VaultFactoryInstance.CreateVaultContract.call();
        let VaultInstance = await Vault.at(VaultAddress);
    });
});

The VaultFactory.sol code that creates the Vault does the following (the Vault's constructor is empty):

function CreateVaultContract ()
    public
    returns(address)
{
    Vault newVault = new Vault();
    emit VaultCreation(msg.sender, newVault, VaultState.Created);
    return address(newVault);
}

The VaultAdress that I get is not empty, however, when I try to get the VaultInstance, it gives me the following error:

Uncaught Error: Cannot create instance of Vault; no code at address 0xed41bb9a56dad9b9d0901400f0a8de72d3cf1854

I tried doing a web3.eth.getCode(VaultAddress); to see if I had any code, but it returns me 0x0.

So, my VaultFactory contract seems to be deployed and looks like it created a Vault. But for some reason, I can't manage to get its instance. Any idea why?


texts:
I'd like to save the contract addresses from DAI and UNI into a mapping when calling the smart contract constructor depending on the network. Below is a minimalistic example that works fine:
contract TokenManager {

   mapping(string => address) public contractERC20;
   address private ZERO_ADDRESS = 0x0000000000000000000000000000000000000000;

   // Contract constructor
   constructor(string memory network) public {
       if (compareStrings(network, "ropsten")) {
           registerERC20("DAI", 0xaD6D458402F60fD3Bd25163575031ACDce07538D);
           registerERC20("UNI", 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984);
       }
   }

   // Compare two strings
   function compareStrings(string memory s1, string memory s2) private pure returns(bool){
       return keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2));
   }

   // Register a ERC20 contract address
   function registerERC20(string memory _tokenName, address _tokenContract) public {
       require(bytes(_tokenName).length != 0,
           "Token name can't be empty");
       require(contractERC20[_tokenName] == ZERO_ADDRESS,
           "ERC20 contract address already registered");
       contractERC20[_tokenName] = _tokenContract;
   }
   // ...
}

However, I believe this is not the best approach since the addresses are hardcoded in the contract, and the full list of tokens multiplied by the number of networks can be big. In addition, it would be better to choose the tokens to be created directly from a migrations file in Truffle (for instance), instead of updating the contract for every deployment.
I was considering passing an array of objects to the constructor with all the addresses, so that the contract loops through this array and assigns each address, but didn't find a way to send such array of objects/mappings to the constructor from Truffle.
Therefore, is there a better way to handle this assignment of addresses during the contract deployment?


texts: NodeJS+web3 - contract method call not a function

texts:
I trying to use nodejs with web3.js to do the full process of compile,delpoly and method call.After read the api here. I found the contract-methods.

myContractReturned.call().getCount();

But when I use it like this, I always got following error:

myContractReturned.call().getCount();
                   ^

TypeError: myContractReturned.call is not a function
    at Object.<anonymous> (/Users/admin/develop/blockchain_workspace/truffle3/main/web3InAction.js:70:20)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:420:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:535:3

After search the internet,I found here that web3.js with javascript seems good.Did anybody have used nodejs with web3.js,any help will appreciate.Environment are as following:

$ node -v
v7.2.0
$ testrpc
EthereumJS TestRPC v3.0.3

Solidity source here:

pragma solidity ^0.4.0;

contract Calc{
  //simple storage
  uint count;

  //change state
  function add(uint a, uint b) returns(uint){
    count++;
    return a + b;
  }

  //no state change
  function getCount() constant returns (uint){
    return count;
  }
}

Full code as following:

let Web3 = require('web3');
let web3;

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

let from = web3.eth.accounts[0];

let source = "pragma solidity ^0.4.0;contract Calc{ uint count;  function add(uint a, uint b) returns(uint){    count++;    return a + b;  }  function getCount() returns (uint){    return count;  }}";

let calcCompiled = web3.eth.compile.solidity(source);

console.log(calcCompiled);
console.log("ABI definition:");
console.log(calcCompiled["info"]["abiDefinition"]);

let abiDefinition = calcCompiled["info"]["abiDefinition"];
let calcContract = web3.eth.contract(abiDefinition);

let deployCode = calcCompiled["code"];

let deployeAddr = web3.eth.accounts[0];

let myContractReturned = calcContract.new({
    data: deployCode,
    from: deployeAddr
}, function(err, myContract) {
    if (!err) {

        if (!myContract.address) {
            console.log("contract deploy transaction hash: " + myContract.transactionHash)

        } else {
            console.log("contract deploy address: " + myContract.address)
        }
    }
});

console.log("returned deployed didn't have address now: " + myContractReturned.address);

//nodeJS?
myContractReturned.call().getCount();


texts:
can I store a big data size, like 100TB on ethereum blockchain?
and then, is this mean that all clients should download 100TB to get full blockchain data!?


texts: error while deploying contract to ropsten

texts: i keep getting this error when i try deploying my contract to ropsten and the mainnet "callback contain no result Error: SyntaxError: Unexpected token < in JSON at position 0" can someone please help me?


texts: price conversion using chainlink ETHUSD price

texts:
I'm storing a product's USD value in contract.
mapping (string => uint256) productUSD;
For example, if it's $52 I'd store it as productUSD[_product] = 52;
Now, when people paying in ETH, I want to make sure they sent in a correct converted amount.
i.e. 0.013 ETH
Chainlink's getThePrice() returns the latest ETH/USD price and found it was returning like this. price = 348365740274
    function getThePrice() public view returns (int) {
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }

Simple math, I can drop 8 decimals from 348365740274 and use 3483 to get a converted ETH amount
i.e. 52 / 3483 = 0.0149296583405111 ETH

how do I calculate this in solidity? not sure how to drop decimals from 348365740274
how do I verify user has sent correct eth amount? i.e. require(msg.value >= ...)


texts:
How can I make my code sequential, meaning I'd like functions to be performed in a certain order.

Can I make a function not run able till another is run.
An example would be great help.


texts: Trouble using delegatecall to pass msg.sender to another contract

texts:
I'm trying to mint an NFT token in contract B by calling a method on contract A, but I want msg.sender (in contract B) to be the address that calls the function on A, not contract A's address.
I thought this should work, but it doesn't. (it reverts on onlyOwner(), etherscan says: Although one or more Error Occurred [Reverted] Contract Execution Completed)
What am I doing wrong here? If I remove onlyOwner on safeMint, it works. So it's definitely a problem with delegatecall. Any help appreciated. Thanks.
    contract A {
        using Counters for Counters.Counter;
        using SafeMath for uint256;
        Counters.Counter private _tokenIds;
        address public nftContract;

        constructor(address _nftContract) public {
         nftContract = _nftContract;
        }

        function mintItem() public returns (uint256) {
                _tokenIds.increment();

                uint256 newItemId = _tokenIds.current();

    nftContract.delegatecall(abi.encodeWithSignature("safeMint(address,uint256)",msg.sender,newItemid));
                }
}

contract B is ERC721 {

    address public owner;
    modifier onlyOwner() {
        require(owner == msg.sender, "Ownable: caller is not the owner");
        _;
    }

    constructor(string memory name,string memory ticker,string memory uri) ERC721(name,ticker) public {
      owner = msg.sender;
      _setBaseURI(uri);
    }

    function safeMint(address to, uint256 tokenId) public onlyOwner{
      _mint(to, tokenId);
    }

}


texts: Can my dapp charge tokens without asking for user permission?

texts:
For instance, say clicking on a button will perform some type of action and it charges the user 1 token, but doesn't show any pop-up dialogs.

I don't want a Metamask window opening up to submit a transaction everytime a tx might occur, since it could ruin the user experience. The user would agree to the terms and conditions allowing the dapp to consume tokens without their explicit permission of course.

I just want to know, is this possible with smart contracts and how?