/**
 * This code was AUTOGENERATED using the Codama library.
 * Please DO NOT EDIT THIS FILE, instead use visitors
 * to add features, then rerun Codama to update it.
 *
 * @see https://github.com/codama-idl/codama
 */

import {
  combineCodec,
  fixDecoderSize,
  fixEncoderSize,
  getAddressEncoder,
  getBytesDecoder,
  getBytesEncoder,
  getProgramDerivedAddress,
  getStructDecoder,
  getStructEncoder,
  transformEncoder,
  type AccountMeta,
  type AccountSignerMeta,
  type Address,
  type FixedSizeCodec,
  type FixedSizeDecoder,
  type FixedSizeEncoder,
  type Instruction,
  type InstructionWithAccounts,
  type InstructionWithData,
  type ReadonlyAccount,
  type ReadonlyUint8Array,
  type TransactionSigner,
  type WritableAccount,
  type WritableSignerAccount,
} from "@solana/kit";
import {
  findEventAuthorityPda,
  findInstructionParamsPda,
  findTransferLiabilityPda,
} from "../pdas";
import { SVM_SPOKE_PROGRAM_ADDRESS } from "../programs";
import {
  expectAddress,
  getAccountMetaFactory,
  type ResolvedAccount,
} from "../shared";

export const EXECUTE_RELAYER_REFUND_LEAF_DEFERRED_DISCRIMINATOR =
  new Uint8Array([110, 112, 89, 208, 38, 116, 93, 10]);

export function getExecuteRelayerRefundLeafDeferredDiscriminatorBytes() {
  return fixEncoderSize(getBytesEncoder(), 8).encode(
    EXECUTE_RELAYER_REFUND_LEAF_DEFERRED_DISCRIMINATOR,
  );
}

export type ExecuteRelayerRefundLeafDeferredInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountSigner extends string | AccountMeta<string> = string,
  TAccountInstructionParams extends string | AccountMeta<string> = string,
  TAccountState extends string | AccountMeta<string> = string,
  TAccountRootBundle extends string | AccountMeta<string> = string,
  TAccountVault extends string | AccountMeta<string> = string,
  TAccountMint extends string | AccountMeta<string> = string,
  TAccountTransferLiability extends string | AccountMeta<string> = string,
  TAccountTokenProgram extends string | AccountMeta<string> =
    "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  TAccountSystemProgram extends string | AccountMeta<string> =
    "11111111111111111111111111111111",
  TAccountEventAuthority extends string | AccountMeta<string> = string,
  TAccountProgram extends string | AccountMeta<string> = string,
  TRemainingAccounts extends readonly AccountMeta<string>[] = [],
> = Instruction<TProgram> &
  InstructionWithData<ReadonlyUint8Array> &
  InstructionWithAccounts<
    [
      TAccountSigner extends string
        ? WritableSignerAccount<TAccountSigner> &
            AccountSignerMeta<TAccountSigner>
        : TAccountSigner,
      TAccountInstructionParams extends string
        ? WritableAccount<TAccountInstructionParams>
        : TAccountInstructionParams,
      TAccountState extends string
        ? ReadonlyAccount<TAccountState>
        : TAccountState,
      TAccountRootBundle extends string
        ? WritableAccount<TAccountRootBundle>
        : TAccountRootBundle,
      TAccountVault extends string
        ? WritableAccount<TAccountVault>
        : TAccountVault,
      TAccountMint extends string
        ? ReadonlyAccount<TAccountMint>
        : TAccountMint,
      TAccountTransferLiability extends string
        ? WritableAccount<TAccountTransferLiability>
        : TAccountTransferLiability,
      TAccountTokenProgram extends string
        ? ReadonlyAccount<TAccountTokenProgram>
        : TAccountTokenProgram,
      TAccountSystemProgram extends string
        ? ReadonlyAccount<TAccountSystemProgram>
        : TAccountSystemProgram,
      TAccountEventAuthority extends string
        ? ReadonlyAccount<TAccountEventAuthority>
        : TAccountEventAuthority,
      TAccountProgram extends string
        ? ReadonlyAccount<TAccountProgram>
        : TAccountProgram,
      ...TRemainingAccounts,
    ]
  >;

export type ExecuteRelayerRefundLeafDeferredInstructionData = {
  discriminator: ReadonlyUint8Array;
};

export type ExecuteRelayerRefundLeafDeferredInstructionDataArgs = {};

export function getExecuteRelayerRefundLeafDeferredInstructionDataEncoder(): FixedSizeEncoder<ExecuteRelayerRefundLeafDeferredInstructionDataArgs> {
  return transformEncoder(
    getStructEncoder([["discriminator", fixEncoderSize(getBytesEncoder(), 8)]]),
    (value) => ({
      ...value,
      discriminator: EXECUTE_RELAYER_REFUND_LEAF_DEFERRED_DISCRIMINATOR,
    }),
  );
}

export function getExecuteRelayerRefundLeafDeferredInstructionDataDecoder(): FixedSizeDecoder<ExecuteRelayerRefundLeafDeferredInstructionData> {
  return getStructDecoder([
    ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
  ]);
}

