@alpha-arcade/sdk 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,7 @@ const indexerClient = new algosdk.Indexer('', 'https://mainnet-idx.algonode.clou
26
26
  const account = algosdk.mnemonicToSecretKey('your twenty five word mnemonic ...');
27
27
  const signer = algosdk.makeBasicAccountTransactionSigner(account);
28
28
 
29
- // 3. Initialize the client
29
+ // 3. Initialize the client (no API key needed!)
30
30
  const client = new AlphaClient({
31
31
  algodClient,
32
32
  indexerClient,
@@ -34,10 +34,9 @@ const client = new AlphaClient({
34
34
  activeAddress: account.addr,
35
35
  matcherAppId: 3078581851,
36
36
  usdcAssetId: 31566704,
37
- apiKey: 'YOUR_API_KEY',
38
37
  });
39
38
 
40
- // 4. Fetch live markets
39
+ // 4. Fetch live markets (reads directly from chain)
41
40
  const markets = await client.getMarkets();
42
41
  console.log(`Found ${markets.length} live markets`);
43
42
 
@@ -72,8 +71,9 @@ new AlphaClient(config: AlphaClientConfig)
72
71
  | `activeAddress` | `string` | Yes | Your Algorand address |
73
72
  | `matcherAppId` | `number` | Yes | Matcher contract app ID (mainnet: `3078581851`) |
74
73
  | `usdcAssetId` | `number` | Yes | USDC ASA ID (mainnet: `31566704`) |
75
- | `apiKey` | `string` | Yes | Alpha partners API key (x-api-key header) |
74
+ | `apiKey` | `string` | No | Alpha partners API key. If provided, `getMarkets()` uses the API for richer data (images, categories, volume). If omitted, markets are discovered on-chain. |
76
75
  | `apiBaseUrl` | `string` | No | API base URL (default: `https://partners.alphaarcade.com/api`) |
76
+ | `marketCreatorAddress` | `string` | No | Market creator address for on-chain discovery (defaults to Alpha Arcade mainnet) |
77
77
 
78
78
  ---
79
79
 
@@ -226,26 +226,37 @@ for (const order of orders) {
226
226
 
227
227
  ### Markets
228
228
 
229
- #### `getMarkets()`
229
+ Markets can be loaded **on-chain** (default, no API key) or via the **REST API** (richer data, requires API key).
230
230
 
231
- Fetches all live, tradeable markets.
231
+ #### `getMarkets()` / `getMarket(marketId)`
232
+
233
+ Smart defaults — uses the API if `apiKey` is set, otherwise reads from chain.
232
234
 
233
235
  ```typescript
234
236
  const markets = await client.getMarkets();
235
237
  for (const m of markets) {
236
- console.log(`${m.title} — Yes: ${m.yesProb}%, Vol: $${m.volume}`);
238
+ console.log(`${m.title} — App ID: ${m.marketAppId}, source: ${m.source}`);
237
239
  }
240
+
241
+ const market = await client.getMarket('12345'); // app ID string for on-chain, UUID for API
238
242
  ```
239
243
 
240
- #### `getMarket(marketId)`
244
+ #### `getMarketsOnChain()` / `getMarketOnChain(marketAppId)`
241
245
 
242
- Fetches a single market by ID.
246
+ Always reads from the blockchain. No API key needed. Returns core data: title, asset IDs, resolution time, fees.
243
247
 
244
248
  ```typescript
245
- const market = await client.getMarket('abc123');
246
- if (market) {
247
- console.log(market.title, market.marketAppId);
248
- }
249
+ const markets = await client.getMarketsOnChain();
250
+ const market = await client.getMarketOnChain(3012345678);
251
+ ```
252
+
253
+ #### `getMarketsFromApi()` / `getMarketFromApi(marketId)`
254
+
255
+ Always uses the REST API. Requires `apiKey`. Returns richer data: images, categories, volume, probabilities.
256
+
257
+ ```typescript
258
+ const markets = await client.getMarketsFromApi();
259
+ const market = await client.getMarketFromApi('uuid-here');
249
260
  ```
250
261
 
251
262
  ---
@@ -296,13 +307,12 @@ const setup = () => {
296
307
  activeAddress: account.addr,
297
308
  matcherAppId: 3078581851,
298
309
  usdcAssetId: 31566704,
299
- apiKey: 'YOUR_API_KEY',
300
310
  });
301
311
  };
302
312
 
303
313
  const run = async () => {
304
314
  const client = setup();
305
- const markets = await client.getMarkets();
315
+ const markets = await client.getMarkets(); // Loads from chain, no API key needed
306
316
 
307
317
  for (const market of markets) {
308
318
  const book = await client.getOrderbook(market.marketAppId);
package/dist/index.cjs CHANGED
@@ -1911,40 +1911,43 @@ var getPositions = async (config, walletAddress) => {
1911
1911
  const amount = Number(asset.amount);
1912
1912
  try {
1913
1913
  const assetInfo = await indexerClient.lookupAssetByID(assetId).do();
1914
- const creator = assetInfo.asset?.params?.creator;
1915
- if (!creator) continue;
1916
- const createdApps = await indexerClient.lookupAccountCreatedApplications(creator).limit(1).do();
1917
- if (!createdApps.applications?.length) continue;
1918
- const appId = createdApps.applications[0].id;
1919
- try {
1920
- const appInfo = await indexerClient.lookupApplications(appId).do();
1921
- const rawState = appInfo.application?.params?.["global-state"];
1922
- if (!rawState) continue;
1923
- let yesAssetIdOnChain = 0;
1924
- let noAssetIdOnChain = 0;
1925
- for (const item of rawState) {
1926
- const key = Buffer.from(item.key, "base64").toString();
1927
- if (key === "yes_asset_id") yesAssetIdOnChain = Number(item.value.uint);
1928
- if (key === "no_asset_id") noAssetIdOnChain = Number(item.value.uint);
1929
- }
1930
- if (yesAssetIdOnChain === 0 && noAssetIdOnChain === 0) continue;
1931
- const existing = positions.get(appId) ?? {
1932
- marketAppId: appId,
1933
- yesAssetId: yesAssetIdOnChain,
1934
- noAssetId: noAssetIdOnChain,
1935
- yesBalance: 0,
1936
- noBalance: 0
1937
- };
1938
- if (assetId === yesAssetIdOnChain) {
1914
+ const assetName = assetInfo.asset?.params?.name ?? "";
1915
+ const unitName = assetInfo.asset?.params?.["unit-name"] ?? "";
1916
+ if (!unitName.startsWith("ALPHA-")) continue;
1917
+ const match = assetName.match(/^Alpha Market (\d+) (Yes|No)$/);
1918
+ if (!match) continue;
1919
+ const marketAppId = Number(match[1]);
1920
+ const side = match[2];
1921
+ const existing = positions.get(marketAppId);
1922
+ if (existing) {
1923
+ if (side === "Yes") {
1939
1924
  existing.yesBalance = amount;
1940
- } else if (assetId === noAssetIdOnChain) {
1941
- existing.noBalance = amount;
1942
1925
  } else {
1926
+ existing.noBalance = amount;
1927
+ }
1928
+ } else {
1929
+ try {
1930
+ const appInfo = await indexerClient.lookupApplications(marketAppId).do();
1931
+ const rawState = appInfo.application?.params?.["global-state"];
1932
+ if (!rawState) continue;
1933
+ let yesAssetIdOnChain = 0;
1934
+ let noAssetIdOnChain = 0;
1935
+ for (const item of rawState) {
1936
+ const key = Buffer.from(item.key, "base64").toString();
1937
+ if (key === "yes_asset_id") yesAssetIdOnChain = Number(item.value.uint);
1938
+ if (key === "no_asset_id") noAssetIdOnChain = Number(item.value.uint);
1939
+ }
1940
+ if (yesAssetIdOnChain === 0 && noAssetIdOnChain === 0) continue;
1941
+ positions.set(marketAppId, {
1942
+ marketAppId,
1943
+ yesAssetId: yesAssetIdOnChain,
1944
+ noAssetId: noAssetIdOnChain,
1945
+ yesBalance: side === "Yes" ? amount : 0,
1946
+ noBalance: side === "No" ? amount : 0
1947
+ });
1948
+ } catch {
1943
1949
  continue;
1944
1950
  }
1945
- positions.set(appId, existing);
1946
- } catch {
1947
- continue;
1948
1951
  }
1949
1952
  } catch {
1950
1953
  continue;
@@ -1955,7 +1958,121 @@ var getPositions = async (config, walletAddress) => {
1955
1958
 
1956
1959
  // src/modules/markets.ts
1957
1960
  var DEFAULT_API_BASE_URL = "https://partners.alphaarcade.com/api";
1958
- var getMarkets = async (config) => {
1961
+ var DEFAULT_MARKET_CREATOR_ADDRESS = "5P5Y6HTWUNG2E3VXBQDZN3ENZD3JPAIR5PKT3LOYJAPAUKOLFD6KANYTRY";
1962
+ var groupMultiChoiceMarkets = (flatMarkets) => {
1963
+ const parentMap = /* @__PURE__ */ new Map();
1964
+ const result = [];
1965
+ for (const m of flatMarkets) {
1966
+ const separatorIdx = m.title.lastIndexOf(" : ");
1967
+ if (separatorIdx === -1) {
1968
+ result.push(m);
1969
+ continue;
1970
+ }
1971
+ const parentTitle = m.title.substring(0, separatorIdx).trim();
1972
+ const optionTitle = m.title.substring(separatorIdx + 3).trim();
1973
+ let parent = parentMap.get(parentTitle);
1974
+ if (!parent) {
1975
+ parent = {
1976
+ id: `group:${parentTitle}`,
1977
+ title: parentTitle,
1978
+ marketAppId: m.marketAppId,
1979
+ // Use first option's app ID as the parent's
1980
+ yesAssetId: 0,
1981
+ noAssetId: 0,
1982
+ endTs: m.endTs,
1983
+ isResolved: m.isResolved,
1984
+ isLive: m.isLive,
1985
+ feeBase: m.feeBase,
1986
+ source: "onchain",
1987
+ options: []
1988
+ };
1989
+ parentMap.set(parentTitle, parent);
1990
+ result.push(parent);
1991
+ }
1992
+ parent.options.push({
1993
+ id: m.id,
1994
+ title: optionTitle,
1995
+ marketAppId: m.marketAppId,
1996
+ yesAssetId: m.yesAssetId,
1997
+ noAssetId: m.noAssetId,
1998
+ yesProb: 0,
1999
+ noProb: 0
2000
+ });
2001
+ }
2002
+ return result;
2003
+ };
2004
+ var getMarketsOnChain = async (config, options) => {
2005
+ const creatorAddress = config.marketCreatorAddress ?? DEFAULT_MARKET_CREATOR_ADDRESS;
2006
+ const activeOnly = options?.activeOnly ?? true;
2007
+ const allApps = [];
2008
+ let nextToken;
2009
+ let hasMore = true;
2010
+ while (hasMore) {
2011
+ let query = config.indexerClient.lookupAccountCreatedApplications(creatorAddress).limit(100);
2012
+ if (nextToken) {
2013
+ query = query.nextToken(nextToken);
2014
+ }
2015
+ const response = await query.do();
2016
+ if (response.applications?.length) {
2017
+ allApps.push(...response.applications);
2018
+ }
2019
+ if (response["next-token"]) {
2020
+ nextToken = response["next-token"];
2021
+ } else {
2022
+ hasMore = false;
2023
+ }
2024
+ }
2025
+ const flatMarkets = [];
2026
+ for (const app of allApps) {
2027
+ if (app.deleted) continue;
2028
+ const rawState = app.params?.["global-state"];
2029
+ if (!rawState) continue;
2030
+ const state = decodeGlobalState(rawState);
2031
+ if (activeOnly && !state.is_activated) continue;
2032
+ if (activeOnly && state.is_resolved) continue;
2033
+ if (activeOnly && state.resolution_time && state.resolution_time < Math.floor(Date.now() / 1e3)) continue;
2034
+ const appId = Number(app.id);
2035
+ flatMarkets.push({
2036
+ id: String(appId),
2037
+ title: state.title || "",
2038
+ marketAppId: appId,
2039
+ yesAssetId: state.yes_asset_id || 0,
2040
+ noAssetId: state.no_asset_id || 0,
2041
+ endTs: state.resolution_time || 0,
2042
+ isResolved: !!state.is_resolved,
2043
+ isLive: !!state.is_activated && !state.is_resolved,
2044
+ feeBase: state.fee_base_percent,
2045
+ source: "onchain"
2046
+ });
2047
+ }
2048
+ return groupMultiChoiceMarkets(flatMarkets);
2049
+ };
2050
+ var getMarketOnChain = async (config, marketAppId) => {
2051
+ try {
2052
+ const appId = typeof marketAppId === "string" ? Number(marketAppId) : marketAppId;
2053
+ const appInfo = await config.algodClient.getApplicationByID(appId).do();
2054
+ const rawState = appInfo.params?.["global-state"] ?? appInfo["params"]?.["global-state"] ?? [];
2055
+ const state = decodeGlobalState(rawState);
2056
+ return {
2057
+ id: String(appId),
2058
+ title: state.title || "",
2059
+ marketAppId: appId,
2060
+ yesAssetId: state.yes_asset_id || 0,
2061
+ noAssetId: state.no_asset_id || 0,
2062
+ endTs: state.resolution_time || 0,
2063
+ isResolved: !!state.is_resolved,
2064
+ isLive: !!state.is_activated && !state.is_resolved,
2065
+ feeBase: state.fee_base_percent,
2066
+ source: "onchain"
2067
+ };
2068
+ } catch {
2069
+ return null;
2070
+ }
2071
+ };
2072
+ var getMarketsFromApi = async (config) => {
2073
+ if (!config.apiKey) {
2074
+ throw new Error("apiKey is required for API-based market fetching. Use getMarketsOnChain() instead, or pass an apiKey.");
2075
+ }
1959
2076
  const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
1960
2077
  const allMarkets = [];
1961
2078
  let lastEvaluatedKey;
@@ -1972,10 +2089,10 @@ var getMarkets = async (config) => {
1972
2089
  }
1973
2090
  const data = await response.json();
1974
2091
  if (Array.isArray(data)) {
1975
- allMarkets.push(...data);
2092
+ allMarkets.push(...data.map((m) => ({ ...m, source: "api" })));
1976
2093
  hasMore = false;
1977
2094
  } else if (data.markets) {
1978
- allMarkets.push(...data.markets);
2095
+ allMarkets.push(...data.markets.map((m) => ({ ...m, source: "api" })));
1979
2096
  lastEvaluatedKey = data.lastEvaluatedKey;
1980
2097
  hasMore = !!lastEvaluatedKey;
1981
2098
  } else {
@@ -1984,7 +2101,10 @@ var getMarkets = async (config) => {
1984
2101
  }
1985
2102
  return allMarkets;
1986
2103
  };
1987
- var getMarket = async (config, marketId) => {
2104
+ var getMarketFromApi = async (config, marketId) => {
2105
+ if (!config.apiKey) {
2106
+ throw new Error("apiKey is required for API-based market fetching. Use getMarketOnChain() instead, or pass an apiKey.");
2107
+ }
1988
2108
  const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
1989
2109
  const url = `${baseUrl}/get-market?marketId=${encodeURIComponent(marketId)}`;
1990
2110
  const response = await fetch(url, { headers: { "x-api-key": config.apiKey } });
@@ -1993,7 +2113,21 @@ var getMarket = async (config, marketId) => {
1993
2113
  throw new Error(`Alpha API error: ${response.status} ${response.statusText}`);
1994
2114
  }
1995
2115
  const data = await response.json();
1996
- return data.market ?? data ?? null;
2116
+ const market = data.market ?? data ?? null;
2117
+ if (market) market.source = "api";
2118
+ return market;
2119
+ };
2120
+ var getMarkets = async (config) => {
2121
+ if (config.apiKey) {
2122
+ return getMarketsFromApi(config);
2123
+ }
2124
+ return getMarketsOnChain(config);
2125
+ };
2126
+ var getMarket = async (config, marketId) => {
2127
+ if (config.apiKey) {
2128
+ return getMarketFromApi(config, marketId);
2129
+ }
2130
+ return getMarketOnChain(config, marketId);
1997
2131
  };
1998
2132
 
1999
2133
  // src/client.ts
@@ -2006,7 +2140,6 @@ var AlphaClient = class {
2006
2140
  if (!config.activeAddress) throw new Error("activeAddress is required");
2007
2141
  if (!config.matcherAppId) throw new Error("matcherAppId is required");
2008
2142
  if (!config.usdcAssetId) throw new Error("usdcAssetId is required");
2009
- if (!config.apiKey) throw new Error("apiKey is required");
2010
2143
  this.config = {
2011
2144
  ...config,
2012
2145
  apiBaseUrl: config.apiBaseUrl ?? "https://partners.alphaarcade.com/api"
@@ -2145,9 +2278,10 @@ var AlphaClient = class {
2145
2278
  // Markets
2146
2279
  // ============================================
2147
2280
  /**
2148
- * Fetches all live, tradeable markets from the Alpha API.
2281
+ * Fetches all live, tradeable markets.
2149
2282
  *
2150
- * Automatically paginates to retrieve all markets.
2283
+ * If an API key is configured, uses the Alpha REST API (richer data: images, categories, volume).
2284
+ * Otherwise, discovers markets on-chain from the market creator address (no API key needed).
2151
2285
  *
2152
2286
  * @returns Array of live markets
2153
2287
  */
@@ -2157,21 +2291,69 @@ var AlphaClient = class {
2157
2291
  /**
2158
2292
  * Fetches a single market by its ID.
2159
2293
  *
2160
- * @param marketId - The market ID
2294
+ * If an API key is configured, uses the Alpha REST API.
2295
+ * Otherwise, reads the market's on-chain global state (pass the market app ID as a string).
2296
+ *
2297
+ * @param marketId - The market ID (UUID for API, app ID string for on-chain)
2161
2298
  * @returns The market data, or null if not found
2162
2299
  */
2163
2300
  async getMarket(marketId) {
2164
2301
  return getMarket(this.config, marketId);
2165
2302
  }
2303
+ /**
2304
+ * Fetches all live markets directly from the blockchain (no API key needed).
2305
+ *
2306
+ * Discovers markets by looking up all apps created by the market creator address.
2307
+ * Returns core data: title, asset IDs, resolution time, fees.
2308
+ * Does NOT include images, categories, volume, or probabilities.
2309
+ *
2310
+ * @returns Array of live markets from on-chain data
2311
+ */
2312
+ async getMarketsOnChain() {
2313
+ return getMarketsOnChain(this.config);
2314
+ }
2315
+ /**
2316
+ * Fetches a single market by app ID directly from the blockchain (no API key needed).
2317
+ *
2318
+ * @param marketAppId - The market app ID
2319
+ * @returns The market data, or null if not found
2320
+ */
2321
+ async getMarketOnChain(marketAppId) {
2322
+ return getMarketOnChain(this.config, marketAppId);
2323
+ }
2324
+ /**
2325
+ * Fetches all live markets from the Alpha REST API (requires API key).
2326
+ *
2327
+ * Returns richer data than on-chain: images, categories, volume, probabilities.
2328
+ *
2329
+ * @returns Array of live markets from the API
2330
+ */
2331
+ async getMarketsFromApi() {
2332
+ return getMarketsFromApi(this.config);
2333
+ }
2334
+ /**
2335
+ * Fetches a single market by ID from the Alpha REST API (requires API key).
2336
+ *
2337
+ * @param marketId - The market UUID
2338
+ * @returns The market data, or null if not found
2339
+ */
2340
+ async getMarketFromApi(marketId) {
2341
+ return getMarketFromApi(this.config, marketId);
2342
+ }
2166
2343
  };
2167
2344
 
2168
2345
  exports.AlphaClient = AlphaClient;
2346
+ exports.DEFAULT_MARKET_CREATOR_ADDRESS = DEFAULT_MARKET_CREATOR_ADDRESS;
2169
2347
  exports.calculateFee = calculateFee;
2170
2348
  exports.calculateFeeFromTotal = calculateFeeFromTotal;
2171
2349
  exports.calculateMatchingOrders = calculateMatchingOrders;
2172
2350
  exports.checkAssetOptIn = checkAssetOptIn;
2173
2351
  exports.decodeGlobalState = decodeGlobalState;
2174
2352
  exports.getEscrowGlobalState = getEscrowGlobalState;
2353
+ exports.getMarketFromApi = getMarketFromApi;
2175
2354
  exports.getMarketGlobalState = getMarketGlobalState;
2355
+ exports.getMarketOnChain = getMarketOnChain;
2356
+ exports.getMarketsFromApi = getMarketsFromApi;
2357
+ exports.getMarketsOnChain = getMarketsOnChain;
2176
2358
  //# sourceMappingURL=index.cjs.map
2177
2359
  //# sourceMappingURL=index.cjs.map