texts: Can the behaviour of the Ropsten Test net be compared to that of the main net?

texts:
can be assumed, that a contract behaves in the same way on the Ropsten Test test as well as on the main net, in terms of gas consumption for example?

(I think, that the gas price might be different?)

Are there examples that show, that there is a major difference (for example when using dependencies like deployed libraries, that are not available on another net).

Thanks.


texts: How to sign pieces of data (ie strings of text) with golang?

texts: I'm trying to figure out how to sign a piece of data (in this case a string) using golang. So far everything I can find is about signing transactions which wont work for signing pieces of data that is not of a type transaction.


texts: How do I compile a Solidity contract with an import to standalone byte code?

texts:
I am trying to compile the MetaCoin contract (part of the Truffle Init Webpack). I need to get the byte code as hex numbers so that I can use it with Nethereum. The MetaCoin contains an import to ConvertLib.sol:

pragma solidity ^0.4.4;

import "./ConvertLib.sol";

contract MetaCoin {
    ...

When I compile it (using either Truffle from the command line or the Solidity extension for VS Code), the byte code I get is:

0x6060 ... 0073__ConvertLib____________________________6396 ... 0029

This is obviously a reference the ConvertLib library. When I use Nethereum to try and deploy the contract:

...
var ByteCode =
    "0x6060 ... 0073__ConvertLib____________________________6396 ... 0029";
var transactionHash = await web3.Eth.DeployContract.SendRequestAsync(
    Abi, ByteCode, Address, Gas, GasPrice);

I get the error message:

System.InvalidOperationException: Character '_' at index '604' is not valid alphanumeric character.

Clearly, it does not like the "ConvertLib" reference in the middle of the byte code. I could just include the library code in the MetaCoin contract and remove the import, but I would like to sort this problem out properly.

How can I compile the MetaCoin contract so that it includes the ConvertLib library in the byte code?


texts: Why doesn't ethereum have a fast relay network like Bitcoin?

texts:
I'm talking about nodes that miners connect to that help relay blocks fast, to reduce hash power wastage and forks:
http://bitcoinrelaynetwork.org/ and http://www.falcon-net.org/


texts: How is the amount of gas required by an op code determined?

texts: Is this proportional to time required to process?  Is a high gas transaction more expensive for the miner to include in a block and does it add more to blockchain size than a low gas transaction?


texts:
Given the RLP of a block header, how do i get the block hash?

https://github.com/ethereum/go-ethereum/blob/master/core/types/block.go#L99

  The above link says: Hash returns the block hash of the header, which is simply the
  keccak256 hash of its RLP encoding

Using values from this example (https://github.com/ethereum/tests/blob/develop/BlockchainTests/bcRandomBlockhashTest/randomStatetest109BC.json#L30), I am trying to take the RLP value here, apply the Keccak256 function on it and see if I can return the hash value mentioned.

  Example:- rlp: "0xf90267f901fca09d6563c8b.............................47d2e96bfdffc0",
  Hash:"0xc061b982e871fb4a41bfee1a4e6aa859df15ac44bdc23643cb072c4d2b9e7ba1"

I am unable to recreate the above block hash value, given the block headers RLP. Any suggestions please.


texts: Apparently some people send transactions with zero gas and positive gas limit, how do they do this? (and I am NOT planning to this but how)

texts:
Have a look at this transaction for example:

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

0 gas, 0 ether but plenty of tokens transferred. Obviously the gas limit is higher than the 21,000 since this is a contract but still the person who send this had spent total 0$ in fees, correct?

Now I am not planning to do this since I am a miner miself and know how absurdly hard mining is, so no need to leech on free resources but there are situations when you may need this (aka: you have token but no ether to cover fees -> you need to send token to keep sending for fees...etc).

So how do they do this? Is it roulette game where crazy node picks up this transaction despite earning nothing? I tried via myetherwallet and the transaction didn't get broadcast, maybe it appears after days?


texts:
I am planning to build a mining rig with 6x Amd PowerColor Rx 480 8GB. They require each 500 watt minimum. What PSU will be handle all of them? Maybe its better to use 2x PSU (3 card with 1 psu and the other 3 with second psu)? I am very confused because each of GPU require 500 watt minimum and i can't decide the proper PSU to handle them.

Another question which i am not sure is how to calculate the total power consumption by whole system. I made some calculation online and my system needs 945 watt. This is the power consumed in 1 hour or 24 hour? Because i need to make a prediction on how money will i use for electricity.

Thank you


texts: Authenticating accounts in Ethereum using web3js

texts:
Is a there a way to authenticate accounts in Ethereum using Web3js? Or if there are any other ways to authenticate accounts?

We are building an application where users can register in our system. Once registered, a username and password along with an ethereum account number will be assigned to the user and he can execute transactions.

The username and password will be stored in the external system(non-blockchain).I am looking for a way to authenticate the user in ethereum with their account numbers - something like the username/password combination.


texts:
In this code, I want to send an array of bytes32 and store them in the struct but I get the error which is
 TypeError: Type string memory[8] memory is not implicitly convertible to expected type bytes32[8] storage ref. i.hash= [ "0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb"]; ^---------------------------------------"

my function code and related code are:
pragma solidity >=0.6.0 <0.7.0;
 struct Info {
    address creator;
    bytes16 id;
    // address owner;
    // address contractAddress;
    string detail;
    bytes32[8]  hash ;
}
uint16 public infoSize = 0;
mapping(bytes16 => Info) public infos;
bytes16[] public infosId;
function newInfo(string memory detail  )
    public
    returns (
        bytes16
    )
{
    // Info storage  i = infos[infoId];
    bytes16 infoId = randomId();
    // console.logBytes16(infoId);
    Info storage i = infos[infoId];
    i.detail = detail;
    i.id = infoId;
    i.creator = msg.sender;
    i.hash= [ "0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb","0x9ba99edb"];
    infosId.push(infoId);
     infoSize=infoSize+1;
    return infoId;
}

I don't know how can I fix it. my next step is to pass this array through function as a parameter


texts:
I've recently found that the value of token transfers are in 10^18 hex value.

For example, in this event, the hex value of the token transfer is 00000000000000000000000000000000000000000000000ad62b76e268960000 converted to decimal is 199900000000000000000. However, the token transfer value should be 199.9 according to here. Therefore, the original number was divided by 10^18.

I found it is the same case for other tokens EOS, QTUM and ICONOMI. Therefore I assume that it is common for Ethereum. I was wondering if 199900000000000000000 is in wei?


texts: What are the IDs for the various Ethereum chains?

texts:
I'm looking to find the chain ID's for each network (homestead, etc.). I believe the v-value of signatures is associated with these to some extent.

I'm also under the impression that the ropsten ID is 3, if that gives any context to what I'm looking for.


texts: solc: exit status 1 when compiling my contract on my private blockchain

texts:
I was trying to compile an example contract as told in the official website: here

it was successful to setSolc and getCompilers ,but some errors occur when compiling the contract available on that website:

  var greeterSource = 'contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }'

undefined

  var greeterCompiled = web3.eth.compile.solidity(greeterSource)
  Error: solc: exit status 1

at web3.js:3119:20
at web3.js:6023:15
at web3.js:4995:36
at <anonymous>:1:23

  greeterSource = 'contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }'
  "contract mortal { address owner; function mortal() { owner = msg.sender; } function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract greeter is mortal { string greeting; function greeter(string _greeting) public { greeting = _greeting; } function greet() constant returns (string) { return greeting; } }"

  greeterCompiled = web3.eth.compile.solidity(greeterSource)

Error: solc: exit status 1
    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at :1:19

  var greeterCompiled = web3.eth.compile.solidity(greeterSource)

Error: solc: exit status 1
    at web3.js:3119:20
    at web3.js:6023:15
    at web3.js:4995:36
    at :1:23


texts: I'm completely new to the "mining world" and started reading about this recently. I thought i could mine when not utilizing my PC since i've got a decent mh/s speed and elecrity rates here are ok. I am currently using lolminer to mine eth and i've joined the Ethermine pool. Now i've been reading a lot about what a share is and i still can't fully understand its concept. I see my miner running and every few secs i see found a share of difficulty xG(i.e 24.1G). What does this mean exactly? Is it better if x is a low or high number? Thanks a lot in advance!


texts: Transaction pending status - blockNumber: null


texts:
I am starting to work on the ethereum blockchain, and i had some thoughts about forking blockchains. i want to know more about forking and its consequences, and how to actually detect any fork attempt.

EDIT
what i mean about fork in this context is the fact of starting an other blockchain starting from a certain block. what i think it does is bypass the data stored in the blocks after the one the fork started with.


texts: Multiple Geth on same machine with different genesis

texts:
i have been running multiple geth instances on a single machine for the conceptualization of private blockchain. Now i am trying to run two different and separate from each other geth instances on same machine but i am running into this error.

INFO [03-18|04:08:42.491] Blockchain manager stopped
INFO [03-18|04:08:42.547] Stopping Ethereum protocol
INFO [03-18|04:08:42.562] Ethereum protocol stopped
INFO [03-18|04:08:42.572] Transaction pool stopped
INFO [03-18|04:08:42.601] Database closed                          database=C:\\Production\\data\\geth\\chaindata
Fatal: Error starting protocol stack: Access is denied.

Is it possible to achieve what i am trying to do? Two different geth instances and each one initialized with different genesis.json but on same machine. Commands i am using to run geth instances for this scenario.

Geth 1 Directory c:/Project

geth --datadir data --port 30311 --ws --wsport 8502 -wsapi 'personal,db,eth,net,web3,txpool,miner' --wsorigins="*" --networkid 786 --gasprice '1' -unlock '0x042b1b16eccb6c6bafdceaafea5e9e117990feef' --password data/password.txt --mine console

Geth 2  Directory c:/production

 geth --datadir data --port 30312 --ws --wsport 8503 -wsapi 'personal,db,eth,net,web3,txpool,miner' --wsorigins="*" --networkid 123 --gasprice '1' -unlock '0x6626ee38f917d1e922b86f3eb7e27ea1749b3242' --password data/password.txt --mine console


texts: How do you know if a contract is destroyed?

texts: I'm using web3.py to interact with contracts. I was wondering, after calling a function with selfdestruct or suicide(address), how do I find out that the contract is in fact dead?


texts: How do Proxy Upgraded Logic Contracts Share Data

texts:
I have been looking at how to make my contracts upgradeable and looking through the Zeppelin docs and source code to try to wrap my head around this.

One thing I cannot work out is:

How do new logic contracts share data (when they have no reference to one another and are deployed in different transactions)?

From a security perspective what stops some bad actor from implementing a new logic contract and hijacking my data (it seems like Zeppelin deals with this with the ifAdmin modifier)?

For example, say I have contract MyLogicV1.sol:

contract MyLogicV1 {
  uint256 public foo;
  // ...
}

I now have v2 which has to ensure its data is ordered the same and only appends new data after existing data:

contract MyLogicV2 is MyLogicv1 {
  uint256 public foo;
  uint256 public bar;
  // ...
}

In the above MyLogicv1 will have a different address to the first MyLogicV2 deployed so the data will be different.

The test examples provided in the Zeppelin SDK do not really shed any light as they are all deployed in the same test meaning the contracts have references to one another. Realistically v1 is deployed and gets an address, v2 will be deployed some arbitrary amount of time later likely in a completely different transaction with no reference to the original contract.

To sum up how is v2 which is an upgrade on v1 see v1's data and how is this secured?


texts: Is there any period of custody for block rewards in Ethereum?

texts: In Bitcoin, some block heights are required for spending coinbase transaction. But in Ethereum, there's no input/output. Then, is there any maturity time for using block rewards in Ethereum? If yes, how it works?


texts: EIP definitions of SHOULD, MUST, OPTIONAL

texts:
I'm reading through the EIP20 specificaiton and have come across the terms SHOULD, MUST, and OPTIONAL.

OPTIONAL seems straightforward, but what is the difference between SHOULD and MUST?

Nothing is mentioned in EIP1 - EIP Purpose and Guidelines.

Where do I find definitions of these terms?


texts: web3 installer not installing dist folder?

texts: I've tried to install web3 with node.js by doing npm install web3 --save, but when I check the node_modules folder,  there's no dist folder and its web3.min.js file anywhere. Any ideas on how or why? Thanks


texts: String parameter not automatically converting into bytes32 when used with form

texts:
I have a solidity function which looks like this-

function issueCertificate(address _recipient, bytes32 _certi_name)

When I call the function using truffle console, I am able to run it using-

issueCertificate("0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe", "random")

But when I run it using web3 and forms with same data in string format, it gives error-

  Error: Given parameter is not bytes: "random"


texts: Extending ERC-721 with additional functionality

texts: I am building a DAPP using ERC-721 tokens. I have some additional functionality I am layering on the ERC-721 contract while keeping all the required interfaces intact. Will it still be an ERC-721 token with the additional functionality (some extra state variables, only allow one token per address, etc)


texts:
Lately I've been thinking about how to integrate Ethereum with other non-Ethereum systems.
Would it be a bad idea to import and Ethereum keypair into an external (mobile/desktop) application,
which could be used to verify one's Ethereum identity/conduct transactions?

Users would authenticate by using one's private key in response to a generated random challenge (decrypt or sign it),
or use the embedded private key to sign Ethereum transactions and send them to some external system.

Would that be in line with the spirit and the general idea of Ethereum and/or pose a security threat to users?

EDIT:

The value of using such an app would be the ability to externally prove the ownership of an Ethereum account. It could be used to prove an ownership of an asset or transaction execution.

It would be possible to integrate smart contracts into existing non-Ethereum systems.


texts: How to convert ETH (Ethereum) to XRP (Ripple)

texts: I have some ETH (Ethereum) in a private wallet. How can I buy XRP (Ripple) with it?


texts: How to jump to any arbitrary location in already deployed contracts

texts:
I’d like to know what is preventing me to write an assembly code who knows the contract address and call some arbitrary functions, even if declared “internal” via a simple JUMP.

In theory I can:
1) discover what is the location to jump to analyzing the bytecode and using some accessible address as baseaddress;
2) write my own assembly code which loads the needed parameters into the stack;
3) make a JUMP to the location discovered at (1).