export function getExecuteRelayerRefundLeafDeferredInstructionDataCodec(): FixedSizeCodec<
  ExecuteRelayerRefundLeafDeferredInstructionDataArgs,
  ExecuteRelayerRefundLeafDeferredInstructionData
> {
  return combineCodec(
    getExecuteRelayerRefundLeafDeferredInstructionDataEncoder(),
    getExecuteRelayerRefundLeafDeferredInstructionDataDecoder(),
  );
}

export type ExecuteRelayerRefundLeafDeferredAsyncInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountState extends string = string,
  TAccountRootBundle extends string = string,
  TAccountVault extends string = string,
  TAccountMint extends string = string,
  TAccountTransferLiability extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams?: Address<TAccountInstructionParams>;
  state: Address<TAccountState>;
  rootBundle: Address<TAccountRootBundle>;
  vault?: Address<TAccountVault>;
  mint: Address<TAccountMint>;
  transferLiability?: Address<TAccountTransferLiability>;
  tokenProgram?: Address<TAccountTokenProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority?: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
};

export async function getExecuteRelayerRefundLeafDeferredInstructionAsync<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountState extends string,
  TAccountRootBundle extends string,
  TAccountVault extends string,
  TAccountMint extends string,
  TAccountTransferLiability extends string,
  TAccountTokenProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: ExecuteRelayerRefundLeafDeferredAsyncInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountRootBundle,
    TAccountVault,
    TAccountMint,
    TAccountTransferLiability,
    TAccountTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): Promise<
  ExecuteRelayerRefundLeafDeferredInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountRootBundle,
    TAccountVault,
    TAccountMint,
    TAccountTransferLiability,
    TAccountTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    instructionParams: {
      value: input.instructionParams ?? null,
      isWritable: true,
    },
    state: { value: input.state ?? null, isWritable: false },
    rootBundle: { value: input.rootBundle ?? null, isWritable: true },
    vault: { value: input.vault ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    transferLiability: {
      value: input.transferLiability ?? null,
      isWritable: true,
    },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    systemProgram: { value: input.systemProgram ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

  // Resolve default values.
  if (!accounts.instructionParams.value) {
    accounts.instructionParams.value = await findInstructionParamsPda({
      signer: expectAddress(accounts.signer.value),
    });
  }
  if (!accounts.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }
  if (!accounts.vault.value) {
    accounts.vault.value = await getProgramDerivedAddress({
      programAddress:
        "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" as Address<"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL">,
      seeds: [
        getAddressEncoder().encode(expectAddress(accounts.state.value)),
        getAddressEncoder().encode(expectAddress(accounts.tokenProgram.value)),
        getAddressEncoder().encode(expectAddress(accounts.mint.value)),
      ],
    });
  }
  if (!accounts.transferLiability.value) {
    accounts.transferLiability.value = await findTransferLiabilityPda({
      mint: expectAddress(accounts.mint.value),
    });
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }
  if (!accounts.eventAuthority.value) {
    accounts.eventAuthority.value = await findEventAuthorityPda();
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.instructionParams),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rootBundle),
      getAccountMeta(accounts.vault),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.transferLiability),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getExecuteRelayerRefundLeafDeferredInstructionDataEncoder().encode(
      {},
    ),
    programAddress,
  } as ExecuteRelayerRefundLeafDeferredInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountRootBundle,
    TAccountVault,
    TAccountMint,
    TAccountTransferLiability,
    TAccountTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ExecuteRelayerRefundLeafDeferredInput<
  TAccountSigner extends string = string,
  TAccountInstructionParams extends string = string,
  TAccountState extends string = string,
  TAccountRootBundle extends string = string,
  TAccountVault extends string = string,
  TAccountMint extends string = string,
  TAccountTransferLiability extends string = string,
  TAccountTokenProgram extends string = string,
  TAccountSystemProgram extends string = string,
  TAccountEventAuthority extends string = string,
  TAccountProgram extends string = string,
> = {
  signer: TransactionSigner<TAccountSigner>;
  instructionParams: Address<TAccountInstructionParams>;
  state: Address<TAccountState>;
  rootBundle: Address<TAccountRootBundle>;
  vault: Address<TAccountVault>;
  mint: Address<TAccountMint>;
  transferLiability: Address<TAccountTransferLiability>;
  tokenProgram?: Address<TAccountTokenProgram>;
  systemProgram?: Address<TAccountSystemProgram>;
  eventAuthority: Address<TAccountEventAuthority>;
  program: Address<TAccountProgram>;
};

export function getExecuteRelayerRefundLeafDeferredInstruction<
  TAccountSigner extends string,
  TAccountInstructionParams extends string,
  TAccountState extends string,
  TAccountRootBundle extends string,
  TAccountVault extends string,
  TAccountMint extends string,
  TAccountTransferLiability extends string,
  TAccountTokenProgram extends string,
  TAccountSystemProgram extends string,
  TAccountEventAuthority extends string,
  TAccountProgram extends string,
  TProgramAddress extends Address = typeof SVM_SPOKE_PROGRAM_ADDRESS,
