# Project export: TrustFile

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2024
- Tagline: Nearly 48,000 Canadian children and ten times as many in the US lack stable document access in foster care. TrustFile offers a blockchain-based solution for secure document storage.
- Devpost: https://devpost.com/software/trustfile
- GitHub: https://github.com/Matt711/TrustFile
- Demo: https://docs.google.com/presentation/d/1d0DE6LQQSvilpXDNuZuupJ1cHLfB-h06K011YSW1-r0/edit?usp=sharing
- Result: winner (Ava Labs / Avalanche: Best Consumer Use Case for Blockchain ($1.5k Cash))
- Team: 3 GitHub contributor(s) — ishika1202 (7 commits), Matthew Murray (6 commits), Dropio12 (3 commits)

## Devpost submission (written by the team)

### Inspiration

Our journey with TrustFile began with a deep-seated concern for the welfare of children in foster care systems. Upon learning about the staggering number of nearly 48,000 children in Canada and ten times more in the US facing instability in document access, we were deeply moved to take action. This ignited our inspiration to develop a solution that could alleviate their challenges. Throughout our journey, we gained invaluable insights into the complexities of document management within foster care systems. We learned about the profound impact that document loss can have on a child's life, affecting their ability to enroll in school, receive necessary medical care, secure employment, and establish their identity. Witnessing these challenges firsthand motivated us to explore innovative approaches to address this critical issue.

### What it does

TrustFile, a decentralized document storage application leveraging blockchain technology. TrustFile empowers users to securely upload and retrieve their documents, ensuring their accessibility and security. By utilizing blockchain's immutable and transparent nature, TrustFile mitigates the risk of document loss and provides foster children with a reliable solution to manage their essential records effectively. So that children have all their necessary documents once they are 18.

### How we built it

Our project, TrustFile, harnesses cutting-edge technologies to provide a secure and decentralized solution for document management. Leveraging the capabilities of the Avalanche Blockchain on the Fuji testnet, we implemented a Smart Contract that facilitates the creation and management of Non-Fungible Tokens (NFTs). The process begins with users uploading their documents to the platform, which triggers the creation of unique NFTs associated with each document. These NFTs are then transferred to the users' wallets, providing them with a secure and verifiable ownership mechanism. Behind the scenes, we utilize the IPFS (InterPlanetary File System) to store the documents securely. Each document uploaded by the user is stored on the IPFS file system, ensuring durability and accessibility while maintaining the decentralized nature of the platform. When a user needs to retrieve a document, they simply present the corresponding NFT associated with that document. Through the Smart Contract's functionality, the NFT is authenticated, allowing the user to access and retrieve their document from the IPFS file system. This seamless integration of blockchain technology, NFTs, and IPFS enables TrustFile to offer a robust and user-friendly solution for document management, empowering users with secure and decentralized access to their important records.

### Challenges we ran into

Our journey with TrustFile presented several challenges, especially considering it was our team's first foray into blockchain technology. One of the most significant hurdles we encountered revolved around the implementation of IPFS libraries. Navigating the intricacies of integrating IPFS into our project proved to be a formidable task. The complexity of the IPFS ecosystem, coupled with the novelty of blockchain development, posed challenges in understanding and effectively utilizing IPFS libraries within our application. We encountered issues with library compatibility, documentation discrepancies, and unfamiliar concepts inherent to decentralized file storage systems. As a result, the process of implementing IPFS functionality into TrustFile required extensive research, experimentation, and troubleshooting.

### Accomplishments we're proud of

Successful Integration of Blockchain Technology: As a team new to blockchain development, successfully integrating blockchain technology into TrustFile was a significant achievement. We overcame the steep learning curve associated with blockchain development and gained valuable insights into its potential applications. Creation of a Decentralized Document Storage Platform: Developing TrustFile as a decentralized document storage platform represents a significant accomplishment. We built a solution that leverages the benefits of blockchain and IPFS to provide users with secure, transparent, and accessible document management. Implementation of Non-Fungible Tokens (NFTs): Integrating NFTs into TrustFile to provide users with verifiable ownership of their documents was a notable accomplishment. By leveraging NFTs, we created a unique and secure mechanism for document authentication and retrieval. Successful Deployment on Avalanche Blockchain: Deploying TrustFile on the Avalanche Blockchain, specifically on the Fuji testnet, was a significant milestone. This achievement validated our ability to work with blockchain networks and showcased our proficiency in deploying decentralized applications. User-Centric Design and Functionality: Designing TrustFile with a user-centric approach and intuitive functionality was an accomplishment we're proud of. We prioritized user experience and usability throughout the development process, ensuring that TrustFile meets the needs of its users effectively.

