Agenda
現象
SolanaのAnchorでProgramを作ったあとに、IDL(target/idl/PJ名.json)をReact内に設置してSolanaのProgramを呼び出すことになると思う。
その際、Reactから呼ぶと、以下のエラーが出る。
Argument of type '{ version: string; name: string; instructions: { name: string; accounts: { name: string; isMut: boolean; isSigner: boolean; }[]; args: { name: string; type: string; }[]; }[]; accounts: { name: string; type: { kind: string; fields: { ...; }[]; }; }[]; metadata: { ...; }; }' is not assignable to parameter of type 'Idl'.
Types of property 'instructions' are incompatible.
Type '{ name: string; accounts: { name: string; isMut: boolean; isSigner: boolean; }[]; args: { name: string; type: string; }[]; }[]' is not assignable to type 'IdlInstruction[]'.
Type '{ name: string; accounts: { name: string; isMut: boolean; isSigner: boolean; }[]; args: { name: string; type: string; }[]; }' is not assignable to type 'IdlInstruction'.
Types of property 'args' are incompatible.
Type '{ name: string; type: string; }[]' is not assignable to type 'IdlField[]'.
Type '{ name: string; type: string; }' is not assignable to type 'IdlField'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type 'IdlType'.ts(2345)
ソース(以下のidlの箇所でエラー)
import * as anchor from '@coral-xyz/anchor';
import idl from "./kumo_no_ito.json"; // Anchorで生成されたIDLファイル
export const getAnchorProgram = (): any => {
if (!import.meta.env.VITE_PROGRAM_ID) throw new Error('Undefined PROGRAM_ID');
const programId = new anchor.web3.PublicKey(import.meta.env.VITE_PROGRAM_ID);
const program = new anchor.Program(idl, programId);
return program;
}
原因
importすると型がanyになるためエラーになっている。
対応
「as anchor.Idl」をつけて型を明示するだけ。
import * as anchor from '@coral-xyz/anchor';
import idl from "./kumo_no_ito.json";
export const getAnchorProgram = (): any => {
if (!import.meta.env.VITE_PROGRAM_ID) throw new Error('Undefined PROGRAM_ID');
const programId = new anchor.web3.PublicKey(import.meta.env.VITE_PROGRAM_ID);
const program = new anchor.Program(idl as anchor.Idl, programId);
return program;
}
参考
Solana web3 Program constructor is expecting a json as one of params