Skip to content

Instantly share code, notes, and snippets.

@kay-is
Created November 22, 2023 10:53
Show Gist options
  • Save kay-is/3e7f6bdfd457931cca33a3612dacc0f1 to your computer and use it in GitHub Desktop.
Save kay-is/3e7f6bdfd457931cca33a3612dacc0f1 to your computer and use it in GitHub Desktop.
MEM Carbon Testnet With Upstash Redis
import { guidGenerator } from "./mem-utils.js"
import { MEM_TESTNET_URL } from "./constants.js"
import axios from "axios"
import { Redis } from "@upstash/redis"
const redisClient = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
})
export async function saveFunction(src, state) {
try {
const function_id = await guidGenerator()
const func = { src, state }
await redisClient
.pipeline()
.set(function_id, func)
.sadd("functions", function_id)
.exec()
return { function_id }
} catch (error) {
console.log(error)
return { function_id: undefined }
}
}
export async function writeFunction(function_id, input) {
try {
const functionExists = await redisClient.sismember("functions", function_id)
if (!functionExists) {
return { error: `${function_id} not deployed on testnet` }
}
const { src, state, exmContext } = await redisClient.get(function_id)
const body = {
contractType: 0,
initState: state,
input: input,
contractSrc: src,
exmContext: exmContext ?? null,
}
const tx = await axios.post(MEM_TESTNET_URL, body)
const newCntx = await updateExmCntx(function_id, tx.data.exmContext)
await redisClient.set(function_id, {
src: src,
state: JSON.stringify(tx.data.state),
exmContext: newCntx,
})
return tx.data
} catch (error) {
console.log(error)
return { state: "error" }
}
}
async function updateExmCntx(function_id, newCntx) {
try {
const func = await redisClient.get(function_id)
const oldCntx = JSON.parse(func?.exmContext)
for (const req in newCntx.requests) {
oldCntx.requests[req] = newCntx.requests[req]
}
for (const v in newCntx.kv) {
oldCntx.kv[v] = newCntx.kv[v]
}
return JSON.stringify(oldCntx)
} catch (error) {
console.log(error)
return JSON.stringify(newCntx)
}
}
export async function getFunction(function_id) {
try {
const functionExists = await redisClient.sismember("functions", function_id)
if (!functionExists) {
return { error: `${function_id} not deployed on testnet` }
}
return await redisClient.get(function_id)
} catch (error) {
console.log(error)
}
}
export async function getAllFunctions() {
try {
const function_ids = await redisClient.smembers("functions")
return await redisClient.mget(function_ids)
} catch (error) {
return []
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment