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

Added new challenge #99

Merged
merged 1 commit into from
Nov 28, 2024
Merged
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
41 changes: 8 additions & 33 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,6 @@ impl Fairing for CORS {

struct QueryRoot;

pub struct ChainParameters {
ship_address: String,
fuel_address: String,
asteria_address: String,
}
impl ChainParameters {
pub fn from_env() -> Self {
Self {
ship_address: env::var("SHIP_ADDRESS")
.expect("SHIP_ADDRESS must be set in the environment"),
fuel_address: env::var("FUEL_ADDRESS")
.expect("FUEL_ADDRESS must be set in the environment"),
asteria_address: env::var("ASTERIA_ADDRESS")
.expect("ASTERIA_ADDRESS must be set in the environment"),
}
}
}

#[derive(Clone)]
pub struct Data {
pub ships: Vec<Ship>,
Expand Down Expand Up @@ -323,16 +305,15 @@ impl QueryRoot {
center: PositionInput,
radius: i32,
shipyard_policy_id: String,
ship_address: String,
fuel_address: String,
asteria_address: String,
) -> Result<Vec<PositionalInterface>, Error> {
// Access the connection pool from the GraphQL context
let pool = ctx
.data::<sqlx::PgPool>()
.map_err(|e| Error::new(e.message))?;

let chain_parameters = ctx
.data::<ChainParameters>()
.map_err(|e| Error::new(e.message))?;

// Query to select map objects within a radius using Manhattan distance
let fetched_objects = sqlx::query!(
"
Expand Down Expand Up @@ -410,9 +391,9 @@ impl QueryRoot {
center.y,
radius,
shipyard_policy_id,
chain_parameters.ship_address,
chain_parameters.fuel_address,
chain_parameters.asteria_address,
ship_address,
fuel_address,
asteria_address,
)
.fetch_all(pool)
.await
Expand Down Expand Up @@ -534,15 +515,12 @@ impl QueryRoot {
&self,
ctx: &Context<'_>,
shipyard_policy_id: String,
ship_address: String,
) -> Result<Vec<LeaderboardRecord>, Error> {
let pool = ctx
.data::<sqlx::PgPool>()
.map_err(|e| Error::new(e.message))?;

let chain_parameters = ctx
.data::<ChainParameters>()
.map_err(|e| Error::new(e.message))?;

let fetched_objects = sqlx::query!(
"
SELECT
Expand All @@ -560,7 +538,7 @@ impl QueryRoot {
ORDER BY distance ASC
",
shipyard_policy_id,
chain_parameters.ship_address,
ship_address,
)
.fetch_all(pool)
.await
Expand Down Expand Up @@ -610,8 +588,6 @@ async fn rocket() -> _ {
let database_url =
env::var("DATABASE_URL").expect("DATABASE_URL must be set in the environment");

let chain_parameters = ChainParameters::from_env();

let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(database_url.as_str())
Expand All @@ -620,7 +596,6 @@ async fn rocket() -> _ {

let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.register_output_type::<PositionalInterface>()
.data(chain_parameters)
.data(pool)
.data(Data::new(200, 100))
.finish();
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/NavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const NavBar: React.FunctionComponent = () => {
>
<img src="/challenge-icon.svg" className="w-6 h-6 mr-3 pointer-events-none" />
<select
value={selected || undefined}
value={selected}
onChange={handleSelect}
className="font-inter-regular text-[#F1E9D9] bg-transparent focus:outline-none appearance-none text-md text-left min-w-36"
>
Expand Down
14 changes: 2 additions & 12 deletions frontend/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { useEffect } from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import type { ReactElement, ReactNode } from 'react';
import type { NextPage } from 'next';
import type { AppProps } from 'next/app';

import NavBar from "@/components/NavBar";
import { useChallengeStore } from '@/stores/challenge';

import "./globals.css";

Expand All @@ -23,18 +21,10 @@ const client = new ApolloClient({
});

export default function App({ Component, pageProps }: AppPropsWithLayout) {
const { select, selected } = useChallengeStore();

useEffect(() => select(0), []);

return (
<ApolloProvider client={client}>
{ selected !== null && (
<>
<NavBar />
<Component {...pageProps} />
</>
)}
<NavBar />
<Component {...pageProps} />
</ApolloProvider>
);
}
11 changes: 8 additions & 3 deletions frontend/src/pages/leaderboard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { useChallengeStore } from '@/stores/challenge';
const PAGE_SIZE = 10;

const GET_LEADERBOARD_RECORDS = gql`
query Leaderboard($shipyardPolicyId: String) {
leaderboard(shipyardPolicyId: $shipyardPolicyId) {
query Leaderboard($shipyardPolicyId: String, $shipAddress: String) {
leaderboard(shipyardPolicyId: $shipyardPolicyId, shipAddress: $shipAddress) {
ranking,
address,
shipName,
Expand Down Expand Up @@ -86,7 +86,12 @@ const LeaderboardRow: React.FunctionComponent<RecordProps> = (props: RecordProps

export default function Leaderboard() {
const { current } = useChallengeStore();
const { loading, error, data } = useQuery<LeaderboardQueryResult>(GET_LEADERBOARD_RECORDS, { variables: { shipyardPolicyId: current().policyId } });
const { data } = useQuery<LeaderboardQueryResult>(GET_LEADERBOARD_RECORDS, {
variables: {
shipyardPolicyId: current().shipyardPolicyId,
shipAddress: current().shipAddress,
},
});
const [ offset, setOffset ] = useState<number>(0);

const hasNextPage = () => {
Expand Down
16 changes: 15 additions & 1 deletion frontend/src/pages/map/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import { useChallengeStore } from '@/stores/challenge';

export default function Map() {
const { current } = useChallengeStore();

const getUrl = (): string => {
const params = new URLSearchParams([
['apiUrl', `${process.env.API_URL}/graphql`],
['shipyardPolicyId', current().shipyardPolicyId],
['shipAddress', current().shipAddress],
['fuelAddress', current().fuelAddress],
['asteriaAddress', current().asteriaAddress]
]);
return `/visualizer/index.html?${params.toString()}`;
};

return (
<div className="w-full h-[calc(100vh-64px)]">
<iframe src="/visualizer/index.html" width="100%" height="100%"></iframe>
<iframe src={getUrl()} width="100%" height="100%"></iframe>
</div>
);
}
23 changes: 18 additions & 5 deletions frontend/src/stores/challenge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,37 @@ import { create } from 'zustand';

export interface Challenge {
label: string;
policyId: string;
shipyardPolicyId: string;
shipAddress: string;
fuelAddress: string;
asteriaAddress: string;
network: string;
}

export interface ChallengeStoreState {
selected: number|null;
selected: number;
challenges: Challenge[];
select: (index: number) => void;
current: () => Challenge;
}

export const useChallengeStore = create<ChallengeStoreState>((set, get) => ({
selected: null,
selected: 0,
challenges: [{
label: 'New challenge',
shipyardPolicyId: '06af6375746881387d42e09977ce826d49c4b1404ec14ca75aa4553b',
shipAddress: 'addr_test1wqr27cm4w35gzwragtsfja7wsfk5n393gp8vzn98t2j92wclzmt4v',
fuelAddress: 'addr_test1wrwy0q8xtcngksdxk7nxd8kxwxvssmha5kl62nyxk7dmuqsf3slrx',
asteriaAddress: 'addr_test1wr44k7mvy2aznjn5qk69xa5gax0fsxmv4q8n9xv9040kqjs9kcchd',
network: 'preview',
}, {
label: 'Builder fest workshop',
policyId: 'ecb96725c35e957f96be46bc1873cc8ae5b134f1b00f457675700511',
shipyardPolicyId: 'ecb96725c35e957f96be46bc1873cc8ae5b134f1b00f457675700511',
shipAddress: 'addr_test1wrktjee9cd0f2lukhertcxrnej9wtvf57xcq73tkw4cq2ygnz27xu',
fuelAddress: 'addr_test1wr37gywvcn3284cuxy4jke2w7np75jfm9apej7ns8d7n5ws3ecjrt',
asteriaAddress: 'addr_test1wzup673azpl4s09hckcxr496xpx6cghnhfhlj4ydsxwpf5qygteap',
network: 'preview',
}],
current: () => get().challenges[get().selected!],
current: () => get().challenges[get().selected],
select: (index: number) => set(() => ({ selected: index })),
}));
44 changes: 31 additions & 13 deletions godot-visualizer/scripts/main.gd
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,23 @@ signal dataset_updated

const radius = 1000

# Fallback api_url and shipyard_policy_id
var api_url = "https://8000-skillful-employee-kb9ou6.us1.demeter.run/graphql"
var shipyard_policy_id = "ecb96725c35e957f96be46bc1873cc8ae5b134f1b00f457675700511"
var api_url = ""
var shipyard_policy_id = ""
var ship_address = ""
var fuel_address = ""
var asteria_address = ""

const headers = ["Content-Type: application/json"]
const query = """
{
objectsInRadius(center: { x: 0, y: 0 }, radius: %s, shipyardPolicyId: "%s") {
objectsInRadius(
center: { x: 0, y: 0 },
radius: %s,
shipyardPolicyId: "%s",
shipAddress: "%s",
fuelAddress: "%s",
asteriaAddress: "%s"
) {
__typename,
position {
x,
Expand All @@ -37,22 +46,31 @@ const query = """
}
"""

func fetch_data():
$HTTPRequest.request(api_url, headers, HTTPClient.METHOD_POST, JSON.stringify({
"query": query % [
radius,
shipyard_policy_id,
ship_address,
fuel_address,
asteria_address
]
}))


func _process(delta: float) -> void:
$GUICanvasLayer/CenterContainer/Loader.rotation += delta * 10


func _ready():
#if OS.is_userfs_persistent():
#var stored_api_url = FileAccess.open("user://api_url", FileAccess.READ).get_as_text()
#if stored_api_url.length() > 0:
#api_url = stored_api_url + "/graphql"
#var stored_shipyard_policy_id = FileAccess.open("user://shipyard_policy_id", FileAccess.READ).get_as_text()
#if stored_shipyard_policy_id.length() > 0:
#shipyard_policy_id = stored_shipyard_policy_id
api_url = JavaScriptBridge.eval("new URL(window.location.href).searchParams.get('apiUrl')")
shipyard_policy_id = JavaScriptBridge.eval("new URL(window.location.href).searchParams.get('shipyardPolicyId')")
ship_address = JavaScriptBridge.eval("new URL(window.location.href).searchParams.get('shipAddress')")
fuel_address = JavaScriptBridge.eval("new URL(window.location.href).searchParams.get('fuelAddress')")
asteria_address = JavaScriptBridge.eval("new URL(window.location.href).searchParams.get('asteriaAddress')")

$HTTPRequest.request_completed.connect(_on_request_completed)
$HTTPRequest.request(api_url, headers, HTTPClient.METHOD_POST, JSON.stringify({ "query": query % [radius, shipyard_policy_id] }))
fetch_data()

var request_timer = Timer.new()
request_timer.wait_time = 20
Expand All @@ -70,7 +88,7 @@ func _on_request_completed(result, response_code, headers, body):


func _on_request_timer_timeout():
$HTTPRequest.request(api_url, headers, HTTPClient.METHOD_POST, JSON.stringify({ "query": query % [radius, shipyard_policy_id] }))
fetch_data()


func update_tooltip_position(position: Vector2) -> void:
Expand Down
Loading