From 3f10aacb723f814918ffae7ed371ad4b35da9a02 Mon Sep 17 00:00:00 2001 From: HermanL02 Date: Mon, 5 May 2025 22:51:21 -0300 Subject: [PATCH] chore: apply prettier --- worker/README.md | 52 +- worker/config-task-prod.yml | 260 +-- worker/config-task-test.yml | 260 +-- worker/jest.config.js | 11 +- worker/src/task/1-task.ts | 3 +- worker/src/task/2-submission.ts | 45 +- worker/src/task/3-audit.ts | 2 +- worker/src/task/5-routes.ts | 4 +- worker/src/utils/check/anthropicCheck.ts | 29 +- worker/src/utils/check/checks.ts | 6 +- worker/src/utils/check/githubCheck.ts | 64 +- worker/src/utils/constant.ts | 2 +- worker/src/utils/existingIssues.ts | 160 +- worker/src/utils/leader.ts | 8 +- .../utils/submissionJSONSignatureDecode.ts | 77 +- worker/src/utils/task/task.ts | 192 +- worker/tests/README.md | 5 + worker/tests/config.ts | 10 +- worker/tests/main.test.ts | 376 ++-- worker/tests/simulateTask.ts | 168 +- worker/tests/test.ts | 4 +- worker/tests/wasm/bincode_js.cjs | 1961 +++++++++-------- worker/tests/wasm/bincode_js.d.ts | 364 +-- worker/tests/wasm/bincode_js_bg.wasm.d.ts | 30 +- worker/tests/webpack.config.js | 62 +- worker/webpack.config.mjs | 22 +- 26 files changed, 2126 insertions(+), 2051 deletions(-) diff --git a/worker/README.md b/worker/README.md index d24385c..df2ed5f 100644 --- a/worker/README.md +++ b/worker/README.md @@ -1,26 +1,26 @@ -# Earn Crypto with AI Agents: Prometheus Document & Summarize Task (Beta v0) - -## Overview - -The **Prometheus Document & Summarize Task** spins up an **AI agent** capable of continuously summarizing repositories, **earning you KOII**. Automated document summarization agents can constantly process and summarize information, increasing the value of the network _and_ your node. Our ultimate goal is to have **AI agents summarizing Koii tasks**, growing the network with **more opportunities for node operators to earn rewards**. - -## Releases - -### Beta v0 - -- This is the **first beta release** of the task. -- The AI agent reads documents and generates summaries automatically. -- Documentations are sent to the user repository. -- Future versions will introduce **enhanced AI logic, more complex summarization tasks, and more!** - -## Task Setup - -**[How to set up a Claude API key and a GitHub API key for the 247 Document & Summarize Task.](https://www.koii.network/blog/Earn-Crypto-With-AI-Agent)** - -## How It Works - -1. The Koii Node **launches an AI agent** inside a lightweight runtime. -2. The agent reads an active **repository list** from the bounty repository. -3. It picks a **repository**, generates the necessary **documentation**, and submits a **Github pull request** (a request to have its documentation added to the repository). -4. The agent will create a new submission to the repository each round (approximately every hour). -5. Koii Nodes **earn rewards** for running the AI agent and contributing documentation. \ No newline at end of file +# Earn Crypto with AI Agents: Prometheus Document & Summarize Task (Beta v0) + +## Overview + +The **Prometheus Document & Summarize Task** spins up an **AI agent** capable of continuously summarizing repositories, **earning you KOII**. Automated document summarization agents can constantly process and summarize information, increasing the value of the network _and_ your node. Our ultimate goal is to have **AI agents summarizing Koii tasks**, growing the network with **more opportunities for node operators to earn rewards**. + +## Releases + +### Beta v0 + +- This is the **first beta release** of the task. +- The AI agent reads documents and generates summaries automatically. +- Documentations are sent to the user repository. +- Future versions will introduce **enhanced AI logic, more complex summarization tasks, and more!** + +## Task Setup + +**[How to set up a Claude API key and a GitHub API key for the 247 Document & Summarize Task.](https://www.koii.network/blog/Earn-Crypto-With-AI-Agent)** + +## How It Works + +1. The Koii Node **launches an AI agent** inside a lightweight runtime. +2. The agent reads an active **repository list** from the bounty repository. +3. It picks a **repository**, generates the necessary **documentation**, and submits a **Github pull request** (a request to have its documentation added to the repository). +4. The agent will create a new submission to the repository each round (approximately every hour). +5. Koii Nodes **earn rewards** for running the AI agent and contributing documentation. diff --git a/worker/config-task-prod.yml b/worker/config-task-prod.yml index bb569fc..aa88e24 100644 --- a/worker/config-task-prod.yml +++ b/worker/config-task-prod.yml @@ -1,130 +1,130 @@ -######################## ALL FIELDS ARE REQUIRED UNLESS OTHERWISE NOTED ######################### - -######################################### TASK METADATA ######################################### -############################ Will be displayed in the desktop node ############################## - -## Task Name ## -# Maximum 24 characters. -task_name: "Prometheus Docs Agent" - -## Task Author ## -author: "Prometheus" - -# Task Description Markdown ## -# If you specify a markdown file, the description field will be ignored. -# Markdown is recommended for better formatting. -markdownDescriptionPath: "./README.md" - -## Task Description ## -# Ignored if you specify a markdown file. -description: "Task description." - -## Repository URL ## -# Must be public for whitelisted tasks. -repositoryUrl: "https://github.com/koii-network/builder-247" - -## Image URL ## -# 230x86 pixels. -imageUrl: "https://koii-k2-task-metadata.s3.us-east-2.amazonaws.com/Docs.png" - -## Info URL ## -infoUrl: "https://www.koii.network/blog/Earn-Crypto-With-AI-Agent" - -####################################### TASK CONFIGURATION ###################################### - -## Task Executable Network ## -# IPFS or DEVELOPMENT -# Keep this as IPFS unless you know you need to change it. -task_executable_network: "IPFS" - -## Task Audit Program ## -# Task Executable Network IPFS: Path to your executable. -# Task Executable Network DEVELOPMENT: The value should be 'main'. -# Keep this as-is unless you know you need to change it. -task_audit_program: "dist/main.js" - -## Round Time ## -# Duration of task, measured in slots (with each slot approximately equal to 408ms). Should be at least 800 slots. -# See https://www.koii.network/docs/concepts/what-are-tasks/what-are-tasks/gradual-consensus for more information on how round time, audit window, and submission window work. -round_time: 3000 - -## Audit Window ## -# The audit window should be at least 1/3 of the round time. -audit_window: 1300 - -## Submission Window ## -# The submission window should be at least 1/3 of the round time. -submission_window: 1300 - -## Minimum Stake Amount ## -# The minimum amount of KOII or KPL that a user must stake in order to participate in the task. -minimum_stake_amount: 0.01 - -## Task Bounty Type ## -# KOII or KPL -task_type: "KOII" - -## Token Mint Address (ONLY for KPL tasks) ## -# The Fire Token address is provided as an example. -token_type: "4qayyw53kWz6GzypcejjT1cvwMXS1qYLSMQRE8se3gTv" - -## Total Bounty Amount ## -# The total bounty amount that will be available for distribution over all rounds. -# Does nothing when updating a task. -total_bounty_amount: 12000 - -## Bounty Amount per Round ## -# The maximum amount that can be distributed per round. -# If the actual distribution per round exceeds this amount, the distribution list will fail. -bounty_amount_per_round: 2001 - -## Allowed Failed Distributions ## -# Number of retries allowed for the distribution list if it is fails audit. -# If all retries fail, the task will not distribute anything for the round. -# This is also the number of rounds of submissions it will keep. -allowed_failed_distributions: 8 - -## Space ## -# Expected Task Data Size in MBs for the account size. -# Minimums: 2 for whitelisted tasks, 1 for production, 0.1 for testing. -# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#space for calculation details. -space: 5 - -## Requirement Tags (Optional) ## -# To add more global variables and task variables, please refer to the type, value, description format shown below. -# The ORCA_TASK addon is REQUIRED -requirementsTags: - - type: ADDON - value: "ORCA_TASK" - - type: CPU - value: "4-core" - - type: RAM - value: "5 GB" - - type: STORAGE - value: "5 GB" - - type: TASK_VARIABLE - value: "ANTHROPIC_API_KEY" - description: "Your Anthropic API key. You can get one here: https://console.anthropic.com/settings/keys" - - type: TASK_VARIABLE - value: "GITHUB_USERNAME" - description: "Your GitHub username. You can sign up for an account here: https://github.com/join" - - type: TASK_VARIABLE - value: "GITHUB_TOKEN" - description: "Your GitHub Personal Access Token. You can create one here: https://github.com/settings/tokens" - -## Tags ## -# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#tags for available tag options. -tags: ["AI"] - -# Environment ## -# TEST or PRODUCTION -# Production mode will expose your task to all the task runners, even if not whitelisted. -environment: "TEST" - -#################################### FOR UPDATING TASKS ONLY #################################### - -## Old Task ID ## -task_id: "5bc74eTjGgNigupFBZXtfzAYVksPqSGBEVgRLubk7ak7" - -## Migration Description ## -migrationDescription: "Log Reminder, Time Based Logic" +######################## ALL FIELDS ARE REQUIRED UNLESS OTHERWISE NOTED ######################### + +######################################### TASK METADATA ######################################### +############################ Will be displayed in the desktop node ############################## + +## Task Name ## +# Maximum 24 characters. +task_name: "Prometheus Docs Agent" + +## Task Author ## +author: "Prometheus" + +# Task Description Markdown ## +# If you specify a markdown file, the description field will be ignored. +# Markdown is recommended for better formatting. +markdownDescriptionPath: "./README.md" + +## Task Description ## +# Ignored if you specify a markdown file. +description: "Task description." + +## Repository URL ## +# Must be public for whitelisted tasks. +repositoryUrl: "https://github.com/koii-network/builder-247" + +## Image URL ## +# 230x86 pixels. +imageUrl: "https://koii-k2-task-metadata.s3.us-east-2.amazonaws.com/Docs.png" + +## Info URL ## +infoUrl: "https://www.koii.network/blog/Earn-Crypto-With-AI-Agent" + +####################################### TASK CONFIGURATION ###################################### + +## Task Executable Network ## +# IPFS or DEVELOPMENT +# Keep this as IPFS unless you know you need to change it. +task_executable_network: "IPFS" + +## Task Audit Program ## +# Task Executable Network IPFS: Path to your executable. +# Task Executable Network DEVELOPMENT: The value should be 'main'. +# Keep this as-is unless you know you need to change it. +task_audit_program: "dist/main.js" + +## Round Time ## +# Duration of task, measured in slots (with each slot approximately equal to 408ms). Should be at least 800 slots. +# See https://www.koii.network/docs/concepts/what-are-tasks/what-are-tasks/gradual-consensus for more information on how round time, audit window, and submission window work. +round_time: 3000 + +## Audit Window ## +# The audit window should be at least 1/3 of the round time. +audit_window: 1300 + +## Submission Window ## +# The submission window should be at least 1/3 of the round time. +submission_window: 1300 + +## Minimum Stake Amount ## +# The minimum amount of KOII or KPL that a user must stake in order to participate in the task. +minimum_stake_amount: 0.01 + +## Task Bounty Type ## +# KOII or KPL +task_type: "KOII" + +## Token Mint Address (ONLY for KPL tasks) ## +# The Fire Token address is provided as an example. +token_type: "4qayyw53kWz6GzypcejjT1cvwMXS1qYLSMQRE8se3gTv" + +## Total Bounty Amount ## +# The total bounty amount that will be available for distribution over all rounds. +# Does nothing when updating a task. +total_bounty_amount: 12000 + +## Bounty Amount per Round ## +# The maximum amount that can be distributed per round. +# If the actual distribution per round exceeds this amount, the distribution list will fail. +bounty_amount_per_round: 2001 + +## Allowed Failed Distributions ## +# Number of retries allowed for the distribution list if it is fails audit. +# If all retries fail, the task will not distribute anything for the round. +# This is also the number of rounds of submissions it will keep. +allowed_failed_distributions: 8 + +## Space ## +# Expected Task Data Size in MBs for the account size. +# Minimums: 2 for whitelisted tasks, 1 for production, 0.1 for testing. +# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#space for calculation details. +space: 5 + +## Requirement Tags (Optional) ## +# To add more global variables and task variables, please refer to the type, value, description format shown below. +# The ORCA_TASK addon is REQUIRED +requirementsTags: + - type: ADDON + value: "ORCA_TASK" + - type: CPU + value: "4-core" + - type: RAM + value: "5 GB" + - type: STORAGE + value: "5 GB" + - type: TASK_VARIABLE + value: "ANTHROPIC_API_KEY" + description: "Your Anthropic API key. You can get one here: https://console.anthropic.com/settings/keys" + - type: TASK_VARIABLE + value: "GITHUB_USERNAME" + description: "Your GitHub username. You can sign up for an account here: https://github.com/join" + - type: TASK_VARIABLE + value: "GITHUB_TOKEN" + description: "Your GitHub Personal Access Token. You can create one here: https://github.com/settings/tokens" + +## Tags ## +# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#tags for available tag options. +tags: ["AI"] + +# Environment ## +# TEST or PRODUCTION +# Production mode will expose your task to all the task runners, even if not whitelisted. +environment: "TEST" + +#################################### FOR UPDATING TASKS ONLY #################################### + +## Old Task ID ## +task_id: "5bc74eTjGgNigupFBZXtfzAYVksPqSGBEVgRLubk7ak7" + +## Migration Description ## +migrationDescription: "Log Reminder, Time Based Logic" diff --git a/worker/config-task-test.yml b/worker/config-task-test.yml index 1c6bfea..70cbb42 100644 --- a/worker/config-task-test.yml +++ b/worker/config-task-test.yml @@ -1,130 +1,130 @@ -######################## ALL FIELDS ARE REQUIRED UNLESS OTHERWISE NOTED ######################### - -######################################### TASK METADATA ######################################### -############################ Will be displayed in the desktop node ############################## - -## Task Name ## -# Maximum 24 characters. -task_name: "Prometheus Docs Agent" - -## Task Author ## -author: "Prometheus" - -# Task Description Markdown ## -# If you specify a markdown file, the description field will be ignored. -# Markdown is recommended for better formatting. -markdownDescriptionPath: "./README.md" - -## Task Description ## -# Ignored if you specify a markdown file. -description: "Task description." - -## Repository URL ## -# Must be public for whitelisted tasks. -repositoryUrl: "https://github.com/koii-network/builder-247" - -## Image URL ## -# 230x86 pixels. -imageUrl: "https://koii-k2-task-metadata.s3.us-east-2.amazonaws.com/Docs.png" - -## Info URL ## -infoUrl: "https://www.koii.network/blog/Earn-Crypto-With-AI-Agent" - -####################################### TASK CONFIGURATION ###################################### - -## Task Executable Network ## -# IPFS or DEVELOPMENT -# Keep this as IPFS unless you know you need to change it. -task_executable_network: "IPFS" - -## Task Audit Program ## -# Task Executable Network IPFS: Path to your executable. -# Task Executable Network DEVELOPMENT: The value should be 'main'. -# Keep this as-is unless you know you need to change it. -task_audit_program: "dist/main.js" - -## Round Time ## -# Duration of task, measured in slots (with each slot approximately equal to 408ms). Should be at least 800 slots. -# See https://www.koii.network/docs/concepts/what-are-tasks/what-are-tasks/gradual-consensus for more information on how round time, audit window, and submission window work. -round_time: 3000 - -## Audit Window ## -# The audit window should be at least 1/3 of the round time. -audit_window: 1300 - -## Submission Window ## -# The submission window should be at least 1/3 of the round time. -submission_window: 1300 - -## Minimum Stake Amount ## -# The minimum amount of KOII or KPL that a user must stake in order to participate in the task. -minimum_stake_amount: 0.01 - -## Task Bounty Type ## -# KOII or KPL -task_type: "KOII" - -## Token Mint Address (ONLY for KPL tasks) ## -# The Fire Token address is provided as an example. -token_type: "4qayyw53kWz6GzypcejjT1cvwMXS1qYLSMQRE8se3gTv" - -## Total Bounty Amount ## -# The total bounty amount that will be available for distribution over all rounds. -# Does nothing when updating a task. -total_bounty_amount: 11 - -## Bounty Amount per Round ## -# The maximum amount that can be distributed per round. -# If the actual distribution per round exceeds this amount, the distribution list will fail. -bounty_amount_per_round: 1 - -## Allowed Failed Distributions ## -# Number of retries allowed for the distribution list if it is fails audit. -# If all retries fail, the task will not distribute anything for the round. -# This is also the number of rounds of submissions it will keep. -allowed_failed_distributions: 8 - -## Space ## -# Expected Task Data Size in MBs for the account size. -# Minimums: 2 for whitelisted tasks, 1 for production, 0.1 for testing. -# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#space for calculation details. -space: 0.1 - -## Requirement Tags (Optional) ## -# To add more global variables and task variables, please refer to the type, value, description format shown below. -# The ORCA_TASK addon is REQUIRED -requirementsTags: - - type: ADDON - value: "ORCA_TASK" - - type: CPU - value: "4-core" - - type: RAM - value: "5 GB" - - type: STORAGE - value: "5 GB" - - type: TASK_VARIABLE - value: "ANTHROPIC_API_KEY" - description: "Your Anthropic API key. You can get one here: https://console.anthropic.com/settings/keys" - - type: TASK_VARIABLE - value: "GITHUB_USERNAME" - description: "Your GitHub username. You can sign up for an account here: https://github.com/join" - - type: TASK_VARIABLE - value: "GITHUB_TOKEN" - description: "Your GitHub Personal Access Token. You can create one here: https://github.com/settings/tokens" - -## Tags ## -# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#tags for available tag options. -tags: ["AI"] - -# Environment ## -# TEST or PRODUCTION -# Production mode will expose your task to all the task runners, even if not whitelisted. -environment: "TEST" - -#################################### FOR UPDATING TASKS ONLY #################################### - -## Old Task ID ## -task_id: "48h3f4r3AR7MdgCMkET4v3yh7PpPHuqGDWzqgH52rny1" - -## Migration Description ## -migrationDescription: "Fix audit bug" +######################## ALL FIELDS ARE REQUIRED UNLESS OTHERWISE NOTED ######################### + +######################################### TASK METADATA ######################################### +############################ Will be displayed in the desktop node ############################## + +## Task Name ## +# Maximum 24 characters. +task_name: "Prometheus Docs Agent" + +## Task Author ## +author: "Prometheus" + +# Task Description Markdown ## +# If you specify a markdown file, the description field will be ignored. +# Markdown is recommended for better formatting. +markdownDescriptionPath: "./README.md" + +## Task Description ## +# Ignored if you specify a markdown file. +description: "Task description." + +## Repository URL ## +# Must be public for whitelisted tasks. +repositoryUrl: "https://github.com/koii-network/builder-247" + +## Image URL ## +# 230x86 pixels. +imageUrl: "https://koii-k2-task-metadata.s3.us-east-2.amazonaws.com/Docs.png" + +## Info URL ## +infoUrl: "https://www.koii.network/blog/Earn-Crypto-With-AI-Agent" + +####################################### TASK CONFIGURATION ###################################### + +## Task Executable Network ## +# IPFS or DEVELOPMENT +# Keep this as IPFS unless you know you need to change it. +task_executable_network: "IPFS" + +## Task Audit Program ## +# Task Executable Network IPFS: Path to your executable. +# Task Executable Network DEVELOPMENT: The value should be 'main'. +# Keep this as-is unless you know you need to change it. +task_audit_program: "dist/main.js" + +## Round Time ## +# Duration of task, measured in slots (with each slot approximately equal to 408ms). Should be at least 800 slots. +# See https://www.koii.network/docs/concepts/what-are-tasks/what-are-tasks/gradual-consensus for more information on how round time, audit window, and submission window work. +round_time: 3000 + +## Audit Window ## +# The audit window should be at least 1/3 of the round time. +audit_window: 1300 + +## Submission Window ## +# The submission window should be at least 1/3 of the round time. +submission_window: 1300 + +## Minimum Stake Amount ## +# The minimum amount of KOII or KPL that a user must stake in order to participate in the task. +minimum_stake_amount: 0.01 + +## Task Bounty Type ## +# KOII or KPL +task_type: "KOII" + +## Token Mint Address (ONLY for KPL tasks) ## +# The Fire Token address is provided as an example. +token_type: "4qayyw53kWz6GzypcejjT1cvwMXS1qYLSMQRE8se3gTv" + +## Total Bounty Amount ## +# The total bounty amount that will be available for distribution over all rounds. +# Does nothing when updating a task. +total_bounty_amount: 11 + +## Bounty Amount per Round ## +# The maximum amount that can be distributed per round. +# If the actual distribution per round exceeds this amount, the distribution list will fail. +bounty_amount_per_round: 1 + +## Allowed Failed Distributions ## +# Number of retries allowed for the distribution list if it is fails audit. +# If all retries fail, the task will not distribute anything for the round. +# This is also the number of rounds of submissions it will keep. +allowed_failed_distributions: 8 + +## Space ## +# Expected Task Data Size in MBs for the account size. +# Minimums: 2 for whitelisted tasks, 1 for production, 0.1 for testing. +# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#space for calculation details. +space: 0.1 + +## Requirement Tags (Optional) ## +# To add more global variables and task variables, please refer to the type, value, description format shown below. +# The ORCA_TASK addon is REQUIRED +requirementsTags: + - type: ADDON + value: "ORCA_TASK" + - type: CPU + value: "4-core" + - type: RAM + value: "5 GB" + - type: STORAGE + value: "5 GB" + - type: TASK_VARIABLE + value: "ANTHROPIC_API_KEY" + description: "Your Anthropic API key. You can get one here: https://console.anthropic.com/settings/keys" + - type: TASK_VARIABLE + value: "GITHUB_USERNAME" + description: "Your GitHub username. You can sign up for an account here: https://github.com/join" + - type: TASK_VARIABLE + value: "GITHUB_TOKEN" + description: "Your GitHub Personal Access Token. You can create one here: https://github.com/settings/tokens" + +## Tags ## +# See https://www.koii.network/docs/develop/command-line-tool/create-task-cli/create-task#tags for available tag options. +tags: ["AI"] + +# Environment ## +# TEST or PRODUCTION +# Production mode will expose your task to all the task runners, even if not whitelisted. +environment: "TEST" + +#################################### FOR UPDATING TASKS ONLY #################################### + +## Old Task ID ## +task_id: "48h3f4r3AR7MdgCMkET4v3yh7PpPHuqGDWzqgH52rny1" + +## Migration Description ## +migrationDescription: "Fix audit bug" diff --git a/worker/jest.config.js b/worker/jest.config.js index ff3592e..ce35bbc 100644 --- a/worker/jest.config.js +++ b/worker/jest.config.js @@ -1,7 +1,6 @@ export default { - transform: { "^.+\\.tsx?$": "babel-jest" }, - transformIgnorePatterns: ["/node_modules/(?!@babel/runtime)"], - moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], - testEnvironment: "node", - }; - \ No newline at end of file + transform: { "^.+\\.tsx?$": "babel-jest" }, + transformIgnorePatterns: ["/node_modules/(?!@babel/runtime)"], + moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], + testEnvironment: "node", +}; diff --git a/worker/src/task/1-task.ts b/worker/src/task/1-task.ts index f97d00a..fa15bf6 100644 --- a/worker/src/task/1-task.ts +++ b/worker/src/task/1-task.ts @@ -21,7 +21,6 @@ export async function task(roundNumber: number): Promise { // FORCE TO PAUSE 30 SECONDS // No submission on Round 0 so no need to trigger fetch audit result before round 3 // Changed from 3 to 4 to have more time - // if (roundNumber >= 4) { // const auditRound = roundNumber - 4; // const response = await fetch(`${middleServerUrl}/summarizer/worker/update-audit-result`, { @@ -32,4 +31,4 @@ export async function task(roundNumber: number): Promise { // console.log(`[TASK] Fetched audit result for round ${auditRound}. Status: ${response.status}`); // } // console.log(`[TASK] EXECUTE TASK FOR ROUND ${roundNumber}`); -} \ No newline at end of file +} diff --git a/worker/src/task/2-submission.ts b/worker/src/task/2-submission.ts index d03a868..938742b 100644 --- a/worker/src/task/2-submission.ts +++ b/worker/src/task/2-submission.ts @@ -24,7 +24,7 @@ export async function submission(roundNumber: number): Promise { * The default implementation handles uploading the proofs to IPFS * and returning the CID */ - if(!await preRunCheck(roundNumber.toString())){ + if (!(await preRunCheck(roundNumber.toString()))) { return; } const stakingKeypair = await namespaceWrapper.getSubmitterAccount(); @@ -34,14 +34,14 @@ export async function submission(roundNumber: number): Promise { throw new Error("No staking keypair or public key found"); } const stakingKey = stakingKeypair.publicKey.toBase58(); - + const secretKey = stakingKeypair.secretKey; console.log(`[SUBMISSION] Starting submission process for round ${roundNumber}`); try { const orcaClient = await initializeOrcaClient(); const shouldMakeSubmission = await namespaceWrapper.storeGet(`shouldMakeSubmission`); - + if (!shouldMakeSubmission || shouldMakeSubmission !== "true") { return; } @@ -51,7 +51,7 @@ export async function submission(roundNumber: number): Promise { roundNumber, stakingKey, publicKey: pubKey, - secretKey + secretKey, }); return cid || void 0; @@ -64,19 +64,19 @@ export async function submission(roundNumber: number): Promise { async function initializeOrcaClient() { console.log("[SUBMISSION] Initializing Orca client..."); const orcaClient = await getOrcaClient(); - + if (!orcaClient) { console.error("[SUBMISSION] Failed to initialize Orca client"); throw new Error("Failed to initialize Orca client"); } - + console.log("[SUBMISSION] Orca client initialized successfully"); return orcaClient; } async function makeSubmission(params: SubmissionParams): Promise { const { orcaClient, roundNumber, stakingKey, publicKey, secretKey } = params; - + const swarmBountyId = await namespaceWrapper.storeGet(`swarmBountyId`); if (!swarmBountyId) { console.log("[SUBMISSION] No swarm bounty id found for this round"); @@ -94,35 +94,36 @@ async function makeSubmission(params: SubmissionParams): Promise prUrl: submissionData.prUrl, stakingKey, publicKey, - secretKey + secretKey, }); - const signature = await signSubmissionPayload({ - taskId: TASK_ID, - roundNumber, - stakingKey, - pubKey: publicKey, - ...submissionData - }, secretKey); + const signature = await signSubmissionPayload( + { + taskId: TASK_ID, + roundNumber, + stakingKey, + pubKey: publicKey, + ...submissionData, + }, + secretKey, + ); const cid = await storeSubmissionOnIPFS(signature); await cleanupSubmissionState(); - + return cid; } async function fetchSubmissionData(orcaClient: any, swarmBountyId: string): Promise { console.log(`[SUBMISSION] Fetching submission data for swarm bounty ${swarmBountyId}`); const result = await orcaClient.podCall(`submission/${swarmBountyId}`); - + if (!result || result.data === "No submission") { console.log("[SUBMISSION] No existing submission found"); return null; } - const submission = typeof result.data === 'object' && 'data' in result.data - ? result.data.data - : result.data; + const submission = typeof result.data === "object" && "data" in result.data ? result.data.data : result.data; if (!submission?.prUrl) { throw new Error("Submission is missing PR URL"); @@ -140,7 +141,7 @@ async function notifyMiddleServer(params: { secretKey: Uint8Array; }) { const { taskId, swarmBountyId, prUrl, stakingKey, publicKey, secretKey } = params; - + const payload = { taskId, swarmBountyId, @@ -184,4 +185,4 @@ async function storeSubmissionOnIPFS(signature: string): Promise { async function cleanupSubmissionState(): Promise { await namespaceWrapper.storeSet(`shouldMakeSubmission`, "false"); await namespaceWrapper.storeSet(`swarmBountyId`, ""); -} \ No newline at end of file +} diff --git a/worker/src/task/3-audit.ts b/worker/src/task/3-audit.ts index d5d180d..796441b 100644 --- a/worker/src/task/3-audit.ts +++ b/worker/src/task/3-audit.ts @@ -82,4 +82,4 @@ export async function audit(cid: string, roundNumber: number, submitterKey: stri // When Error---NO RETURN; // return true; } -} \ No newline at end of file +} diff --git a/worker/src/task/5-routes.ts b/worker/src/task/5-routes.ts index 7c61d42..bee1f53 100644 --- a/worker/src/task/5-routes.ts +++ b/worker/src/task/5-routes.ts @@ -14,7 +14,6 @@ import { middleServerUrl, status } from "../utils/constant"; //Example route export async function routes() { - app.get("/value", async (_req, res) => { const value = await namespaceWrapper.storeGet("value"); console.log("value", value); @@ -64,7 +63,7 @@ export async function routes() { const message = req.body.message; console.log("[TASK] req.body", req.body); try { - if (!success){ + if (!success) { console.error("[TASK] Error summarizing repository:", message); return; } @@ -128,7 +127,6 @@ export async function routes() { }); } - // TODO: To be completed app.post("/failed-task", async (req, res) => { res.status(200).json({ result: "Successfully saved task result" }); diff --git a/worker/src/utils/check/anthropicCheck.ts b/worker/src/utils/check/anthropicCheck.ts index 0cc627a..124f365 100644 --- a/worker/src/utils/check/anthropicCheck.ts +++ b/worker/src/utils/check/anthropicCheck.ts @@ -1,36 +1,35 @@ export function isValidAnthropicApiKey(key: string) { - const regex = /^sk-ant-[a-zA-Z0-9_-]{32,}$/; - return regex.test(key); + const regex = /^sk-ant-[a-zA-Z0-9_-]{32,}$/; + return regex.test(key); } export async function checkAnthropicAPIKey(apiKey: string) { - const response = await fetch('https://api.anthropic.com/v1/messages', { - method: 'POST', + const response = await fetch("https://api.anthropic.com/v1/messages", { + method: "POST", headers: { - 'x-api-key': apiKey, - 'anthropic-version': '2023-06-01', - 'content-type': 'application/json', + "x-api-key": apiKey, + "anthropic-version": "2023-06-01", + "content-type": "application/json", }, body: JSON.stringify({ - model: 'claude-3-opus-20240229', // or a cheaper model + model: "claude-3-opus-20240229", // or a cheaper model max_tokens: 1, // minimal usage - messages: [{ role: 'user', content: 'Hi' }], + messages: [{ role: "user", content: "Hi" }], }), }); if (response.status === 200) { - console.log('✅ API key is valid and has credit.'); + console.log("✅ API key is valid and has credit."); return true; } else { const data = await response.json().catch(() => ({})); if (response.status === 401) { - console.log('❌ Invalid API key.'); - } else if (response.status === 403 && data.error?.message?.includes('billing')) { - console.log('❌ API key has no credit or is not authorized.'); + console.log("❌ Invalid API key."); + } else if (response.status === 403 && data.error?.message?.includes("billing")) { + console.log("❌ API key has no credit or is not authorized."); } else { - console.log('⚠️ Unexpected error:', data); + console.log("⚠️ Unexpected error:", data); } return false; } } - diff --git a/worker/src/utils/check/checks.ts b/worker/src/utils/check/checks.ts index 7d3a8c7..7bd9f98 100644 --- a/worker/src/utils/check/checks.ts +++ b/worker/src/utils/check/checks.ts @@ -5,8 +5,8 @@ import { LogLevel } from "@_koii/namespace-wrapper/dist/types"; import { errorMessage, actionMessage, status } from "../constant"; import { checkAnthropicAPIKey } from "./anthropicCheck"; import { checkGitHub } from "./githubCheck"; -export async function preRunCheck(roundNumber:string){ -if (!process.env.ANTHROPIC_API_KEY) { +export async function preRunCheck(roundNumber: string) { + if (!process.env.ANTHROPIC_API_KEY) { await namespaceWrapper.logMessage( LogLevel.Error, errorMessage.ANTHROPIC_API_KEY_INVALID, @@ -54,4 +54,4 @@ if (!process.env.ANTHROPIC_API_KEY) { return false; } return true; -} \ No newline at end of file +} diff --git a/worker/src/utils/check/githubCheck.ts b/worker/src/utils/check/githubCheck.ts index 84ea624..6d14fff 100644 --- a/worker/src/utils/check/githubCheck.ts +++ b/worker/src/utils/check/githubCheck.ts @@ -1,36 +1,36 @@ export async function checkGitHub(username: string, token: string) { - // 1. Check username - const userRes = await fetch(`https://api.github.com/users/${username}`); - const isUsernameValid = userRes.status === 200; - - // 2. Check token - const tokenRes = await fetch('https://api.github.com/user', { - headers: { - Authorization: `token ${token}`, - }, - }); - const isTokenValid = tokenRes.status === 200; - const isIdentityValid = await checkGitHubIdentity(username, token); - return isIdentityValid&&isUsernameValid&&isTokenValid + // 1. Check username + const userRes = await fetch(`https://api.github.com/users/${username}`); + const isUsernameValid = userRes.status === 200; + + // 2. Check token + const tokenRes = await fetch("https://api.github.com/user", { + headers: { + Authorization: `token ${token}`, + }, + }); + const isTokenValid = tokenRes.status === 200; + const isIdentityValid = await checkGitHubIdentity(username, token); + return isIdentityValid && isUsernameValid && isTokenValid; } async function checkGitHubIdentity(username: string, token: string) { - const res = await fetch('https://api.github.com/user', { - headers: { - Authorization: `token ${token}`, - Accept: 'application/vnd.github.v3+json', - }, - }); - - if (res.status !== 200) { - return false - } - - const data = await res.json(); - - if (data.login.toLowerCase() !== username.toLowerCase()) { - return false - } - - return true -} \ No newline at end of file + const res = await fetch("https://api.github.com/user", { + headers: { + Authorization: `token ${token}`, + Accept: "application/vnd.github.v3+json", + }, + }); + + if (res.status !== 200) { + return false; + } + + const data = await res.json(); + + if (data.login.toLowerCase() !== username.toLowerCase()) { + return false; + } + + return true; +} diff --git a/worker/src/utils/constant.ts b/worker/src/utils/constant.ts index a97d70c..8456abe 100644 --- a/worker/src/utils/constant.ts +++ b/worker/src/utils/constant.ts @@ -59,4 +59,4 @@ export const defaultBountyMarkdownFile = export const customReward = 400 * 10 ** 9; // This should be in ROE! -export const middleServerUrl = "https://builder247-prod.dev.koii.network"; \ No newline at end of file +export const middleServerUrl = "https://builder247-prod.dev.koii.network"; diff --git a/worker/src/utils/existingIssues.ts b/worker/src/utils/existingIssues.ts index 3101d3e..095b770 100644 --- a/worker/src/utils/existingIssues.ts +++ b/worker/src/utils/existingIssues.ts @@ -12,90 +12,90 @@ interface BountyIssue { } export async function getExistingIssues(): Promise { - try { - // read from the bounty markdown file + try { + // read from the bounty markdown file // console.log('Fetching markdown file from:', defaultBountyMarkdownFile); - const bountyMarkdownFile = await fetch(defaultBountyMarkdownFile); - const bountyMarkdownFileText = await bountyMarkdownFile.text(); - - // console.log('Raw markdown content:', bountyMarkdownFileText); - - const bountyMarkdownFileLines = bountyMarkdownFileText.split("\n"); - // console.log('Number of lines:', bountyMarkdownFileLines.length); - - const issues: BountyIssue[] = []; - let isTableStarted = false; - - for (const line of bountyMarkdownFileLines) { - // Skip empty lines - if (line.trim() === '') { - // console.log('Skipping empty line'); - continue; - } - - // console.log('Processing line:', line); - - // Skip the title line starting with # - if (line.startsWith('#')) { - // console.log('Found title line:', line); - continue; - } - - // Skip the header and separator lines - if (line.startsWith('|') && line.includes('GitHub URL')) { - //console.log('Found header line'); - continue; - } - if (line.startsWith('|') && line.includes('-----')) { - // console.log('Found separator line'); - continue; - } - - // Process table rows - if (line.startsWith('|')) { - isTableStarted = true; - // Remove first and last | and split by | - const cells = line.slice(1, -1).split('|').map(cell => cell.trim()); - // console.log('Parsed cells:', cells); - - // Extract GitHub URL and name from markdown link format [name](url) - const githubUrlMatch = cells[0].match(/\[(.*?)\]\((.*?)\)/); - // console.log('GitHub URL match:', githubUrlMatch); - - const projectName = githubUrlMatch ? githubUrlMatch[1] : ''; - const githubUrl = githubUrlMatch ? githubUrlMatch[2] : ''; - - const issue: BountyIssue = { - githubUrl, - projectName, - bountyTask: cells[1], - description: cells[3], - bountyAmount: cells[4], - bountyType: cells[5], - transactionHash: cells[6], - status: cells[7] - }; - - // console.log('Created issue object:', issue); - issues.push(issue); - } - } - // Filter all issues with status "Initialized" && Bounty Task is Document & Summarize - console.log('Final parsed issues number:', issues.length); - return issues - } catch (error) { - // console.error('Error processing markdown:', error); - throw error; - } -} + const bountyMarkdownFile = await fetch(defaultBountyMarkdownFile); + const bountyMarkdownFileText = await bountyMarkdownFile.text(); + // console.log('Raw markdown content:', bountyMarkdownFileText); + + const bountyMarkdownFileLines = bountyMarkdownFileText.split("\n"); + // console.log('Number of lines:', bountyMarkdownFileLines.length); + + const issues: BountyIssue[] = []; + let isTableStarted = false; + + for (const line of bountyMarkdownFileLines) { + // Skip empty lines + if (line.trim() === "") { + // console.log('Skipping empty line'); + continue; + } + + // console.log('Processing line:', line); + + // Skip the title line starting with # + if (line.startsWith("#")) { + // console.log('Found title line:', line); + continue; + } + + // Skip the header and separator lines + if (line.startsWith("|") && line.includes("GitHub URL")) { + //console.log('Found header line'); + continue; + } + if (line.startsWith("|") && line.includes("-----")) { + // console.log('Found separator line'); + continue; + } + + // Process table rows + if (line.startsWith("|")) { + isTableStarted = true; + // Remove first and last | and split by | + const cells = line + .slice(1, -1) + .split("|") + .map((cell) => cell.trim()); + // console.log('Parsed cells:', cells); + + // Extract GitHub URL and name from markdown link format [name](url) + const githubUrlMatch = cells[0].match(/\[(.*?)\]\((.*?)\)/); + // console.log('GitHub URL match:', githubUrlMatch); + + const projectName = githubUrlMatch ? githubUrlMatch[1] : ""; + const githubUrl = githubUrlMatch ? githubUrlMatch[2] : ""; + + const issue: BountyIssue = { + githubUrl, + projectName, + bountyTask: cells[1], + description: cells[3], + bountyAmount: cells[4], + bountyType: cells[5], + transactionHash: cells[6], + status: cells[7], + }; + + // console.log('Created issue object:', issue); + issues.push(issue); + } + } + // Filter all issues with status "Initialized" && Bounty Task is Document & Summarize + console.log("Final parsed issues number:", issues.length); + return issues; + } catch (error) { + // console.error('Error processing markdown:', error); + throw error; + } +} export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[]) { - - return issues.filter(issue => issue.status === "Initialized" && issue.bountyTask === "Document & Summarize"); + return issues.filter((issue) => issue.status === "Initialized" && issue.bountyTask === "Document & Summarize"); } - // async function main(){ // const existingIssues = await getExistingIssues(); // const transactionHashs = [ @@ -146,7 +146,7 @@ export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[ // if (initializedDocumentSummarizeIssues.length == 0) { // console.log("No issues pending to be summarized"); // return; -// } +// } // console.log("Initialized Document & Summarize issues number:", initializedDocumentSummarizeIssues.length); // } // async function main() { @@ -158,4 +158,4 @@ export async function getInitializedDocumentSummarizeIssues(issues: BountyIssue[ // } // } -// main(); \ No newline at end of file +// main(); diff --git a/worker/src/utils/leader.ts b/worker/src/utils/leader.ts index 4e79a09..4d2575f 100644 --- a/worker/src/utils/leader.ts +++ b/worker/src/utils/leader.ts @@ -140,13 +140,13 @@ export async function getRandomNodes(roundNumber: number, numberOfNodes: number) const lastRoundSubmissions = lastRoundSubmission.submissions; console.log("Last round submissions:", lastRoundSubmissions); - + // Get the last round number const lastRound = Object.keys(lastRoundSubmissions).pop(); if (!lastRound) { return []; } - + // Get the submissions for that round const submissions = lastRoundSubmissions[lastRound]; console.log("Submissions:", submissions); @@ -156,12 +156,12 @@ export async function getRandomNodes(roundNumber: number, numberOfNodes: number) if (availableKeys.length <= numberOfNodes) { return availableKeys; } - + const seed = TASK_ID + roundNumber.toString() || "default" + roundNumber; const rng = seedrandom(seed); // Use the keys from the submissions object const randomKeys = availableKeys.sort(() => rng() - 0.5).slice(0, numberOfNodes); - + console.log("Random keys:", randomKeys); return randomKeys; } diff --git a/worker/src/utils/submissionJSONSignatureDecode.ts b/worker/src/utils/submissionJSONSignatureDecode.ts index 35b4788..d7866d2 100644 --- a/worker/src/utils/submissionJSONSignatureDecode.ts +++ b/worker/src/utils/submissionJSONSignatureDecode.ts @@ -3,38 +3,45 @@ import { getFile } from "./ipfs"; import { Submission } from "@_koii/namespace-wrapper/dist/types"; import { Submitter } from "@_koii/task-manager/dist/types/global"; import { namespaceWrapper } from "@_koii/namespace-wrapper"; -export async function submissionJSONSignatureDecode({submission_value, submitterPublicKey, roundNumber}: {submission_value: string, submitterPublicKey: string, roundNumber: number}) { - let submissionString; - try { - console.log("Getting file from IPFS", submission_value); - submissionString = await getFile(submission_value); - console.log("submissionString", submissionString); - } catch (error) { - - console.log("error", error); - console.error("INVALID SIGNATURE DATA"); - return null; - } - // verify the signature of the submission - const submission = JSON.parse(submissionString); - console.log("submission", submission); - const signaturePayload = await namespaceWrapper.verifySignature(submission.signature, submitterPublicKey); - if (!signaturePayload.data) { - console.error("INVALID SIGNATURE"); - return null; - } - const data = JSON.parse(signaturePayload.data); - console.log("signaturePayload", signaturePayload); - console.log("data", data); - if ( - data.taskId !== TASK_ID || - data.roundNumber !== roundNumber || - data.stakingKey !== submitterPublicKey || - !data.pubKey || - !data.prUrl - ) { - console.error("INVALID SIGNATURE DATA"); - return null; - } - return data; -} \ No newline at end of file +export async function submissionJSONSignatureDecode({ + submission_value, + submitterPublicKey, + roundNumber, +}: { + submission_value: string; + submitterPublicKey: string; + roundNumber: number; +}) { + let submissionString; + try { + console.log("Getting file from IPFS", submission_value); + submissionString = await getFile(submission_value); + console.log("submissionString", submissionString); + } catch (error) { + console.log("error", error); + console.error("INVALID SIGNATURE DATA"); + return null; + } + // verify the signature of the submission + const submission = JSON.parse(submissionString); + console.log("submission", submission); + const signaturePayload = await namespaceWrapper.verifySignature(submission.signature, submitterPublicKey); + if (!signaturePayload.data) { + console.error("INVALID SIGNATURE"); + return null; + } + const data = JSON.parse(signaturePayload.data); + console.log("signaturePayload", signaturePayload); + console.log("data", data); + if ( + data.taskId !== TASK_ID || + data.roundNumber !== roundNumber || + data.stakingKey !== submitterPublicKey || + !data.pubKey || + !data.prUrl + ) { + console.error("INVALID SIGNATURE DATA"); + return null; + } + return data; +} diff --git a/worker/src/utils/task/task.ts b/worker/src/utils/task/task.ts index b19d153..fe7a5c3 100644 --- a/worker/src/utils/task/task.ts +++ b/worker/src/utils/task/task.ts @@ -5,105 +5,107 @@ import { actionMessage, errorMessage, middleServerUrl } from "../constant"; import { TASK_ID, namespaceWrapper } from "@_koii/namespace-wrapper"; import { LogLevel } from "@_koii/namespace-wrapper/dist/types"; -export async function task(){ - while (true) { - try { - let requiredWorkResponse; - const orcaClient = await getOrcaClient(); - // check if the env variable is valid - const stakingKeypair = await namespaceWrapper.getSubmitterAccount()!; - const pubKey = await namespaceWrapper.getMainAccountPubkey(); - if (!orcaClient || !stakingKeypair || !pubKey) { - await namespaceWrapper.logMessage(LogLevel.Error, errorMessage.NO_ORCA_CLIENT, actionMessage.NO_ORCA_CLIENT); - // Wait for 1 minute before retrying - await new Promise(resolve => setTimeout(resolve, 60000)); - continue; - } - const stakingKey = stakingKeypair.publicKey.toBase58(); +export async function task() { + while (true) { + try { + let requiredWorkResponse; + const orcaClient = await getOrcaClient(); + // check if the env variable is valid + const stakingKeypair = await namespaceWrapper.getSubmitterAccount()!; + const pubKey = await namespaceWrapper.getMainAccountPubkey(); + if (!orcaClient || !stakingKeypair || !pubKey) { + await namespaceWrapper.logMessage(LogLevel.Error, errorMessage.NO_ORCA_CLIENT, actionMessage.NO_ORCA_CLIENT); + // Wait for 1 minute before retrying + await new Promise((resolve) => setTimeout(resolve, 60000)); + continue; + } + const stakingKey = stakingKeypair.publicKey.toBase58(); - /****************** All these issues need to be generate a markdown file ******************/ + /****************** All these issues need to be generate a markdown file ******************/ - const signature = await namespaceWrapper.payloadSigning( - { - taskId: TASK_ID, - // roundNumber: roundNumber, - action: "fetch-todo", - githubUsername: stakingKey, - stakingKey: stakingKey, - }, - stakingKeypair.secretKey, - ); - - const retryDelay = 10000; // 10 seconds in milliseconds + const signature = await namespaceWrapper.payloadSigning( + { + taskId: TASK_ID, + // roundNumber: roundNumber, + action: "fetch-todo", + githubUsername: stakingKey, + stakingKey: stakingKey, + }, + stakingKeypair.secretKey, + ); - while (true) { - requiredWorkResponse = await fetch(`${middleServerUrl}/summarizer/worker/fetch-todo`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ signature: signature, stakingKey: stakingKey }), - }); + const retryDelay = 10000; // 10 seconds in milliseconds - if (requiredWorkResponse.status === 200) { - break; - } + while (true) { + requiredWorkResponse = await fetch(`${middleServerUrl}/summarizer/worker/fetch-todo`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ signature: signature, stakingKey: stakingKey }), + }); - console.log(`[TASK] Server returned status ${requiredWorkResponse.status}, retrying in ${retryDelay/1000} seconds...`); - await new Promise(resolve => setTimeout(resolve, retryDelay)); - } - - // check if the response is 200 after all retries - if (!requiredWorkResponse || requiredWorkResponse.status !== 200) { - // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.NO_ISSUES_PENDING_TO_BE_SUMMARIZED); - return; - } - const requiredWorkResponseData = await requiredWorkResponse.json(); - console.log("[TASK] requiredWorkResponseData: ", requiredWorkResponseData); - // const uuid = uuidv4(); - const alreadyAssigned = await namespaceWrapper.storeGet(JSON.stringify(requiredWorkResponseData.data.id)); - if (alreadyAssigned) { - return; - }else{ - await namespaceWrapper.storeSet(JSON.stringify(requiredWorkResponseData.data.id), "initialized"); - } - - const podcallPayload = { - taskId: TASK_ID, - }; - - const podCallSignature = await namespaceWrapper.payloadSigning(podcallPayload, stakingKeypair.secretKey); - - const jsonBody = { - task_id: TASK_ID, - swarmBountyId: requiredWorkResponseData.data.id, - repo_url: `https://github.com/${requiredWorkResponseData.data.repo_owner}/${requiredWorkResponseData.data.repo_name}`, - podcall_signature: podCallSignature, - }; - console.log("[TASK] jsonBody: ", jsonBody); - try { - const repoSummaryResponse = await orcaClient.podCall(`worker-task`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(jsonBody), - }); - console.log("[TASK] repoSummaryResponse: ", repoSummaryResponse); - if (repoSummaryResponse.status !== 200) { - // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED); - } - } catch (error) { - // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED); - console.error("[TASK] EXECUTE TASK ERROR:", error); - } - } catch (error) { - console.error("[TASK] EXECUTE TASK ERROR:", error); - // Wait for 1 minute before retrying on error - await new Promise(resolve => setTimeout(resolve, 60000)); + if (requiredWorkResponse.status === 200) { + break; } - - // Wait for 1 minute before starting the next iteration - await new Promise(resolve => setTimeout(resolve, 60000)); + + console.log( + `[TASK] Server returned status ${requiredWorkResponse.status}, retrying in ${retryDelay / 1000} seconds...`, + ); + await new Promise((resolve) => setTimeout(resolve, retryDelay)); + } + + // check if the response is 200 after all retries + if (!requiredWorkResponse || requiredWorkResponse.status !== 200) { + // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.NO_ISSUES_PENDING_TO_BE_SUMMARIZED); + return; + } + const requiredWorkResponseData = await requiredWorkResponse.json(); + console.log("[TASK] requiredWorkResponseData: ", requiredWorkResponseData); + // const uuid = uuidv4(); + const alreadyAssigned = await namespaceWrapper.storeGet(JSON.stringify(requiredWorkResponseData.data.id)); + if (alreadyAssigned) { + return; + } else { + await namespaceWrapper.storeSet(JSON.stringify(requiredWorkResponseData.data.id), "initialized"); + } + + const podcallPayload = { + taskId: TASK_ID, + }; + + const podCallSignature = await namespaceWrapper.payloadSigning(podcallPayload, stakingKeypair.secretKey); + + const jsonBody = { + task_id: TASK_ID, + swarmBountyId: requiredWorkResponseData.data.id, + repo_url: `https://github.com/${requiredWorkResponseData.data.repo_owner}/${requiredWorkResponseData.data.repo_name}`, + podcall_signature: podCallSignature, + }; + console.log("[TASK] jsonBody: ", jsonBody); + try { + const repoSummaryResponse = await orcaClient.podCall(`worker-task`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(jsonBody), + }); + console.log("[TASK] repoSummaryResponse: ", repoSummaryResponse); + if (repoSummaryResponse.status !== 200) { + // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED); + } + } catch (error) { + // await namespaceWrapper.storeSet(`result-${roundNumber}`, status.ISSUE_SUMMARIZATION_FAILED); + console.error("[TASK] EXECUTE TASK ERROR:", error); + } + } catch (error) { + console.error("[TASK] EXECUTE TASK ERROR:", error); + // Wait for 1 minute before retrying on error + await new Promise((resolve) => setTimeout(resolve, 60000)); } -} \ No newline at end of file + + // Wait for 1 minute before starting the next iteration + await new Promise((resolve) => setTimeout(resolve, 60000)); + } +} diff --git a/worker/tests/README.md b/worker/tests/README.md index 6e77406..62c96f4 100644 --- a/worker/tests/README.md +++ b/worker/tests/README.md @@ -19,11 +19,13 @@ tests/ ## Prerequisites 1. Install the test framework: + ```bash pip install -e test-framework/ ``` 2. Set up environment variables in `.env`: + ``` ANTHROPIC_API_KEY=your_test_key GITHUB_USERNAME=your_test_username @@ -47,12 +49,15 @@ python -m tests.e2e --reset ## Test Flow 1. API Key Validation + - Validates Anthropic API key 2. GitHub Validation + - Validates GitHub credentials 3. Todo Management + - Fetches todos for each worker - Generates summaries - Submits results diff --git a/worker/tests/config.ts b/worker/tests/config.ts index c7f0510..08a9f4d 100644 --- a/worker/tests/config.ts +++ b/worker/tests/config.ts @@ -1,12 +1,8 @@ import "dotenv/config"; -export const TASK_ID = - process.env.TASK_ID || "BXbYKFdXZhQgEaMFbeShaisQBYG1FD4MiSf9gg4n6mVn"; -export const WEBPACKED_FILE_PATH = - process.env.WEBPACKED_FILE_PATH || "../dist/main.js"; +export const TASK_ID = process.env.TASK_ID || "BXbYKFdXZhQgEaMFbeShaisQBYG1FD4MiSf9gg4n6mVn"; +export const WEBPACKED_FILE_PATH = process.env.WEBPACKED_FILE_PATH || "../dist/main.js"; const envKeywords = process.env.TEST_KEYWORDS ?? ""; -export const TEST_KEYWORDS = envKeywords - ? envKeywords.split(",") - : ["TEST", "EZ TESTING"]; +export const TEST_KEYWORDS = envKeywords ? envKeywords.split(",") : ["TEST", "EZ TESTING"]; diff --git a/worker/tests/main.test.ts b/worker/tests/main.test.ts index 32c11a5..b0157c7 100644 --- a/worker/tests/main.test.ts +++ b/worker/tests/main.test.ts @@ -1,188 +1,188 @@ -import { initializeTaskManager, taskRunner } from "@_koii/task-manager"; -import { setup } from "../src/task/0-setup"; -import { task } from "../src/task/1-task"; -import { submission } from "../src/task/2-submission"; -import { audit } from "../src/task/3-audit"; -import { distribution } from "../src/task/4-distribution"; -import { routes } from "../src/task/5-routes"; -import { namespaceWrapper, _server } from "@_koii/task-manager/namespace-wrapper"; -import Joi from "joi"; -import axios from "axios"; -import { Submitter } from "@_koii/task-manager"; -beforeAll(async () => { - await namespaceWrapper.defaultTaskSetup(); - initializeTaskManager({ - setup, - task, - submission, - audit, - distribution, - routes, - }); -}); - -describe("Performing the task", () => { - it("should performs the core logic task", async () => { - const round = 1; - await taskRunner.task(round); - const value = await namespaceWrapper.storeGet("value"); - expect(value).toBeDefined(); - expect(value).not.toBeNull(); - }); - - it("should make the submission to k2 for dummy round 1", async () => { - const round = 1; - await taskRunner.submitTask(round); - const taskState = await namespaceWrapper.getTaskState({}); - const schema = Joi.object() - .pattern( - Joi.string(), - Joi.object().pattern( - Joi.string(), - Joi.object({ - submission_value: Joi.string().required(), - slot: Joi.number().integer().required(), - round: Joi.number().integer().required(), - }), - ), - ) - .required() - .min(1); - const validationResult = schema.validate(taskState?.submissions); - try { - expect(validationResult.error).toBeUndefined(); - } catch (e) { - throw new Error("Submission doesn't exist or is incorrect"); - } - }); - - it("should make an audit on submission", async () => { - const round = 1; - await taskRunner.auditTask(round); - const taskState = await namespaceWrapper.getTaskState({}); - console.log("TASK STATE", taskState); - console.log("audit task", taskState?.submissions_audit_trigger); - const schema = Joi.object() - .pattern( - Joi.string(), - Joi.object().pattern( - Joi.string(), - Joi.object({ - trigger_by: Joi.string().required(), - slot: Joi.number().integer().required(), - votes: Joi.array().required(), - }), - ), - ) - .required(); - const validationResult = schema.validate(taskState?.submissions_audit_trigger); - try { - expect(validationResult.error).toBeUndefined(); - } catch (e) { - throw new Error("Submission audit is incorrect"); - } - }); - it("should make the distribution submission to k2 for dummy round 1", async () => { - const round = 1; - await taskRunner.submitDistributionList(round); - - const taskState = await namespaceWrapper.getTaskState({}); - const schema = Joi.object() - .pattern( - Joi.string(), - Joi.object().pattern( - Joi.string(), - Joi.object({ - submission_value: Joi.string().required(), - slot: Joi.number().integer().required(), - round: Joi.number().integer().required(), - }), - ), - ) - .required() - .min(1); - console.log("Distribution submission", taskState?.distribution_rewards_submission); - const validationResult = schema.validate(taskState?.distribution_rewards_submission); - try { - expect(validationResult.error).toBeUndefined(); - } catch (e) { - throw new Error("Distribution submission doesn't exist or is incorrect"); - } - }); - it("should make an audit on distribution submission", async () => { - const round = 1; - await taskRunner.auditDistribution(round); - const taskState = await namespaceWrapper.getTaskState({}); - console.log("audit task", taskState?.distributions_audit_trigger); - const schema = Joi.object() - .pattern( - Joi.string(), - Joi.object().pattern( - Joi.string(), - Joi.object({ - trigger_by: Joi.string().required(), - slot: Joi.number().integer().required(), - votes: Joi.array().required(), - }), - ), - ) - .required(); - const validationResult = schema.validate(taskState?.distributions_audit_trigger); - try { - expect(validationResult.error).toBeUndefined(); - } catch (e) { - throw new Error("Distribution audit is incorrect"); - } - }); - - it("should make sure the submitted distribution list is valid", async () => { - const round = 1; - const distributionList = await namespaceWrapper.getDistributionList("", round); - console.log("Generated distribution List", JSON.parse(distributionList.toString())); - const schema = Joi.object().pattern(Joi.string().required(), Joi.number().integer().required()).required(); - const validationResult = schema.validate(JSON.parse(distributionList.toString())); - console.log(validationResult); - try { - expect(validationResult.error).toBeUndefined(); - } catch (e) { - throw new Error("Submitted distribution list is not valid"); - } - }); - - it("should test the endpoint", async () => { - const response = await axios.get("http://localhost:3000"); - expect(response.status).toBe(200); - expect(response.data).toEqual({ message: "Running", status: 200 }); - }); - - it("should generate a empty distribution list when submission is 0", async () => { - const submitters: Submitter[] = []; - const bounty = Math.floor(Math.random() * 1e15) + 1; - const roundNumber = Math.floor(Math.random() * 1e5) + 1; - const distributionList = await distribution(submitters, bounty, roundNumber); - expect(distributionList).toEqual({}); - }); - - it("should generate a distribution list contains all the submitters", async () => { - const simulatedSubmitters = 5; - const submitters: Submitter[] = []; - // 10k is the rough maximum number of submitters - for (let i = 0; i < simulatedSubmitters; i++) { - const publicKey = `mockPublicKey${i}`; - submitters.push({ - publicKey, - votes: Math.floor(Math.random() * simulatedSubmitters) - 5000, - stake: Math.floor(Math.random() * 1e9) + 1, - }); - } - const bounty = Math.floor(Math.random() * 1e15) + 1; - const roundNumber = 1; - const distributionList = await distribution(submitters, bounty, roundNumber); - expect(Object.keys(distributionList).length).toBe(submitters.length); - expect(Object.keys(distributionList).sort()).toEqual(submitters.map((submitter) => submitter.publicKey).sort()); - }); -}); - -afterAll(async () => { - _server.close(); -}); +import { initializeTaskManager, taskRunner } from "@_koii/task-manager"; +import { setup } from "../src/task/0-setup"; +import { task } from "../src/task/1-task"; +import { submission } from "../src/task/2-submission"; +import { audit } from "../src/task/3-audit"; +import { distribution } from "../src/task/4-distribution"; +import { routes } from "../src/task/5-routes"; +import { namespaceWrapper, _server } from "@_koii/task-manager/namespace-wrapper"; +import Joi from "joi"; +import axios from "axios"; +import { Submitter } from "@_koii/task-manager"; +beforeAll(async () => { + await namespaceWrapper.defaultTaskSetup(); + initializeTaskManager({ + setup, + task, + submission, + audit, + distribution, + routes, + }); +}); + +describe("Performing the task", () => { + it("should performs the core logic task", async () => { + const round = 1; + await taskRunner.task(round); + const value = await namespaceWrapper.storeGet("value"); + expect(value).toBeDefined(); + expect(value).not.toBeNull(); + }); + + it("should make the submission to k2 for dummy round 1", async () => { + const round = 1; + await taskRunner.submitTask(round); + const taskState = await namespaceWrapper.getTaskState({}); + const schema = Joi.object() + .pattern( + Joi.string(), + Joi.object().pattern( + Joi.string(), + Joi.object({ + submission_value: Joi.string().required(), + slot: Joi.number().integer().required(), + round: Joi.number().integer().required(), + }), + ), + ) + .required() + .min(1); + const validationResult = schema.validate(taskState?.submissions); + try { + expect(validationResult.error).toBeUndefined(); + } catch (e) { + throw new Error("Submission doesn't exist or is incorrect"); + } + }); + + it("should make an audit on submission", async () => { + const round = 1; + await taskRunner.auditTask(round); + const taskState = await namespaceWrapper.getTaskState({}); + console.log("TASK STATE", taskState); + console.log("audit task", taskState?.submissions_audit_trigger); + const schema = Joi.object() + .pattern( + Joi.string(), + Joi.object().pattern( + Joi.string(), + Joi.object({ + trigger_by: Joi.string().required(), + slot: Joi.number().integer().required(), + votes: Joi.array().required(), + }), + ), + ) + .required(); + const validationResult = schema.validate(taskState?.submissions_audit_trigger); + try { + expect(validationResult.error).toBeUndefined(); + } catch (e) { + throw new Error("Submission audit is incorrect"); + } + }); + it("should make the distribution submission to k2 for dummy round 1", async () => { + const round = 1; + await taskRunner.submitDistributionList(round); + + const taskState = await namespaceWrapper.getTaskState({}); + const schema = Joi.object() + .pattern( + Joi.string(), + Joi.object().pattern( + Joi.string(), + Joi.object({ + submission_value: Joi.string().required(), + slot: Joi.number().integer().required(), + round: Joi.number().integer().required(), + }), + ), + ) + .required() + .min(1); + console.log("Distribution submission", taskState?.distribution_rewards_submission); + const validationResult = schema.validate(taskState?.distribution_rewards_submission); + try { + expect(validationResult.error).toBeUndefined(); + } catch (e) { + throw new Error("Distribution submission doesn't exist or is incorrect"); + } + }); + it("should make an audit on distribution submission", async () => { + const round = 1; + await taskRunner.auditDistribution(round); + const taskState = await namespaceWrapper.getTaskState({}); + console.log("audit task", taskState?.distributions_audit_trigger); + const schema = Joi.object() + .pattern( + Joi.string(), + Joi.object().pattern( + Joi.string(), + Joi.object({ + trigger_by: Joi.string().required(), + slot: Joi.number().integer().required(), + votes: Joi.array().required(), + }), + ), + ) + .required(); + const validationResult = schema.validate(taskState?.distributions_audit_trigger); + try { + expect(validationResult.error).toBeUndefined(); + } catch (e) { + throw new Error("Distribution audit is incorrect"); + } + }); + + it("should make sure the submitted distribution list is valid", async () => { + const round = 1; + const distributionList = await namespaceWrapper.getDistributionList("", round); + console.log("Generated distribution List", JSON.parse(distributionList.toString())); + const schema = Joi.object().pattern(Joi.string().required(), Joi.number().integer().required()).required(); + const validationResult = schema.validate(JSON.parse(distributionList.toString())); + console.log(validationResult); + try { + expect(validationResult.error).toBeUndefined(); + } catch (e) { + throw new Error("Submitted distribution list is not valid"); + } + }); + + it("should test the endpoint", async () => { + const response = await axios.get("http://localhost:3000"); + expect(response.status).toBe(200); + expect(response.data).toEqual({ message: "Running", status: 200 }); + }); + + it("should generate a empty distribution list when submission is 0", async () => { + const submitters: Submitter[] = []; + const bounty = Math.floor(Math.random() * 1e15) + 1; + const roundNumber = Math.floor(Math.random() * 1e5) + 1; + const distributionList = await distribution(submitters, bounty, roundNumber); + expect(distributionList).toEqual({}); + }); + + it("should generate a distribution list contains all the submitters", async () => { + const simulatedSubmitters = 5; + const submitters: Submitter[] = []; + // 10k is the rough maximum number of submitters + for (let i = 0; i < simulatedSubmitters; i++) { + const publicKey = `mockPublicKey${i}`; + submitters.push({ + publicKey, + votes: Math.floor(Math.random() * simulatedSubmitters) - 5000, + stake: Math.floor(Math.random() * 1e9) + 1, + }); + } + const bounty = Math.floor(Math.random() * 1e15) + 1; + const roundNumber = 1; + const distributionList = await distribution(submitters, bounty, roundNumber); + expect(Object.keys(distributionList).length).toBe(submitters.length); + expect(Object.keys(distributionList).sort()).toEqual(submitters.map((submitter) => submitter.publicKey).sort()); + }); +}); + +afterAll(async () => { + _server.close(); +}); diff --git a/worker/tests/simulateTask.ts b/worker/tests/simulateTask.ts index b1d0f23..8b48f69 100644 --- a/worker/tests/simulateTask.ts +++ b/worker/tests/simulateTask.ts @@ -1,84 +1,84 @@ -import { taskRunner } from "@_koii/task-manager"; - -import "../src/index.js"; -import { namespaceWrapper } from "@_koii/task-manager/namespace-wrapper"; -import { Keypair } from "@_koii/web3.js"; - -const numRounds = parseInt(process.argv[2]) || 1; -const roundDelay = parseInt(process.argv[3]) || 5000; -const functionDelay = parseInt(process.argv[4]) || 1000; - -let TASK_TIMES: number[] = []; -let SUBMISSION_TIMES: number[] = []; -let AUDIT_TIMES: number[] = []; - -function sleep(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -async function executeTasks() { - const keypair = Keypair.generate(); - await namespaceWrapper.stakeOnChain(keypair.publicKey, keypair, keypair.publicKey, 10000); - for (let round = 0; round < numRounds; round++) { - const taskStartTime = Date.now(); - await taskRunner.task(round); - const taskEndTime = Date.now(); - TASK_TIMES.push(taskEndTime - taskStartTime); - await sleep(functionDelay); - - const taskSubmissionStartTime = Date.now(); - await taskRunner.submitTask(round); - const taskSubmissionEndTime = Date.now(); - SUBMISSION_TIMES.push(taskSubmissionEndTime - taskSubmissionStartTime); - await sleep(functionDelay); - - const auditStartTime = Date.now(); - await taskRunner.auditTask(round); - const auditEndTime = Date.now(); - AUDIT_TIMES.push(auditEndTime - auditStartTime); - await sleep(functionDelay); - - await taskRunner.selectAndGenerateDistributionList(round); - await sleep(functionDelay); - - await taskRunner.auditDistribution(round); - - if (round < numRounds - 1) { - await sleep(roundDelay); - } - } - console.log("TIME METRICS BELOW"); - function metrics(name: string, times: number[]) { - const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; - const formatTime = (ms: number) => (ms / 1000).toFixed(4); - const formatSlot = (ms: number) => Math.ceil(ms / 408); - const min = Math.min(...times); - const max = Math.max(...times); - const avg = average(times); - const timeMin = formatTime(min); - const timeMax = formatTime(max); - const timeAvg = formatTime(avg); - const slotMin = formatSlot(min); - const slotMax = formatSlot(max); - const slotAvg = formatSlot(avg); - - return { - Metric: `SIMULATED ${name} WINDOW`, - "Avg Time (s)": timeAvg, - "Avg Slots": slotAvg, - "Min Time (s)": timeMin, - "Min Slots": slotMin, - "Max Time (s)": timeMax, - "Max Slots": slotMax, - }; - } - const timeMetrics = metrics("TASK", TASK_TIMES); - const submissionMetrics = metrics("SUBMISSION", SUBMISSION_TIMES); - const auditMetrics = metrics("AUDIT", AUDIT_TIMES); - - console.table([timeMetrics, submissionMetrics, auditMetrics]); - - console.log("All tasks executed. Test completed."); - process.exit(0); -} -setTimeout(executeTasks, 1500); +import { taskRunner } from "@_koii/task-manager"; + +import "../src/index.js"; +import { namespaceWrapper } from "@_koii/task-manager/namespace-wrapper"; +import { Keypair } from "@_koii/web3.js"; + +const numRounds = parseInt(process.argv[2]) || 1; +const roundDelay = parseInt(process.argv[3]) || 5000; +const functionDelay = parseInt(process.argv[4]) || 1000; + +let TASK_TIMES: number[] = []; +let SUBMISSION_TIMES: number[] = []; +let AUDIT_TIMES: number[] = []; + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function executeTasks() { + const keypair = Keypair.generate(); + await namespaceWrapper.stakeOnChain(keypair.publicKey, keypair, keypair.publicKey, 10000); + for (let round = 0; round < numRounds; round++) { + const taskStartTime = Date.now(); + await taskRunner.task(round); + const taskEndTime = Date.now(); + TASK_TIMES.push(taskEndTime - taskStartTime); + await sleep(functionDelay); + + const taskSubmissionStartTime = Date.now(); + await taskRunner.submitTask(round); + const taskSubmissionEndTime = Date.now(); + SUBMISSION_TIMES.push(taskSubmissionEndTime - taskSubmissionStartTime); + await sleep(functionDelay); + + const auditStartTime = Date.now(); + await taskRunner.auditTask(round); + const auditEndTime = Date.now(); + AUDIT_TIMES.push(auditEndTime - auditStartTime); + await sleep(functionDelay); + + await taskRunner.selectAndGenerateDistributionList(round); + await sleep(functionDelay); + + await taskRunner.auditDistribution(round); + + if (round < numRounds - 1) { + await sleep(roundDelay); + } + } + console.log("TIME METRICS BELOW"); + function metrics(name: string, times: number[]) { + const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length; + const formatTime = (ms: number) => (ms / 1000).toFixed(4); + const formatSlot = (ms: number) => Math.ceil(ms / 408); + const min = Math.min(...times); + const max = Math.max(...times); + const avg = average(times); + const timeMin = formatTime(min); + const timeMax = formatTime(max); + const timeAvg = formatTime(avg); + const slotMin = formatSlot(min); + const slotMax = formatSlot(max); + const slotAvg = formatSlot(avg); + + return { + Metric: `SIMULATED ${name} WINDOW`, + "Avg Time (s)": timeAvg, + "Avg Slots": slotAvg, + "Min Time (s)": timeMin, + "Min Slots": slotMin, + "Max Time (s)": timeMax, + "Max Slots": slotMax, + }; + } + const timeMetrics = metrics("TASK", TASK_TIMES); + const submissionMetrics = metrics("SUBMISSION", SUBMISSION_TIMES); + const auditMetrics = metrics("AUDIT", AUDIT_TIMES); + + console.table([timeMetrics, submissionMetrics, auditMetrics]); + + console.log("All tasks executed. Test completed."); + process.exit(0); +} +setTimeout(executeTasks, 1500); diff --git a/worker/tests/test.ts b/worker/tests/test.ts index 3f3d96f..f1ab985 100644 --- a/worker/tests/test.ts +++ b/worker/tests/test.ts @@ -4,7 +4,7 @@ // headers: { // "Content-Type": "application/json", // }, -// body: JSON.stringify({ +// body: JSON.stringify({ // text: `[TASK] Error summarizing issue:\n ${JSON.stringify({ // status: "error", // data: { @@ -16,4 +16,4 @@ // console.log("[TASK] slackResponse: ", slackResponse); // } -// testSlackWebhook(); \ No newline at end of file +// testSlackWebhook(); diff --git a/worker/tests/wasm/bincode_js.cjs b/worker/tests/wasm/bincode_js.cjs index d4857f9..7096249 100644 --- a/worker/tests/wasm/bincode_js.cjs +++ b/worker/tests/wasm/bincode_js.cjs @@ -1,24 +1,24 @@ let imports = {}; -imports['__wbindgen_placeholder__'] = module.exports; +imports["__wbindgen_placeholder__"] = module.exports; let wasm; const { TextDecoder, TextEncoder } = require(`util`); -let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); +let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }); cachedTextDecoder.decode(); let cachedUint8Memory0 = null; function getUint8Memory0() { - if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { - cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8Memory0; + if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) { + cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer); + } + return cachedUint8Memory0; } function getStringFromWasm0(ptr, len) { - ptr = ptr >>> 0; - return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); + ptr = ptr >>> 0; + return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len)); } const heap = new Array(128).fill(undefined); @@ -28,1184 +28,1231 @@ heap.push(undefined, null, true, false); let heap_next = heap.length; function addHeapObject(obj) { - if (heap_next === heap.length) heap.push(heap.length + 1); - const idx = heap_next; - heap_next = heap[idx]; + if (heap_next === heap.length) heap.push(heap.length + 1); + const idx = heap_next; + heap_next = heap[idx]; - heap[idx] = obj; - return idx; + heap[idx] = obj; + return idx; } -function getObject(idx) { return heap[idx]; } +function getObject(idx) { + return heap[idx]; +} function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; + if (idx < 132) return; + heap[idx] = heap_next; + heap_next = idx; } function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; + const ret = getObject(idx); + dropObject(idx); + return ret; } function isLikeNone(x) { - return x === undefined || x === null; + return x === undefined || x === null; } let cachedFloat64Memory0 = null; function getFloat64Memory0() { - if (cachedFloat64Memory0 === null || cachedFloat64Memory0.byteLength === 0) { - cachedFloat64Memory0 = new Float64Array(wasm.memory.buffer); - } - return cachedFloat64Memory0; + if (cachedFloat64Memory0 === null || cachedFloat64Memory0.byteLength === 0) { + cachedFloat64Memory0 = new Float64Array(wasm.memory.buffer); + } + return cachedFloat64Memory0; } let cachedInt32Memory0 = null; function getInt32Memory0() { - if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { - cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); - } - return cachedInt32Memory0; + if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) { + cachedInt32Memory0 = new Int32Array(wasm.memory.buffer); + } + return cachedInt32Memory0; } let WASM_VECTOR_LEN = 0; -let cachedTextEncoder = new TextEncoder('utf-8'); +let cachedTextEncoder = new TextEncoder("utf-8"); -const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' +const encodeString = + typeof cachedTextEncoder.encodeInto === "function" ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); -} + return cachedTextEncoder.encodeInto(arg, view); + } : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; -}); + const buf = cachedTextEncoder.encode(arg); + view.set(buf); + return { + read: arg.length, + written: buf.length, + }; + }; function passStringToWasm0(arg, malloc, realloc) { - - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8Memory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8Memory0().subarray(ptr + offset, ptr + len); - const ret = encodeString(arg, view); - - offset += ret.written; - } - - WASM_VECTOR_LEN = offset; + if (realloc === undefined) { + const buf = cachedTextEncoder.encode(arg); + const ptr = malloc(buf.length, 1) >>> 0; + getUint8Memory0() + .subarray(ptr, ptr + buf.length) + .set(buf); + WASM_VECTOR_LEN = buf.length; return ptr; + } + + let len = arg.length; + let ptr = malloc(len, 1) >>> 0; + + const mem = getUint8Memory0(); + + let offset = 0; + + for (; offset < len; offset++) { + const code = arg.charCodeAt(offset); + if (code > 0x7f) break; + mem[ptr + offset] = code; + } + + if (offset !== len) { + if (offset !== 0) { + arg = arg.slice(offset); + } + ptr = realloc(ptr, len, (len = offset + arg.length * 3), 1) >>> 0; + const view = getUint8Memory0().subarray(ptr + offset, ptr + len); + const ret = encodeString(arg, view); + + offset += ret.written; + } + + WASM_VECTOR_LEN = offset; + return ptr; } function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches.length > 1) { - className = builtInMatches[1]; + // primitive types + const type = typeof val; + if (type == "number" || type == "boolean" || val == null) { + return `${val}`; + } + if (type == "string") { + return `"${val}"`; + } + if (type == "symbol") { + const description = val.description; + if (description == null) { + return "Symbol"; } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); + return `Symbol(${description})`; } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } + } + if (type == "function") { + const name = val.name; + if (typeof name == "string" && name.length > 0) { + return `Function(${name})`; + } else { + return "Function"; } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; + } + // objects + if (Array.isArray(val)) { + const length = val.length; + let debug = "["; + if (length > 0) { + debug += debugString(val[0]); } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; + for (let i = 1; i < length; i++) { + debug += ", " + debugString(val[i]); + } + debug += "]"; + return debug; + } + // Test for built-in + const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); + let className; + if (builtInMatches.length > 1) { + className = builtInMatches[1]; + } else { + // Failed to match the standard '[object ClassName]' + return toString.call(val); + } + if (className == "Object") { + // we're a user defined class or Object + // JSON.stringify avoids problems with cycles, and is generally much + // easier than looping through ownProperties of `val`. + try { + return "Object(" + JSON.stringify(val) + ")"; + } catch (_) { + return "Object"; + } + } + // errors + if (val instanceof Error) { + return `${val.name}: ${val.message}\n${val.stack}`; + } + // TODO we could test for more things here, like `Set`s and `Map`s. + return className; } /** -* @param {any} val -* @returns {any} -*/ -module.exports.bincode_js_deserialize = function(val) { - const ret = wasm.bincode_js_deserialize(addHeapObject(val)); - return takeObject(ret); + * @param {any} val + * @returns {any} + */ +module.exports.bincode_js_deserialize = function (val) { + const ret = wasm.bincode_js_deserialize(addHeapObject(val)); + return takeObject(ret); }; /** -* @param {any} val -* @returns {any} -*/ -module.exports.borsh_bpf_js_deserialize = function(val) { - const ret = wasm.borsh_bpf_js_deserialize(addHeapObject(val)); - return takeObject(ret); + * @param {any} val + * @returns {any} + */ +module.exports.borsh_bpf_js_deserialize = function (val) { + const ret = wasm.borsh_bpf_js_deserialize(addHeapObject(val)); + return takeObject(ret); }; /** -* Initialize Javascript logging and panic handler -*/ -module.exports.solana_program_init = function() { - wasm.solana_program_init(); + * Initialize Javascript logging and panic handler + */ +module.exports.solana_program_init = function () { + wasm.solana_program_init(); }; function _assertClass(instance, klass) { - if (!(instance instanceof klass)) { - throw new Error(`expected instance of ${klass.name}`); - } - return instance.ptr; + if (!(instance instanceof klass)) { + throw new Error(`expected instance of ${klass.name}`); + } + return instance.ptr; } function getArrayU8FromWasm0(ptr, len) { - ptr = ptr >>> 0; - return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len); + ptr = ptr >>> 0; + return getUint8Memory0().subarray(ptr / 1, ptr / 1 + len); } let cachedUint32Memory0 = null; function getUint32Memory0() { - if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) { - cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer); - } - return cachedUint32Memory0; + if (cachedUint32Memory0 === null || cachedUint32Memory0.byteLength === 0) { + cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer); + } + return cachedUint32Memory0; } function passArrayJsValueToWasm0(array, malloc) { - const ptr = malloc(array.length * 4, 4) >>> 0; - const mem = getUint32Memory0(); - for (let i = 0; i < array.length; i++) { - mem[ptr / 4 + i] = addHeapObject(array[i]); - } - WASM_VECTOR_LEN = array.length; - return ptr; + const ptr = malloc(array.length * 4, 4) >>> 0; + const mem = getUint32Memory0(); + for (let i = 0; i < array.length; i++) { + mem[ptr / 4 + i] = addHeapObject(array[i]); + } + WASM_VECTOR_LEN = array.length; + return ptr; } function handleError(f, args) { - try { - return f.apply(this, args); - } catch (e) { - wasm.__wbindgen_exn_store(addHeapObject(e)); - } + try { + return f.apply(this, args); + } catch (e) { + wasm.__wbindgen_exn_store(addHeapObject(e)); + } } /** -* A hash; the 32-byte output of a hashing algorithm. -* -* This struct is used most often in `solana-sdk` and related crates to contain -* a [SHA-256] hash, but may instead contain a [blake3] hash, as created by the -* [`blake3`] module (and used in [`Message::hash`]). -* -* [SHA-256]: https://en.wikipedia.org/wiki/SHA-2 -* [blake3]: https://github.com/BLAKE3-team/BLAKE3 -* [`blake3`]: crate::blake3 -* [`Message::hash`]: crate::message::Message::hash -*/ + * A hash; the 32-byte output of a hashing algorithm. + * + * This struct is used most often in `solana-sdk` and related crates to contain + * a [SHA-256] hash, but may instead contain a [blake3] hash, as created by the + * [`blake3`] module (and used in [`Message::hash`]). + * + * [SHA-256]: https://en.wikipedia.org/wiki/SHA-2 + * [blake3]: https://github.com/BLAKE3-team/BLAKE3 + * [`blake3`]: crate::blake3 + * [`Message::hash`]: crate::message::Message::hash + */ class Hash { + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Hash.prototype); + obj.__wbg_ptr = ptr; - static __wrap(ptr) { - ptr = ptr >>> 0; - const obj = Object.create(Hash.prototype); - obj.__wbg_ptr = ptr; + return obj; + } - return obj; - } + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_hash_free(ptr); + } + /** + * Create a new Hash object + * + * * `value` - optional hash as a base58 encoded string, `Uint8Array`, `[number]` + * @param {any} value + */ + constructor(value) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hash_constructor(retptr, addHeapObject(value)); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Hash.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_hash_free(ptr); + } + /** + * Return the base58 string representation of the hash + * @returns {string} + */ + toString() { + let deferred1_0; + let deferred1_1; + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hash_toString(retptr, this.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + deferred1_0 = r0; + deferred1_1 = r1; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); } - /** - * Create a new Hash object - * - * * `value` - optional hash as a base58 encoded string, `Uint8Array`, `[number]` - * @param {any} value - */ - constructor(value) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.hash_constructor(retptr, addHeapObject(value)); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var r2 = getInt32Memory0()[retptr / 4 + 2]; - if (r2) { - throw takeObject(r1); - } - return Hash.__wrap(r0); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } - } - /** - * Return the base58 string representation of the hash - * @returns {string} - */ - toString() { - let deferred1_0; - let deferred1_1; - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.hash_toString(retptr, this.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - deferred1_0 = r0; - deferred1_1 = r1; - return getStringFromWasm0(r0, r1); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); - } - } - /** - * Checks if two `Hash`s are equal - * @param {Hash} other - * @returns {boolean} - */ - equals(other) { - _assertClass(other, Hash); - const ret = wasm.hash_equals(this.__wbg_ptr, other.__wbg_ptr); - return ret !== 0; - } - /** - * Return the `Uint8Array` representation of the hash - * @returns {Uint8Array} - */ - toBytes() { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.hash_toBytes(retptr, this.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var v1 = getArrayU8FromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 1); - return v1; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } + } + /** + * Checks if two `Hash`s are equal + * @param {Hash} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, Hash); + const ret = wasm.hash_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } + /** + * Return the `Uint8Array` representation of the hash + * @returns {Uint8Array} + */ + toBytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.hash_toBytes(retptr, this.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v1 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } + } } module.exports.Hash = Hash; /** -* A directive for a single invocation of a Solana program. -* -* An instruction specifies which program it is calling, which accounts it may -* read or modify, and additional data that serves as input to the program. One -* or more instructions are included in transactions submitted by Solana -* clients. Instructions are also used to describe [cross-program -* invocations][cpi]. -* -* [cpi]: https://docs.solana.com/developing/programming-model/calling-between-programs -* -* During execution, a program will receive a list of account data as one of -* its arguments, in the same order as specified during `Instruction` -* construction. -* -* While Solana is agnostic to the format of the instruction data, it has -* built-in support for serialization via [`borsh`] and [`bincode`]. -* -* [`borsh`]: https://docs.rs/borsh/latest/borsh/ -* [`bincode`]: https://docs.rs/bincode/latest/bincode/ -* -* # Specifying account metadata -* -* When constructing an [`Instruction`], a list of all accounts that may be -* read or written during the execution of that instruction must be supplied as -* [`AccountMeta`] values. -* -* Any account whose data may be mutated by the program during execution must -* be specified as writable. During execution, writing to an account that was -* not specified as writable will cause the transaction to fail. Writing to an -* account that is not owned by the program will cause the transaction to fail. -* -* Any account whose lamport balance may be mutated by the program during -* execution must be specified as writable. During execution, mutating the -* lamports of an account that was not specified as writable will cause the -* transaction to fail. While _subtracting_ lamports from an account not owned -* by the program will cause the transaction to fail, _adding_ lamports to any -* account is allowed, as long is it is mutable. -* -* Accounts that are not read or written by the program may still be specified -* in an `Instruction`'s account list. These will affect scheduling of program -* execution by the runtime, but will otherwise be ignored. -* -* When building a transaction, the Solana runtime coalesces all accounts used -* by all instructions in that transaction, along with accounts and permissions -* required by the runtime, into a single account list. Some accounts and -* account permissions required by the runtime to process a transaction are -* _not_ required to be included in an `Instruction`s account list. These -* include: -* -* - The program ID — it is a separate field of `Instruction` -* - The transaction's fee-paying account — it is added during [`Message`] -* construction. A program may still require the fee payer as part of the -* account list if it directly references it. -* -* [`Message`]: crate::message::Message -* -* Programs may require signatures from some accounts, in which case they -* should be specified as signers during `Instruction` construction. The -* program must still validate during execution that the account is a signer. -*/ + * A directive for a single invocation of a Solana program. + * + * An instruction specifies which program it is calling, which accounts it may + * read or modify, and additional data that serves as input to the program. One + * or more instructions are included in transactions submitted by Solana + * clients. Instructions are also used to describe [cross-program + * invocations][cpi]. + * + * [cpi]: https://docs.solana.com/developing/programming-model/calling-between-programs + * + * During execution, a program will receive a list of account data as one of + * its arguments, in the same order as specified during `Instruction` + * construction. + * + * While Solana is agnostic to the format of the instruction data, it has + * built-in support for serialization via [`borsh`] and [`bincode`]. + * + * [`borsh`]: https://docs.rs/borsh/latest/borsh/ + * [`bincode`]: https://docs.rs/bincode/latest/bincode/ + * + * # Specifying account metadata + * + * When constructing an [`Instruction`], a list of all accounts that may be + * read or written during the execution of that instruction must be supplied as + * [`AccountMeta`] values. + * + * Any account whose data may be mutated by the program during execution must + * be specified as writable. During execution, writing to an account that was + * not specified as writable will cause the transaction to fail. Writing to an + * account that is not owned by the program will cause the transaction to fail. + * + * Any account whose lamport balance may be mutated by the program during + * execution must be specified as writable. During execution, mutating the + * lamports of an account that was not specified as writable will cause the + * transaction to fail. While _subtracting_ lamports from an account not owned + * by the program will cause the transaction to fail, _adding_ lamports to any + * account is allowed, as long is it is mutable. + * + * Accounts that are not read or written by the program may still be specified + * in an `Instruction`'s account list. These will affect scheduling of program + * execution by the runtime, but will otherwise be ignored. + * + * When building a transaction, the Solana runtime coalesces all accounts used + * by all instructions in that transaction, along with accounts and permissions + * required by the runtime, into a single account list. Some accounts and + * account permissions required by the runtime to process a transaction are + * _not_ required to be included in an `Instruction`s account list. These + * include: + * + * - The program ID — it is a separate field of `Instruction` + * - The transaction's fee-paying account — it is added during [`Message`] + * construction. A program may still require the fee payer as part of the + * account list if it directly references it. + * + * [`Message`]: crate::message::Message + * + * Programs may require signatures from some accounts, in which case they + * should be specified as signers during `Instruction` construction. The + * program must still validate during execution that the account is a signer. + */ class Instruction { + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Instruction.prototype); + obj.__wbg_ptr = ptr; - static __wrap(ptr) { - ptr = ptr >>> 0; - const obj = Object.create(Instruction.prototype); - obj.__wbg_ptr = ptr; + return obj; + } - return obj; - } + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; - } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_instruction_free(ptr); - } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_instruction_free(ptr); + } } module.exports.Instruction = Instruction; /** -*/ + */ class Instructions { + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Instructions.prototype); + obj.__wbg_ptr = ptr; - static __wrap(ptr) { - ptr = ptr >>> 0; - const obj = Object.create(Instructions.prototype); - obj.__wbg_ptr = ptr; + return obj; + } - return obj; - } + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; - } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_instructions_free(ptr); - } - /** - */ - constructor() { - const ret = wasm.instructions_constructor(); - return Instructions.__wrap(ret); - } - /** - * @param {Instruction} instruction - */ - push(instruction) { - _assertClass(instruction, Instruction); - var ptr0 = instruction.__destroy_into_raw(); - wasm.instructions_push(this.__wbg_ptr, ptr0); - } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_instructions_free(ptr); + } + /** + */ + constructor() { + const ret = wasm.instructions_constructor(); + return Instructions.__wrap(ret); + } + /** + * @param {Instruction} instruction + */ + push(instruction) { + _assertClass(instruction, Instruction); + var ptr0 = instruction.__destroy_into_raw(); + wasm.instructions_push(this.__wbg_ptr, ptr0); + } } module.exports.Instructions = Instructions; /** -* A Solana transaction message (legacy). -* -* See the [`message`] module documentation for further description. -* -* [`message`]: crate::message -* -* Some constructors accept an optional `payer`, the account responsible for -* paying the cost of executing a transaction. In most cases, callers should -* specify the payer explicitly in these constructors. In some cases though, -* the caller is not _required_ to specify the payer, but is still allowed to: -* in the `Message` structure, the first account is always the fee-payer, so if -* the caller has knowledge that the first account of the constructed -* transaction's `Message` is both a signer and the expected fee-payer, then -* redundantly specifying the fee-payer is not strictly required. -*/ + * A Solana transaction message (legacy). + * + * See the [`message`] module documentation for further description. + * + * [`message`]: crate::message + * + * Some constructors accept an optional `payer`, the account responsible for + * paying the cost of executing a transaction. In most cases, callers should + * specify the payer explicitly in these constructors. In some cases though, + * the caller is not _required_ to specify the payer, but is still allowed to: + * in the `Message` structure, the first account is always the fee-payer, so if + * the caller has knowledge that the first account of the constructed + * transaction's `Message` is both a signer and the expected fee-payer, then + * redundantly specifying the fee-payer is not strictly required. + */ class Message { + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; - } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_message_free(ptr); - } - /** - * The id of a recent ledger entry. - * @returns {Hash} - */ - get recent_blockhash() { - const ret = wasm.__wbg_get_message_recent_blockhash(this.__wbg_ptr); - return Hash.__wrap(ret); - } - /** - * The id of a recent ledger entry. - * @param {Hash} arg0 - */ - set recent_blockhash(arg0) { - _assertClass(arg0, Hash); - var ptr0 = arg0.__destroy_into_raw(); - wasm.__wbg_set_message_recent_blockhash(this.__wbg_ptr, ptr0); - } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_message_free(ptr); + } + /** + * The id of a recent ledger entry. + * @returns {Hash} + */ + get recent_blockhash() { + const ret = wasm.__wbg_get_message_recent_blockhash(this.__wbg_ptr); + return Hash.__wrap(ret); + } + /** + * The id of a recent ledger entry. + * @param {Hash} arg0 + */ + set recent_blockhash(arg0) { + _assertClass(arg0, Hash); + var ptr0 = arg0.__destroy_into_raw(); + wasm.__wbg_set_message_recent_blockhash(this.__wbg_ptr, ptr0); + } } module.exports.Message = Message; /** -* The address of a [Solana account][acc]. -* -* Some account addresses are [ed25519] public keys, with corresponding secret -* keys that are managed off-chain. Often, though, account addresses do not -* have corresponding secret keys — as with [_program derived -* addresses_][pdas] — or the secret key is not relevant to the operation -* of a program, and may have even been disposed of. As running Solana programs -* can not safely create or manage secret keys, the full [`Keypair`] is not -* defined in `solana-program` but in `solana-sdk`. -* -* [acc]: https://docs.solana.com/developing/programming-model/accounts -* [ed25519]: https://ed25519.cr.yp.to/ -* [pdas]: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses -* [`Keypair`]: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/struct.Keypair.html -*/ + * The address of a [Solana account][acc]. + * + * Some account addresses are [ed25519] public keys, with corresponding secret + * keys that are managed off-chain. Often, though, account addresses do not + * have corresponding secret keys — as with [_program derived + * addresses_][pdas] — or the secret key is not relevant to the operation + * of a program, and may have even been disposed of. As running Solana programs + * can not safely create or manage secret keys, the full [`Keypair`] is not + * defined in `solana-program` but in `solana-sdk`. + * + * [acc]: https://docs.solana.com/developing/programming-model/accounts + * [ed25519]: https://ed25519.cr.yp.to/ + * [pdas]: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses + * [`Keypair`]: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/struct.Keypair.html + */ class Pubkey { + static __wrap(ptr) { + ptr = ptr >>> 0; + const obj = Object.create(Pubkey.prototype); + obj.__wbg_ptr = ptr; - static __wrap(ptr) { - ptr = ptr >>> 0; - const obj = Object.create(Pubkey.prototype); - obj.__wbg_ptr = ptr; + return obj; + } - return obj; - } + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_pubkey_free(ptr); + } + /** + * Create a new Pubkey object + * + * * `value` - optional public key as a base58 encoded string, `Uint8Array`, `[number]` + * @param {any} value + */ + constructor(value) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.pubkey_constructor(retptr, addHeapObject(value)); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Pubkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_pubkey_free(ptr); + } + /** + * Return the base58 string representation of the public key + * @returns {string} + */ + toString() { + let deferred1_0; + let deferred1_1; + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.pubkey_toString(retptr, this.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + deferred1_0 = r0; + deferred1_1 = r1; + return getStringFromWasm0(r0, r1); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); + wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); } - /** - * Create a new Pubkey object - * - * * `value` - optional public key as a base58 encoded string, `Uint8Array`, `[number]` - * @param {any} value - */ - constructor(value) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.pubkey_constructor(retptr, addHeapObject(value)); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var r2 = getInt32Memory0()[retptr / 4 + 2]; - if (r2) { - throw takeObject(r1); - } - return Pubkey.__wrap(r0); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } + } + /** + * Check if a `Pubkey` is on the ed25519 curve. + * @returns {boolean} + */ + isOnCurve() { + const ret = wasm.pubkey_isOnCurve(this.__wbg_ptr); + return ret !== 0; + } + /** + * Checks if two `Pubkey`s are equal + * @param {Pubkey} other + * @returns {boolean} + */ + equals(other) { + _assertClass(other, Pubkey); + const ret = wasm.pubkey_equals(this.__wbg_ptr, other.__wbg_ptr); + return ret !== 0; + } + /** + * Return the `Uint8Array` representation of the public key + * @returns {Uint8Array} + */ + toBytes() { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + wasm.pubkey_toBytes(retptr, this.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var v1 = getArrayU8FromWasm0(r0, r1).slice(); + wasm.__wbindgen_free(r0, r1 * 1); + return v1; + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } - /** - * Return the base58 string representation of the public key - * @returns {string} - */ - toString() { - let deferred1_0; - let deferred1_1; - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.pubkey_toString(retptr, this.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - deferred1_0 = r0; - deferred1_1 = r1; - return getStringFromWasm0(r0, r1); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); - } + } + /** + * Derive a Pubkey from another Pubkey, string seed, and a program id + * @param {Pubkey} base + * @param {string} seed + * @param {Pubkey} owner + * @returns {Pubkey} + */ + static createWithSeed(base, seed, owner) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + _assertClass(base, Pubkey); + const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(owner, Pubkey); + wasm.pubkey_createWithSeed(retptr, base.__wbg_ptr, ptr0, len0, owner.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Pubkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } - /** - * Check if a `Pubkey` is on the ed25519 curve. - * @returns {boolean} - */ - isOnCurve() { - const ret = wasm.pubkey_isOnCurve(this.__wbg_ptr); - return ret !== 0; + } + /** + * Derive a program address from seeds and a program id + * @param {any[]} seeds + * @param {Pubkey} program_id + * @returns {Pubkey} + */ + static createProgramAddress(seeds, program_id) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArrayJsValueToWasm0(seeds, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(program_id, Pubkey); + wasm.pubkey_createProgramAddress(retptr, ptr0, len0, program_id.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return Pubkey.__wrap(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } - /** - * Checks if two `Pubkey`s are equal - * @param {Pubkey} other - * @returns {boolean} - */ - equals(other) { - _assertClass(other, Pubkey); - const ret = wasm.pubkey_equals(this.__wbg_ptr, other.__wbg_ptr); - return ret !== 0; - } - /** - * Return the `Uint8Array` representation of the public key - * @returns {Uint8Array} - */ - toBytes() { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.pubkey_toBytes(retptr, this.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var v1 = getArrayU8FromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 1); - return v1; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } - } - /** - * Derive a Pubkey from another Pubkey, string seed, and a program id - * @param {Pubkey} base - * @param {string} seed - * @param {Pubkey} owner - * @returns {Pubkey} - */ - static createWithSeed(base, seed, owner) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - _assertClass(base, Pubkey); - const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(owner, Pubkey); - wasm.pubkey_createWithSeed(retptr, base.__wbg_ptr, ptr0, len0, owner.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var r2 = getInt32Memory0()[retptr / 4 + 2]; - if (r2) { - throw takeObject(r1); - } - return Pubkey.__wrap(r0); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } - } - /** - * Derive a program address from seeds and a program id - * @param {any[]} seeds - * @param {Pubkey} program_id - * @returns {Pubkey} - */ - static createProgramAddress(seeds, program_id) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passArrayJsValueToWasm0(seeds, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(program_id, Pubkey); - wasm.pubkey_createProgramAddress(retptr, ptr0, len0, program_id.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var r2 = getInt32Memory0()[retptr / 4 + 2]; - if (r2) { - throw takeObject(r1); - } - return Pubkey.__wrap(r0); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } - } - /** - * Find a valid program address - * - * Returns: - * * `[PubKey, number]` - the program address and bump seed - * @param {any[]} seeds - * @param {Pubkey} program_id - * @returns {any} - */ - static findProgramAddress(seeds, program_id) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passArrayJsValueToWasm0(seeds, wasm.__wbindgen_malloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(program_id, Pubkey); - wasm.pubkey_findProgramAddress(retptr, ptr0, len0, program_id.__wbg_ptr); - var r0 = getInt32Memory0()[retptr / 4 + 0]; - var r1 = getInt32Memory0()[retptr / 4 + 1]; - var r2 = getInt32Memory0()[retptr / 4 + 2]; - if (r2) { - throw takeObject(r1); - } - return takeObject(r0); - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } + } + /** + * Find a valid program address + * + * Returns: + * * `[PubKey, number]` - the program address and bump seed + * @param {any[]} seeds + * @param {Pubkey} program_id + * @returns {any} + */ + static findProgramAddress(seeds, program_id) { + try { + const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); + const ptr0 = passArrayJsValueToWasm0(seeds, wasm.__wbindgen_malloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(program_id, Pubkey); + wasm.pubkey_findProgramAddress(retptr, ptr0, len0, program_id.__wbg_ptr); + var r0 = getInt32Memory0()[retptr / 4 + 0]; + var r1 = getInt32Memory0()[retptr / 4 + 1]; + var r2 = getInt32Memory0()[retptr / 4 + 2]; + if (r2) { + throw takeObject(r1); + } + return takeObject(r0); + } finally { + wasm.__wbindgen_add_to_stack_pointer(16); } + } } module.exports.Pubkey = Pubkey; class SystemInstruction { + __destroy_into_raw() { + const ptr = this.__wbg_ptr; + this.__wbg_ptr = 0; - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; + return ptr; + } - return ptr; - } - - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_systeminstruction_free(ptr); - } - /** - * @param {Pubkey} from_pubkey - * @param {Pubkey} to_pubkey - * @param {bigint} lamports - * @param {bigint} space - * @param {Pubkey} owner - * @returns {Instruction} - */ - static createAccount(from_pubkey, to_pubkey, lamports, space, owner) { - _assertClass(from_pubkey, Pubkey); - _assertClass(to_pubkey, Pubkey); - _assertClass(owner, Pubkey); - const ret = wasm.systeminstruction_createAccount(from_pubkey.__wbg_ptr, to_pubkey.__wbg_ptr, lamports, space, owner.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} from_pubkey - * @param {Pubkey} to_pubkey - * @param {Pubkey} base - * @param {string} seed - * @param {bigint} lamports - * @param {bigint} space - * @param {Pubkey} owner - * @returns {Instruction} - */ - static createAccountWithSeed(from_pubkey, to_pubkey, base, seed, lamports, space, owner) { - _assertClass(from_pubkey, Pubkey); - _assertClass(to_pubkey, Pubkey); - _assertClass(base, Pubkey); - const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(owner, Pubkey); - const ret = wasm.systeminstruction_createAccountWithSeed(from_pubkey.__wbg_ptr, to_pubkey.__wbg_ptr, base.__wbg_ptr, ptr0, len0, lamports, space, owner.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} pubkey - * @param {Pubkey} owner - * @returns {Instruction} - */ - static assign(pubkey, owner) { - _assertClass(pubkey, Pubkey); - _assertClass(owner, Pubkey); - const ret = wasm.systeminstruction_assign(pubkey.__wbg_ptr, owner.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} pubkey - * @param {Pubkey} base - * @param {string} seed - * @param {Pubkey} owner - * @returns {Instruction} - */ - static assignWithSeed(pubkey, base, seed, owner) { - _assertClass(pubkey, Pubkey); - _assertClass(base, Pubkey); - const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(owner, Pubkey); - const ret = wasm.systeminstruction_assignWithSeed(pubkey.__wbg_ptr, base.__wbg_ptr, ptr0, len0, owner.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} from_pubkey - * @param {Pubkey} to_pubkey - * @param {bigint} lamports - * @returns {Instruction} - */ - static transfer(from_pubkey, to_pubkey, lamports) { - _assertClass(from_pubkey, Pubkey); - _assertClass(to_pubkey, Pubkey); - const ret = wasm.systeminstruction_transfer(from_pubkey.__wbg_ptr, to_pubkey.__wbg_ptr, lamports); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} from_pubkey - * @param {Pubkey} from_base - * @param {string} from_seed - * @param {Pubkey} from_owner - * @param {Pubkey} to_pubkey - * @param {bigint} lamports - * @returns {Instruction} - */ - static transferWithSeed(from_pubkey, from_base, from_seed, from_owner, to_pubkey, lamports) { - _assertClass(from_pubkey, Pubkey); - _assertClass(from_base, Pubkey); - const ptr0 = passStringToWasm0(from_seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(from_owner, Pubkey); - _assertClass(to_pubkey, Pubkey); - const ret = wasm.systeminstruction_transferWithSeed(from_pubkey.__wbg_ptr, from_base.__wbg_ptr, ptr0, len0, from_owner.__wbg_ptr, to_pubkey.__wbg_ptr, lamports); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} pubkey - * @param {bigint} space - * @returns {Instruction} - */ - static allocate(pubkey, space) { - _assertClass(pubkey, Pubkey); - const ret = wasm.systeminstruction_allocate(pubkey.__wbg_ptr, space); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} address - * @param {Pubkey} base - * @param {string} seed - * @param {bigint} space - * @param {Pubkey} owner - * @returns {Instruction} - */ - static allocateWithSeed(address, base, seed, space, owner) { - _assertClass(address, Pubkey); - _assertClass(base, Pubkey); - const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - _assertClass(owner, Pubkey); - const ret = wasm.systeminstruction_allocateWithSeed(address.__wbg_ptr, base.__wbg_ptr, ptr0, len0, space, owner.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} from_pubkey - * @param {Pubkey} nonce_pubkey - * @param {Pubkey} authority - * @param {bigint} lamports - * @returns {Array} - */ - static createNonceAccount(from_pubkey, nonce_pubkey, authority, lamports) { - _assertClass(from_pubkey, Pubkey); - _assertClass(nonce_pubkey, Pubkey); - _assertClass(authority, Pubkey); - const ret = wasm.systeminstruction_createNonceAccount(from_pubkey.__wbg_ptr, nonce_pubkey.__wbg_ptr, authority.__wbg_ptr, lamports); - return takeObject(ret); - } - /** - * @param {Pubkey} nonce_pubkey - * @param {Pubkey} authorized_pubkey - * @returns {Instruction} - */ - static advanceNonceAccount(nonce_pubkey, authorized_pubkey) { - _assertClass(nonce_pubkey, Pubkey); - _assertClass(authorized_pubkey, Pubkey); - const ret = wasm.systeminstruction_advanceNonceAccount(nonce_pubkey.__wbg_ptr, authorized_pubkey.__wbg_ptr); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} nonce_pubkey - * @param {Pubkey} authorized_pubkey - * @param {Pubkey} to_pubkey - * @param {bigint} lamports - * @returns {Instruction} - */ - static withdrawNonceAccount(nonce_pubkey, authorized_pubkey, to_pubkey, lamports) { - _assertClass(nonce_pubkey, Pubkey); - _assertClass(authorized_pubkey, Pubkey); - _assertClass(to_pubkey, Pubkey); - const ret = wasm.systeminstruction_withdrawNonceAccount(nonce_pubkey.__wbg_ptr, authorized_pubkey.__wbg_ptr, to_pubkey.__wbg_ptr, lamports); - return Instruction.__wrap(ret); - } - /** - * @param {Pubkey} nonce_pubkey - * @param {Pubkey} authorized_pubkey - * @param {Pubkey} new_authority - * @returns {Instruction} - */ - static authorizeNonceAccount(nonce_pubkey, authorized_pubkey, new_authority) { - _assertClass(nonce_pubkey, Pubkey); - _assertClass(authorized_pubkey, Pubkey); - _assertClass(new_authority, Pubkey); - const ret = wasm.systeminstruction_authorizeNonceAccount(nonce_pubkey.__wbg_ptr, authorized_pubkey.__wbg_ptr, new_authority.__wbg_ptr); - return Instruction.__wrap(ret); - } + free() { + const ptr = this.__destroy_into_raw(); + wasm.__wbg_systeminstruction_free(ptr); + } + /** + * @param {Pubkey} from_pubkey + * @param {Pubkey} to_pubkey + * @param {bigint} lamports + * @param {bigint} space + * @param {Pubkey} owner + * @returns {Instruction} + */ + static createAccount(from_pubkey, to_pubkey, lamports, space, owner) { + _assertClass(from_pubkey, Pubkey); + _assertClass(to_pubkey, Pubkey); + _assertClass(owner, Pubkey); + const ret = wasm.systeminstruction_createAccount( + from_pubkey.__wbg_ptr, + to_pubkey.__wbg_ptr, + lamports, + space, + owner.__wbg_ptr, + ); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} from_pubkey + * @param {Pubkey} to_pubkey + * @param {Pubkey} base + * @param {string} seed + * @param {bigint} lamports + * @param {bigint} space + * @param {Pubkey} owner + * @returns {Instruction} + */ + static createAccountWithSeed(from_pubkey, to_pubkey, base, seed, lamports, space, owner) { + _assertClass(from_pubkey, Pubkey); + _assertClass(to_pubkey, Pubkey); + _assertClass(base, Pubkey); + const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(owner, Pubkey); + const ret = wasm.systeminstruction_createAccountWithSeed( + from_pubkey.__wbg_ptr, + to_pubkey.__wbg_ptr, + base.__wbg_ptr, + ptr0, + len0, + lamports, + space, + owner.__wbg_ptr, + ); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} pubkey + * @param {Pubkey} owner + * @returns {Instruction} + */ + static assign(pubkey, owner) { + _assertClass(pubkey, Pubkey); + _assertClass(owner, Pubkey); + const ret = wasm.systeminstruction_assign(pubkey.__wbg_ptr, owner.__wbg_ptr); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} pubkey + * @param {Pubkey} base + * @param {string} seed + * @param {Pubkey} owner + * @returns {Instruction} + */ + static assignWithSeed(pubkey, base, seed, owner) { + _assertClass(pubkey, Pubkey); + _assertClass(base, Pubkey); + const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(owner, Pubkey); + const ret = wasm.systeminstruction_assignWithSeed(pubkey.__wbg_ptr, base.__wbg_ptr, ptr0, len0, owner.__wbg_ptr); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} from_pubkey + * @param {Pubkey} to_pubkey + * @param {bigint} lamports + * @returns {Instruction} + */ + static transfer(from_pubkey, to_pubkey, lamports) { + _assertClass(from_pubkey, Pubkey); + _assertClass(to_pubkey, Pubkey); + const ret = wasm.systeminstruction_transfer(from_pubkey.__wbg_ptr, to_pubkey.__wbg_ptr, lamports); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} from_pubkey + * @param {Pubkey} from_base + * @param {string} from_seed + * @param {Pubkey} from_owner + * @param {Pubkey} to_pubkey + * @param {bigint} lamports + * @returns {Instruction} + */ + static transferWithSeed(from_pubkey, from_base, from_seed, from_owner, to_pubkey, lamports) { + _assertClass(from_pubkey, Pubkey); + _assertClass(from_base, Pubkey); + const ptr0 = passStringToWasm0(from_seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(from_owner, Pubkey); + _assertClass(to_pubkey, Pubkey); + const ret = wasm.systeminstruction_transferWithSeed( + from_pubkey.__wbg_ptr, + from_base.__wbg_ptr, + ptr0, + len0, + from_owner.__wbg_ptr, + to_pubkey.__wbg_ptr, + lamports, + ); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} pubkey + * @param {bigint} space + * @returns {Instruction} + */ + static allocate(pubkey, space) { + _assertClass(pubkey, Pubkey); + const ret = wasm.systeminstruction_allocate(pubkey.__wbg_ptr, space); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} address + * @param {Pubkey} base + * @param {string} seed + * @param {bigint} space + * @param {Pubkey} owner + * @returns {Instruction} + */ + static allocateWithSeed(address, base, seed, space, owner) { + _assertClass(address, Pubkey); + _assertClass(base, Pubkey); + const ptr0 = passStringToWasm0(seed, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len0 = WASM_VECTOR_LEN; + _assertClass(owner, Pubkey); + const ret = wasm.systeminstruction_allocateWithSeed( + address.__wbg_ptr, + base.__wbg_ptr, + ptr0, + len0, + space, + owner.__wbg_ptr, + ); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} from_pubkey + * @param {Pubkey} nonce_pubkey + * @param {Pubkey} authority + * @param {bigint} lamports + * @returns {Array} + */ + static createNonceAccount(from_pubkey, nonce_pubkey, authority, lamports) { + _assertClass(from_pubkey, Pubkey); + _assertClass(nonce_pubkey, Pubkey); + _assertClass(authority, Pubkey); + const ret = wasm.systeminstruction_createNonceAccount( + from_pubkey.__wbg_ptr, + nonce_pubkey.__wbg_ptr, + authority.__wbg_ptr, + lamports, + ); + return takeObject(ret); + } + /** + * @param {Pubkey} nonce_pubkey + * @param {Pubkey} authorized_pubkey + * @returns {Instruction} + */ + static advanceNonceAccount(nonce_pubkey, authorized_pubkey) { + _assertClass(nonce_pubkey, Pubkey); + _assertClass(authorized_pubkey, Pubkey); + const ret = wasm.systeminstruction_advanceNonceAccount(nonce_pubkey.__wbg_ptr, authorized_pubkey.__wbg_ptr); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} nonce_pubkey + * @param {Pubkey} authorized_pubkey + * @param {Pubkey} to_pubkey + * @param {bigint} lamports + * @returns {Instruction} + */ + static withdrawNonceAccount(nonce_pubkey, authorized_pubkey, to_pubkey, lamports) { + _assertClass(nonce_pubkey, Pubkey); + _assertClass(authorized_pubkey, Pubkey); + _assertClass(to_pubkey, Pubkey); + const ret = wasm.systeminstruction_withdrawNonceAccount( + nonce_pubkey.__wbg_ptr, + authorized_pubkey.__wbg_ptr, + to_pubkey.__wbg_ptr, + lamports, + ); + return Instruction.__wrap(ret); + } + /** + * @param {Pubkey} nonce_pubkey + * @param {Pubkey} authorized_pubkey + * @param {Pubkey} new_authority + * @returns {Instruction} + */ + static authorizeNonceAccount(nonce_pubkey, authorized_pubkey, new_authority) { + _assertClass(nonce_pubkey, Pubkey); + _assertClass(authorized_pubkey, Pubkey); + _assertClass(new_authority, Pubkey); + const ret = wasm.systeminstruction_authorizeNonceAccount( + nonce_pubkey.__wbg_ptr, + authorized_pubkey.__wbg_ptr, + new_authority.__wbg_ptr, + ); + return Instruction.__wrap(ret); + } } module.exports.SystemInstruction = SystemInstruction; -module.exports.__wbindgen_error_new = function(arg0, arg1) { - const ret = new Error(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); +module.exports.__wbindgen_error_new = function (arg0, arg1) { + const ret = new Error(getStringFromWasm0(arg0, arg1)); + return addHeapObject(ret); }; -module.exports.__wbindgen_object_drop_ref = function(arg0) { - takeObject(arg0); +module.exports.__wbindgen_object_drop_ref = function (arg0) { + takeObject(arg0); }; -module.exports.__wbg_log_fb911463b057a706 = function(arg0, arg1) { - console.log(getStringFromWasm0(arg0, arg1)); +module.exports.__wbg_log_fb911463b057a706 = function (arg0, arg1) { + console.log(getStringFromWasm0(arg0, arg1)); }; -module.exports.__wbindgen_number_new = function(arg0) { - const ret = arg0; - return addHeapObject(ret); +module.exports.__wbindgen_number_new = function (arg0) { + const ret = arg0; + return addHeapObject(ret); }; -module.exports.__wbindgen_bigint_from_u64 = function(arg0) { - const ret = BigInt.asUintN(64, arg0); - return addHeapObject(ret); +module.exports.__wbindgen_bigint_from_u64 = function (arg0) { + const ret = BigInt.asUintN(64, arg0); + return addHeapObject(ret); }; -module.exports.__wbindgen_string_new = function(arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); +module.exports.__wbindgen_string_new = function (arg0, arg1) { + const ret = getStringFromWasm0(arg0, arg1); + return addHeapObject(ret); }; -module.exports.__wbindgen_object_clone_ref = function(arg0) { - const ret = getObject(arg0); - return addHeapObject(ret); +module.exports.__wbindgen_object_clone_ref = function (arg0) { + const ret = getObject(arg0); + return addHeapObject(ret); }; -module.exports.__wbindgen_is_object = function(arg0) { - const val = getObject(arg0); - const ret = typeof(val) === 'object' && val !== null; - return ret; +module.exports.__wbindgen_is_object = function (arg0) { + const val = getObject(arg0); + const ret = typeof val === "object" && val !== null; + return ret; }; -module.exports.__wbindgen_jsval_loose_eq = function(arg0, arg1) { - const ret = getObject(arg0) == getObject(arg1); - return ret; +module.exports.__wbindgen_jsval_loose_eq = function (arg0, arg1) { + const ret = getObject(arg0) == getObject(arg1); + return ret; }; -module.exports.__wbindgen_boolean_get = function(arg0) { - const v = getObject(arg0); - const ret = typeof(v) === 'boolean' ? (v ? 1 : 0) : 2; - return ret; +module.exports.__wbindgen_boolean_get = function (arg0) { + const v = getObject(arg0); + const ret = typeof v === "boolean" ? (v ? 1 : 0) : 2; + return ret; }; -module.exports.__wbindgen_number_get = function(arg0, arg1) { - const obj = getObject(arg1); - const ret = typeof(obj) === 'number' ? obj : undefined; - getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret; - getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret); +module.exports.__wbindgen_number_get = function (arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === "number" ? obj : undefined; + getFloat64Memory0()[arg0 / 8 + 1] = isLikeNone(ret) ? 0 : ret; + getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret); }; -module.exports.__wbindgen_string_get = function(arg0, arg1) { - const obj = getObject(arg1); - const ret = typeof(obj) === 'string' ? obj : undefined; - var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - getInt32Memory0()[arg0 / 4 + 1] = len1; - getInt32Memory0()[arg0 / 4 + 0] = ptr1; +module.exports.__wbindgen_string_get = function (arg0, arg1) { + const obj = getObject(arg1); + const ret = typeof obj === "string" ? obj : undefined; + var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + var len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbg_set_20cbc34131e76824 = function(arg0, arg1, arg2) { - getObject(arg0)[takeObject(arg1)] = takeObject(arg2); +module.exports.__wbg_set_20cbc34131e76824 = function (arg0, arg1, arg2) { + getObject(arg0)[takeObject(arg1)] = takeObject(arg2); }; -module.exports.__wbg_instruction_new = function(arg0) { - const ret = Instruction.__wrap(arg0); - return addHeapObject(ret); +module.exports.__wbg_instruction_new = function (arg0) { + const ret = Instruction.__wrap(arg0); + return addHeapObject(ret); }; -module.exports.__wbg_pubkey_new = function(arg0) { - const ret = Pubkey.__wrap(arg0); - return addHeapObject(ret); +module.exports.__wbg_pubkey_new = function (arg0) { + const ret = Pubkey.__wrap(arg0); + return addHeapObject(ret); }; -module.exports.__wbindgen_is_undefined = function(arg0) { - const ret = getObject(arg0) === undefined; - return ret; +module.exports.__wbindgen_is_undefined = function (arg0) { + const ret = getObject(arg0) === undefined; + return ret; }; -module.exports.__wbg_debug_9a6b3243fbbebb61 = function(arg0) { - console.debug(getObject(arg0)); +module.exports.__wbg_debug_9a6b3243fbbebb61 = function (arg0) { + console.debug(getObject(arg0)); }; -module.exports.__wbg_error_788ae33f81d3b84b = function(arg0) { - console.error(getObject(arg0)); +module.exports.__wbg_error_788ae33f81d3b84b = function (arg0) { + console.error(getObject(arg0)); }; -module.exports.__wbg_info_2e30e8204b29d91d = function(arg0) { - console.info(getObject(arg0)); +module.exports.__wbg_info_2e30e8204b29d91d = function (arg0) { + console.info(getObject(arg0)); }; -module.exports.__wbg_log_1d3ae0273d8f4f8a = function(arg0) { - console.log(getObject(arg0)); +module.exports.__wbg_log_1d3ae0273d8f4f8a = function (arg0) { + console.log(getObject(arg0)); }; -module.exports.__wbg_warn_d60e832f9882c1b2 = function(arg0) { - console.warn(getObject(arg0)); +module.exports.__wbg_warn_d60e832f9882c1b2 = function (arg0) { + console.warn(getObject(arg0)); }; -module.exports.__wbg_new_abda76e883ba8a5f = function() { - const ret = new Error(); - return addHeapObject(ret); +module.exports.__wbg_new_abda76e883ba8a5f = function () { + const ret = new Error(); + return addHeapObject(ret); }; -module.exports.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) { - const ret = getObject(arg1).stack; - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getInt32Memory0()[arg0 / 4 + 1] = len1; - getInt32Memory0()[arg0 / 4 + 0] = ptr1; +module.exports.__wbg_stack_658279fe44541cf6 = function (arg0, arg1) { + const ret = getObject(arg1).stack; + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) { - let deferred0_0; - let deferred0_1; - try { - deferred0_0 = arg0; - deferred0_1 = arg1; - console.error(getStringFromWasm0(arg0, arg1)); - } finally { - wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); - } +module.exports.__wbg_error_f851667af71bcfc6 = function (arg0, arg1) { + let deferred0_0; + let deferred0_1; + try { + deferred0_0 = arg0; + deferred0_1 = arg1; + console.error(getStringFromWasm0(arg0, arg1)); + } finally { + wasm.__wbindgen_free(deferred0_0, deferred0_1, 1); + } }; -module.exports.__wbindgen_is_string = function(arg0) { - const ret = typeof(getObject(arg0)) === 'string'; - return ret; +module.exports.__wbindgen_is_string = function (arg0) { + const ret = typeof getObject(arg0) === "string"; + return ret; }; -module.exports.__wbg_get_44be0491f933a435 = function(arg0, arg1) { - const ret = getObject(arg0)[arg1 >>> 0]; - return addHeapObject(ret); +module.exports.__wbg_get_44be0491f933a435 = function (arg0, arg1) { + const ret = getObject(arg0)[arg1 >>> 0]; + return addHeapObject(ret); }; -module.exports.__wbg_length_fff51ee6522a1a18 = function(arg0) { - const ret = getObject(arg0).length; - return ret; +module.exports.__wbg_length_fff51ee6522a1a18 = function (arg0) { + const ret = getObject(arg0).length; + return ret; }; -module.exports.__wbg_new_898a68150f225f2e = function() { - const ret = new Array(); - return addHeapObject(ret); +module.exports.__wbg_new_898a68150f225f2e = function () { + const ret = new Array(); + return addHeapObject(ret); }; -module.exports.__wbindgen_is_function = function(arg0) { - const ret = typeof(getObject(arg0)) === 'function'; - return ret; +module.exports.__wbindgen_is_function = function (arg0) { + const ret = typeof getObject(arg0) === "function"; + return ret; }; -module.exports.__wbg_new_56693dbed0c32988 = function() { - const ret = new Map(); - return addHeapObject(ret); +module.exports.__wbg_new_56693dbed0c32988 = function () { + const ret = new Map(); + return addHeapObject(ret); }; -module.exports.__wbg_next_526fc47e980da008 = function(arg0) { - const ret = getObject(arg0).next; - return addHeapObject(ret); +module.exports.__wbg_next_526fc47e980da008 = function (arg0) { + const ret = getObject(arg0).next; + return addHeapObject(ret); }; -module.exports.__wbg_next_ddb3312ca1c4e32a = function() { return handleError(function (arg0) { +module.exports.__wbg_next_ddb3312ca1c4e32a = function () { + return handleError(function (arg0) { const ret = getObject(arg0).next(); return addHeapObject(ret); -}, arguments) }; - -module.exports.__wbg_done_5c1f01fb660d73b5 = function(arg0) { - const ret = getObject(arg0).done; - return ret; + }, arguments); }; -module.exports.__wbg_value_1695675138684bd5 = function(arg0) { - const ret = getObject(arg0).value; - return addHeapObject(ret); +module.exports.__wbg_done_5c1f01fb660d73b5 = function (arg0) { + const ret = getObject(arg0).done; + return ret; }; -module.exports.__wbg_iterator_97f0c81209c6c35a = function() { - const ret = Symbol.iterator; - return addHeapObject(ret); +module.exports.__wbg_value_1695675138684bd5 = function (arg0) { + const ret = getObject(arg0).value; + return addHeapObject(ret); }; -module.exports.__wbg_get_97b561fb56f034b5 = function() { return handleError(function (arg0, arg1) { +module.exports.__wbg_iterator_97f0c81209c6c35a = function () { + const ret = Symbol.iterator; + return addHeapObject(ret); +}; + +module.exports.__wbg_get_97b561fb56f034b5 = function () { + return handleError(function (arg0, arg1) { const ret = Reflect.get(getObject(arg0), getObject(arg1)); return addHeapObject(ret); -}, arguments) }; + }, arguments); +}; -module.exports.__wbg_call_cb65541d95d71282 = function() { return handleError(function (arg0, arg1) { +module.exports.__wbg_call_cb65541d95d71282 = function () { + return handleError(function (arg0, arg1) { const ret = getObject(arg0).call(getObject(arg1)); return addHeapObject(ret); -}, arguments) }; - -module.exports.__wbg_new_b51585de1b234aff = function() { - const ret = new Object(); - return addHeapObject(ret); + }, arguments); }; -module.exports.__wbg_newwithlength_3ec098a360da1909 = function(arg0) { - const ret = new Array(arg0 >>> 0); - return addHeapObject(ret); +module.exports.__wbg_new_b51585de1b234aff = function () { + const ret = new Object(); + return addHeapObject(ret); }; -module.exports.__wbg_set_502d29070ea18557 = function(arg0, arg1, arg2) { - getObject(arg0)[arg1 >>> 0] = takeObject(arg2); +module.exports.__wbg_newwithlength_3ec098a360da1909 = function (arg0) { + const ret = new Array(arg0 >>> 0); + return addHeapObject(ret); }; -module.exports.__wbg_isArray_4c24b343cb13cfb1 = function(arg0) { - const ret = Array.isArray(getObject(arg0)); - return ret; +module.exports.__wbg_set_502d29070ea18557 = function (arg0, arg1, arg2) { + getObject(arg0)[arg1 >>> 0] = takeObject(arg2); }; -module.exports.__wbg_push_ca1c26067ef907ac = function(arg0, arg1) { - const ret = getObject(arg0).push(getObject(arg1)); - return ret; +module.exports.__wbg_isArray_4c24b343cb13cfb1 = function (arg0) { + const ret = Array.isArray(getObject(arg0)); + return ret; }; -module.exports.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb = function(arg0) { - let result; - try { - result = getObject(arg0) instanceof ArrayBuffer; - } catch { - result = false; - } - const ret = result; - return ret; +module.exports.__wbg_push_ca1c26067ef907ac = function (arg0, arg1) { + const ret = getObject(arg0).push(getObject(arg1)); + return ret; }; -module.exports.__wbg_values_e80af618f92c8649 = function(arg0) { - const ret = getObject(arg0).values(); - return addHeapObject(ret); +module.exports.__wbg_instanceof_ArrayBuffer_39ac22089b74fddb = function (arg0) { + let result; + try { + result = getObject(arg0) instanceof ArrayBuffer; + } catch { + result = false; + } + const ret = result; + return ret; }; -module.exports.__wbg_set_bedc3d02d0f05eb0 = function(arg0, arg1, arg2) { - const ret = getObject(arg0).set(getObject(arg1), getObject(arg2)); - return addHeapObject(ret); +module.exports.__wbg_values_e80af618f92c8649 = function (arg0) { + const ret = getObject(arg0).values(); + return addHeapObject(ret); }; -module.exports.__wbg_isSafeInteger_bb8e18dd21c97288 = function(arg0) { - const ret = Number.isSafeInteger(getObject(arg0)); - return ret; +module.exports.__wbg_set_bedc3d02d0f05eb0 = function (arg0, arg1, arg2) { + const ret = getObject(arg0).set(getObject(arg1), getObject(arg2)); + return addHeapObject(ret); }; -module.exports.__wbg_buffer_085ec1f694018c4f = function(arg0) { - const ret = getObject(arg0).buffer; - return addHeapObject(ret); +module.exports.__wbg_isSafeInteger_bb8e18dd21c97288 = function (arg0) { + const ret = Number.isSafeInteger(getObject(arg0)); + return ret; }; -module.exports.__wbg_new_8125e318e6245eed = function(arg0) { - const ret = new Uint8Array(getObject(arg0)); - return addHeapObject(ret); +module.exports.__wbg_buffer_085ec1f694018c4f = function (arg0) { + const ret = getObject(arg0).buffer; + return addHeapObject(ret); }; -module.exports.__wbg_set_5cf90238115182c3 = function(arg0, arg1, arg2) { - getObject(arg0).set(getObject(arg1), arg2 >>> 0); +module.exports.__wbg_new_8125e318e6245eed = function (arg0) { + const ret = new Uint8Array(getObject(arg0)); + return addHeapObject(ret); }; -module.exports.__wbg_length_72e2208bbc0efc61 = function(arg0) { - const ret = getObject(arg0).length; - return ret; +module.exports.__wbg_set_5cf90238115182c3 = function (arg0, arg1, arg2) { + getObject(arg0).set(getObject(arg1), arg2 >>> 0); }; -module.exports.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4 = function(arg0) { - let result; - try { - result = getObject(arg0) instanceof Uint8Array; - } catch { - result = false; - } - const ret = result; - return ret; +module.exports.__wbg_length_72e2208bbc0efc61 = function (arg0) { + const ret = getObject(arg0).length; + return ret; }; -module.exports.__wbindgen_debug_string = function(arg0, arg1) { - const ret = debugString(getObject(arg1)); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getInt32Memory0()[arg0 / 4 + 1] = len1; - getInt32Memory0()[arg0 / 4 + 0] = ptr1; +module.exports.__wbg_instanceof_Uint8Array_d8d9cb2b8e8ac1d4 = function (arg0) { + let result; + try { + result = getObject(arg0) instanceof Uint8Array; + } catch { + result = false; + } + const ret = result; + return ret; }; -module.exports.__wbindgen_throw = function(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); +module.exports.__wbindgen_debug_string = function (arg0, arg1) { + const ret = debugString(getObject(arg1)); + const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); + const len1 = WASM_VECTOR_LEN; + getInt32Memory0()[arg0 / 4 + 1] = len1; + getInt32Memory0()[arg0 / 4 + 0] = ptr1; }; -module.exports.__wbindgen_memory = function() { - const ret = wasm.memory; - return addHeapObject(ret); +module.exports.__wbindgen_throw = function (arg0, arg1) { + throw new Error(getStringFromWasm0(arg0, arg1)); }; -const path = require('path').join(__dirname, 'bincode_js_bg.wasm'); -const bytes = require('fs').readFileSync(path); +module.exports.__wbindgen_memory = function () { + const ret = wasm.memory; + return addHeapObject(ret); +}; + +const path = require("path").join(__dirname, "bincode_js_bg.wasm"); +const bytes = require("fs").readFileSync(path); const wasmModule = new WebAssembly.Module(bytes); const wasmInstance = new WebAssembly.Instance(wasmModule, imports); wasm = wasmInstance.exports; module.exports.__wasm = wasm; - diff --git a/worker/tests/wasm/bincode_js.d.ts b/worker/tests/wasm/bincode_js.d.ts index 69452b2..4b03418 100644 --- a/worker/tests/wasm/bincode_js.d.ts +++ b/worker/tests/wasm/bincode_js.d.ts @@ -1,225 +1,225 @@ /* tslint:disable */ /* eslint-disable */ /** -* @param {any} val -* @returns {any} -*/ + * @param {any} val + * @returns {any} + */ export function bincode_js_deserialize(val: any): any; /** -* @param {any} val -* @returns {any} -*/ + * @param {any} val + * @returns {any} + */ export function borsh_bpf_js_deserialize(val: any): any; /** -* Initialize Javascript logging and panic handler -*/ + * Initialize Javascript logging and panic handler + */ export function solana_program_init(): void; /** -* A hash; the 32-byte output of a hashing algorithm. -* -* This struct is used most often in `solana-sdk` and related crates to contain -* a [SHA-256] hash, but may instead contain a [blake3] hash, as created by the -* [`blake3`] module (and used in [`Message::hash`]). -* -* [SHA-256]: https://en.wikipedia.org/wiki/SHA-2 -* [blake3]: https://github.com/BLAKE3-team/BLAKE3 -* [`blake3`]: crate::blake3 -* [`Message::hash`]: crate::message::Message::hash -*/ + * A hash; the 32-byte output of a hashing algorithm. + * + * This struct is used most often in `solana-sdk` and related crates to contain + * a [SHA-256] hash, but may instead contain a [blake3] hash, as created by the + * [`blake3`] module (and used in [`Message::hash`]). + * + * [SHA-256]: https://en.wikipedia.org/wiki/SHA-2 + * [blake3]: https://github.com/BLAKE3-team/BLAKE3 + * [`blake3`]: crate::blake3 + * [`Message::hash`]: crate::message::Message::hash + */ export class Hash { free(): void; -/** -* Create a new Hash object -* -* * `value` - optional hash as a base58 encoded string, `Uint8Array`, `[number]` -* @param {any} value -*/ + /** + * Create a new Hash object + * + * * `value` - optional hash as a base58 encoded string, `Uint8Array`, `[number]` + * @param {any} value + */ constructor(value: any); -/** -* Return the base58 string representation of the hash -* @returns {string} -*/ + /** + * Return the base58 string representation of the hash + * @returns {string} + */ toString(): string; -/** -* Checks if two `Hash`s are equal -* @param {Hash} other -* @returns {boolean} -*/ + /** + * Checks if two `Hash`s are equal + * @param {Hash} other + * @returns {boolean} + */ equals(other: Hash): boolean; -/** -* Return the `Uint8Array` representation of the hash -* @returns {Uint8Array} -*/ + /** + * Return the `Uint8Array` representation of the hash + * @returns {Uint8Array} + */ toBytes(): Uint8Array; } /** -* A directive for a single invocation of a Solana program. -* -* An instruction specifies which program it is calling, which accounts it may -* read or modify, and additional data that serves as input to the program. One -* or more instructions are included in transactions submitted by Solana -* clients. Instructions are also used to describe [cross-program -* invocations][cpi]. -* -* [cpi]: https://docs.solana.com/developing/programming-model/calling-between-programs -* -* During execution, a program will receive a list of account data as one of -* its arguments, in the same order as specified during `Instruction` -* construction. -* -* While Solana is agnostic to the format of the instruction data, it has -* built-in support for serialization via [`borsh`] and [`bincode`]. -* -* [`borsh`]: https://docs.rs/borsh/latest/borsh/ -* [`bincode`]: https://docs.rs/bincode/latest/bincode/ -* -* # Specifying account metadata -* -* When constructing an [`Instruction`], a list of all accounts that may be -* read or written during the execution of that instruction must be supplied as -* [`AccountMeta`] values. -* -* Any account whose data may be mutated by the program during execution must -* be specified as writable. During execution, writing to an account that was -* not specified as writable will cause the transaction to fail. Writing to an -* account that is not owned by the program will cause the transaction to fail. -* -* Any account whose lamport balance may be mutated by the program during -* execution must be specified as writable. During execution, mutating the -* lamports of an account that was not specified as writable will cause the -* transaction to fail. While _subtracting_ lamports from an account not owned -* by the program will cause the transaction to fail, _adding_ lamports to any -* account is allowed, as long is it is mutable. -* -* Accounts that are not read or written by the program may still be specified -* in an `Instruction`'s account list. These will affect scheduling of program -* execution by the runtime, but will otherwise be ignored. -* -* When building a transaction, the Solana runtime coalesces all accounts used -* by all instructions in that transaction, along with accounts and permissions -* required by the runtime, into a single account list. Some accounts and -* account permissions required by the runtime to process a transaction are -* _not_ required to be included in an `Instruction`s account list. These -* include: -* -* - The program ID — it is a separate field of `Instruction` -* - The transaction's fee-paying account — it is added during [`Message`] -* construction. A program may still require the fee payer as part of the -* account list if it directly references it. -* -* [`Message`]: crate::message::Message -* -* Programs may require signatures from some accounts, in which case they -* should be specified as signers during `Instruction` construction. The -* program must still validate during execution that the account is a signer. -*/ + * A directive for a single invocation of a Solana program. + * + * An instruction specifies which program it is calling, which accounts it may + * read or modify, and additional data that serves as input to the program. One + * or more instructions are included in transactions submitted by Solana + * clients. Instructions are also used to describe [cross-program + * invocations][cpi]. + * + * [cpi]: https://docs.solana.com/developing/programming-model/calling-between-programs + * + * During execution, a program will receive a list of account data as one of + * its arguments, in the same order as specified during `Instruction` + * construction. + * + * While Solana is agnostic to the format of the instruction data, it has + * built-in support for serialization via [`borsh`] and [`bincode`]. + * + * [`borsh`]: https://docs.rs/borsh/latest/borsh/ + * [`bincode`]: https://docs.rs/bincode/latest/bincode/ + * + * # Specifying account metadata + * + * When constructing an [`Instruction`], a list of all accounts that may be + * read or written during the execution of that instruction must be supplied as + * [`AccountMeta`] values. + * + * Any account whose data may be mutated by the program during execution must + * be specified as writable. During execution, writing to an account that was + * not specified as writable will cause the transaction to fail. Writing to an + * account that is not owned by the program will cause the transaction to fail. + * + * Any account whose lamport balance may be mutated by the program during + * execution must be specified as writable. During execution, mutating the + * lamports of an account that was not specified as writable will cause the + * transaction to fail. While _subtracting_ lamports from an account not owned + * by the program will cause the transaction to fail, _adding_ lamports to any + * account is allowed, as long is it is mutable. + * + * Accounts that are not read or written by the program may still be specified + * in an `Instruction`'s account list. These will affect scheduling of program + * execution by the runtime, but will otherwise be ignored. + * + * When building a transaction, the Solana runtime coalesces all accounts used + * by all instructions in that transaction, along with accounts and permissions + * required by the runtime, into a single account list. Some accounts and + * account permissions required by the runtime to process a transaction are + * _not_ required to be included in an `Instruction`s account list. These + * include: + * + * - The program ID — it is a separate field of `Instruction` + * - The transaction's fee-paying account — it is added during [`Message`] + * construction. A program may still require the fee payer as part of the + * account list if it directly references it. + * + * [`Message`]: crate::message::Message + * + * Programs may require signatures from some accounts, in which case they + * should be specified as signers during `Instruction` construction. The + * program must still validate during execution that the account is a signer. + */ export class Instruction { free(): void; } /** -*/ + */ export class Instructions { free(): void; -/** -*/ + /** + */ constructor(); -/** -* @param {Instruction} instruction -*/ + /** + * @param {Instruction} instruction + */ push(instruction: Instruction): void; } /** -* A Solana transaction message (legacy). -* -* See the [`message`] module documentation for further description. -* -* [`message`]: crate::message -* -* Some constructors accept an optional `payer`, the account responsible for -* paying the cost of executing a transaction. In most cases, callers should -* specify the payer explicitly in these constructors. In some cases though, -* the caller is not _required_ to specify the payer, but is still allowed to: -* in the `Message` structure, the first account is always the fee-payer, so if -* the caller has knowledge that the first account of the constructed -* transaction's `Message` is both a signer and the expected fee-payer, then -* redundantly specifying the fee-payer is not strictly required. -*/ + * A Solana transaction message (legacy). + * + * See the [`message`] module documentation for further description. + * + * [`message`]: crate::message + * + * Some constructors accept an optional `payer`, the account responsible for + * paying the cost of executing a transaction. In most cases, callers should + * specify the payer explicitly in these constructors. In some cases though, + * the caller is not _required_ to specify the payer, but is still allowed to: + * in the `Message` structure, the first account is always the fee-payer, so if + * the caller has knowledge that the first account of the constructed + * transaction's `Message` is both a signer and the expected fee-payer, then + * redundantly specifying the fee-payer is not strictly required. + */ export class Message { free(): void; -/** -* The id of a recent ledger entry. -*/ + /** + * The id of a recent ledger entry. + */ recent_blockhash: Hash; } /** -* The address of a [Solana account][acc]. -* -* Some account addresses are [ed25519] public keys, with corresponding secret -* keys that are managed off-chain. Often, though, account addresses do not -* have corresponding secret keys — as with [_program derived -* addresses_][pdas] — or the secret key is not relevant to the operation -* of a program, and may have even been disposed of. As running Solana programs -* can not safely create or manage secret keys, the full [`Keypair`] is not -* defined in `solana-program` but in `solana-sdk`. -* -* [acc]: https://docs.solana.com/developing/programming-model/accounts -* [ed25519]: https://ed25519.cr.yp.to/ -* [pdas]: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses -* [`Keypair`]: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/struct.Keypair.html -*/ + * The address of a [Solana account][acc]. + * + * Some account addresses are [ed25519] public keys, with corresponding secret + * keys that are managed off-chain. Often, though, account addresses do not + * have corresponding secret keys — as with [_program derived + * addresses_][pdas] — or the secret key is not relevant to the operation + * of a program, and may have even been disposed of. As running Solana programs + * can not safely create or manage secret keys, the full [`Keypair`] is not + * defined in `solana-program` but in `solana-sdk`. + * + * [acc]: https://docs.solana.com/developing/programming-model/accounts + * [ed25519]: https://ed25519.cr.yp.to/ + * [pdas]: https://docs.solana.com/developing/programming-model/calling-between-programs#program-derived-addresses + * [`Keypair`]: https://docs.rs/solana-sdk/latest/solana_sdk/signer/keypair/struct.Keypair.html + */ export class Pubkey { free(): void; -/** -* Create a new Pubkey object -* -* * `value` - optional public key as a base58 encoded string, `Uint8Array`, `[number]` -* @param {any} value -*/ + /** + * Create a new Pubkey object + * + * * `value` - optional public key as a base58 encoded string, `Uint8Array`, `[number]` + * @param {any} value + */ constructor(value: any); -/** -* Return the base58 string representation of the public key -* @returns {string} -*/ + /** + * Return the base58 string representation of the public key + * @returns {string} + */ toString(): string; -/** -* Check if a `Pubkey` is on the ed25519 curve. -* @returns {boolean} -*/ + /** + * Check if a `Pubkey` is on the ed25519 curve. + * @returns {boolean} + */ isOnCurve(): boolean; -/** -* Checks if two `Pubkey`s are equal -* @param {Pubkey} other -* @returns {boolean} -*/ + /** + * Checks if two `Pubkey`s are equal + * @param {Pubkey} other + * @returns {boolean} + */ equals(other: Pubkey): boolean; -/** -* Return the `Uint8Array` representation of the public key -* @returns {Uint8Array} -*/ + /** + * Return the `Uint8Array` representation of the public key + * @returns {Uint8Array} + */ toBytes(): Uint8Array; -/** -* Derive a Pubkey from another Pubkey, string seed, and a program id -* @param {Pubkey} base -* @param {string} seed -* @param {Pubkey} owner -* @returns {Pubkey} -*/ + /** + * Derive a Pubkey from another Pubkey, string seed, and a program id + * @param {Pubkey} base + * @param {string} seed + * @param {Pubkey} owner + * @returns {Pubkey} + */ static createWithSeed(base: Pubkey, seed: string, owner: Pubkey): Pubkey; -/** -* Derive a program address from seeds and a program id -* @param {any[]} seeds -* @param {Pubkey} program_id -* @returns {Pubkey} -*/ + /** + * Derive a program address from seeds and a program id + * @param {any[]} seeds + * @param {Pubkey} program_id + * @returns {Pubkey} + */ static createProgramAddress(seeds: any[], program_id: Pubkey): Pubkey; -/** -* Find a valid program address -* -* Returns: -* * `[PubKey, number]` - the program address and bump seed -* @param {any[]} seeds -* @param {Pubkey} program_id -* @returns {any} -*/ + /** + * Find a valid program address + * + * Returns: + * * `[PubKey, number]` - the program address and bump seed + * @param {any[]} seeds + * @param {Pubkey} program_id + * @returns {any} + */ static findProgramAddress(seeds: any[], program_id: Pubkey): any; } diff --git a/worker/tests/wasm/bincode_js_bg.wasm.d.ts b/worker/tests/wasm/bincode_js_bg.wasm.d.ts index 97a7922..9d03261 100644 --- a/worker/tests/wasm/bincode_js_bg.wasm.d.ts +++ b/worker/tests/wasm/bincode_js_bg.wasm.d.ts @@ -8,13 +8,37 @@ export function __wbg_get_message_recent_blockhash(a: number): number; export function __wbg_set_message_recent_blockhash(a: number, b: number): void; export function solana_program_init(): void; export function systeminstruction_createAccount(a: number, b: number, c: number, d: number, e: number): number; -export function systeminstruction_createAccountWithSeed(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number): number; +export function systeminstruction_createAccountWithSeed( + a: number, + b: number, + c: number, + d: number, + e: number, + f: number, + g: number, + h: number, +): number; export function systeminstruction_assign(a: number, b: number): number; export function systeminstruction_assignWithSeed(a: number, b: number, c: number, d: number, e: number): number; export function systeminstruction_transfer(a: number, b: number, c: number): number; -export function systeminstruction_transferWithSeed(a: number, b: number, c: number, d: number, e: number, f: number, g: number): number; +export function systeminstruction_transferWithSeed( + a: number, + b: number, + c: number, + d: number, + e: number, + f: number, + g: number, +): number; export function systeminstruction_allocate(a: number, b: number): number; -export function systeminstruction_allocateWithSeed(a: number, b: number, c: number, d: number, e: number, f: number): number; +export function systeminstruction_allocateWithSeed( + a: number, + b: number, + c: number, + d: number, + e: number, + f: number, +): number; export function systeminstruction_createNonceAccount(a: number, b: number, c: number, d: number): number; export function systeminstruction_advanceNonceAccount(a: number, b: number): number; export function systeminstruction_withdrawNonceAccount(a: number, b: number, c: number, d: number): number; diff --git a/worker/tests/webpack.config.js b/worker/tests/webpack.config.js index 0c076d3..b9dce85 100644 --- a/worker/tests/webpack.config.js +++ b/worker/tests/webpack.config.js @@ -1,31 +1,31 @@ -import path from 'path' -import Dotenv from 'dotenv-webpack' -import { fileURLToPath } from "url"; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -export default { - mode: "development", - entry: "./src/index.ts", - output: { - filename: "main.js", - path: path.resolve(__dirname, "dist"), - libraryTarget: "commonjs2", - }, - target: "node", - resolve: { - extensions: [".ts", ".js"], - }, - module: { - rules: [ - { - test: /\.ts$/, - use: "ts-loader", - exclude: /node_modules/, - }, - ], - }, - devtool: "source-map", - plugins: [new Dotenv()], -}; +import path from "path"; +import Dotenv from "dotenv-webpack"; +import { fileURLToPath } from "url"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +export default { + mode: "development", + entry: "./src/index.ts", + output: { + filename: "main.js", + path: path.resolve(__dirname, "dist"), + libraryTarget: "commonjs2", + }, + target: "node", + resolve: { + extensions: [".ts", ".js"], + }, + module: { + rules: [ + { + test: /\.ts$/, + use: "ts-loader", + exclude: /node_modules/, + }, + ], + }, + devtool: "source-map", + plugins: [new Dotenv()], +}; diff --git a/worker/webpack.config.mjs b/worker/webpack.config.mjs index 132df1b..3caf2af 100644 --- a/worker/webpack.config.mjs +++ b/worker/webpack.config.mjs @@ -11,14 +11,14 @@ export default { filename: "main.js", path: path.resolve(__dirname, "dist"), libraryTarget: "commonjs2", - clean: true + clean: true, }, target: "node", - + resolve: { - extensions: [".ts", ".js"] + extensions: [".ts", ".js"], }, - + module: { rules: [ { @@ -26,16 +26,14 @@ export default { use: { loader: "ts-loader", options: { - transpileOnly: true - } + transpileOnly: true, + }, }, - exclude: /node_modules/ - } - ] + exclude: /node_modules/, + }, + ], }, - - plugins: [ - ], + plugins: [], devtool: "source-map", };