Skip to content

Commit

Permalink
web3 integration
Browse files Browse the repository at this point in the history
  • Loading branch information
echo-sg committed Feb 11, 2021
1 parent e9801a6 commit 2b8418c
Show file tree
Hide file tree
Showing 20 changed files with 22,553 additions and 215 deletions.
2 changes: 1 addition & 1 deletion .eslintcache

Large diffs are not rendered by default.

63 changes: 36 additions & 27 deletions contracts/DStock.sol
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,34 @@ contract DStock{

event TokenBought(address _buyer, uint256 _amount);
event TokenRedeemed(address _buyer, uint256 _amount);
uint public assetCount;
uint public personCount;

uint256 public assetCount;
uint8 public personCount;

struct asset{
uint assetId;
uint256 assetId;
string hash;
address creatorAddress;
uint cost;
uint soldCount;
uint256 cost;
uint256 soldCount;
}

struct person{
uint personId;
uint256 personId;
address personAddress;
uint earning;
uint tokenCount;
uint[] assetsUploaded;
uint[] assetsBought;
uint256 earning;
uint256 tokenCount;
uint256[] assetsUploaded;
uint256[] assetsBought;
bool initialized;
}

mapping (uint => asset) public assets;
mapping (uint => person) public persons;
mapping (address=> uint) public getMyId;
mapping (uint256=> asset) public assets;
mapping (uint256=> person) public persons;
mapping (address=> uint8) public getMyId;

event itemUploaded(address creator, string hash);
event itemPurchased(string hash, uint cost);
event itemPurchased(string hash, uint256 cost);

constructor(DStockToken _tokenContract, uint256 _tokenPrice) public {
admin = msg.sender;
Expand All @@ -55,39 +55,36 @@ contract DStock{
persons[personCount].earning= 0;
persons[personCount].tokenCount = 0 ;
persons[personCount].initialized = true;
persons[personCount].assetsUploaded = new uint[](0);
persons[personCount].assetsBought = new uint[](0);
persons[personCount].assetsUploaded = new uint256[](0);
persons[personCount].assetsBought = new uint256[](0);
}


function multiply(uint x, uint y) internal pure returns (uint z) {
function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}

function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == multiply(_numberOfTokens, tokenPrice));
require(msg.value == multiply(_numberOfTokens, tokenPrice));//should be equal ideally
require(tokenContract.balanceOf(admin) >= _numberOfTokens);
// require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
require(tokenContract.transfer(msg.sender, _numberOfTokens),"Token should be transfer to the buyer");
initializePerson(msg.sender);

tokensSold += _numberOfTokens;

emit TokenBought(msg.sender, _numberOfTokens);
}

function redeemTokens(address payable _to, uint256 _numberOfTokens ) public{ //payable not used
require(tokenContract.balanceOf(msg.sender) >= _numberOfTokens);
require(tokenContract.transferFrom(msg.sender, admin, _numberOfTokens));
initializePerson(msg.sender);
_to.transfer(multiply(_numberOfTokens, tokenPrice));

tokensSold -= _numberOfTokens;
emit TokenRedeemed(msg.sender, _numberOfTokens);
}