### What we learned

Throughout the development journey, we encountered various technical challenges, from blockchain integration to IPFS implementation. Successfully overcoming these challenges demonstrated our team's resilience, problem-solving skills, and commitment to delivering a high-quality product. By developing TrustFile, we contributed to addressing real-world challenges faced by children in foster care systems. This social impact aspect of our project is a source of pride for our team, as it reflects our commitment to leveraging technology for positive change.

### What's next

Our journey with TrustFile has been just the beginning of our mission to revolutionize document management and make a positive impact in the world. Moving forward, we are committed to further developing and expanding TrustFile into a full-fledged decentralized application (DApp) that can address novel causes and serve a broader user base.

## README (from the GitHub repository)

No README available.

## Detected evidence (automated analysis)

Indexed codebase: 16 recognized source files, 27 KB.
- CSS (language) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- React (technology) — detected in the code
- Solidity (language) — detected in the code
- TypeScript (language) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (26 of 26)

```
.npmignore
README.md
trustfile-app/.env.example
trustfile-app/.github/ISSUE_TEMPLATE/bug_report.md
trustfile-app/.github/ISSUE_TEMPLATE/feature_request.md
trustfile-app/.gitignore
trustfile-app/LICENSE.md
trustfile-app/package.json
trustfile-app/public/index.html
trustfile-app/public/manifest.json
trustfile-app/public/robots.txt
trustfile-app/README.md
trustfile-app/src/App.js
trustfile-app/src/index.js
trustfile-app/src/reportWebVitals.js
trustfile-app/src/setupTests.js
trustfile-app/src/styles/globals.css
trustfile-app/src/styles/Home.css
trustfile-app/src/YourContractABI.json
trustfile/.gitignore
trustfile/contractABI.json
trustfile/contracts/doc.sol
trustfile/hardhat.config.js
trustfile/package.json
trustfile/README.md
trustfile/web3.js
```

### Dependencies

- trustfile-app/package.json: @testing-library/jest-dom@^5.16.5, @testing-library/react@^13.4.0, @testing-library/user-event@^14.4.3, @thirdweb-dev/react@^4, @thirdweb-dev/sdk@^4, assert@^2.0.0, browserify-zlib@latest, ethers@^5, http@npm:http-browserify, http-browserify@latest, https@npm:https-browserify, https-browserify@latest, ipfs-http-client@^60.0.1, react@^18.2, react-dom@^18.2, react-scripts@^5.0.1, stream@^0.0.2, url@latest, web-vitals@^3.1.0, zlib@npm:browserify-zlib
- trustfile/package.json: @matterlabs/hardhat-zksync-solc@^0.3.17, @thirdweb-dev/contracts@^3.8.0, hardhat@^2.13.0, zksync-web3@^0.14.3

### Recent commits (newest first)

- Update doc.sol
- Merge branch 'main' of github.com:Matt711/TrustFile
- Instantiate the ipfs-http-client
- Add buttons and field for tokenID
- Update doc.sol
- Update doc.sol
- Update doc.sol
- Create contractABI.json
- Update web3.js
- Create web3.js
- Addd front end structure
- Update doc.sol
- Update doc.sol
- Create doc.sol
- Add project structure
- Add readme

## Key source files (fetched from GitHub, selected and truncated for size)

### trustfile-app/LICENSE.md