>(
  input: ExecuteRelayerRefundLeafDeferredInput<
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountRootBundle,
    TAccountVault,
    TAccountMint,
    TAccountTransferLiability,
    TAccountTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >,
  config?: { programAddress?: TProgramAddress },
): ExecuteRelayerRefundLeafDeferredInstruction<
  TProgramAddress,
  TAccountSigner,
  TAccountInstructionParams,
  TAccountState,
  TAccountRootBundle,
  TAccountVault,
  TAccountMint,
  TAccountTransferLiability,
  TAccountTokenProgram,
  TAccountSystemProgram,
  TAccountEventAuthority,
  TAccountProgram
> {
  // Program address.
  const programAddress = config?.programAddress ?? SVM_SPOKE_PROGRAM_ADDRESS;

  // Original accounts.
  const originalAccounts = {
    signer: { value: input.signer ?? null, isWritable: true },
    instructionParams: {
      value: input.instructionParams ?? null,
      isWritable: true,
    },
    state: { value: input.state ?? null, isWritable: false },
    rootBundle: { value: input.rootBundle ?? null, isWritable: true },
    vault: { value: input.vault ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    transferLiability: {
      value: input.transferLiability ?? null,
      isWritable: true,
    },
    tokenProgram: { value: input.tokenProgram ?? null, isWritable: false },
    systemProgram: { value: input.systemProgram ?? null, isWritable: false },
    eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
    program: { value: input.program ?? null, isWritable: false },
  };
  const accounts = originalAccounts as Record<
    keyof typeof originalAccounts,
    ResolvedAccount
  >;

  // Resolve default values.
  if (!accounts.tokenProgram.value) {
    accounts.tokenProgram.value =
      "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" as Address<"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA">;
  }
  if (!accounts.systemProgram.value) {
    accounts.systemProgram.value =
      "11111111111111111111111111111111" as Address<"11111111111111111111111111111111">;
  }

  const getAccountMeta = getAccountMetaFactory(programAddress, "programId");
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.signer),
      getAccountMeta(accounts.instructionParams),
      getAccountMeta(accounts.state),
      getAccountMeta(accounts.rootBundle),
      getAccountMeta(accounts.vault),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.transferLiability),
      getAccountMeta(accounts.tokenProgram),
      getAccountMeta(accounts.systemProgram),
      getAccountMeta(accounts.eventAuthority),
      getAccountMeta(accounts.program),
    ],
    data: getExecuteRelayerRefundLeafDeferredInstructionDataEncoder().encode(
      {},
    ),
    programAddress,
  } as ExecuteRelayerRefundLeafDeferredInstruction<
    TProgramAddress,
    TAccountSigner,
    TAccountInstructionParams,
    TAccountState,
    TAccountRootBundle,
    TAccountVault,
    TAccountMint,
    TAccountTransferLiability,
    TAccountTokenProgram,
    TAccountSystemProgram,
    TAccountEventAuthority,
    TAccountProgram
  >);
}

export type ParsedExecuteRelayerRefundLeafDeferredInstruction<
  TProgram extends string = typeof SVM_SPOKE_PROGRAM_ADDRESS,
  TAccountMetas extends readonly AccountMeta[] = readonly AccountMeta[],
> = {
  programAddress: Address<TProgram>;
  accounts: {
    signer: TAccountMetas[0];
    instructionParams: TAccountMetas[1];
    state: TAccountMetas[2];
    rootBundle: TAccountMetas[3];
    vault: TAccountMetas[4];
    mint: TAccountMetas[5];
    transferLiability: TAccountMetas[6];
    tokenProgram: TAccountMetas[7];
    systemProgram: TAccountMetas[8];
    eventAuthority: TAccountMetas[9];
    program: TAccountMetas[10];
  };
  data: ExecuteRelayerRefundLeafDeferredInstructionData;
};

export function parseExecuteRelayerRefundLeafDeferredInstruction<
  TProgram extends string,
  TAccountMetas extends readonly AccountMeta[],
>(
  instruction: Instruction<TProgram> &
    InstructionWithAccounts<TAccountMetas> &
    InstructionWithData<ReadonlyUint8Array>,
): ParsedExecuteRelayerRefundLeafDeferredInstruction<TProgram, TAccountMetas> {
  if (instruction.accounts.length < 11) {
    // TODO: Coded error.
    throw new Error("Not enough accounts");
  }
  let accountIndex = 0;
  const getNextAccount = () => {
    const accountMeta = (instruction.accounts as TAccountMetas)[accountIndex]!;
    accountIndex += 1;
    return accountMeta;
  };
  return {
    programAddress: instruction.programAddress,
    accounts: {
      signer: getNextAccount(),
      instructionParams: getNextAccount(),
      state: getNextAccount(),
      rootBundle: getNextAccount(),
      vault: getNextAccount(),
      mint: getNextAccount(),
      transferLiability: getNextAccount(),
      tokenProgram: getNextAccount(),
      systemProgram: getNextAccount(),
      eventAuthority: getNextAccount(),
      program: getNextAccount(),
    },
    data: getExecuteRelayerRefundLeafDeferredInstructionDataDecoder().decode(
      instruction.data,
    ),
  };
}
