Skip to content

Commit

Permalink
Added upload transaction functionality
Browse files Browse the repository at this point in the history
- The user can now upload a transaction in a specific format and submit it to the connected net.
- A modal will then display the returned callback and allow the user to easily copy the ID.
  • Loading branch information
apratimshukla6 committed Sep 30, 2024
1 parent 829354a commit 486e2f6
Show file tree
Hide file tree
Showing 2 changed files with 225 additions and 95 deletions.
156 changes: 78 additions & 78 deletions public/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,95 +236,95 @@ chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
})();

return true; // Keep the message channel open for async sendResponse
} else if (request.action === 'submitTransaction') {
} else if (request.action === 'submitTransactionFromDashboard') {
(async function() {
const senderUrl = sender.tab ? sender.tab.url : sender.url || null;
console.log('Sender URL:', senderUrl);
const domain = getBaseDomain(senderUrl);
console.log('Domain:', domain);
// Retrieve the necessary data
const transactionData = request.transactionData;
const domain = request.domain;
const net = request.net;

// Validate transactionData
if (!transactionData || !transactionData.asset || !transactionData.recipientAddress || !transactionData.amount) {
sendResponse({ success: false, error: 'Invalid transaction data.' });
return;
}

// Retrieve the signer's keys and URL from storage
chrome.storage.local.get(['keys', 'connectedNets'], async function (result) {
const keys = result.keys || {};
const connectedNets = result.connectedNets || {};
console.log('ConnectedNets:', connectedNets);
const net = connectedNets[domain];
console.log('Net for domain:', domain, 'is', net);

if (keys[domain] && keys[domain][net]) {
const { publicKey, privateKey, url, exportedKey } = keys[domain][net];

try {
// Import the key material from JWK format
const keyMaterial = await crypto.subtle.importKey(
'jwk',
exportedKey,
{ name: 'AES-GCM' },
true,
['encrypt', 'decrypt']
);

const decryptedPublicKey = await decryptData(publicKey.ciphertext, publicKey.iv, keyMaterial);
const decryptedPrivateKey = await decryptData(privateKey.ciphertext, privateKey.iv, keyMaterial);
const decryptedUrl = await decryptData(url.ciphertext, url.iv, keyMaterial);

// Check if required fields are defined
if (!decryptedPublicKey || !decryptedPrivateKey || !request.recipient) {
console.error('Missing required fields for transaction submission');
sendResponse({ success: false, error: 'Missing required fields for transaction' });
return;
}
if (!connectedNets[domain] || connectedNets[domain] !== net) {
sendResponse({ success: false, error: 'Not connected to the specified net for this domain.' });
return;
}

// Prepare asset data as a JSON string
const assetData = JSON.stringify({
data: request.data || {}
});
if (!keys[domain] || !keys[domain][net]) {
sendResponse({ success: false, error: 'Keys not found for the specified domain and net.' });
return;
}

// Construct the GraphQL mutation
const mutation = `
mutation {
postTransaction(data: {
operation: "CREATE",
amount: ${parseInt(request.amount)},
signerPublicKey: "${escapeGraphQLString(decryptedPublicKey)}",
signerPrivateKey: "${escapeGraphQLString(decryptedPrivateKey)}",
recipientPublicKey: "${escapeGraphQLString(request.recipient)}",
asset: """${assetData}"""
}) {
id
}
const { publicKey, privateKey, url, exportedKey } = keys[domain][net];

try {
// Import the key material from JWK format
const keyMaterial = await crypto.subtle.importKey(
'jwk',
exportedKey,
{ name: 'AES-GCM',
},
true,
['encrypt', 'decrypt']
);

const decryptedPublicKey = await decryptData(publicKey.ciphertext, publicKey.iv, keyMaterial);
const decryptedPrivateKey = await decryptData(privateKey.ciphertext, privateKey.iv, keyMaterial);
const decryptedUrl = await decryptData(url.ciphertext, url.iv, keyMaterial);

// Prepare the asset data
const assetData = JSON.stringify(transactionData.asset);

// Construct the GraphQL mutation
const mutation = `
mutation {
postTransaction(data: {
operation: "CREATE",
amount: ${parseInt(transactionData.amount)},
signerPublicKey: "${escapeGraphQLString(decryptedPublicKey)}",
signerPrivateKey: "${escapeGraphQLString(decryptedPrivateKey)}",
recipientPublicKey: "${escapeGraphQLString(transactionData.recipientAddress)}",
asset: """${assetData}"""
}) {
id
}
`;

// Log the mutation for debugging
console.log('Mutation:', mutation);

const response = await fetch(decryptedUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: mutation }),
});

if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
`;

// Send the mutation
const response = await fetch(decryptedUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: mutation }),
});

const resultData = await response.json();
if (resultData.errors) {
console.error('GraphQL errors:', resultData.errors);
sendResponse({ success: false, errors: resultData.errors });
} else {
console.log('Transaction submitted successfully:', resultData.data);
sendResponse({ success: true, data: resultData.data });
}
} catch (error) {
console.error('Error submitting transaction:', error);
sendResponse({ success: false, error: error.message });
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
} else {
console.error('No keys found for domain:', domain, 'and net:', net);
console.log('Available keys:', keys);
sendResponse({ error: "No keys found for domain and net" });

const resultData = await response.json();
if (resultData.errors) {
console.error('GraphQL errors:', resultData.errors);
sendResponse({ success: false, error: 'GraphQL errors occurred.', errors: resultData.errors });
} else {
console.log('Transaction submitted successfully:', resultData.data);
sendResponse({ success: true, data: resultData.data });
}

} catch (error) {
console.error('Error submitting transaction:', error);
sendResponse({ success: false, error: error.message });
}
});
})();
Expand Down
Loading

0 comments on commit 486e2f6

Please sign in to comment.