```markdown
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1.  Definitions.

    "License" shall mean the terms and conditions for use, reproduction,
    and distribution as defined by Sections 1 through 9 of this document.

    "Licensor" shall mean the copyright owner or entity authorized by
    the copyright owner that is granting the License.

    "Legal Entity" shall mean the union of the acting entity and all
    other entities that control, are controlled by, or are under common
    control with that entity. For the purposes of this definition,
    "control" means (i) the power, direct or indirect, to cause the
    direction or management of such entity, whether by contract or
    otherwise, or (ii) ownership of fifty percent (50%) or more of the
    outstanding shares, or (iii) beneficial ownership of such entity.

    "You" (or "Your") shall mean an individual or Legal Entity
    exercising permissions granted by this License.

    "Source" form shall mean the preferred form for making modifications,
    including but not limited to software source code, documentation
    source, and configuration files.

    "Object" form shall mean any form resulting from mechanical
    transformation or translation of a Source form, including but
    not limited to compiled object code, generated documentation,
    and conversions to other media types.

    "Work" shall mean the work of authorship, whether in Source or
    Object form, made available under the License, as indicated by a
    copyright notice that is included in or attached to the work
    (an example is provided in the Appendix below).

    "Derivative Works" shall mean any work, whether in Source or Object
    form, that is based on (or derived from) the Work and for which the
    editorial revisions, annotations, elaborations, or other modifications
    represent, as a whole, an original work of authorship. For the purposes
    of this License, Derivative Works shall not include works that remain
    separable from, or merely link (or bind by name) to the interfaces of,
    the Work and Derivative Works thereof.

    "Contribution" shall mean any work of authorship, including
    the original version of the Work and any modifications or additions
    to that Work or Derivative Works thereof, that is intentionally
    submitted to Licensor for inclusion in the Work by the copyright owner
    or by an individual or Legal Entity authorized to submit on behalf of
    the copyright owner. For the purposes of this definition, "submitted"
    means any form of electronic, verbal, or written communication sent
    to the Licensor or its representatives, including but not limited to
    communication on electronic mailing lists, source code control systems,
    and issue tracking systems that are managed by, or on behalf of, the
    L
[truncated — 7942 more characters]
```

### trustfile-app/.github/ISSUE_TEMPLATE/feature_request.md

```markdown
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.

```

### trustfile/package.json

```
{
  "name": "hardhat-javascript-starter",
  "scripts": {
    "build": "npx thirdweb@latest detect",
    "deploy": "npx thirdweb@latest deploy",
    "release": "npx thirdweb@latest release"
  },
  "devDependencies": {
    "@matterlabs/hardhat-zksync-solc": "^0.3.17",
    "hardhat": "^2.13.0"
  },
  "dependencies": {
    "@thirdweb-dev/contracts": "^3.8.0",
    "zksync-web3": "^0.14.3"
  }
}

```

### trustfile-app/package.json

```
{
  "name": "trustfile-app",
  "homepage": ".",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^14.4.3",
    "@thirdweb-dev/react": "^4",
    "@thirdweb-dev/sdk": "^4",
    "assert": "^2.0.0",
    "browserify-zlib": "latest",
    "ethers": "^5",
    "http": "npm:http-browserify",
    "http-browserify": "latest",
    "https": "npm:https-browserify",
    "https-browserify": "latest",
    "ipfs-http-client": "^60.0.1",
    "react": "^18.2",
    "react-dom": "^18.2",
    "react-scripts": "^5.0.1",
    "stream": "^0.0.2",
    "url": "latest",
    "web-vitals": "^3.1.0",
    "zlib": "npm:browserify-zlib"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "deploy": "yarn build && npx thirdweb@latest upload build"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

```

### trustfile-app/src/index.js

```javascript
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { ThirdwebProvider } from "@thirdweb-dev/react";
import "./styles/globals.css";

// This is the chain your dApp will work on.
// Change this to the chain your app is built for.
// You can also import additional chains from `@thirdweb-dev/chains` and pass them directly.
const activeChain = "ethereum";

const container = document.getElementById("root");
const root = createRoot(container);
root.render(
  <React.StrictMode>
    <ThirdwebProvider
      activeChain={activeChain}
      clientId={process.env.REACT_APP_TEMPLATE_CLIENT_ID}
    >
      <App />
    </ThirdwebProvider>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

```

### trustfile-app/src/App.js

