Skip to content

Conversation

gaboesquivel
Copy link
Contributor

@gaboesquivel gaboesquivel commented May 9, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a CLI tool for BitCash token management, supporting token creation and listing.
    • Added a CLI for interacting with the Delphi Oracle contract, enabling registration, data submission, rewards claiming, trading pair management, and more.
    • Provided SDKs for both BitCash tokens and Delphi Oracle, allowing programmatic contract interactions such as creating tokens, querying stats, and managing oracles.
    • Added comprehensive, strongly-typed contract interfaces for BitCash token, BitCash accounts, bank, and Delphi Oracle smart contracts.
    • Included environment configuration modules for both BitCash token and Delphi Oracle packages.
  • Documentation

    • Added a README with setup and usage instructions for the BitCash token package.
  • Chores

    • Added configuration files such as TypeScript config, package manifest, and .gitignore for the BitCash token package.
    • Removed the .npmrc configuration file, reverting to default package management behavior.
  • Style

    • Updated package description for the BitCash accounts SDK.

Copy link

coderabbitai bot commented May 9, 2025

Walkthrough

This update introduces new TypeScript modules, SDKs, and CLI tools for interacting with several smart contracts (accounts.bk, bank.bk, delphioracle.bk, and token.bk) on Antelope-based blockchains. It adds type-safe contract interfaces, table mappings, and action parameter schemas. Environment configuration modules and package setup files are included. The update also removes the root .npmrc configuration, reverting to default package management behavior.

Changes

File(s) Change Summary
.npmrc Removed custom npm/yarn configuration file, eliminating settings for dependency hoisting and peer dependency management.
packages/accounts.bk/package.json Updated package description from "Delphi Oracle SDK for TypeScript" to "Bitcash accounts SDK for TypeScript".
packages/accounts.bk/src/accounts.bk.ts Added a new TypeScript module defining a fully typed, ABI-driven contract interface for accounts.bk, including table and action parameter schemas, and a typed contract class.
packages/bank.bk/src/bank.bk.ts Added a new TypeScript module defining a comprehensive, type-safe contract interface for bank.bk, including ABI, table structures, action parameter types, and a typed contract class.
packages/delphioracle/src/cli.ts Introduced a CLI tool (delphioracle-cli) with commands for oracle registration, data writing, claiming rewards, managing pairs, voting, and more, using the SDK functions.
packages/delphioracle/src/delphioracle.ts Added a new TypeScript module providing a typed interface for the delphioracle.bk smart contract, including ABI, table/action schemas, and a contract class for type-safe interaction.
packages/delphioracle/src/environment.ts Added an environment configuration module exporting an env object with key variables and default values, including contract name, RPC endpoint, and debug flag.
packages/delphioracle/src/sdk.ts Added a comprehensive SDK for Delphi Oracle, providing functions for user registration, data writing, claims, pair management, voting, and error handling, with manual transaction creation and signing.
packages/token.bk/.gitignore Added a Node.js-based .gitignore to exclude logs, build outputs, environment files, IDE settings, and other transient files from version control.
packages/token.bk/README.md Added a README with installation and usage instructions for the @l1network/token.bk package, including Bun runtime details.
packages/token.bk/package.json Added a new package manifest for @l1network/token.bk specifying metadata, entry point, module type, and dependencies.
packages/token.bk/src/cli.ts Introduced a CLI tool (bitcash-token-cli) for managing BitCash tokens, supporting create and list commands with appropriate options and output.
packages/token.bk/src/environment.ts Added a module to read and export the PRIVATE_KEY environment variable, with error handling if unset.
packages/token.bk/src/index.ts Added a simple entry file that prints "Hello via Bun!" to the console.
packages/token.bk/src/sdk.ts Added an SDK module for token.bk contract: functions for session creation, token creation, and querying all tokens, with error handling and type-safe blockchain interaction.
packages/token.bk/src/token.bk.ts Added a TypeScript module defining a type-safe contract interface for token.bk, including ABI, structured types for tables/actions, and a contract class for interaction.
packages/token.bk/tsconfig.json Added a TypeScript configuration extending a base config, specifying module resolution, path aliases, and file inclusions/exclusions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant SDK
    participant Blockchain

    User->>CLI: Run command (e.g., create token, write oracle data)
    CLI->>SDK: Call corresponding SDK function with parameters
    SDK->>Blockchain: Build, sign, and send transaction or query
    Blockchain-->>SDK: Respond with result or error
    SDK-->>CLI: Return result or error
    CLI-->>User: Output success or error message
