Skip to content

Commit

Permalink
Merge pull request #204 from SpaceTurtle-Dao/fix/state
Browse files Browse the repository at this point in the history
Fix/state
  • Loading branch information
ALLiDoizCode authored Feb 15, 2025
2 parents 93ec742 + b2a11c6 commit 45c597a
Show file tree
Hide file tree
Showing 35 changed files with 835 additions and 843 deletions.
115 changes: 115 additions & 0 deletions buyer.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@

-- Name: Ore Seller

local json = require("json")
local ao = require("ao")

Constants = Constants or {}

Constants.Name = "Ore Seller"

Constants.GameplayProcess = "ElHCsTvRsN7_5Bpy1d3dC4kaVtAXMWiCMVz46H6sP3k"

Constants.TARGET_WORLD_PID = "_9QcH-Ma0LRvYInsa36d8zEkMRB9tfoAyEaLHmlUw3U"

Constants.ARToken = "xU9zFkq3X2ZQ6olwNVvr1vUWIjc3kXTWr7xKQD6dh10"

Constants.BazarUCM = "U3TjJAZWJjlWBB4KAXSHKzuky81jtyh0zqH8rUL4Wd0"

Constants.OrePrice = 100000000000

Constants.OrderMessage = "Create-Order"

Constants.SwapToken = "eLAgDHhcthcmjeaywlqkKTo8oPLZOc3YTQdU5ENJjKY"

-- Schema
function BuyOreSchemaTags()
return [[
{
"type": "object",
"required": [
"Action",
"Target",
"Recipient",
"Quantity",
"X-Order-Action",
"X-Swap-Token"
],
"properties": {
"Action": {
"type": "string",
"const": "Transfer"
},
"Target": {
"type": "string",
"const": "]] .. Constants.ARToken .. [["
},
"Recipient": {
"type": "string",
"const": "]] .. Constants.BazarUCM .. [["
},
"Quantity": {
"type": "number",
"const": ]] .. (Constants.OrePrice) .. [[,
},
"X-Order-Action": {
"type": "string",
"const": "]] .. Constants.OrderMessage .. [["
},
"X-Swap-Token": {
"type": "string",
"const": "]] .. Constants.SwapToken .. [["
}
}
}
]]
end

function SchemaExternalHasProfile(profileId)
return {
BuyOre = {
Target = profileId, -- Can be nil? In that case it must be supplied externally
Title = "Purchase Strange Ore",
Description =
"By clicking submit you are calling your Profile process to purchase Strange Ore for 0.1 AR on Bazar.",
Schema = {
Tags = json.decode(BuyOreSchemaTags()),
-- Data
-- Result?
},
},
}
end

Handlers.add(
'Profile-Response',
Handlers.utils.hasMatchingTag("Action", "Profile-Response"),
function(msg)
print("profile response")
local profileId = msg.Tags.Profile
local userId = msg.Tags.UserId
print("profile: " .. profileId .. "user: " .. userId)

ao.send({
Target = userId,
Tags = { Type = 'SchemaExternal' },
Data = json.encode(SchemaExternalHasProfile(profileId))
})
end
)

Handlers.add(
'SchemaExternal',
Handlers.utils.hasMatchingTag('Action', 'SchemaExternal'),
function(msg)
print('SchemaExternal')
ao.send({
Target = Constants.GameplayProcess,
Tags = {
Action = 'Profile',
UserId = msg.From,
},
})
end
)

12 changes: 0 additions & 12 deletions src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import Profile from "$lib/components/views/profile/Profile.svelte";
import IndividualPost from "$lib/components/posts/IndividualPost.svelte";
import MessagesPage from "$lib/components/Messages/MessagesPage.svelte";
import { followListStore } from "$lib/stores/follow-list.store";
import MobileTopView from "$lib/components/views/main/MobileTopView.svelte";
import MobileBottomNavBar from "$lib/components/views/main/MobileBottomNavBar.svelte";
Expand Down Expand Up @@ -78,17 +77,6 @@
}
}
});
currentUser.subscribe((user) => {
if (user && !isFollowListAlreadyFetched) {
followListStore.sync();
isFollowListAlreadyFetched = true;
}
});
followListStore.subscribe((followlistset) => {
console.log("follow list changed", Array.from(followlistset));
});
</script>

{#if isLoading}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/ao/process.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
// @ts-ignore
export const read = async (processId, tags) => {
console.log("reading data")
//console.log("reading data")
// The only 2 mandatory parameters here are process and signer
// connect to the extension
// @ts-ignore
Expand All @@ -63,7 +63,7 @@
// Tags that the process will use as input.
tags: tags,
});
console.log(result)
//console.log(result)
if (result.Messages) {
let message = result.Messages.pop();
return message;
Expand Down
87 changes: 20 additions & 67 deletions src/lib/ao/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { FetchEvents } from "$lib/ao/messegeFactory.svelte";
import { HUB_ID } from "$lib/constants";
import type { Tag } from "$lib/models/Tag";
import type { Profile } from "$lib/models/Profile";
import type { profile } from "console";

export const event = async (tags: Array<Tag>) => {
const actionTag: Tag = {
Expand All @@ -30,23 +31,18 @@ export const fetchEvents = async (filters: string): Promise<any[]> => {
let message = FetchEvents(filters);
let result = await read(HUB_ID(), message);
if (result) {
//console.log(result);
let json = JSON.parse(result.Data);
//console.log("***Filters***")
//console.log(JSON.parse(filters));
//console.log("***Got Events***")
//console.log(json);
events = json;
}
} catch (e) {
console.log(e);
throw e;
//throw e;
}
return events;
};

export const fetchProfile = async (address: string): Promise<Profile> => {
console.log("Address", address);
//console.log("Address", address);
const filter = JSON.stringify([
{
kinds: ["0"],
Expand All @@ -56,7 +52,7 @@ export const fetchProfile = async (address: string): Promise<Profile> => {
]);

let messages = await fetchEvents(filter);
console.log("Messages from App", messages);
//console.log("Messages from App", messages);

try {
// messages[0] give the latest profile change of this address and it return that
Expand All @@ -66,61 +62,17 @@ export const fetchProfile = async (address: string): Promise<Profile> => {
profile.address = message.From;
profile.created_at = messages[0].Timestamp;
profile.updated_at = message.Timestamp;
console.log("Profile from App", profile);
//console.log("Profile from App", profile);
return profile;
} catch (e) {
console.error(e);
throw e;
}
};

export const fetchProfiles = async (
authors: Array<string>
): Promise<Profile[]> => {
let filter = "";
if (authors.length > 0) {
filter = JSON.stringify([
{
kinds: ["0"],
authors: authors,
// limit: 1,
},
]);
} else {
filter = JSON.stringify([
{
kinds: ["0"],
// limit: 1,
},
]);
}
let messages = await fetchEvents(filter);
// console.log("Messages from App with all profiless", messages);

try {
return messages.map((message) => {
let profile = JSON.parse(message.Content);

profile.address = message.From;

profile.created_at = messages[0].Timestamp;

profile.updated_at = message.Timestamp;

console.log("Profile from App in new Fetch all Profiles", profile);

return profile;
}) as Profile[];
} catch (e) {
console.error(e);
throw e;
}
};

export const fetchFollowList = async (
address: string
): Promise<Array<string>> => {
console.log("Address", address);
//console.log("Address", address);
let followList: Array<string> = [];
const filter = JSON.stringify([
{
Expand All @@ -131,14 +83,14 @@ export const fetchFollowList = async (
]);

let messages = await fetchEvents(filter);
console.log("Messages from App", messages);
//console.log("Messages from App", messages);

try {
console.log(`Follow List messages for ${address}`, messages);
//console.log(`Follow List messages for ${address}`, messages);
let message = messages[0]; // Latest Follow List at index 0
if (message.p) {
if (message && message.p) {
followList = JSON.parse(message.p);
console.log(`Latest Follow List for ${address}`, followList);
//console.log(`Latest Follow List for ${address}`, followList);
}
} catch (e) {
console.log(e);
Expand All @@ -147,14 +99,15 @@ export const fetchFollowList = async (
};

// Modified fetchProfilesForUsersProfileMap with pagination
export const fetchProfilesForUsersProfileMap = async (
/*export const fetchProfilesForUsersProfileMap = async (
page: number = 0,
limit: number = 10
limit: number = 10,
profiles: string []
): Promise<Map<string, Profile>> => {
// Calculate start and end indices for pagination
const startIndex = page * limit;
let allProfiles = await fetchProfiles([]);
let allProfiles = await fetchProfiles(profiles);
// Paginate the profiles array
const paginatedProfiles = allProfiles.slice(startIndex, startIndex + limit);
Expand Down Expand Up @@ -186,10 +139,10 @@ export const fetchProfilesForUsersProfileMap = async (
console.error(e);
throw e;
}
};
};*/

// that stores all profiles and returns paginated results from cache
export class ProfileCache {
/*export class ProfileCache {
private static instance: ProfileCache;
private profiles: Profile[] = [];
private lastFetch: number = 0;
Expand All @@ -204,15 +157,15 @@ export class ProfileCache {
return ProfileCache.instance;
}
private async refreshCache(): Promise<void> {
/*private async refreshCache(): Promise<void> {
const now = Date.now();
if (now - this.lastFetch > this.CACHE_DURATION || this.profiles.length === 0) {
this.profiles = await fetchProfiles([]);
this.lastFetch = now;
}
}
}*/

async getPaginatedProfiles(page: number, limit: number): Promise<Map<string, Profile>> {
/*async getPaginatedProfiles(page: number, limit: number): Promise<Map<string, Profile>> {
await this.refreshCache();
const startIndex = page * limit;
Expand Down Expand Up @@ -260,4 +213,4 @@ export const fetchPaginatedProfilesForUsersProfileMap = async (
export const hasMoreProfiles = (page: number, limit: number): boolean => {
const cache = ProfileCache.getInstance();
return cache.hasMoreProfiles(page, limit);
};
};*/
10 changes: 5 additions & 5 deletions src/lib/components/Follow/Follow.svelte
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
<script lang="ts">
import ButtonWithLoader from "../ButtonWithLoader/ButtonWithLoader.svelte";
import { followListStore } from "$lib/stores/follow-list.store";
import { currentUser } from "$lib/stores/current-user.store";
export let address: string;
// let isSubscribed: boolean = $followListStore.has(address);
let isSubscribed: boolean = false;
followListStore.subscribe((set) => {
isSubscribed = set.has(address);
currentUser.subscribe((_currentUser) => {
isSubscribed = _currentUser.followList.includes(address);
});
let loader = false;
async function unsubscribe() {
loader = true;
await followListStore.unfollow(address);
await currentUser.unfollow(address);
loader = false;
}
async function subscribe() {
loader = true;
await followListStore.follow(address);
await currentUser.follow(address);
loader = false;
}
</script>
Expand Down
Loading

0 comments on commit 45c597a

Please sign in to comment.