Skip to content
Draft
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
55 changes: 13 additions & 42 deletions js/onchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ import { dbIGAI, dbTo, dbRef, dbGetRef } from "./supabase.js";
import { NonceManager as O } from "@ethersproject/experimental";
import ethers from "ethers";

let n = null;
let nonceLock = Promise.resolve();

const { providers, Contract, Wallet } = ethers,
{ JsonRpcProvider } = providers,
w = new Wallet(PK, new JsonRpcProvider(pr)),
Expand Down Expand Up @@ -50,53 +47,27 @@ export async function getInfo(a) {
}
}

async function getNextNonce() {
await nonceLock;
let releaseLock;
nonceLock = new Promise((resolve) => {
releaseLock = resolve;
});
try {
if (n === null) {
n = await w.provider.getTransactionCount(w.address, "pending");
console.log("Fetched initial nonce:", n);
}
const nonceToUse = n;
n++;
return nonceToUse;
} finally {
releaseLock();
}
}

export async function processQueue() {
if (p) return;
p = true;
while (q.length > 0) {
const { d, ra, rt, aa } = q.shift();
try {
await b();
const uploadPromise = (async () => {
const cid = (
await c.uploadFile(new File([JSON.stringify(d)], ""))
).toString();
dbIGAI(cid, ra, rt);
})();
let txPromise = Promise.resolve();
try {
const nonce = await getNextNonce();
const tx = await r.deduct(ra, aa, { nonce });
await tx.wait(1);
} catch (err) {
n = await w.provider.getTransactionCount(w.address, "pending");
throw err;
}
await Promise.all([uploadPromise, txPromise]);
// Run upload and transaction in parallel
await Promise.all([
(async () => {
const cid = (
await c.uploadFile(new File([JSON.stringify(d)], ""))
).toString();
dbIGAI(cid, ra, rt);
})(),
(async () => {
const tx = await r.deduct(ra, aa);
await tx.wait(1);
})(),
]);
} catch (e) {
if (String(e).includes("Invalid nonce")) {
n = await w.provider.getTransactionCount(w.address, "pending");
console.warn("Nonce reset to", n);
}
console.error(new Date().toISOString(), "Retrying...", e);
q.push({ d, ra, rt, aa });
await new Promise((r) => setTimeout(r, 5000));
Expand Down