Loading

Poem

🐇
New contracts bloom, the code takes flight,
Typed ABIs bring safety and light.
CLI tools now join the show,
To help your tokens, oracles grow.
With configs set and Bun in hand,
The blockchain’s magic, close at hand!
— A happy rabbit coder

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 16

🔭 Outside diff range comments (1)
packages/accounts.bk/package.json (1)

1-12: 💡 Verification agent

🧩 Analysis chain

Address pipeline warning about workspaces

The CI pipeline reports that pnpm doesn't support the "workspaces" field in package.json.


🏁 Script executed:

#!/bin/bash
# Check if a pnpm-workspace.yaml file exists at the root
if [ -f "pnpm-workspace.yaml" ]; then
  echo "pnpm-workspace.yaml already exists"
  cat pnpm-workspace.yaml
else
  echo "pnpm-workspace.yaml does not exist"
  # Check if there's a workspaces field in the root package.json
  grep -A 5 "\"workspaces\"" package.json 2>/dev/null || echo "No workspaces field found in root package.json"
fi

Length of output: 206


Add a pnpm-workspace.yaml to define your workspaces

Pnpm ignores the "workspaces" field in package.json and emits a warning because there’s no pnpm-workspace.yaml at the repo root. To resolve:

• At the repository root, create pnpm-workspace.yaml with:

packages:
  - "apps/*"
  - "packages/*"

• Remove the top-level "workspaces" field from package.json.

This will eliminate the CI pipeline warning and ensure pnpm correctly picks up your workspaces.

🧰 Tools
🪛 GitHub Actions: Test

[warning] 1-1: The "workspaces" field in package.json is not supported by pnpm. Create a "pnpm-workspace.yaml" file instead.

🧹 Nitpick comments (13)
packages/delphioracle/src/environment.ts (1)

1-9: Fix inconsistent indentation

The code has inconsistent indentation levels that should be standardized.

// Environment setup
const env = {
-    oracleContract: process.env.ORACLE_CONTRACT || 'delphioracle',
-    defaultRpc: process.env.RPC_ENDPOINT || 'https://api.np.animus.is',
-    defaultPrivateKey: process.env.PRIVATE_KEY || '',
-    defaultPermission: process.env.PERMISSION || 'active',
-    debug: process.env.DEBUG === 'true' || false,
-    oracle: process.env.ORACLE || 'delphioracle'
-  }
+  oracleContract: process.env.ORACLE_CONTRACT || 'delphioracle',
+  defaultRpc: process.env.RPC_ENDPOINT || 'https://api.np.animus.is',
+  defaultPrivateKey: process.env.PRIVATE_KEY || '',
+  defaultPermission: process.env.PERMISSION || 'active',
+  debug: process.env.DEBUG === 'true' || false,
+  oracle: process.env.ORACLE || 'delphioracle'
+}
packages/token.bk/src/environment.ts (3)

1-4: Consider using standard Node.js types

Instead of manually declaring the process type, consider using the standard Node.js types.

-declare const process: {
-    env: Record<string, string | undefined>
-    exit: (code: number) => never
-  }
+// Either add this import:
+// import { process } from 'node:process';
+// Or add @types/node to your devDependencies

6-6: Remove unnecessary whitespace

There's an extra blank line with whitespace that should be removed.

-  
+

14-14: Consider using a more comprehensive environment configuration

The current environment setup is minimal compared to the delphioracle package. Consider adding more configuration options for consistency across packages.

-export const env = { privateKey }
+export const env = { 
+  privateKey,
+  tokenContract: process.env.TOKEN_CONTRACT || 'token.bk',
+  defaultRpc: process.env.RPC_ENDPOINT || 'https://api.np.animus.is',
+  defaultPermission: process.env.PERMISSION || 'active',
+  debug: process.env.DEBUG === 'true' || false,
+}
packages/token.bk/src/cli.ts (2)

29-33: Improve error message formatting