What is the mechanism that should prevent me to do that?

(I understand that the various “call” type opcodes jump to the initial location of the called code, but apparently the JUMP and JUMPI instructions have no such limitation. Reading yellow paper sections 9.4.2 and 9.4.3 AND the Geth implementation apparently do not contradict the possibility to jump to an arbitrary absolute address, but for an unclear definition of “permitted jump range” which apparently simply requires that a JUMPDEST opcode be present in the location where the EVM jumps. And this is easy to find in the attacked contract opcode. Some further analysis is required and previous answer to similar questions is to much rough and straight and do not give evidences)


texts: Is it possible to assign a map as a mappings value

texts:
Essentially I have several mappings that I would love to be able to access with a string, or bytes32 value on occasion, but mostly access directly

mapping(int256 => mapping(int256 => address)) public mapOfA;
mapping(int256 => mapping(int256 => address)) public mapOfB;
mapping(int256 => mapping(int256 => address)) public mapOfC;

I want to be able to access one of these mappings depending on a variable (either string or bytes32)

I have tried:

mapping(string => mapping(int256 => mapping(int256 => address)) public mapIndex;

When I try to set:

mapIndex["A"] = mapOfA;

I get the following error:

Error: Mappings cannot be assigned to.
mapIndex["A"]

Am I missing something or is in not possible to assign a map as a mappings value?


texts: Created Standard Token, deployed successfully but on Myetherwallet error

texts:
Here is the token contract I created - https://ropsten.etherscan.io/address/0x2cccce414fcdf028c0574766af4302a4abeb5788
Address: 0x2CCcCe414FCdF028C0574766Af4302A4aBEB5788

For some reason I can not see its total supply or any other info on etherscan, and also when I add a new token on Myetherwallet it gives an error - (error_21) Not a valid ERC-20 token.

What could be the reason? Please help the noob.

I used openzeppelin/truffle/infura, pretty simple contract:

pragma solidity ^0.4.24;

import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol";

contract TestToken is StandardToken {

string public name = "Token";
string public symbol = "T1";
uint8 public decimals = 18;
uint public INITIAL_SUPPLY = 4000000000000000000000000000;

constructor() public {
  totalSupply_ = INITIAL_SUPPLY;
  balances[msg.sender] = INITIAL_SUPPLY;
}
}


texts: Solidity: Saving arbitrary data into bytes array and later parsing it

texts:
I want to create a function that receives two addresses and saves them into a bytes array.
later a matching function will receive this bytes array and parse the two addresses.

function addressesToBytes(address add1, address add2) public view returns(bytes combined) {
    combined = new bytes(40); //since each address is 20 bytes
    //store the two addresses in the bytes array
}

function bytesToAddresses(bytes combined) returnes(address add1, address add2) {
     // here set add1 and add2 values from combined bytes array
}

I saw this answer. but it was not enough :(.


texts: Are there any best practices for optimizing computations?

texts: As complex computations cost a lot of gas (sometimes more than actually forecasted), so are there any popular ways or techniques where I can optimize a complex computation to a simplified version of the same, for saving on the gas costs?


texts: How to transfer eth to specific address in smart contract?

texts:
I want to send eth to specific amount by calling smart contract.
This is my contract.
pragma solidity ^0.6.7;

contract MyContract {
　　address payable receiver;

    constructor(address _icb_address) public {
        receiver = msg.sender;
    }

    function sendEther(uint _amount) public returns(bool success) {
        receiver.transfer(_amount);
        success = true;
    }

}

I called endEther from an address which is not same as receiver, but I got this error.
gas required exceeds allowance (10000000) or always failing transaction
This is failed transaction on etherscan.
https://rinkeby.etherscan.io/tx/0x5652cad647ee5146cdb1e2e97f8376075a630e98021e0927cb629ed0efbe1099
It seems like transfer function is called from contract.
I couldn't understand why this function is executed by contract address not msg.sender.
How to send eth to spesific address on smart contract?
Could you give me any advise, please?


texts: I would like to run a private node on EthereumJ. I don't know how to start mining on EthereumJ and how to start EthereumJ node. I will be very grateful if someone tell me where to start looking (documentation or code) in EthereumJ.


texts: I am currently working on a smart contract and using modifiers. I want to restrict access to a function only to a single account. I can do this with 'msg.sender' but to my knowledge this limits only to the account that deployed the contract. I want only the account 'web3.eth.accounts[2]' to access the function. Is this possible in solidity?


texts: Cancel a transaction that has not been pushed via Mist

texts:
I submitted a transaction via Mist with the fee slider at the leftmost position. Nothing happened for a day now, so I suspect that the displayed gas price has been to small, although Mist told me that the transaction is likely to be executed in a few minutes.

I searched the internet on how to cancel a transaction and found that in principle there is no way.

However, the transaction does not even show up on etherscan yet, so I suspect that it might not even have been published(?). If it is so, is there a way to stop Mist from doing so?

I also found that you can send another transaction with a higher gas price but the same nonce such that only the latter transaction is executed. I could send a zero-valued transaction to myself with the same nonce. Is there a possibility in Mist to find out the Nonce of the displayed transaction and to send another transaction with the same nonce?

Edit: The linked "possible duplicate" does not explain how to get the nonce from a transaction in Mist and submit a new transaction with the same nonce.


texts:
I'm trying to get web3.personal.ecRecover to work.
This is my setup:

Chrome using Remix IDE
MetaMask to inject web3.js

Now I'm trying the following commands in the Chrome Dev Console:

msg = web3.sha3('Schoolbus')

web3.eth.sign(web3.eth.accounts[0], msg , function(error, result){
     if(!error)
         console.log(result)
    else
        console.error(error);
})

this returns:

0xd030d9a04df643f62a1502b017f51c41a659268091abbd20e2de97b935724d7c

Now I set:

 signature = "0x36f32cbd6133ce6be7efa4cb73ff3f9ddf9b7db3ba15fa543ab0a93d04a96c102693739f946f2d89eca9030b4c8e01bb6fada1c23f05b6a4956dd63deaf187501b"

and try:

web3.personal.ecRecover(msg,signature, function(error, result){
    if(!error)
        console.log(result)
    else
        console.error(error);
})

and get:

0xcc3f70c6caa9fee58bab68f292bdf3132c3c9ae2

Obviously this is not the public address I used in (i.e web3.eth.accounts[0])

Any suggestions to improve this code?
Thanks!

S


texts:
Tried to make a Ethereum transaction, was able to sign successfully and when using web3.js sendsignedtransaction to broadcast the signed transaction got a success response (returned the hash of the transaction). But when the transaction hash was queried through the block explorer and from the geth full node, it return 'No transaction found'. Transaction is not even on mempool. Transcation was lost completely. When trying to make the exact same transaction, it is considered as replacement transaction.
Few details about the host machine.

The Hostmachine has lower IOPS which was sufficient enough to sync
Rinkeby. (Throttled down for testing purpose)
Hostmachine runs geth along with bitcoin-core and rippled.

Can lower IOPS causes such issues with transactions ?


texts: Does Swarm architecture supports streaming video files

texts: Though the prototypes are less in number, swarm architecture is able to upload picture files (alpha tested in LETH android app).Is Swarm presently equipped to support streaming videos or pre-recorded video file uploads while communicating using whisper. If yes, Is there any max upload limit?


texts:
I have implemented a function call in truffle(web3js):

await this.token1.transferFrom(holder1, holder2, transferAmount, {from: holder1});

and now I want to get the tx hash for that specific function. Any ideas, I'm quite new with truffle so I don't really know.


texts: Get Uniswap Exchange Rate of any Token with Web3

texts:
I need to get the exchange rate for every token on Uniswap with Web3 like Uniswap itself which they then display on their web interface on app.uniswap.org like this:

So when I enter to swap the amount of tokens I want to to give (1 ETH in this example) it shows me the estimated amount of tokens I will receive (1691.53 DAI in this example)
What I've tried
I want to get the information directly from the blockchain and don't wanna use an API because I need the prices to be as up to date as possible so I thought of searching for a function in one of Uniswap's smart contracts but only found a function called quote() but I couldn't do anything with that.
-> If someone can help me please provide me with some code examples on how to exactly do that.
Also I need to know if I got the concept of Uniswap... To be able to exchange one token for another there has to be a pool already for this exact pair I want to exchange is this right?


texts: Truffle returns no code at address after contract update

texts:
etherjs (5.0) is used to deployed a smart contract Hello.sol. Here is the js code (truffle 5.1.52/ganache CLI 6.12.1):
  import { ContractFactory, ethers } from "ethers";

  let privateKey = "0xf43608a210da70d40115ad23526e50f2a502c018aeffd56477fcbe44119b53cc"; //<<==private key from ganache-cli
  let wallet = new ethers.Wallet(privateKey);  //address of the wallet
  console.log("wallet : ", wallet);
  //deploy
  const factory = new ContractFactory(abi, bytecode, signer); //<<==abi, bytecode, signer defined before
  const contract = await factory.deploy(wallet.address);
  console.log("contract deployed : ", contract);
  console.log("contract address : ", contract.address);
  // The transaction that the signer sent to deploy
  contract.deployTransaction;
  // Wait until the transaction is mined
  contract.deployTransaction.wait();

The execution of code above generates the output on ganache-cli -b 3:
  Transaction: 0x5c626a276ba9ddf0b0b69c4fab774b5ac2e8026fe7dd0bb149b4939a2b1ca25d
  Contract created: 0xaec5a7f864e3e5e42554b5d645f62ba07add7517
  Gas usage: 122107
  Block Number: 1075
  Block Time: Sun Nov 15 2020 13:15:03 GMT-0800 (Pacific Standard Time)

eth_blockNumber
eth_chainId
eth_getTransactionReceipt

The contract is deployed at the address of 0xaec5a7f864e3e5e42554b5d645f62ba07add7517. Then launching truffle development and hello = await Hello.at("0xaec5a7f864e3e5e42554b5d645f62ba07add7517") returns the instance of the contract deployed. The problem is that after Hello.sol is updated with addition of 2 functions, now the hello = await... returns an error:
truffle(develop)> hello = await Hello.at("0xaec5a7f864e3e5e42554b5d645f62ba07add7517")
Uncaught:
Error: Cannot create instance of Hello; no code at address 0xaec5a7f864e3e5e42554b5d645f62ba07add7517
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at Function.at (C:\D\code\js\node_modules\truffle\build\webpack:\packages\contract\lib\contract\constructorMethods.js:74:1)
    at Object.checkCode (C:\D\code\js\node_modules\truffle\build\webpack:\packages\contract\lib\utils\index.js:265:1)

Here is the step the Hello.sol was updated:

function setValue and getValue were added to the contract in remix
compile successfully with abi and bytecode
update the Hello.sol in VS code
run truffle compile successfully
After deploying the contract in VS code, use the contract address returned in ganache to make connection in truffle development

What is wrong causing the contract is not at the address returned by ganache after update?
UPDATE:here is the part of the truffle-config.js:
networks: {
      development: {
        host: "localhost",
        port: 8545,  //testing
        network_id: "*" // Match any network id
      }
    },


texts: Two external function calls not working in combination in our smart contract

texts:
So I have the following functions

buyTokens

function buyTokens(address beneficiary) public payable {
    require(beneficiary != address(0));
    require(validPurchase());

    uint256 weiAmount = msg.value;

    uint256 tokens = weiAmount.mul(getRate());

    weiRaised = weiRaised.add(weiAmount);

    token.issue(address(vault), tokens);
    vault.deposit.value(msg.value)(beneficiary, tokens);

    emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);

    forwardFunds();
}

forwardFunds

function forwardFunds() internal {
    wallet.transfer(msg.value);
}

deposit (in another smart contract)

function deposit(address supporter, uint256 tokensAmount) onlyOwner public payable{

    depositedETH[supporter] = depositedETH[supporter].add(msg.value);
    depositedToken[supporter] = depositedToken[supporter].add(tokensAmount);

    emit Deposit(supporter, msg.value, tokensAmount);
}

So buyTokens won't work unless I comment out EITHER the deposit call or the forwardFunds call. After doing some reading I was thinking that it had something to do with gas?

Furthermore, if I call the deposit function by passing the value as a param rather than receiving through the msg object in the other function (not using .value() methodology) it works fine.

vault.deposit(beneficiary, tokens, msg.value)

Is there an issue with using a .value() call and also forwarding to an internal function that uses .transfer()?

Thanks!


texts:
I have a contract / dapp that is "pay to play". You send X amount of Eth, and you can play.
I have a price feed working via Chainlink, but I'd like to peg the Eth amount to USD.
Where the contract is now looking like..
uint public price = 0.15 ether;

I'd like to make that more dynamic.
uint public price = <$2.00 USD expressed as Eth>;

I'm not sure if this is even possible, because the price of Eth fluctuates so much. A tx could fire and while in the mempool, the price of Eth could jump and once the tx hits the function, it would be rejected.
function play() external payable returns(bool) {
    require(
      msg.value == price,
      'Please send the correct amount of ETH'
    );

So rather the price following the fluctuations of Eth so closely, perhaps it could change the price every hour or so?
Another idea I had was to make a function that changes the price, available only to the contracts author.
function changePrice(uint memory price) external ownerAddressOnly() {
    this.price = price;
  }

Where I could manually change the price when I choose, without having to redeploy a new contract.
How are operations like typically this handled in Solidity / Chainlink?


texts: Geth Mismatch of the highestBlock while syncing

texts:
While syncing on my Ubuntu 16.04 machine on ropsten yesterday the highestBlock matched the current highestBlock

> eth.syncing
{
  currentBlock: 2587196,
  **highestBlock: 3528808**,
  knownStates: 3685462,
  pulledStates: 3676041,
  startingBlock: 0
}

while I had to restart for some reason now when I again start it today I see this.

> eth.syncing
{
  currentBlock: 2785412,
  **highestBlock: 3113093**,
  knownStates: 4120516,
  pulledStates: 4113759,
  startingBlock: 2729984
}

The highestBlock has changed. Earlier it was showing the correct highestBlock but now it is showing the incorrect one. Is this normal and will the geth client correct itself on the way ?
The syncing is working normally.

System details
geth VERSION: 1.8.11-stable-dea1ce05
OS Ubuntu 16.04

Edit:
The synchronisation has stopped at this state and is now stagnant and not progressing.

> eth.syncing
{
  currentBlock: 3116323,
  highestBlock: 3116388,
  knownStates: 27269500,
  pulledStates: 27259299,
  startingBlock: 3116323
}
> eth.blockNumber
0

Is this issue somehow related with this github issue
https://github.com/ethereum/go-ethereum/issues/16202


texts: simplest way to call an external/public contrat function

texts:
Let's suppose i've deployed a smartcontract and let's suppose i have deleted the solidity source code on my computer.

I know the deployed address
I know a function signature

What is the simplest way to call this function ?
I have tried web3js code but in my opinion it it is a very complex way
Thanks
*** EDIT ***
Here is a basic web3js code.
My main problem is i do not know the full ABI. I only know my function's signature (name, arguments and return type)
const Web3 = require('web3')
const web3 = new Web3("https://ropsten.infura.io/v3/<myprojectid>")
const ABI = [ { "inputs": [ { ...
const instance = new web3.eth.Contract(ABI, "0x<contract_address>");
instance.methods.the_function_i_want_to_call().call((err, data) => {
  console.log(data);
});


texts: Illegal transactions can also be mined on geth

texts:
I used web3 to call the contract method (I initialized web3 with metamask, then metamask listens for the geth node).

I used to deploy the contract to ganache. When I used the illegal parameter to call the contract method (the contract method uses 'require' to determine if the parameter is correct), the result is revert, which is normal. But when I deployed the contract to the private network I built with geth and then called the method with illegal parameters, the result was no error, which is not normal.
And the transaction can be mined as a normal transaction


texts: Can we decrypt a message by using private key through Metamask

texts:
Say I have a hash of a file which is stored on IPFS.I want to encrypt the hash with public keys of few people.
How can I do the encryption of the hash (encrypted hash should be stored on smart contract) using react web application.
And can others decrypt the encrypted hash ,to get the actual IPFS document ,using their private key (Asking a user to enter their private key in a web app can be a bad practice) ,can we do this using decryption using Metamask or any?


texts: How to explain string serialization when invoking contract method?


texts: Get past events or store them in traditional databases

texts:
I have a question about showing some results to users.
I have a smart contract which has multiple arrays and mappings. I use events to store their data when I set data in functions.
is it better to store these arrays and mappings data to other traditional databases (e.g. SQLServer)  and then query them to show in my web app or just use getpast events and load them directly from blockchain?
if the answer is get past events, what if the data goes real huge?


texts:
What is a simple utility or command line function I can add to a batch file or run independently to automatically update the computer's clock with a NIST time server?   Ideally I'd love a utility or agent which syncs it every hour.

I've tried numerous times with Windows 10 registry options to no avail.   I've also replaced the motherboard battery.  I can 'unsync' and then 'sync' again using the Microsoft time settings interface, but it's inconvenient.

I've had clock drift while mining in the past and would love to not have to worry about this issue going forward.


texts:
Hi i now read everywhere that a transaction fee has to be paid in ETH.

But I also found via the ethereum page the following page:

https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs#data-feeds

where it says

  setFeeCurrency

  setFeeCurrency(address _feeCurrency)

  Sets the currency that the fee is paid in

  The latter two methods are optional; also, note that the fee may be
  charged either in ether or subcurrency;

So is it finally possible to create an ERC20 Token that is able to transfer its tokes and is paid in the token itself? If so, is there an example contract somewhere or do I just have to add it into the constructor? If so what exactly has to be the _feeCurrency variable? The AdminAddress of the contract?


texts: Function selector of function that takes enum as argument

texts:
If a function takes an enum as a parameter

function foo(MyEnum arg1, uint256 arg2) public returns (bool);

how do I properly compute the function selector for that function?


texts: Dag generation failure: Invalid Argument

texts: I have been mining for a while now. I restarted my computer this evening and I have been receiving the error " DAG Generation Failure. Reason: Invalid argument" when running the same bat file I always do. I have not made any changes to my system.


texts:
My claymore miner running on my Linux Mint mining rig was running fine but now this is happening?

ETH: Stratum - Connected (eth-eu1.nanopool.org:9999)
ETH: Authorized
Setting DAG epoch #115...
server: bind failed with error: 98 (check -mport option value), next attempt in 20sec...
Setting DAG epoch #115 for GPU #0
Create GPU buffer for GPU #0
OpenCL error - cannot allocate big buffer for DAG. Check readme.txt for possible solutions.
Setting DAG epoch #115 for GPU #0
GPU 0, OpenCL error -38 - cannot write buffer for DAG
ETH: 04/03/17-20:23:32 - New job from eth-eu1.nanopool.org:9999

Any ideas? Thanks.


texts: Block Chain Polling/Voting using Honest/Costly Signalling [Why is this wrong, can this system work?]

texts:
This Poll measures (Support for X) not (People who support X)

You signal support for a candidate by forfeiting any amount of value to a candidate specific address in return you get...

A public and verifiable vote, proof that it effected the outcome of this poll.
Reasonable belief that the participates in this poll made an honest choice in their selection with full knowledge of its costs. One rich guy can skew the polls but forfeiture of the underlying value is what keeps the poll as honest as possible. Are you really willing to forfeit X amount to show support for Y candidate? Both lying and telling the truth have the same outcome, you forfeit the value and your vote is recorded. Its in everyone best interest to tell the truth.
A free (beer&speech) pseudo-anonymous data set, hosted on the blockchain

Example:
You vote in the poll with your 1cent cryptokitty.

Worse case the crypto kitty market explodes and that specific cat shoots to 1million, you forfeited the value in support of a candidate. (This is why its important to tell the truth)

Best case it goes down to .01cent or stays the same, you have a shit coin out your wallet.

In both cases your vote is recorded on the block chain open for anyone to verify, study, or use as a teaching aid.

You can even vote in the poll using a made up token where the value is only the gas fee and time you spent making it.

I'm trying to make sure my logic is sound.


texts:
I set up a wallet via Linux Terminal in November, I know there is a balance there and just checked. I set up MIST 2 nights ago and was told that MIST recognizes the wallet in computer (which I didn't know was even possible) but the new wallet does NOT show that address or any balance being carried over to the new MIST wallet.

I take it just import the keys like any wallet?

I was just curious if it was supposed to recognize the existing wallet as others have told me. My friend just set up MIST last night and automatically carried over his balance. What did I do wrong or what should I do?


texts: How to set a transaction timeout in txpool properly?

texts:
I want to limit transaction pending time to 5 seconds, after that the transaction considered as failed;

does --txpool.lifetime  solve the problem ?


texts: Publish and verify the source contract code in Ethscan. I tried it but it keeps failing. Can anyone help me?

texts:
https://etherscan.io/token/0xa0005edc8897fe1f9e2705a1682431497a504657

I followed other answers but could not succeed.


texts: Ether not programmaticaly sending from one contract to another

texts:
I have two contracts. My goal is to send ether to contract ContractSendTo with the deposit() method by calling it from ContractSendFrom's depositToSendTo() method. When I execute depositToSendTo(), the Ether remains in ContractSendFrom, and I am not sure what I am doing incorrectly.

pragma solidity ^0.4.19;

contract ContractSendTo {

    function deposit() public payable {

    }

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

contract ContractSendFrom {
    ContractSendTo contractSendTo;
    constructor(address sendTo) public {
        contractSendTo = ContractSendTo(sendTo);
    }

    function depositToSendTo() public payable {
        contractSendTo.deposit.value(msg.value);
    }

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


texts: I accidently started and canceled a fast sync with the blockchain almost fully downloaded, its at the beginning

texts: I accidently started and canceled a fast sync with the blockchain almost fully downloaded. Now its at the beginning again when I start Mist. How can I get it to recognize the old blockchain.


texts: truffle test - TypeError : myFunction is not a function

texts:
I'm using truffle and testrpc to check whether my addMember function works or not.

And here is my contract code.

/*make Stakeholder*/
function addMember(bytes32 _name, uint256 _threshold, uint256 _fund, uint _rate, bytes32 _character){
    uint id;
    address targetStakeholder = msg.sender;
    if (stakeholderId[targetStakeholder] == 0) {

       stakeholderId[targetStakeholder] = stakeholders.length;
       id = stakeholders.length++;
       stakeholders[id].name=_name;
       stakeholders[id].threshold=_threshold;
       stakeholders[id].fund=_fund;
       stakeholders[id].id=id;
       stakeholders[id].rate=_rate;
       stakeholders[id].addr=msg.sender;
       stakeholders[id].since=now;
       stakeholders[id].character= _character;
    } else {
        id = stakeholderId[targetStakeholder];
        Stakeholder m = stakeholders[id];
    }

    MembershipChanged(targetStakeholder, true);
}

And the following is my truffle test code.

contract('Congress', function(accounts) {
  it("adding new member", function() {
    var temp = Congress.deployed();
    return temp.addMember("John", 100, 100, 50, "buyer", {from:accounts[1]}).then(function(txs){
      console.log(txs);
    });
  });
});

However, the truffle console shows me the error message

  TypeError: temp.addMember is not a function

And I just can't figure out why.

Any suggestion is appreciated.
Thank you so much!


texts: Token Restrictions Helping me Understand Blockchain Logic

texts:
To execute the transfer or transferFrom ERC-20 token functions in a Solidity contract, ie:
// moves token from contract to personal address
        ERC20Token.transfer(msg.sender, tokenamount);
// moves token from personal account to contract
        ERC20Token.transferFrom(msg.sender, address(this), tokenamount);

I must first execute the approve function in javascript outside solidity, like this:
  contract = w3.eth.contract(address=contract_address, abi=contract_abi['abi'])
  nonce = w3.eth.getTransactionCount(wallet_address)
  txn_dict = contract.functions.approve(contract_address, amount).buildTransaction({
  'gas': 500000,
  'gasPrice': w3.toWei(gas_p, 'gwei'),
  'nonce': nonce,
})
signed_txn = w3.eth.account.signTransaction(txn_dict, private_key=wallet_private_key)
result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)

I was wondering if it was possible to put that 'approve' method into the Solidity contract, but then thought, this would be bad because a malicious contract might execute the approve & transfer functions within the same block, allowing a token overspend. Is that the right way to think about it? [I could be wrong in my assumption that you cannot approve an ERC-20 token expenditure within a Solidity contract]
It's interesting because, on one hand, I could imagine the token's allowance amount would be modified when a transfer function was called, or not, depending on whether the Solidity contracts are run sequentially in a block, or simultaneously.


texts: OpenSSL error message when decrypting Ethereum encrypted private key

texts:
I'm trying to help a friend recover his password for an older format ethereum encrypted private key (EPK).  My friend thinks he knows the password.  My plan has been to use his best guess at the password to brute force the actual password.
The EPK is a 132 character string, and it looks something like this:
U2FsdGV0X185M9YAa/27pmEvFzC5pqLI4xWrA6ouGVCx0EeJ9s8DzeGuBtYJPDCKDy0m80yvHdQYDMPa+Hwv2JPbuGJNoUMhFWpcQW1VF+EAy0tYb7Wtv2+IRWZzcpsE8e2a
(That is: 128 ASCII digits and/or letters, plus three "+" and a "/".)
This article (https://www.reddit.com/r/Bitcoin/comments/3gwdge/importing_old_encrypted_private_keys/) seems to describe a very similar EPK.  The author of that post decrypted their key with the following command:
openssl enc -in FILE_OF_KEYS -a -d -salt -aes256 -pass pass:"PASSWORD_HERE"

I have tried this same approach, but I'm getting an error:

EVP_DecryptFinal_ex:wrong final block length

Here's an example:
/usr/bin/openssl enc -d -aes-256-cbc -a -in enc_private_key.txt -out recovered.key -pass pass:TheBig7ebowski

And here's the output:

bad decrypt
140220549330848:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:581:

I'm not sure how to interpret that output.  I could interpret it as:

Your system for decrypting the password is perfect, but: this is not
the right password.
There's something wrong with the EPK -- its
length must be a multiple of the AES block length.
There's something
wrong with the unencrypted private key -- its length must be a
multiple of the AES block length.
Something else entirely

Can anyone help me understand how to interpret this error message?


texts: Function call error in ethereum smart contract

texts:
I am trying to call a ethereum smart contract function but it gives me error. It works perfectly fine with remix JVM environment but throws error with web3 provider. I am just trying to call a function but it is showing me different contract address , as if it has created new contract. Is there any problem with the contract ?

error :-

"Transaction has been reverted by the EVM:
{
  "blockHash": "0xac0800a862fb3f6864f2fadc354baa47b11279095ce1c1e130af5176c97140df",
  "blockNumber": 6369858,
  "contractAddress": "0xb7fcf989EDB79DAd87990DF85412DF116AC7406E",
  "cumulativeGasUsed": 2100000,
  "from": "0xf61343ef22bbccc7221dcda85c5a69219ea00c2b",
  "gasUsed": 2100000,
  "logs": [],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "status": false,
  "to": null,
  "transactionHash": "0xab70d64929785cb3e718c78238575c3d21e9f4d4f5e481d26ca4069f269ae9d9",
  "transactionIndex": 0
}"

web3 code :-

const NODE_ADDRESS = config.web3Provider;
    const PRIVATE_KEY = reqdata.signerPriKey;

    const sourceCode = fs.readFileSync('path_to_contract', 'utf8').toString();
    const compiledCode = compiler.compile(sourceCode, 1).contracts[':PropertyContract']
    const abi = JSON.parse(compiledCode.interface);

    async function send(web3, account, transaction) {
        while (true) {
            try {
                const options = {
                    data: transaction.encodeABI(),
                    //gas: await transaction.estimateGas({ from: account.address }),
                    gas: 2100000,
                    gasPrice: 10000000000,
                };
                const signed = await web3.eth.accounts.signTransaction(options, account.privateKey);
                const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
                return receipt;
            }
            catch (error) {
                return error
            }
        }
    }

    async function run() {
        try {
            const web3 = new Web3(NODE_ADDRESS);
            const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
            const contract = new web3.eth.Contract(abi, reqdata.contractAddr);
            const transaction = contract.methods.signAgreement(reqdata.signerPubKey);
            const receipt = await send(web3, account, transaction);
            console.log(JSON.stringify(receipt, null, 4));
            if (web3.currentProvider.constructor.name == "WebsocketProvider")
                web3.currentProvider.connection.close();
            if (receipt) {
                next(null, receipt)
            }
        } catch (error) {
            next(error, null)
        }
    }
    run();


texts: How to connect multiple machines to a private blockchain?

texts: I have created a private blockchain in my machine using geth and now i need multiple machines to connect to that same blockchain and use the contracts deployed in that private blockchain from all machines connected to that blockchain. Can anyone help me with this?


texts: How to get token prices with UNISWAP API

texts:
I am using uniswap python api to get live token prices. I am using all the variation of the built-in functions. However, it does not give me the right value.
HERE IS MY CODE
address = "0x0000000000000000000000000000000000000000"
private_key =  None
uniswap_wrapper = Uniswap(address, private_key,infura_url,version=2)
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"

print(uniswap_wrapper.get_eth_token_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_input_price(dai, 5*10**18))
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18))
print(uniswap_wrapper.get_token_eth_output_price(dai, 5*10**18))

And these are my results respectively,
609629848330146249678
24997277527023953
25306950626771242
2676124437498249933489

I don't want to use coingecko or coinmarketcaps api as they do not list newly released token prices immediately.
I tried etherscan to get token prices but it does not have a built-in function for that. Does anybody has any suggestions on how to fix that or do you know any alternatives?
HERE IS THE FULL API : https://uniswap.org/docs/v2/API/entities/


texts: Confirm Oraclize is not working on Ropsten? (No callback returned)

texts:
I have a contract on Ropsten testnet that was working fine up until 2 hours and 30 minutes ago. I don't believe it is an error on my side because the code hasn't been changed or redeployed.

You can see the oraclize query still being sent out in the internal transactions section of my contract on on Etherscan but there is never any callback returned from Oraclize anymore in the last few hours. Is this assessment correct? I've contacted Oraclize support on their Gitter channel as well.

Here is the contract on Etherscan: https://ropsten.etherscan.io/address/0x8466bc490d87b01d7b0d0f9b5682a806e49966d6

Thanks for any help!


texts: How can I use Ethereum smart contracts with another crypto currency?

texts:
I am learning/playing around with some concepts of the blockchain, smart contracts and Ethereum. I have created my own "toy" cryptocurency ("myCoin") by forking a coin using the CryptoNote algo.

I want to use the Ethereum platform, to write smart contracts which are "denoted" using "myCoin" currency (i.e. tokens), instead of ether.

So for example a contract might state (pseudocode):

Definition of Event A
Definition of Event B

When Event A is raised by a user
Pay user X units of myCoin

When Event B is raised by a user
Request user Y units of myCoin from user

Can someone outline the steps needed to write such smart contracts that are decoupled from ETH and instead rely on my alt coin?


texts: How to store addresses of incoming transactions and delete them afterwards

texts:
I'm building a basic "lottery" where you send 1 ether to a smart contract, I save your address, and after 5 transactions I randomly choose one of the 5 addresses and send the 5 ethers to the "winner".

So I'll be saving ethereum addresses after each transaction, and after 5 transactions deleteing them all to start over.

Should I use mapping? array? byte[100]?
Do I need an index to select an address, or is there a function to select a random address from the mapping/array?
How do I afterwards "delete" all the addresses stored?

Thanks


texts: Does any client maintain a mapping of hashes to addresses?

texts:
As explained in the Design Rationale wiki:

  Using sha3(k) as the key in the "secure tree" (used in the state and account storage tries): this makes it much more difficult to DoS the trie by setting up maximally unfavorable chains of diverge nodes 64 levels deep and repeatedly calling SLOAD and SSTORE on them. Note that this makes it more difficult to enumerate the tree; if you want to have enumeration capability in your client, the simplest approach is to maintain a database mapping sha3(k) -> k.

Does any client maintain such a mapping? It'd make it possible to enumerate all addresses in the network easily (see this answer for context How to list accounts / addresses?)


texts: Speed up transaction processing in a private chain

texts:
Given a private chain where all transactions are sent with the same amount of gas and gasprice, is it possible to speed up transaction processing by lowering the complexity of a block?

Or by any other way :)


texts:
How expensive are loops in solidity? (in terms of gas usage).
I need to loop through ~1000 wallet address, and send each of them some tokens.

my code:

struct User {
    uint32 frozenAt ;
    uint earnedTokens;
    bool isValid;
}

mapping(address => User) users;
address[] public usersAddresses;

uint reciversLength = usersAddresses.length;
for (uint i = 0; i < reciversLength; i++) {
    User storage theUser = users[usersAddresses[i]];

    // transfer(usersAddresses[i], theUser.earnedTokens);
}

should i be worry about gas usage?
anything i can do to optimize this loop?

maybe instead of a truct for each user i should do couple of mappings? (i read somewhere that this is more efficient)

I was wondering if the better way would be grabbing the data from a node.js server, and send the token for each user using tronweb. would doing this worth the trouble?

any help would be appreciated


texts:
I'm finding a way to subscribe the specific event in the Smart Contract and there is a web3.eth.subscribe to subscribe an event.

[Web3.js 1.0.0]

The web3.eth.subscribe function lets you subscribe to specific events in the blockchain.

>> web3.eth.subscribe(type [, options] [, callback]);

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

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

I want to make a script which will be running on the server and then, get the result back after noticing the event occur while the script is listening. For instance, now I have to ask consistently the state of variable to the smart contract using myContractInstacne.methods.MyMethods.call() using setInterval() in the script but what I want to do in this situation is just keep listening and get the result only the moment when the event was occuring.

Do you guys have an idea with this? Is it impossible to implement this?


texts: How long does a smart contract typically take to complete?

texts:
I have been developing an application using a smart contract, the application is similar to this one:
https://www.ethereum.org/crowdsale

I went ahead and initiated a request, below is the codebase for it:

import React, { Component } from "react";
import { Form, Button, Message, Input } from "semantic-ui-react";
import Campaign from "../../../ethereum/campaign";
import web3 from "../../../ethereum/web3";
import { Link, Router } from "../../../routes";
import Layout from "../../../components/Layout";

class RequestNew extends Component {
  state = {
    value: "",
    description: "",
    recipient: "",
    loading: false,
    errorMessage: ""
  };

  static async getInitialProps(props) {
    const { address } = props.query;

    return { address };
  }

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

    const campaign = Campaign(this.props.address);
    const { description, value, recipient } = this.state;

    this.setState({ loading: true, errorMessage: "" });

    try {
      const accounts = await web3.eth.getAccounts();
      await campaign.methods
        .createRequest(description, web3.utils.toWei(value, "ether"), recipient)
        .send({ from: accounts[0] });

      Router.pushRoute(`/campaigns/${this.props.address}/requests`);
    } catch (err) {
      this.setState({ errorMessage: err.message });
    }

    this.setState({ loading: false });
  };

  render() {
    return (
      <Layout>
        <Link route={`/campaigns/${this.props.address}/requests`}>
          Back
        </Link>

Create a Request

        <Form onSubmit={this.onSubmit} error={!!this.state.errorMessage}>
          <Form.Field>
            Description
            <Input
              value={this.state.description}
              onChange={event =>
                this.setState({ description: event.target.value })
              }
            />
          </Form.Field>

          <Form.Field>
            Value in Ether
            <Input
              value={this.state.value}
              onChange={event => this.setState({ value: event.target.value })}
            />
          </Form.Field>

          <Form.Field>
            Recipient
            <Input
              value={this.state.recipient}
              onChange={event =>
                this.setState({ recipient: event.target.value })
              }
            />
          </Form.Field>

          <Message error header="Oops!" content={this.state.errorMessage} />
          <Button primary loading={this.state.loading}>
            Create!
          </Button>
        </Form>
      </Layout>
    );
  }
}

export default RequestNew;

The button has a spinner that has been spinning now for over 20 minutes since the request was initiated.

I go over to Metamask and I am still seeing Contract Interaction in Pending status with a time of 21:51.

The last transaction I initiated the last time I was developing this application only took 14:47.

How long should it take? Is this the norm? How much longer should I wait? What are my options?

This is just testing on the Rinkeby Test Network by the way, so I am not so much concerned about loss as I am about time spent in pending status.


texts:
How can I write a contract that sends some of the ether it receives on to one wallet, and the rest of the ether back to the sender (or another wallet)

The following code works if I comment out either line 17 or 18 but doesn't when both are uncommented:

pragma solidity ^0.4.24;

contract Forwarder {

    address public destinationAddress;
    address constant public otherAddress = 0xf17f52151EbEF6C7334FAD080c5704D77216b732;

    event LogForwarded(address indexed sender, uint amount);
    event LogFlushed(address indexed sender, uint amount);

    function Forwarder() public {
        destinationAddress = msg.sender;
    }

    function() payable public {
        emit LogForwarded(msg.sender, msg.value);
        otherAddress.transfer(msg.value /3);        // 17
        destinationAddress.transfer(msg.value /3);  // 18
    }

    function flush() public {
        emit LogFlushed(msg.sender, address(this).balance);
        destinationAddress.transfer(address(this).balance);
    }

}


texts:
myprojectcode is removed for privacy
I'm using the docs 1:1 and still get this error
https://web3js.readthedocs.io/en/v1.3.4/web3-eth.html#signtransaction
import Web3 from 'web3';
const web3 = new Web3('wss://ropsten.infura.io/ws/v3/myprojectcode');
web3.eth.signTransaction({
   from: "0xEB014f8c8B418Db6b45774c326A0E64C78914dC0",
   gasPrice: "20000000000",
   gas: "21000",
   to: '0x3535353535353535353535353535353535353535',
   value: "1000000000000000000",
   data: ""
}).then(console.log);

returns this error

node:86351) UnhandledPromiseRejectionWarning: Error: Returned error:
The method eth_signTransaction does not exist/is not available

using nodejs with web3 1.3.5


texts:
What tools there exist to run automate test suite against Solidity contracts?

Set up scenarios how transactions are executed
Assert the contract state variables are valid after execution


texts: Can a chain link node listen to ethereum smart contracts events? Let’s say I want to provide data to a node from a smart contract. Can a I link a chain link node and use a smart contract as an oracle?


texts: How to query the txpool from a BSC Full Node?

texts:
I installed a bsc full node successfully (I think)
The log file keep saying things like:
t=2021-05-04T11:09:00+0200 lvl=info msg="Initializing fast sync bloom"        items=18543225 errorrate=0.000 elapsed=9m30.594s
t=2021-05-04T11:09:03+0200 lvl=info msg="Imported new block headers"          count=1    elapsed=1.202ms   number=7125319 hash=0x13096855414f2c753255b7b117d57aa25af084ce1b11cffbfc034e7d754355ce age=5m30s
t=2021-05-04T11:09:07+0200 lvl=info msg="Imported new block headers"          count=1    elapsed=841.489µs number=7125320 hash=0x396fdb1882b7757526a9ce93ac05b669d4095515827bcbf71a4df622f854a152 age=5m31s
t=2021-05-04T11:09:08+0200 lvl=info msg="Initializing fast sync bloom"        items=18543225 errorrate=0.000 elapsed=9m38.596s
t=2021-05-04T11:09:10+0200 lvl=info msg="Imported new block headers"          count=1    elapsed=1.089ms   number=7125321 hash=0x61e363a7c50cd7610208374f340dd1081d620dbe949eadf7fd8a4a4ce7d2a724 age=5m31s

So I assume it's working.
By the way, I can't inspect the txpool.
The following command:
 curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"txpool_content","params":[],"id":1}' http://localhost:8545

Result in:
{"jsonrpc":"2.0","id":1,"result":{"pending":{},"queued":{}}}

I tried to change ID from 1 to 56 but the result is the same.
What am I doing wrong?


texts:
I have find this assembly code

function toBytes(address a) constant returns (bytes b){
   assembly {
        let m := mload(0x40)
        mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
        mstore(0x40, add(m, 52))
        b := m
   }
}

on this post : https://ethereum.stackexchange.com/a/13663/17618

There is some things that i don't understand.

Someone can help me to understand this please ?

(I didn't have enough reputation to post a comment on this post, this is why i post a new thread)

Thanks !


texts: Mining hangs on Generating DAG in progress

texts:
I am trying to initialize rpc using the below command and start miner using miner.start(1);
geth --rpcapi eth,web3,personal --rpc --networkid=15

Mining starts successfully with below logs but it doesn't proceed further and hangs here only.
INFO [08-28|18:20:52.808] Generating DAG in progress               epoch=1 percentage=98 elapsed=12.725s
INFO [08-28|18:20:53.063] Generating DAG in progress               epoch=1 percentage=99 elapsed=12.981s
INFO [08-28|18:20:53.065] Generated ethash verification cache      epoch=1 elapsed=12.983s

Things i tried till now.

https://ethereum.stackexchange.com/a/13610/41204
action : 64GB RAM 128GB HD and 16CPU so this is not the problem i guess.

https://stackoverflow.com/a/46430217/6572971
action : Have set primary account using eth.defaultAccount=eth.coinbase which returns "0x-----"

https://ethereum.stackexchange.com/a/39000/41204
action : Have done as suggested but no luck.


texts: I want to build a blockchain network such that if one node updates, all the other linked nodes gets update too. Think of it as Centralized Hospital record in multiple cities, if any of the city pushes the record it gets updated on each node. Any idea how to get started on that? I have pretty basic knowledge on building DAPP's any help will be highly appreciated, thanks.


texts: Is it possible to have user-defined Struct as a _KeyType in a Mapping in Solidity?

texts:
I'm trying to define a Struct type, and use it as a _keytype for a mapping.

contract TestContract
{
    struct Structure {
        bytes32 structure_name;
    }

    mapping (Structure => address) public test_mapping;
}

Using Solidity real time compiler I get the following error message:

  Error: Expected elementary type name for mapping key type

However, according to Solidity's documentation, every data type except for 'mapping' can be used for _keytype:

  Mapping types are declared as mapping _KeyType => _ValueType, where _KeyType can be almost any type except for a mapping and _ValueType can actually be any type, including mappings.

Did I understand the documentation wrongly?


texts: Call an arbitrary JSON-RPC method with web3

texts: I want to use web3 to call evm_snapshot (only available on testrpc). This is not in web3's list of methods, but I don't want to have to make an actual http call.


texts: Transactions fails in rinkeby but succeeds on localhost, gas limit 1000000 is cited

texts:
http://lucidity-eth-r.surge.sh/
Rinkeby test for buying funding token (search Honduras Agriculture Project, may have to click submit a few times), then go to funder view, and type in any amount/tenor. On localhost this works just fine, has never thrown me an error.
I get this error, no matter what I set my wallet gas limit too. Thanks!
https://github.com/andrewhong5297/DFTP-core repo for reference is that helps.


texts: Hi guys, I'm stuck in here. Thank you for helping


texts: Advantage of using a contract constructor with parameters

texts: What is the advantage of using a constructor with parameters instead of hard coding the values? Is there a possibility to reuse a once deployed contract?


texts: how can i use web3.eth.getCode() on html

texts:
I want to use web3.eth.getCode() on html.

So I use this code on my html:

<script src = "https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js ">
    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"));
    }
</script>

When I use alert(web3.version.api),
it returns 0.20.3

But when I use alert(web3.eth.getCode("0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8")), it doesn't work.

Did I forget something about gas or something else?

Please give me some advice on how to handle a situation like this. Thank you in advance.


texts:
Ok so Ive found Openzeppelin a slightly easier Code to use, it explains better than Solidity does.
But now my problem is the Math bit. Im no mathematician neither and cannot get my head around how it works.
So if I want 3 ether per token at 18 decimals for the one example, and 8 decimals for the other for example, how do I input it into the code because what I have now is not accepted, I get errors with the math bit as well as the part for constructor.
Please can somebody explain this to me and highlight whats the correct library needed or input so that I dont get any errors.

Im using Metamsk Web.3, Remix, Solidity and Openzeppelin.

Thanks a mill guys, I really would appreciated the help.

pragma solidity ^0.5.0;

import "@openzeppelin/contracts/crowdsale/Crowdsale.sol";
import  "@openzeppelin/contracts/crowdsale/CappedCrowdsale.sol";
import "@openzeppelin/contracts/crowdsale/CappedCrowdsale.sol";

/**
 * @title SimpleCrowdsale
 * @dev This is an example of a fully fledged crowdsale.
 *
contract SimpleCrowdsale is Crowdsale {
    constructor (
        uint256 rate, 10**18
        address payable wallet,
        IERC20 token
    )
        public
        Crowdsale(rate, wallet, token)
    {
    }

contract MyCrowdsale is Crowdsale, CappedCrowdsale, TimedCrowdsale {

    constructor(
        uint256 rate,  10**18          // rate, in bits
        address payable wallet,   // wallet to send Ether
        IERC20 token,            // the token
        uint256 cap,     66028410000000000000000000     // total cap, in wei
        uint256 openingTime,  Date(2020, 4, 02, 16, 30)  // opening time in unix epoch seconds
        uint256 closingTime    Date(2020, 4, 17, 16, 30) // closing time in unix epoch seconds
    )
        CappedCrowdsale(cap)
        TimedCrowdsale(openingTime, closingTime)
        Crowdsale(rate, wallet, token)
        public
    {
        // nice, we just created a crowdsale that's only open
        // for a certain amount of time
        // and stops accepting contributions once it reaches `cap`
    }
}

contract MyCrowdsale is Crowdsale, TimedCrowdsale, PostDeliveryCrowdsale {

    constructor(
        uint256 rate,    10**18        // rate, in bits
        address payable wallet,  // wallet to send Ether
        IERC20 token,            // the token
        uint256 openingTime,  Date(2020, 4, 02, 16, 30)   // opening time in unix epoch seconds
        uint256 closingTime   Date(2020, 4, 17, 16, 30)   // closing time in unix epoch seconds
    )
        PostDeliveryCrowdsale()
        TimedCrowdsale(openingTime, closingTime)
        Crowdsale(rate, wallet, token)
        public
    {
        // nice! this Crowdsale will keep all of the tokens until the end of the crowdsale
        // and then users can `withdrawTokens()` to get the tokens they're owed
    }
}


texts:
admin.getPeer in the past returned something like this:

admin.addPeer("enode://cc92c3aff13bb5c81f8c4a172a3847d5c6c6874a0acd607cf37f0e8bbd643d851fe727ce35245bbe22e5fc246e1efe957dd66161924692898d231541307f6d4e@47.104.183.34:36590");

With recent updates it is returning something like this:

admin.addPeer("enode://2640824ef05d35d14b46cab77e814a2b367ae0ab7906b4d3f8aa624bfc3c4705@54.86.13.24:30303");

As you can see the new enode is much shorter than the original. Has something changed?


texts:
I'm new to this web3 API and I'm trying to use it with NodeJS. I've not been able to make a single transaction from one address to another. I've been able to successfully retrieve the balance of my address.

The method I'm using is documented here but when I execute the script, it will give an error saying that my params are not formatted well

  Returned error: Invalid params: invalid type: map, expected a 0x-prefixed, hex-encoded vector of bytes.

My params:

amount = '0x' + (+web3.utils.toWei('0.06', 'ether')).toString(16)
var rawTx = {
    from: ethAddress,
    to: destinationAddress,
    value: amount
}

The variables ethAddress and destinationAddress are set correctly.

Any help would be much appreciated!


texts: solidity two dimentional mapping or array

texts:
I want to use two dimensional mapping or array but one key should be address  and the other key is a number ,how can I do this?
Similar to Mapping (address , uint256=> unit)
How to do it? Use struct? Thanks


texts: If I deposit A-tokens to contract, then contract owns A-tokens?

texts:
If I deposit A-tokens(erc20) to smartcontract, then smartcontract owns A-tokens?
If so, is it possible another user send TX to the smartcontract above to interact with another smartcontract with A-tokens included?

should I do something like approve and transferfrom to make this case feasible?


texts:
As I know, coinbase is the default account that stores ether when mining.
Does a node only contain a coinbase?
If there are many different users who have many accounts in one node, will there be many coinbase? If not, does it mean there are only one user (who may have one or more accounts) in one node?


texts: Not able to add ether in my private network's account

texts:
1. I have created a small ethereum private network. I opened launched the private network from terminal 1, launched the geth console from terminal 2, and opened mist browser in terminal 3. Once mist is launched, I created a new account (Eherbase) which has currently 0 ether. Now, when I do miner.start(), it gives  null and "INFO [03-04|10:49:12] Commit new mining work number=1   txs=0 uncles=0 elapsed=777.632µs", on other console, but the balance for the account is still zero. How can I add ether to my account?

2. I started again with new genesis.json file with a account already having some ether, but I am now not able to see that account in my mist browser? what should I do?

OS - Ubuntu 14.04
geth-  1.8.1-stable-1e67410e
mist -  0.8.10

commands that I used:
terminal 1-
Created private network # geth --datadir=./chaindata/ init genesis.json
launch network # geth --port "35555" --datadir=./chaindata/
terminal 2-
open geth console # geth attach ipc:/address_to_geth.ipc
terminal 3-
open mist # mist --rpc /address_to_geth.ipc

genesis.json file

{

"config": {

"chainId": 15,

"homesteadBlock": 0,

"eip155Block": 0,

"eip158Block": 0

},

"difficulty": "0x20",

"gasLimit": "2100000",

"alloc": {

"7df9a875a174b3bc565e6424a0050ebc1b2d1d82":
    { "balance": "300000" },

"f41c74c9ae680c1aa78f42e5647a62f353b7bdde":
    { "balance": "400000" }

}

}


texts: Here is my sample code, whether the contract to contract calls in setName function is synchronous or asynchronous?


texts: Storing data in the blockchain inside a transaction

texts:
This question is related to this one and this one. I'm trying to store data in the blockchain inside the transaction data field:

The second question offers a solution using a contract but is it possible to use only the transaction field. In pyethapp it is defined as follows:

class Transaction(rlp.Serializable):

    """
    A transaction is stored as:
    [nonce, gasprice, startgas, to, value, data, v, r, s]

    nonce is the number of transactions already sent by that account, encoded
    in binary form (eg.  0 -> '', 7 -> '\x07', 1000 -> '\x03\xd8').

    (v,r,s) is the raw Electrum-style signature of the transaction without the
    signature made with the private key corresponding to the sending account,
    with 0 <= v <= 3. From an Electrum-style signature (65 bytes) it is
    possible to extract the public key, and thereby the address, directly.

    A valid transaction is one where:
    (i) the signature is well-formed (ie. 0 <= v <= 3, 0 <= r < P, 0 <= s < N,
        0 <= r < P - N if v >= 2), and
    (ii) the sending account has enough funds to pay the fee and the value.
    """

    fields = [
        ('nonce', big_endian_int),
        ('gasprice', big_endian_int),
        ('startgas', big_endian_int),
        ('to', utils.address),
        ('value', big_endian_int),
        ('data', binary),
        ('v', big_endian_int),
        ('r', big_endian_int),
        ('s', big_endian_int),
    ]

    _sender = None

    def __init__(self, nonce, gasprice, startgas, to, value, data, v=0, r=0, s=0):
        self.data = None

        to = utils.normalize_address(to, allow_blank=True)
        assert len(to) == 20 or len(to) == 0
        super(Transaction, self).__init__(nonce, gasprice, startgas, to, value, data, v, r, s)
        self.logs = []

        if self.gasprice >= TT256 or self.startgas >= TT256 or \
                self.value >= TT256 or self.nonce >= TT256:
            raise InvalidTransaction("Values way too high!")
        if self.startgas < self.intrinsic_gas_used:
            raise InvalidTransaction("Startgas too low")

        log.debug('deserialized tx', tx=encode_hex(self.hash)[:8])

I'm not sure whether the field has an upper bound in terms of size.

How much data can be stored within a transaction?


texts: Is there any way to conduct multilateral netting on a DLT platform?

texts: Multilateral Netting is generally used as a method to counter high liquidity requirement for the participating members. We always use a central clearing house/central counterparty who does this netting for the participants. I was wondering if there is any possible decentralized architecture where we can remove the dependency on a central clearing house yet achieve tamper proof multilateral netting


texts: How do I monitor deposits for the account on ethereum? I saw some APIs that do this and I have tried to do the same on js web3 with filter but without any luck. What I would need is to get all the past transactions for specific address, maybe from the specified hash or just from the beginning if that is not possible.


texts: What's the point of having static nodes when IP addresses keep changing?

texts: In the <datadir>/static-nodes.json file, we can mention the enode URI of a node that we want to re-connect to, in case of a connection failure. Assume A is a static node which has been rebooted. Now, it has a different IP address to the one stored in static-nodes.json file. Since IP address is a part of the enode URI, how do other nodes find out the new IP address of A and re-connect to it (in a private blockchain network). Is the static-nodes.json file updated every time this happens?


texts: Exponentiation Error "TypeError: Type rational_const"

texts:
I can not get the answer of the expression

int256 test2 = ((0.0035+1)**120)*(10**18);

  TypeError: Type rational_const 2021...(389 digits omitted)...2001 /
  1329...(371 digits omitted)...0000 is not implicitly convertible to expected type int256. Try converting to type ufixed256x58 or use an
  explicit conversion.

int256 test2 = ((0.0035+1)**4)*(10**18);

  This expression does not give an error

How can I solve such an expression with the help of Solidity?

int256 test2 = ((0.0035+1)**120)*(10**18);


texts:
I'm trying to run geth on a new mac and it gets stuck when trying to sync.
I'm running geth --testnet --syncmode "fast"

This is the console output:

  INFO [01-06|11:33:20] Starting peer-to-peer node
  instance=Geth/v1.7.3-stable/darwin-amd64/go1.9.2 INFO [01-06|11:33:20]
  Allocated cache and file handles
  database=/Users/pabloruiz55/Library/Ethereum/testnet/geth/chaindata
  cache=128 handles=1024 INFO [01-06|11:33:20] Writing custom genesis
  block  INFO [01-06|11:33:20] Initialised chain configuration
  config="{ChainID: 3 Homestead: 0 DAO:  DAOSupport: true EIP150: 0
  EIP155: 10 EIP158: 10 Byzantium: 1700000 Engine: ethash}" INFO
  [01-06|11:33:20] Disk storage enabled for ethash caches
  dir=/Users/pabloruiz55/Library/Ethereum/testnet/geth/ethash count=3
  INFO [01-06|11:33:20] Disk storage enabled for ethash DAGs
  dir=/Users/pabloruiz55/.ethash                              count=2
  INFO [01-06|11:33:20] Initialising Ethereum protocol
  versions="[63 62]" network=3 INFO [01-06|11:33:20] Loaded most recent
  local header          number=0 hash=419410…ca4a2d td=1048576 INFO
  [01-06|11:33:20] Loaded most recent local full block      number=0
  hash=419410…ca4a2d td=1048576 INFO [01-06|11:33:20] Loaded most recent
  local fast block      number=0 hash=419410…ca4a2d td=1048576 INFO
  [01-06|11:33:20] Regenerated local transaction journal
  transactions=0 accounts=0 INFO [01-06|11:33:20] Starting P2P
  networking  INFO [01-06|11:33:23] UDP listener up
  self=enode://cff9f6def208edea618095eeec2b2f96532188e248775447c14bcf092eb73f97ed27411f56b1737d3caf0815b677c1b47cc72dbb8c0ab7ef4d2f0192c56a23e6@190.55.195.86:30303
  INFO [01-06|11:33:23] RLPx listener up
  self=enode://cff9f6def208edea618095eeec2b2f96532188e248775447c14bcf092eb73f97ed27411f56b1737d3caf0815b677c1b47cc72dbb8c0ab7ef4d2f0192c56a23e6@190.55.195.86:30303
  INFO [01-06|11:33:23] IPC endpoint opened:
  /Users/pabloruiz55/Library/Ethereum/testnet/geth.ipc

It always gets stuck after that last message.
Tried using --syncmode "light" or just geth --testnet, but it's the same.

Syncing mainnet DOES work.
Syncing Rinkeby DOES work.

Any ideas?


texts: aAAVE (Atoken) accidently transferred from Metamask wallet to exchange AAVE wallet - HELP PLEASE!

texts:
Really hoping someone here can help.
I have AAVE being used as collateral on AAVEV2 as I borrowed some USDC at very low LTV. I use metamask to connect to AAVE and in my wallet you can see aAAVE (interest beaing atoken) and normal AAVE. I mistakingly sent 10 aAAVE instead of normal AAVE to coinbase exchange AAVE wallet. See on etherscan below.
https://etherscan.io/tx/0xbc19fc4884f8c8ab1650bfa886e37f5d621805e22b476dfdcad0688371fa69df
The transaction was completed and I now presume my aAAVE tokens stuck in my coinbase AAVE wallet as it was received but naturally doesnt show up in AAVE wallet.
My question, is what can I do if anything??
I have sent request to support at coinbase but suspect they will take forever to respond. Is there anything I can do to get coins back?
Also, why when aAAVE was collateral, would I be allowed to send direct from Metamask to coinbase in 1st place i fit was collaterized?
many thanks in advance for any help.
D


texts:
In my contract I have a mapping like this mapping(uint => myStruct)

I have a check function where I give a uint id and I want to get all the info in the struct (there are strings, addresses, uints, ...) with a call function in my truffle app.js.

What's the best way to do that? Can I convert every field to a string and send an array of strings? Should I make a separate getter for each field and use as many call functions?

For now I just return struct and I get invalid solidity type!: tuple


texts: Verifying Signatures from other ECC Curves with ecRecover

texts:
My Question is, can I verify a ECDSA Signature from a different ECC Curve like scep128r1 or secp256k1 with the ecRecover function?

If not, are there any good Library's which have implemented this feature?


texts:
I'm in a situation to implement the following scenario,

Need to transfer ERC20 standard token(own by my contract) to some
another wallet.
When recording transaction on Ethereum, need to add
custom data(eg: why this transaction happens.)
When executing
getBalance method on any wallet address it should be able to read
custom data as well.

Is there any way that I can add custom data on transactions while maintaining the ERC20 standard? Appreciate any help.


texts: Can you provide a real world example of using Ethereum network?

texts:
Is there any practical real world example which you can provide in order to understand the simple benefits for using Ethereum network by the ordinary user?

Especially in terms of purchasing something that can make user's life much easier, efficient and less time consuming than using a standard method by a non-technical user (like PayPal or Skrill, not to mention standard method of paying by card)?


texts:
I have been using structs like:

contract gas {

    struct example {
       uint256 num;
       string name;
      }

}

I want to use an instance of other Contract in struct like:

contract token {

   struct example2 {
     gas g1; //instance of gas
     uint256 num;
     ...
     }

}

Is it possible to use contract gas' g1 instance in struct of contract token (and later instantiate it when instantiating the example2 struct)? disclaimer: Im new in solidity (like 3 days new) so go easy! :)


texts: Are there well-solved patterns and practices for handling errors in Solidity?

texts:
In the spirit of Are there well-solved and simple storage patterns for Solidity?...

Are there known, battle-tested practices for how to deal with errors in large Solidity codebases?

It's common in software engineering to have a clear collection of error names, codes and descriptions, usually implemented via enums. The only project I've seen which adheres to this rigorous take on error handling is Compound, but there must be more. Compound's codebase is big and interwoven with other finesses like formal verification scripts, so their's is not strictly the best implementation to refer to when answering this question.


texts: How do I share an enum definition between contracts?

texts:
I have two related contracts, let's call them Supplier and Producer.

A Supplier can have a State of inactive, active, or kaput, but only active suppliers can be added to a Producer.

So something like this:

contract Supplier {
  enum State { inactive, active, kaput }
  State constant DEFAULT_STATE = State.inactive

  State public status;

  function Supplier() {
    status = DEFAULT_STATE;
  }
}

But doing this doesn't work.

contract Producer {
  function addSupplier(Supplier _supplier) {
    require(_supplier.status == Supplier.State.active);
  }
}

I considered using an Interface but enum is specifically disallowed in an Interface.

How do I expose enum definitions to external contracts without resorting to something ugly like require(uint(supplier.status) == 1);


texts: Is it possible to define a smart contract as the address when mining on a pool like ethermine?

texts:
I would like to create a contract that shares mining rewards between multiple accounts.

Can I set this contract address as the target address when running eth-proxy ?


texts: What happens when contract is making delegatecall to deleted contract?

texts:
I read the whole Suicide Parity Multi-sig hack. One thing I don't understand is what happens when you call delegate call on deleted contract?
I thought that contract should throw an exception but due to the attack description it doesn't. Why this code returned true?

function isOwner(address _addr) constant returns (bool) {
   return _walletLibrary.delegatecall(msg.data);
}


texts: How to create a Buy link like coinbase in Metamask

texts:
When I'm using Metamask using Main Ethereum Network, and click on the [Buy] button, I will be presented with two links (Coinbase, ShapeShift).

May I know how can I create link like these? I would like to create one in my privatenode for testing.

Thanks in advance.


texts:
I have looked to split and sell my etc and have successfully split with test transactions replaying on classic, however the main transaction has not replayed for 24 hours and I would like to force a replay. I have both blockchains available.

I have tried taking the output of web3.eth.getTransaction(hash) on ETH and tried recreating it with ethereumjs-tx signed and unsigned on classic without much success.

I haven't seen a method to get the raw hex of a transaction in geth to inject it via web3.eth.sendRawTransaction

My alternative is to perform the same transaction I did on ETH but on ETC


texts: How do Miners get the GAS Used so close the GAS Limit?

texts:
Are the Miners calculating the actual GAS USED for each Transaction (specifically for contract execution) before they stuff it into the Candidate Block to get so close to the Block GAS Limit?
The above would take some time which is why block 10832612 is empty for example.  The Miner is mining an empty Block.  When the maximum GAS USED Block is built, they start mining this new more profitable block?
Is my understanding correct?
Thank you


texts:
I know there have been quite a few questions surrounding time, and the use of block.timestamp. However, I still have a few questions design-wise.

At what point exactly is it 'dangerous' to use block.timestamp? I'm building a PoC which would use time units as little as 5 minutes. The average blocktime is 15 seconds in ethereum. I also heard miners can manipulate this timestamp by up to 900(!) seconds. This all seems like it would make developing smart contracts which use small time units unfeasible.
Expanding on the previous question, is there an alternative to this construct? I've heard oracles can be used, but this would incur a gas cost for even simple checks. Is there any other way?
How will future protocol developments impact the current way of working with time? For instance the switch to PoS,Plasma,...

I know the problem time gives, being that smart contracts need to be deterministic and time isn't, but it seems as if the current way of doing this severely limits the amount of things you can actually do with Ethereum smart contracts.


texts: How to calculate the price after trade on Uniswap?

texts: I would like to get the price of a token after a swap. For example the price is now $1, and I would like to see how much will be the price after my swap. Is the execution price what I need in this case?


texts:
At the moment all Ethereum services seems to be running on web3.js and this requires a full node to be running, most users will never install 30+ GB to use a website or service. I my self have tried to MANY times and wasted lots of effort trying to get geth and parity to sync but here in Asia the nodes get stuck and stop syncing for some reason. Not enough peers.

-When will the light client protocol be ready?
-Why do more Ethereum websites not just serve normal webpages (rendered with web3.js server side)
-Is there anyway to get stating writing smart contract AND deploying them on the main net without a node running?


texts:
I'm having an issue with running truffle test on a Javascript test. I get the error TypeError: Cannot read property 'getBlock' of undefined.

I am trying to get the time of the latest block by using a snippet from OpenZeppelin:

async function latestTime () {
  const block = await web3.eth.getBlock('latest');
  return block.timestamp;
}

When I run this in truffle console,  web3.eth.getBlock('latest') works fine.


texts: How to query incoming transactions to an ethereum address via web3j?

texts:
i know this question has been asked many times in this forum, but none of them give clear cut answer to the questions. I tried the snippet mentioned in this answer: Common useful JavaScript snippets for geth ; But, it gives me the reply as "undefined" when run in the node.

Can someone please guide me on how i can query the blockchain to get incoming transactions to an address?

Thanks!!


texts:
Quick question...

... I'm trying to run a Parity public node but cannot connect to it from any computer other than the one it's running on.

Parity v1.8.6 on
Windows 10 x64 - all updates

When I open 127.0.0.1:8180 from the computer it's running on I get the UI, no issues.
When I try to connect from any other computer on my LAN to 192.168.1.4:8180 I get:

  This site can’t be reached
  192.168.1.4 refused to connect.

Parity is fully sync'd and I have no firewalls running on any of the computers.
Not sure what I'm doing wrong here...

Thanks!


texts: It's is possible to track by API, if block was forked/orphaned? Will be glad to see some example.


texts:
a user send 10 ethers to Smart Contract A, then Smart Contract A send 10 ethers to Smart Contract B.

Would that be 2 transactions, or 1 transactions?

(What I heard is that the answer is 1, why is that?)


texts: How do i know if my sync is in fast mode?

texts:
I entered "geth" command from my powerShell comandline. There was no ChainData directory.
I am running Windows 10 64 bit. I downloaded Geth v1.8.3 for windows 64 bit
The machine has 250 GB SSD. The internet connection is 3 Mbps. No other process is running.

its 3 days now, about 4300 files downloaded in my ChainData folder and sync is still running.

How do i know if it is running in fast mode?
How long is it going to still take? In other words, how many more nodes it still has to download, like "downloading 4300 out of 10000"?


texts: On Ethereum blockchain. Store secret inside a smartcontract with private keyword?

texts:
If I use private variable, can attacker or anyone be able to know what the variable is?

For example.

I declare a private variable named "secret" without initialize its value.

Later after I created the contract, I then interacted with my contract by set the "secret" variable to "hello". Suppose I did this using ether wallet with metamask.

setSecret("hello")

In theory, I know that anyone can't get my private secret by interacting with my Secret contract. But since I set the secret to "hello" in the previous transaction. Will the word "hello" get record in a log file, transaction, or somewhere which can be dig up?

I'm just trying to understand how to keep a secret inside my contract.

This is my example contract

pragma solidity ^0.4.15;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permission"
 */
contract Ownable {

    address public owner;

    /**
     * @dev The Ownable constructor sets the original 'owner' of the contract to the sender
     * account.
     */
    function Ownable() internal {
        owner = msg.sender;
    }

    /**
     *  @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

}

contract Secret is Ownable {

  string private secret;

  function Secret() public {
    secret = "";
  }

  function setSecret(string _secret) public onlyOwner {
    secret = _secret;
  }

}


texts: function not returning a uint256 while using Hardhat testing

texts:
Here's the function that's supposed to return a uint256
function initializeToken(string memory name, string memory symbol) public returns (uint256) {

   // _creatorIds is a @openzeppelin counter
   address creator = msg.sender;
   _creatorIds.increment();
   newId = _creatorIds.current();

   Token token = new Token(symbol, name, creator);
   _tokens[newId] = address(token);
   return newId;
}

I followed the testing instructions given here

The when I console.log() the result in a test file and run it with hardhat it returns a
{ Object (hash, blockHash, ...) }

instead of a
{ BigNumber (_hex, _isBigNumber) }

So I can't do any equality tests.

There's probably a really easy answer to this, but I've tried recompiling multiple times, and it still doesn't work.
edit:

Here's the test code as requested:

const { expect } = require('chai');

describe("TokenDistributor contract", function() {
    it("Deployment should return a Token with name Test Token and symbol TTN", async function() {
      const [distributor] = await ethers.getSigners();

      const TokenDistributor = await ethers.getContractFactory("TokenDistributor");

      const instance = await TokenDistributor.deploy();
      await instance.deployed();

      var tokenId = await instance.initializeToken("Test Token","TTN");
      console.log(tokenId); //This is where I did the console.log to see what was wrong

      expect(tokenId).to.equal(1); //this is where the test fails
    });
  });


texts: A NodeJS app running on AWS instance + Web3 object

texts:
I have an NodeJS app running on AWS instance(the one you get for free). I want to get access to Web3 object in my server.js file. I don't think that installing and running full client like Geth on AWS instance is possible/viable, because of how much computational resources it requires or some other technical reasons, I'm talking out of my armpit right now. Maybe some kind of light client is the answer, idk.

I've also read somewhere that it's possible to connect an app to a remote node through and RPC or something like that, but I also remember that it's not secure for some reasons.

So, what are my options, good sirs?


texts:
I have a blockchain dapp which is working fine in web browser.
Wallet : Metamask
OS     : Ubuntu 20
Node   : 10.19.0
Npm    : 6.14.4

But, I would like to run the dapp in mobile view using truffle react-native. Could you please suggest any sample latest dapp code using truffle react-native?
I already tried truffle suite dapp, but it's not working for me.
Help will be appreciated


texts:
how to send an erc20 in web3py please, I have that :
tx_hash = contract.functions.transfer(destination_address, value).transact({'from': myaddress })
and I get this error :
ValueError: {'code': -32601, 'message': 'The method eth_sendTransaction does not exist/is not available'}
I guess am missing signing that or something like that, how can I make a successful  erc20 transfer.