function uploadAsset(string memory _hash, uint _cost) public {
function uploadAsset(string memory _hash, uint256 _cost) public {
require(bytes(_hash).length > 0,"Hash cannot be empty");
require(_cost != 0, "Cost cannot be 0");
initializePerson(msg.sender);
Expand All @@ -97,7 +94,7 @@ contract DStock{
emit itemUploaded(msg.sender,_hash);
}

function buyAsset(uint _assetId) public {
function buyAsset(uint256 _assetId) public {
require( _assetId>= 0 && _assetId < assetCount,"Asset count invalid");
initializePerson(msg.sender);
require(tokenContract.transferFrom(msg.sender, assets[_assetId].creatorAddress, assets[_assetId].cost));
Expand All @@ -106,11 +103,23 @@ contract DStock{
emit itemPurchased(assets[_assetId].hash , assets[_assetId].cost);
}

function showAssets() public view returns (uint[] memory){
function showAssets() public view returns (uint256[] memory){
return persons[getMyId[msg.sender]].assetsBought;
}

function showUploads() public view returns (uint[] memory){
function showUploads() public view returns (uint256[] memory){
return persons[getMyId[msg.sender]].assetsUploaded;
}

function getId() public view returns (uint8){
return getMyId[msg.sender];
}

// function getAsset() public view returns (uint8){
// return persons[getId()];
// }

function getPerson() public view returns(address a, uint b, uint c){
return (persons[getMyId[msg.sender]].personAddress, persons[getMyId[msg.sender]].earning, persons[getMyId[msg.sender]].tokenCount);
}
}
18 changes: 10 additions & 8 deletions contracts/DStockToken.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ contract DStockToken {
string public symbol = "DST";
string public standard = "DStock Token v1.0";
uint256 public totalSupply;
address public admin;

event Transfer(
address indexed _from,
Expand All @@ -22,37 +23,38 @@ contract DStockToken {
mapping(address => mapping(address => uint256)) public allowance;

constructor(uint256 _initialSupply) public {
balanceOf[msg.sender] = _initialSupply;
admin = msg.sender;
balanceOf[admin] = _initialSupply;//this
totalSupply = _initialSupply;
}

function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
require(balanceOf[admin] >= _value);

balanceOf[msg.sender] -= _value;
balanceOf[admin] -= _value;
balanceOf[_to] += _value;

emit Transfer(msg.sender, _to, _value);
emit Transfer(admin, _to, _value);

return true;
}

function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
allowance[admin][_spender] = _value;

emit Approval(msg.sender, _spender, _value);
emit Approval(admin, _spender, _value);

return true;
}

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
require(_value <= allowance[_from][admin]);

balanceOf[_from] -= _value;
balanceOf[_to] += _value;

allowance[_from][msg.sender] -= _value;
allowance[_from][admin] -= _value;

emit Transfer(_from, _to, _value);

Expand Down
5 changes: 4 additions & 1 deletion migrations/2_DStockToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ module.exports = function(deployer) {
var tokenPrice = 1000000000000000;
return deployer.deploy(DStock, DStockToken.address, tokenPrice);
});
};
};


// issues while migrating and testing while increasing price count
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,17 @@
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"big-integer": "^1.6.48",
"big-number": "^2.0.0",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"ipfs-http-client": "^48.2.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"truffle": "^5.1.60",
"web-vitals": "^0.2.4"
"web-vitals": "^0.2.4",
"web3": "^1.3.3"
},
"scripts": {
"start": "react-scripts start",
Expand Down
144 changes: 137 additions & 7 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,141 @@
import {React,Component} from 'react';
import './App.css';
import NavigationTabs from "./components/navigation";
import DStock from './abis/DStock.json'
import Web3 from 'web3';

function App() {
return (
<div className="App">
<NavigationTabs />
</div>
);
const ipfsClient = require('ipfs-http-client')
const ipfs = ipfsClient({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' })

class App extends Component {


async componentWillMount() {
await this.loadWeb3()
await this.loadBlockchainData()
}

async loadWeb3() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum)
await window.ethereum.enable()
}
else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider)
}
else {
window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!')
}
}

async loadBlockchainData() {
const web3 = window.web3
const accounts = await web3.eth.getAccounts()
this.setState({ account: accounts[0] })
const networkId = await web3.eth.net.getId()
const networkData = DStock.networks[networkId]
if(networkData) {
const dstock = new web3.eth.Contract(DStock.abi, networkData.address)
this.setState({ dstock })
const assetcount = await dstock.methods.assetCount.call()
this.setState({ assetcount })
// for (var i = 0; i < assetcount; i++) {
// const asset = await dstock.methods.assets(i).call()
// this.setState({
// asset: [...this.state.asset, asset]
// })
// }

const myId = await dstock.methods.getId.call({ from: this.state.account })
let Person = await dstock.methods.getPerson.call({ from: this.state.account })
// const Person = await dstock.methods.getPerson.call({ from: this.state.account })
// const address = Person[0];
// const earning = Person[1];
// const tokenCount = Person[2];
// this.setState({address, earning ,tokenCount})
// console.log(address, earning ,tokenCount)
this.setState({ loading: false})
} else {
window.alert('Contract not deployed to detected network.')
}
console.log(this.state)
}

captureFile = event => {

event.preventDefault()
const file = event.target.files[0]
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)

reader.onloadend = () => {
this.setState({ buffer: Buffer(reader.result) })
console.log('buffer', this.state.buffer)
}
}

uploadAsset = (cost) => {
console.log("Submitting file to ipfs...")
ipfs.add(this.state.buffer, (error, result) => { //This isnt executed
console.log('Ipfs result', result)
if(error) {
console.log("Error")
console.error(error)
return
}
console.log("no error")
this.setState({ loading: true })
this.state.dstock.methods.uploadAsset(result[0].hash, cost).send({ from: this.state.account }).on('transactionHash', (hash) => {
this.setState({ loading: false })
})
})
}

buyAsset = (assetId) =>{
this.setState({ loading: true })
this.state.dstock.methods.buyAsset(assetId).send({ from: this.state.account}).on('transactionHash', (hash) => {
this.setState({ loading: false })
})
}

// showUploads = () =>{

// }
// showStats = () =>{

// }
constructor(props) {
super(props)
this.state = {
account: '',
tokenCount: 0,
earnings: 0,
address:'',
dstock: null,
asset: [],
buffer:[],
loading: true
}

this.uploadAsset = this.uploadAsset.bind(this)
this.captureFile = this.captureFile.bind(this)
this.buyAsset = this.buyAsset.bind(this)
}

render() {
return (
<div className="App">
{ this.state.loading
? <div id="loader" className="text-center mt-5"><p>Loading...</p></div>
: <NavigationTabs
account={this.state.account}
captureFile={this.captureFile}
uploadAsset={this.uploadAsset}
buyAsset={this.buyAsset} />
}
</div>
);
}
}
export default App;

export default App;
Loading

0 comments on commit 2b8418c

Please sign in to comment.