```javascript
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import YourContractABI from './YourContractABI.json'; // Import your smart contract ABI
const contractAddress = '0x8ccb73933d257Bb687DFE544DC43e7F4c12bF0aE'; // Replace with your contract address

function App() {
  const [web3, setWeb3] = useState(null);

  useEffect(() => {
    const initWeb3 = async () => {
      if (window.ethereum) {
        const web3Instance = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          setWeb3(web3Instance);
        } catch (error) {
          console.error(error);
        }
      } else if (window.web3) {
        // Legacy dapp browsers
        const web3Instance = new Web3(window.web3.currentProvider);
        setWeb3(web3Instance);
      } else {
        // Fallback to Infura provider
        const infuraEndpoint = 'https://avalanche-fuji.infura.io/v3/5c6647137bbc40dd9b7d04aa03c7f6c3';
        const web3Instance = new Web3(new Web3.providers.HttpProvider(infuraEndpoint));
        setWeb3(web3Instance);
      }
    };    
    initWeb3();
  }, []);

  const handleFileChange = async (event) => {
    if (!web3) {
      console.error('Web3 not initialized');
      return;
    }
    try {
      const file = event.target.files[0];
      const accounts = await web3.eth.getAccounts();
      if (accounts.length === 0) {
        console.error('No accounts found. Make sure MetaMask is installed and unlocked.');
        return;
      }
      const contract = new web3.eth.Contract(YourContractABI, contractAddress);
      const from = accounts[0];
      // Accessing the file name
      const fileName = file ? file.name : '';
      // Send the file name or the entire file to your contract method
      const result = await contract.methods.mintNFT("QmTBNvKjguUDa4jDwCAEo3Y4GZin3FrjibyFCBuBFZDw9V").send({ from });
      console.log('Upload successful!', result);
    } catch (error) {
      console.error('Error uploading:', error);
    }
  };

  const download = async () => {
    if (!web3) {
      console.error('Web3 not initialized');
      return;
    }
    try {
      const accounts = await web3.eth.getAccounts();
      const contract = new web3.eth.Contract(YourContractABI, contractAddress);
      await contract.methods.download().send({ from: accounts[0] });
      console.log('Download successful!');
    } catch (error) {
      console.error('Error downloading:', error);
    }
  };

  const handleFormSubmit = async (event) => {
    event.preventDefault();
    const tokenId = event.target.tokenId.value;
    await download(tokenId);
  };

  return (
    <div>
      <h1>Trust File</h1>
      {/* Visual hide but still clickable */}
      <input
        type="file"
        style={{ position: 'absolute', top: '-9999px' }}
        onChange={handleFileChange}
      />
      <button onClick={() => document.querySelector('input[type=file]').click()}>Upload</button>
      <button onClick={download}>Download</button>
      <form onSubmit={handleFormSubmit}>
        <label>
          Token ID:
          <input type="text" name="tokenId" />
        </label>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;

```

### trustfile/hardhat.config.js

```javascript
require("@matterlabs/hardhat-zksync-solc");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  zksolc: {
    version: "1.3.9",
    compilerSource: "binary",
    settings: {
      optimizer: {
        enabled: true,
      },
    },
  },
  networks: {
    zksync_testnet: {
      url: "https://zksync2-testnet.zksync.dev",
      ethNetwork: "goerli",
      chainId: 280,
      zksync: true,
    },
    zksync_mainnet: {
      url: "https://zksync2-mainnet.zksync.io/",
      ethNetwork: "mainnet",
      chainId: 324,
      zksync: true,
    },
  },
  paths: {
    artifacts: "./artifacts-zk",
    cache: "./cache-zk",
    sources: "./contracts",
    tests: "./test",
  },
  solidity: {
    version: "0.8.17",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
    },
  },
};

```

### trustfile/web3.js

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


const web3 = new Web3('https://avalanche-fuji.infura.io/v3/5c6647137bbc40dd9b7d04aa03c7f6c3'); 


const contractABI = JSON.parse(fs.readFileSync('YourContractABI.json', 'utf8')); 


const contractAddress = '0x8ccb73933d257Bb687DFE544DC43e7F4c12bF0aE'; 
const contract = new web3.eth.Contract(contractABI, contractAddress);


async function mintNFTAndUploadImage(imagePath) {
    try {
        
        const ipfsHash = await uploadImageToIPFS(imagePath);

      
        const accounts = await web3.eth.getAccounts();
        const result = await contract.methods.mintAndUploadDocument(ipfsHash).send({ from: accounts[0] });

        console.log('NFT minted. Transaction hash:', result.transactionHash);
    } catch (error) {
        console.error('Error minting NFT and uploading image:', error);
    }
}

```

### trustfile-app/src/setupTests.js

```javascript
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

```

### trustfile-app/src/reportWebVitals.js

```javascript
const reportWebVitals = onPerfEntry => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;

```

[5 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]