The error object is directly logged, which might result in verbose and hard-to-read output.

    if (result.success) {
      console.log('Token created successfully!')
    } else {
-      console.error('Error creating token:', result.error)
+      console.error('Error creating token:', result.error?.message || 'Unknown error')
    }

56-57: Same issue with error message formatting in list command

    } else {
-      console.error('Error getting tokens:', result.error)
+      console.error('Error getting tokens:', result.error?.message || 'Unknown error')
    }
packages/token.bk/src/sdk.ts (2)

1-1: Unused default import

The default import session is never used in the code.

-import session, { Session } from '@wharfkit/session'
+import { Session } from '@wharfkit/session'

74-74: Duplicated default RPC endpoint URL

The default RPC endpoint URL is duplicated here and in the chain configuration.

-export const getAllTokens = async (rpcEndpoint = 'https://api.np.animus.is') => {
+export const getAllTokens = async (rpcEndpoint = defaultChain.url) => {
packages/delphioracle/src/sdk.ts (2)

315-318: UInt64.from silently truncates floats

If a caller passes a non-integer value, UInt64.from() will floor anything after the decimal
without warning.
Add an explicit check or rounding to prevent silent precision loss.

-  value: UInt64.from(q.value),
+  value: UInt64.from(Math.round(Number(q.value))),

466-482: Filtering active pairs on the client may hide authoritative errors

pair.active is evaluated client-side after all rows have been fetched.
If the table grows large, this wastes RAM/network and may exceed the node’s row-limit.

Consider adding a secondary index or using lower_bound/upper_bound parameters so that only active
pairs are returned by the chain API.

packages/delphioracle/src/cli.ts (2)

117-126: Option name/case mismatch can set undefined values

Commander converts option names to camelCase, therefore
--base-symboloptions.baseSymbol, not options.base_symbol.
The current mapping is correct, but the subsequent numeric fields
(baseType, quoteType, quotedPrecision) are parsed with parseInt
without validating that the option was actually provided; if missing,
NaN will be sent on-chain, causing the transaction to fail.

Add upfront validation:

const baseType = Number.parseInt(options.baseType, 10)
if (Number.isNaN(baseType)) {
  console.error('Invalid --base-type')
  process.exit(1)
}

178-185: Inconsistent label – Owner vs Proposer

The output lists “Owner” but prints the pair.proposer field.
Rename the label to avoid confusion:

- console.log(`Owner: ${pair.proposer}`)
+ console.log(`Proposer: ${pair.proposer}`)
packages/bank.bk/src/bank.bk.ts (1)

838-856: Consider tightening generic bounds in table helper

super.table(name, scope, TableMap[name]) relies on TableMap[name] always being defined.
Add a runtime assertion or narrow the generic so that a misspelled table name surfaces as a compile-time error:

-    table<T extends TableNames>(name: T, scope?: NameType): Table<RowType<T>> {
-        return super.table(name, scope, TableMap[name])
+    table<T extends TableNames>(
+        name: T,
+        scope?: NameType
+    ): Table<RowType<T>> {
+        const model = TableMap[name]
+        if (!model) {
+            throw new Error(`Unknown table name: ${String(name)}`)
+        }
+        return super.table(name, scope, model)
     }

This prevents silent undefined look-ups if TableMap ever diverges from the ABI.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd9dfee and a51b0a0.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • .npmrc (0 hunks)
  • packages/accounts.bk/package.json (1 hunks)
  • packages/accounts.bk/src/accounts.bk.ts (1 hunks)
  • packages/bank.bk/src/bank.bk.ts (1 hunks)
  • packages/delphioracle/src/cli.ts (1 hunks)
  • packages/delphioracle/src/delphioracle.ts (1 hunks)
  • packages/delphioracle/src/environment.ts (1 hunks)
  • packages/delphioracle/src/sdk.ts (1 hunks)
  • packages/token.bk/.gitignore (1 hunks)
  • packages/token.bk/README.md (1 hunks)
  • packages/token.bk/package.json (1 hunks)
  • packages/token.bk/src/cli.ts (1 hunks)
  • packages/token.bk/src/environment.ts (1 hunks)
  • packages/token.bk/src/index.ts (1 hunks)
  • packages/token.bk/src/sdk.ts (1 hunks)
  • packages/token.bk/src/token.bk.ts (1 hunks)
  • packages/token.bk/tsconfig.json (1 hunks)
💤 Files with no reviewable changes (1)
  • .npmrc
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/token.bk/src/cli.ts (2)
packages/token.bk/src/sdk.ts (2)
  • createToken (36-67)
  • getAllTokens (74-110)
packages/token.bk/src/environment.ts (1)
  • env (14-14)
🪛 GitHub Actions: Test
packages/accounts.bk/package.json

[warning] 1-1: The "workspaces" field in package.json is not supported by pnpm. Create a "pnpm-workspace.yaml" file instead.

packages/token.bk/package.json

[warning] 1-1: The "workspaces" field in package.json is not supported by pnpm. Create a "pnpm-workspace.yaml" file instead.

🔇 Additional comments (5)
packages/token.bk/.gitignore (1)

1-176: Comprehensive .gitignore follows official Node.js template.

This .gitignore is based on the GitHub Node.js template and appropriately excludes logs, caches, runtime data, coverage reports, dependency directories, build outputs, environment files, IDE-specific files, and other common artifacts. It ensures the token.bk package remains clean by preventing transient and environment-specific files from being committed.

packages/accounts.bk/package.json (1)

3-3: Description update looks appropriate

The package description has been correctly updated to match this package's purpose.

packages/token.bk/package.json (1)

1-12:

❌ Incorrect review comment

Add pnpm workspace configuration

The pipeline warning indicates that pnpm workspaces aren't properly configured.


🏁 Script executed:

#!/bin/bash
# Check if a pnpm-workspace.yaml file exists at the root level
if [ -f "../../../pnpm-workspace.yaml" ]; then
  echo "pnpm-workspace.yaml exists at root"
  cat "../../../pnpm-workspace.yaml"
else
  echo "pnpm-workspace.yaml not found at root"
fi

Length of output: 126


I want to verify whether a pnpm-workspace.yaml (or equivalent workspace config) truly exists at the repo root before recommending adding one.


🏁 Script executed:

#!/bin/bash
# Search for pnpm-workspace.yaml anywhere in the repo
echo "Looking for pnpm-workspace.yaml files:"
find . -type f -name 'pnpm-workspace.yaml'

# Check if root package.json declares workspaces
echo -e "\nChecking root package.json for a 'workspaces' field:"
if [ -f package.json ]; then
  jq '.workspaces // "none"' package.json
else
  echo "No root package.json found"
fi

Length of output: 355


🌐 Web query:

Does pnpm recognize workspace configuration defined in the root package.json "workspaces" field, or is a pnpm-workspace.yaml file required?

💡 Result:

Yes, pnpm recognizes workspace configurations defined in the root package.json file's workspaces field. This approach aligns with the conventions of other package managers like npm and Yarn, which also use the workspaces field in package.json to define workspaces. (github.com)

While pnpm also supports a pnpm-workspace.yaml file for workspace configuration, it is not required. The pnpm-workspace.yaml file allows for more advanced configurations, such as including or excluding specific directories from the workspace. However, for basic workspace setups, defining the workspaces field in package.json is sufficient. (pnpm.io)

In summary, pnpm can recognize workspace configurations in both the workspaces field of package.json and the pnpm-workspace.yaml file. The choice between them depends on your project's specific needs and whether you require the additional configuration options provided by the YAML file.

Citations:


Workspace configuration already defined in root package.json

pnpm recognizes the "workspaces" field in your root package.json, so you don’t need a separate pnpm-workspace.yaml for basic monorepo setups. The existing configuration:

  • "workspaces": ["apps/*", "packages/*"]

already includes packages/token.bk. You can safely ignore the pipeline warning unless you require advanced includes/excludes via a YAML file.

Likely an incorrect or invalid review comment.

🧰 Tools
🪛 GitHub Actions: Test

[warning] 1-1: The "workspaces" field in package.json is not supported by pnpm. Create a "pnpm-workspace.yaml" file instead.

packages/delphioracle/src/delphioracle.ts (1)

400-416: Duplicate / unclear npairs entry in TableMap

TableMap (and TableTypes) export both pairs and npairs, each using the same Types.pairs model.
Unless the ABI truly defines a second table called npairs, this duplication:

  • confuses consumers (“which one do I query?”)
  • risks inconsistency if only one key is maintained later

Action points:

  1. Verify the ABI contains a table named npairs.
  2. If not, remove the npairs entry from both TableMap and TableTypes.
packages/token.bk/src/token.bk.ts (1)

74-82: Nice, minimal & accurate table mapping

The TableMap and TableTypes are concise and perfectly aligned with the ABI – this keeps the contract wrapper lightweight and easy to consume.

@@ -0,0 +1 @@
console.log("Hello via Bun!");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

This appears to be a placeholder entry point

This minimal console.log statement serves as a basic entry point for the package, demonstrating Bun runtime integration. As this is an SDK package, consider replacing this with meaningful exports of your actual SDK functionality.

-console.log("Hello via Bun!");
+// Export key components from the SDK
+export * from './token.bk';
+export * from './sdk';
+export { env } from './environment';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log("Hello via Bun!");
// Export key components from the SDK
export * from './token.bk';
export * from './sdk';
export { env } from './environment';

const env = {
oracleContract: process.env.ORACLE_CONTRACT || 'delphioracle',
defaultRpc: process.env.RPC_ENDPOINT || 'https://api.np.animus.is',
defaultPrivateKey: process.env.PRIVATE_KEY || '',
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider validating the private key

The private key is set to an empty string by default, which could lead to silent failures when signing transactions.

-  defaultPrivateKey: process.env.PRIVATE_KEY || '',
+  defaultPrivateKey: process.env.PRIVATE_KEY || (() => {
+    if (process.env.NODE_ENV === 'production') {
+      console.warn('Warning: No private key provided in production environment');
+    }
+    return '';
+  })(),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
defaultPrivateKey: process.env.PRIVATE_KEY || '',
defaultPrivateKey: process.env.PRIVATE_KEY || (() => {
if (process.env.NODE_ENV === 'production') {
console.warn('Warning: No private key provided in production environment');
}
return '';
})(),

oracle: process.env.ORACLE || 'delphioracle'
}

console.log(`🍓 env: `, env)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove or redact sensitive information in logs

Logging the entire environment object could expose sensitive information like private keys in logs.

-  console.log(`🍓 env: `, env)
+  console.log(`🍓 env: `, {
+    ...env,
+    defaultPrivateKey: env.defaultPrivateKey ? '***' : undefined
+  })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(`🍓 env: `, env)
console.log(`🍓 env: `, {
...env,
defaultPrivateKey: env.defaultPrivateKey ? '***' : undefined
})

Comment on lines +1 to +15
# @l1network/token.bk

To install dependencies:

```bash
bun install
```

To run:

```bash
bun run index.ts
```

This project was created using `bun init` in bun v1.2.2. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Expand README with actual package information

This appears to be the default README generated by bun init. For an SDK package, it should include information about what the package does, its API, and examples of how to use it.

Consider expanding the README with:

  1. A brief description of what the token.bk SDK does
  2. Installation instructions (already present)
  3. Basic usage examples
  4. API documentation or links to more detailed docs
  5. Any configuration requirements (like required environment variables)

For example:

# @l1network/token.bk

TypeScript SDK for interacting with the token.bk smart contract on Antelope-based blockchains.

## Features

- Create and manage tokens
- Query token information
- Typed contract interfaces

## Installation

```bash
bun install @l1network/token.bk

Configuration

This SDK requires a private key to sign transactions:

export PRIVATE_KEY=your_private_key_here

Usage Examples

import { TokenSDK } from '@l1network/token.bk';

// Initialize the SDK
const sdk = new TokenSDK();

// Create a new token
await sdk.createToken({
  symbol: 'TEST',
  name: 'Test Token',
  decimals: 4,
  supply: '1000.0000'
});

// List all tokens
const tokens = await sdk.listTokens();
console.log(tokens);

<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +9 to +12
if (!privateKey) {
throw new Error('PRIVATE_KEY environment variable is required')
process.exit(1)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix unreachable code after throw statement

The process.exit(1) line will never execute because it's after a throw statement.

if (!privateKey) {
  throw new Error('PRIVATE_KEY environment variable is required')
-  process.exit(1)
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!privateKey) {
throw new Error('PRIVATE_KEY environment variable is required')
process.exit(1)
}
if (!privateKey) {
throw new Error('PRIVATE_KEY environment variable is required')
}

Comment on lines +6 to +9
export const chain = {
id: Checksum256.from('e28174b34639a5ba006265f3641c8ffc1021d65c4cd12fbf242e5c6a6fde6a55'),
url: 'https://api.np.animus.is',
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Hardcoded chain configuration

The chain configuration is hardcoded, making it difficult to use this SDK with different environments.

-export const chain = {
-  id: Checksum256.from('e28174b34639a5ba006265f3641c8ffc1021d65c4cd12fbf242e5c6a6fde6a55'),
-  url: 'https://api.np.animus.is',
-}
+export const defaultChain = {
+  id: Checksum256.from('e28174b34639a5ba006265f3641c8ffc1021d65c4cd12fbf242e5c6a6fde6a55'),
+  url: 'https://api.np.animus.is',
+}
+
+export const configureChain = (id?: string, url?: string) => {
+  return {
+    id: id ? Checksum256.from(id) : defaultChain.id,
+    url: url || defaultChain.url,
+  }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const chain = {
id: Checksum256.from('e28174b34639a5ba006265f3641c8ffc1021d65c4cd12fbf242e5c6a6fde6a55'),
url: 'https://api.np.animus.is',
}
export const defaultChain = {
id: Checksum256.from('e28174b34639a5ba006265f3641c8ffc1021d65c4cd12fbf242e5c6a6fde6a55'),
url: 'https://api.np.animus.is',
}
export const configureChain = (id?: string, url?: string) => {
return {
id: id ? Checksum256.from(id) : defaultChain.id,
url: url || defaultChain.url,
}
}

Comment on lines +17 to +24
export const createSession = async ({ privateKey, permission }: {
privateKey: string
permission?: string
}) => {
const walletPlugin = new WalletPluginPrivateKey(privateKey)
const session = new Session({ chain, permissionLevel: permission, walletPlugin })
return { session }
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update createSession to use configurable chain

export const createSession = async ({ privateKey, permission }: {
  privateKey: string
  permission?: string
+  chainId?: string
+  rpcEndpoint?: string
}) => {
  const walletPlugin = new WalletPluginPrivateKey(privateKey)
-  const session = new Session({ chain, permissionLevel: permission, walletPlugin })
+  const configuredChain = configureChain(chainId, rpcEndpoint)
+  const session = new Session({ chain: configuredChain, permissionLevel: permission, walletPlugin })
  return { session }
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +76 to +82
export interface ActionNameParams {
login: ActionParams.login
migrateaccts: ActionParams.migrateaccts
reg: ActionParams.reg
reset: ActionParams.reset
setrcvrid: ActionParams.setrcvrid
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

❌ Type-mismatch will break compilation

ActionNameParams references ActionParams.migrateaccts and ActionParams.setrcvrid, but these identifiers are not declared in the ActionParams namespace (the declared names are migrate_accounts and set_recovery_id).
This causes a TS error: “Property 'migrateaccts' does not exist on type 'typeof ActionParams'” and blocks the build.

 export interface ActionNameParams {
     login: ActionParams.login
-    migrateaccts: ActionParams.migrateaccts
+    migrateaccts: ActionParams.migrate_accounts
     reg: ActionParams.reg
     reset: ActionParams.reset
-    setrcvrid: ActionParams.setrcvrid
+    setrcvrid: ActionParams.set_recovery_id
 }

If the on-chain action names are migrateaccts / setrcvrid, consider adding type aliases in ActionParams instead, e.g.:

export interface migrateaccts extends migrate_accounts {}
export interface setrcvrid   extends set_recovery_id {}

Comment on lines +80 to +87
debugLog('Pushing transaction', {
action: action.name,
account,
contract: env.oracleContract,
permission,
transaction: Serializer.encode({ object: transaction }).toString('hex').substring(0, 50) + '...'
})

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid leaking sensitive signing data in debug logs

Even behind the env.debug flag, logging a (partial) serialized transaction + signature can reveal
nonce, expiration, and other metadata that might aid replay or phishing attacks,
especially when logs are collected centrally.

-  transaction: Serializer.encode({ object: transaction }).toString('hex').substring(0, 50) + '...'
+  // Only log the action name & trx id to prevent accidental leakage of sensitive data
+  // trx id is safe because it is already broadcast-visible.
+  trx_id: Checksum256.hash(Serializer.encode({object: transaction}))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
debugLog('Pushing transaction', {
action: action.name,
account,
contract: env.oracleContract,
permission,
transaction: Serializer.encode({ object: transaction }).toString('hex').substring(0, 50) + '...'
})
debugLog('Pushing transaction', {
action: action.name,
account,
contract: env.oracleContract,
permission,
// Only log the action name & trx id to prevent accidental leakage of sensitive data
// trx id is safe because it is already broadcast-visible.
trx_id: Checksum256.hash(Serializer.encode({object: transaction}))
})

Comment on lines +799 to +836
export interface ActionNameParams {
addcrptoken: ActionParams.addcrptoken
addforexpair: ActionParams.addforexpair
addpair: ActionParams.addpair
addstbtoken: ActionParams.addstbtoken
buygem: ActionParams.buygem
cancelp2p: ActionParams.cancelp2p
cnlbuygem: ActionParams.cnlbuygem
cnlsellgem: ActionParams.cnlsellgem
confirmp2p: ActionParams.confirmp2p
crptransfer: ActionParams.crptransfer
crpwdllog: ActionParams.crpwdllog
depositlog: ActionParams.depositlog
fillbuygem: ActionParams.fillbuygem
fillsellgem: ActionParams.fillsellgem
forextrade: ActionParams.forextrade
fxtrdlog: ActionParams.fxtrdlog
longtrdlog: ActionParams.longtrdlog
mdfcrptoken: ActionParams.mdfcrptoken
mdfforexpair: ActionParams.mdfforexpair
mdfpair: ActionParams.mdfpair
mgrspotpairs: ActionParams.mgrspotpairs
mgrspotpos: ActionParams.mgrspotpos
mgrstbtkns: ActionParams.mgrstbtkns
pause: ActionParams.pause
sellgem: ActionParams.sellgem
sellp2p: ActionParams.sellp2p
sellp2plog: ActionParams.sellp2plog
setconfig: ActionParams.setconfig
setltvlevel: ActionParams.setltvlevel
setwdlmt: ActionParams.setwdlmt
shorttrdlog: ActionParams.shorttrdlog
stbtransfer: ActionParams.stbtransfer
stbwdllog: ActionParams.stbwdllog
unpause: ActionParams.unpause
withdraw: ActionParams.withdraw
withdrawstbl: ActionParams.withdrawstbl
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Mismatch between ActionNameParams keys and declared ActionParams interfaces breaks type-safety & compilation

ActionNameParams is currently pointing to non-existent members such as ActionParams.addcrptoken, cnlbuygem, withdrawstbl, etc.
The actual interfaces are declared with underscore-separated names (add_crypto_token, cancel_buy_gem, withdraw_stable, …).
Because TypeScript treats these as distinct identifiers, every mapped type in this block is now never, causing:

  • compilation failures (Property 'addcrptoken' does not exist on type 'typeof ActionParams')
  • loss of autocomplete / static guarantees for consumers of Contract.action

Fix by mapping the on-chain (12-char) action names to the correct interface names:

 export interface ActionNameParams {
-    addcrptoken: ActionParams.addcrptoken
-    addforexpair: ActionParams.addforexpair
-    addpair: ActionParams.addpair
-    addstbtoken: ActionParams.addstbtoken
-    buygem: ActionParams.buygem
-    cancelp2p: ActionParams.cancelp2p
-    cnlbuygem: ActionParams.cnlbuygem
-    cnlsellgem: ActionParams.cnlsellgem
+    addcrptoken: ActionParams.add_crypto_token
+    addforexpair: ActionParams.add_forex_pair
+    addpair: ActionParams.add_pair
+    addstbtoken: ActionParams.add_stable_token
+    buygem: ActionParams.buy_gem
+    cancelp2p: ActionParams.cancel_p2p
+    cnlbuygem: ActionParams.cancel_buy_gem
+    cnlsellgem: ActionParams.cancel_sell_gem
@@
-    sellp2p: ActionParams.sellp2p
-    sellp2plog: ActionParams.sellp2plog
-    setconfig: ActionParams.setconfig
-    setltvlevel: ActionParams.setltvlevel
-    setwdlmt: ActionParams.setwdlmt
+    sellp2p: ActionParams.sell_p2p
+    sellp2plog: ActionParams.sell_p2p_log
+    setconfig: ActionParams.set_config
+    setltvlevel: ActionParams.set_ltv_level
+    setwdlmt: ActionParams.set_withdraw_limit
@@
-    withdraw: ActionParams.withdraw
-    withdrawstbl: ActionParams.withdrawstbl
+    withdraw: ActionParams.withdraw
+    withdrawstbl: ActionParams.withdraw_stable
 }

Ensure every remaining key follows the same pattern (e.g. fxtrdlogforex_trade_log, longtrdloglong_trade_log, etc.).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface ActionNameParams {
addcrptoken: ActionParams.addcrptoken
addforexpair: ActionParams.addforexpair
addpair: ActionParams.addpair
addstbtoken: ActionParams.addstbtoken
buygem: ActionParams.buygem
cancelp2p: ActionParams.cancelp2p
cnlbuygem: ActionParams.cnlbuygem
cnlsellgem: ActionParams.cnlsellgem
confirmp2p: ActionParams.confirmp2p
crptransfer: ActionParams.crptransfer
crpwdllog: ActionParams.crpwdllog
depositlog: ActionParams.depositlog
fillbuygem: ActionParams.fillbuygem
fillsellgem: ActionParams.fillsellgem
forextrade: ActionParams.forextrade
fxtrdlog: ActionParams.fxtrdlog
longtrdlog: ActionParams.longtrdlog
mdfcrptoken: ActionParams.mdfcrptoken
mdfforexpair: ActionParams.mdfforexpair
mdfpair: ActionParams.mdfpair
mgrspotpairs: ActionParams.mgrspotpairs
mgrspotpos: ActionParams.mgrspotpos
mgrstbtkns: ActionParams.mgrstbtkns
pause: ActionParams.pause
sellgem: ActionParams.sellgem
sellp2p: ActionParams.sellp2p
sellp2plog: ActionParams.sellp2plog
setconfig: ActionParams.setconfig
setltvlevel: ActionParams.setltvlevel
setwdlmt: ActionParams.setwdlmt
shorttrdlog: ActionParams.shorttrdlog
stbtransfer: ActionParams.stbtransfer
stbwdllog: ActionParams.stbwdllog
unpause: ActionParams.unpause
withdraw: ActionParams.withdraw
withdrawstbl: ActionParams.withdrawstbl
}
export interface ActionNameParams {
addcrptoken: ActionParams.add_crypto_token
addforexpair: ActionParams.add_forex_pair
addpair: ActionParams.add_pair
addstbtoken: ActionParams.add_stable_token
buygem: ActionParams.buy_gem
cancelp2p: ActionParams.cancel_p2p
cnlbuygem: ActionParams.cancel_buy_gem
cnlsellgem: ActionParams.cancel_sell_gem
confirmp2p: ActionParams.confirmp2p
crptransfer: ActionParams.crptransfer
crpwdllog: ActionParams.crpwdllog
depositlog: ActionParams.depositlog
fillbuygem: ActionParams.fillbuygem
fillsellgem: ActionParams.fillsellgem
forextrade: ActionParams.forextrade
fxtrdlog: ActionParams.fxtrdlog
longtrdlog: ActionParams.longtrdlog
mdfcrptoken: ActionParams.mdfcrptoken
mdfforexpair: ActionParams.mdfforexpair
mdfpair: ActionParams.mdfpair
mgrspotpairs: ActionParams.mgrspotpairs
mgrspotpos: ActionParams.mgrspotpos
mgrstbtkns: ActionParams.mgrstbtkns
pause: ActionParams.pause
sellgem: ActionParams.sellgem
sellp2p: ActionParams.sell_p2p
sellp2plog: ActionParams.sell_p2p_log
setconfig: ActionParams.set_config
setltvlevel: ActionParams.set_ltv_level
setwdlmt: ActionParams.set_withdraw_limit
shorttrdlog: ActionParams.shorttrdlog
stbtransfer: ActionParams.stbtransfer
stbwdllog: ActionParams.stbwdllog
unpause: ActionParams.unpause
withdraw: ActionParams.withdraw
withdrawstbl: ActionParams.withdraw_stable
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant