Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

move save_to_blockchain to backend api #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/api/post-journal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Arweave from 'arweave/node';

const arweave = Arweave.init({ host: 'arweave.net', port: 443, protocol: 'https' });

// grab the wallet from secrets/env
const wallet = JSON.parse(process.env.WALLET_JSON);

export async function saveToBlockchain(post) {

let transaction = await arweave.createTransaction({
data: JSON.stringify(post),
}, wallet);

transaction.addTag('App-Name', 'QuarantineJournal')
transaction.addTag('App-Version', '1.0.0')
transaction.addTag('TestData', 'false')
transaction.addTag('production', 'true')
transaction.addTag('deployed', 'true')
transaction.addTag('ISO-Time', post.isoDateTime)
transaction.addTag('loc-lat', post.locLat)
transaction.addTag('loc-long', post.locLong)

await arweave.transactions.sign(transaction, wallet);
const response = await arweave.transactions.post(transaction);

if (response.status >= 200 && response.status < 300) {
return { transactionId: transaction.id }
}
console.error(`Error posting to Arweave, ${resp.status}`);
throw new Error(`Error posting ${resp.status}`);
}
85 changes: 26 additions & 59 deletions src/routes/new.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
window.verifyUser = null;
})

function addPost(){
async function addPost(){
console.log("submit clicked");

var dt = DateTime.local();
Expand All @@ -57,12 +57,33 @@
socialLink: socialLink,
description: description,
currDate: currDate,
location: place.formatted_address
location: place.formatted_address,
isoDateTime: isoDateTime,
locLat: place.geometry.location.lat(),
locLong: place.geometry.location.lng()
};
console.log(newPost);

saveToBlockchain(newPost);
console.log(newPost);
localStorage['post'] = JSON.stringify(post);
console.log("Saving post to cache: ", JSON.stringify(post));

const resp = await fetch('/api/save_to_blockchain',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
);

if (resp.status === 200) {
const result = await resp.body.json();
localStorage['transactionId'] = result.transactionId;
navigateAndSave();
} else {
alert(`There was a problem saving :( ${resp.status}`)
}

// ??
return 1;
title = '';
description = '';
Expand All @@ -71,61 +92,7 @@
location = '';
}

function saveToBlockchain(post) {
const arweave = Arweave.init({ host: 'arweave.net', port: 443, protocol: 'https' });
console.log(arweave);

let key = privateKey;

(async () => {
var unixTime = Math.round((new Date()).getTime() / 1000)

arweave.wallets.jwkToAddress(key).then((address) => {
arweave.wallets.getBalance(address).then((balance) => {
let winston = balance;
console.log(winston);
});
});
localStorage['post'] = JSON.stringify(post);
console.log("Saving post to cache: ", JSON.stringify(post));

let transaction = await arweave.createTransaction({
data: JSON.stringify(post),
}, key);

transaction.addTag('App-Name', 'QuarantineJournal')
transaction.addTag('App-Version', '1.0.0')
transaction.addTag('TestData', 'false')
transaction.addTag('production', 'true')
transaction.addTag('deployed', 'true')
transaction.addTag('ISO-Time', isoDateTime)
transaction.addTag('loc-lat', place.geometry.location.lat())
transaction.addTag('loc-long', place.geometry.location.lng())

await arweave.transactions.sign(transaction, key);
const response = await arweave.transactions.post(transaction);

console.log("Status: ", response.status);

localStorage['transactionId'] = transaction.id;

console.log("TransactionID: ", transaction.id);

await arweave.transactions.post(transaction);
if (response.status === 200) {
navigateAndSave();
}
if (response.status == 400) {
alert("400: The transaction is invalid, couldn't be verified, or the wallet does not have suffucuent funds.")
}
if (response.status == 429) {
alert("429: The request has exceeded the clients rate limit quota.")
}
if (response.status == 503) {
alert("503: The nodes was unable to verify the transaction.")
}
})()
}

</script>

<style>
Expand Down
15 changes: 15 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,33 @@ import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';
import { json } from 'body-parser';
import { saveToBlockchain } from './api/post-journal';

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

const app =
polka()
.use(json)
.get('/api/test', (req, res) => {
res.end('Hello World');
})
.get('/api/test_json', (req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ hello: 'world' }));
})
.post('/api/save_to_blockchain', async(req, res) => {
const post = req.body;
try {
const result = await saveToBlockchain(post);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (e) {
res.writeHead(500);
res.end('Server Error');
}
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
Expand Down