import { createHelia } from 'helia';
import { unixfs } from '@helia/unixfs';
import { ApiPromise, WsProvider, Keyring } from '@polkadot/api';
import { defaultOptions } from '@peaq-network/types';
import { decodeAddress, blake2AsHex } from '@polkadot/util-crypto';
import { u8aToU8a, u8aToHex, u8aConcat, hexToString} from "@polkadot/util";
const provider = new WsProvider(WSS_URL);
const api = await ApiPromise.create({ provider, ...defaultOptions });
// create node
const helia = await createHelia();
// create filesystem
const fs = unixfs(helia);
async function createAddHelia() {
// convert string to Uint8Array
const encoder = new TextEncoder();
const bytes = encoder.encode('Hello peaq data');
// adds bytes to node and receives a CID back (content identifier)
const cid = await fs.addBytes(bytes);
console.log('CID of the data added:', cid.toString());
helia.stop();
return cid;
}
async function peaqStorageAdd(item_type, cid){
const keyring = new Keyring({ type: 'sr25519' });
// Add Alice to our keyring with a hard-derivation path.
// Can add agung funded wallet here with your substrate wallet's mnemonic phrase (recommended).
const UserPair = keyring.addFromUri('//Alice');
await api.tx.peaqStorage.addItem(item_type, cid).signAndSend(UserPair);
return UserPair;
}
async function peaqStorageRetrieve(UserPair, item_type){
// generate storage key
const storageKeyByteArray = [];
const decodedAddress = decodeAddress(UserPair.address, false, 42);
storageKeyByteArray.push(decodedAddress);
const hashItemType = u8aToU8a(item_type);
storageKeyByteArray.push(hashItemType);
const key = u8aConcat(...storageKeyByteArray);
const storageKey = blake2AsHex(key, 256);
const val = await api.query.peaqStorage.itemStore(storageKey);
// convert u8a to hex to obtain data from peaq storage
var retrieved_cid = hexToString(u8aToHex(val));
return retrieved_cid
}
async function readHelia(returned_cid){
// decoder converts Uint8Array to strings
const decoder = new TextDecoder()
let stored_data = ''
for await (const data of fs.cat(returned_cid)) {
stored_data += decoder.decode(data, {
stream: true
})
}
console.log('Read file contents from data IPFS store:\n', stored_data);
}
async function main() {
const cid = await createAddHelia();
const item_type = 'user-data-1';
const UserPair = await peaqStorageAdd(item_type, cid);
await sleep(25000); // 25 second delay to guarantee it has been added
const returned_cid = await peaqStorageRetrieve(UserPair, item_type); // may have to wait until block has been appended before reading
await readHelia(returned_cid);
// disconnect to terminate the process
await api.disconnect();
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();