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

feat(oracle): accept invitation (wip) #11

Open
wants to merge 19 commits into
base: main
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
11 changes: 10 additions & 1 deletion oracle-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,23 @@
"node": ">=18.14.x"
},
"dependencies": {
"@agoric/assert": "^0.6.1-u11wf.0",
"@agoric/casting": "^0.4.3-u12.0",
"@agoric/cosmic-proto": "^0.3.0",
"@agoric/internal": "^0.4.0-u12.0",
"@agoric/notifier": "^0.6.3-u12.0",
"@agoric/smart-wallet": "^0.5.4-u12.0",
"@agoric/vats": "^0.15.2-u12.0",
"@cosmjs/crypto": "^0.31.3",
"@cosmjs/encoding": "^0.31.3",
"@cosmjs/math": "^0.31.3",
"@cosmjs/proto-signing": "^0.31.3",
"@cosmjs/stargate": "^0.31.3",
"@endo/init": "^0.5.57",
"@endo/marshal": "^0.8.8",
"@fastify/cookie": "^9.1.0",
"@fastify/oauth2": "^7.5.0",
"@octokit/auth-app": "^6.0.1",
"agoric": "^0.21.2-u12.0",
"dotenv": "^16.3.1",
"fastify": "^4.21.0",
"fastify-plugin": "^4.5.1",
Expand Down
14 changes: 13 additions & 1 deletion oracle-server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,29 @@ import { githubOAuthPlugin } from "./plugins/github.js";
import { health } from "./routes/health.js";
import { auth } from "./routes/auth.js";
import { job } from "./routes/job.js";
import { admin } from "./routes/admin.js";
import { makeOracleService, OracleService } from "./lib/oracleService.js";

dotenv.config();
declare module "fastify" {
interface FastifyInstance {
oracleService: OracleService;
}
}

export const makeApp = (opts: FastifyServerOptions = {}) => {
export const makeApp = async (opts: FastifyServerOptions = {}) => {
const app = fastify(opts);

app.register(githubOAuthPlugin);

const oracleService = await makeOracleService();
app.decorate("oracleService", oracleService);

app.register(health);
app.register(auth);
app.register(job);
// not secure, testing only!
app.register(admin);

return app;
};
2 changes: 2 additions & 0 deletions oracle-server/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ export interface ProcessEnv {
GITHUB_CLIENT_SECRET: string;
GITHUB_INSTALLATION_ID: string;
GITHUB_PEM_PATH: string;
AGORIC_NET: "local" | "devnet" | "emerynet" | "main";
WALLET_MNEMONIC: string;
}
58 changes: 58 additions & 0 deletions oracle-server/src/lib/chainInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Decimal } from "@cosmjs/math";
import { stringToPath } from "@cosmjs/crypto";

/** @typedef {import('@keplr-wallet/types').Bech32Config} Bech32Config */
/** @typedef {import('@keplr-wallet/types').FeeCurrency} FeeCurrency */

/** @type {FeeCurrency} */
export const stakeCurrency = {
coinDenom: "BLD",
coinMinimalDenom: "ubld",
coinDecimals: 6,
coinGeckoId: undefined,
gasPriceStep: {
low: 0,
average: 0,
high: 0,
},
};

/** @type {FeeCurrency} */
export const stableCurrency = {
coinDenom: "IST",
coinMinimalDenom: "uist",
coinDecimals: 6,
coinGeckoId: undefined,
gasPriceStep: {
low: 0,
average: 0,
high: 0,
},
};

/** @type {Bech32Config} */
export const bech32Config = {
bech32PrefixAccAddr: "agoric",
bech32PrefixAccPub: "agoricpub",
bech32PrefixValAddr: "agoricvaloper",
bech32PrefixValPub: "agoricvaloperpub",
bech32PrefixConsAddr: "agoricvalcons",
bech32PrefixConsPub: "agoricvalconspub",
};

export const Agoric = {
Bech32MainPrefix: "agoric",
CoinType: 564,
proto: {
swingset: {
MsgWalletSpendAction: {
typeUrl: "/agoric.swingset.MsgWalletSpendAction",
},
},
},
fee: { amount: [], gas: "50000000" }, // arbitrary fee...
gasPrice: { denom: "uist", amount: Decimal.fromUserInput("50000000", 0) },
};

export const hdPath = (coinType = 118, account = 0) =>
stringToPath(`m/44'/${coinType}'/${account}'/0/0`);
38 changes: 38 additions & 0 deletions oracle-server/src/lib/networkConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { NonNullish } from "@agoric/assert";
import { boardSlottingMarshaller } from "@agoric/vats/tools/board-utils.js";

export { boardSlottingMarshaller };

export const networkConfigUrl = (agoricNetSubdomain: string): string =>
`https://${agoricNetSubdomain}.agoric.net/network-config`;
export const rpcUrl = (agoricNetSubdomain: string): string =>
`https://${agoricNetSubdomain}.rpc.agoric.net:443`;

export type MinimalNetworkConfig = {
rpcAddrs: string[];
chainName: string;
};

const fromAgoricNet = (str: string): Promise<MinimalNetworkConfig> => {
const [netName, chainName] = str.split(",");
if (chainName) {
return Promise.resolve({ chainName, rpcAddrs: [rpcUrl(netName)] });
}
return fetch(networkConfigUrl(netName)).then((res) => res.json());
};

export const getNetworkConfig = async (
env: typeof process.env,
): Promise<MinimalNetworkConfig> => {
if (!("AGORIC_NET" in env) || env.AGORIC_NET === "local") {
return { rpcAddrs: ["http://0.0.0.0:26657"], chainName: "agoriclocal" };
}

return fromAgoricNet(NonNullish(env.AGORIC_NET)).catch((err) => {
throw Error(
`cannot get network config (${env.AGORIC_NET || "local"}): ${
err.message
}`,
);
});
};
118 changes: 118 additions & 0 deletions oracle-server/src/lib/oracleService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { AgoricChainStoragePathKind as Kind } from "./ui-kit/types.js";
import { getNetworkConfig } from "./networkConfig.js";
import {
makeAgoricChainStorageWatcher,
ChainStorageWatcher,
} from "./ui-kit/chainStorageWatcher.js";
import { makeAgoricWalletConnection } from "./ui-kit/walletConnection.js";
import { getEnvVar } from "../utils/getEnvVar.js";

const getNetConfig = async () => {
const networkConfig = await getNetworkConfig(process.env);
const { chainName, rpcAddrs } = networkConfig;
return {
chainName,
rpcUrl: rpcAddrs[0],
};
};

export type JobReport = {
deliverDepositAddr: string;
issueURL: string;
jobID: bigint;
prURL: string;
};

export type OracleService = {
walletConnection: Awaited<ReturnType<typeof makeAgoricWalletConnection>>;
watcher: ChainStorageWatcher;
acceptOracleOffer: () => Promise<void>;
sendJobReport: (jobReport: JobReport) => Promise<void>;
};

let watcher: ChainStorageWatcher;
let walletConnection: Awaited<ReturnType<typeof makeAgoricWalletConnection>>;
let oracleService: OracleService;
let acceptId: string; // keeps track of last acceptId. // todo, persist better

export const makeOracleService = async () => {
if (oracleService) return oracleService;
const { rpcUrl, chainName } = await getNetConfig();
watcher = makeAgoricChainStorageWatcher(rpcUrl, chainName, console.error);
const mnemonic = getEnvVar("WALLET_MNEMONIC");
walletConnection = await makeAgoricWalletConnection(
watcher,
rpcUrl,
mnemonic,
);

const instance = await watcher
.queryOnce([Kind.Data, "published.agoricNames.instance"])
.then((x) => Object.fromEntries(x as [string, unknown][])["GiMiX"])
.catch(console.error);

const acceptOracleOffer = async () => {
console.log("instance", instance);
if (!instance) throw new Error("cannot find contract instance");
return walletConnection?.makeOffer(
{
source: "purse",
instance: instance,
description: "gimix oracle invitation",
},
{},
undefined,
(update: { status: string; data?: unknown }) => {
if (update.status === "error") {
console.log(`Offer error: ${update.data}`);
}
if (update.status === "accepted") {
console.log("Offer accepted", update);
/// XXX TODO, save acceptId
acceptId = update.data as string;
console.log("acceptId", acceptId);
}
if (update.status === "refunded") {
console.log("Offer rejected", update);
}
},
);
};

const sendJobReport = async (jobReport: JobReport) => {
if (!instance) throw new Error("cannot find contract instance");
if (!acceptId) throw new Error("cannot found oracle acceptId");
const { deliverDepositAddr, issueURL, jobID, prURL } = jobReport;
return walletConnection?.makeOffer(
{
source: "continuing",
previousOffer: acceptId,
invitationMakerName: "JobReport",
instance: instance,
invitationArgs: [{ deliverDepositAddr, issueURL, jobID, prURL }],
},
{},
undefined,
(update: { status: string; data?: unknown }) => {
if (update.status === "error") {
console.log(`Offer error: ${update.data}`);
}
if (update.status === "accepted") {
console.log("Offer accepted");
}
if (update.status === "refunded") {
console.log("Offer rejected");
}
},
);
};

oracleService = {
walletConnection,
watcher,
acceptOracleOffer,
sendJobReport,
};

return oracleService;
};
1 change: 0 additions & 1 deletion oracle-server/src/lib/stargate.ts

This file was deleted.

4 changes: 4 additions & 0 deletions oracle-server/src/lib/store.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
/**
* store for gh refresh tokens
*/

import type { Token } from "@fastify/oauth2";

type MemoryStore = Map<string, Token>;
Expand Down
100 changes: 100 additions & 0 deletions oracle-server/src/lib/ui-kit/batchQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { FromCapData } from "@endo/marshal";
import { AgoricChainStoragePathKind } from "./types.js";

export const pathToKey = (path: [AgoricChainStoragePathKind, string]) =>
path.join(".");

export const keyToPath = (key: string) => {
const parts = key.split(".");
return [parts[0], parts.slice(1).join(".")] as [
AgoricChainStoragePathKind,
string
];
};

export const batchVstorageQuery = (
node: string,
unmarshal: FromCapData<string>,
paths: [AgoricChainStoragePathKind, string][]
) => {
const options = {
method: "POST",
body: JSON.stringify(
paths.map((path, index) => ({
jsonrpc: "2.0",
id: index,
method: "abci_query",
params: { path: `/custom/vstorage/${path[0]}/${path[1]}` },
}))
),
};

return fetch(node, options)
.then((res) => res.json())
.then((res) =>
Object.fromEntries(
(Array.isArray(res) ? res : [res]).map((entry) => {
const { id: index } = entry;
if (entry.result.response.code) {
const { code, codespace, log: message } = entry.result.response;
return [
pathToKey(paths[index]),
{ error: { code, codespace, message } },
];
}

if (!entry.result.response.value) {
return [
pathToKey(paths[index]),
{
error: {
message: `Cannot parse value of response for path [${
paths[index]
}]: ${JSON.stringify(entry)}`,
},
},
];
}

const data = JSON.parse(
Buffer.from(entry.result.response.value, "base64").toString(
"binary",
),
);

if (paths[index][0] === AgoricChainStoragePathKind.Children) {
return [
pathToKey(paths[index]),
{ value: data.children, blockHeight: undefined },
];
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parseIfJSON = (d: any) => {
try {
return JSON.parse(d);
} catch {
return d;
}
};
const value = parseIfJSON(data.value);

const latestValue = Object.hasOwn(value, "values")
? parseIfJSON(value.values[value.values.length - 1])
: value;

const unserialized = Object.hasOwn(latestValue, "slots")
? unmarshal(latestValue)
: latestValue;

return [
pathToKey(paths[index]),
{
blockHeight: value.blockHeight,
value: unserialized,
},
];
})
)
);
};
Loading