import { Context, isSelfCall } from '@coinweb/contract-kit';

import { MethodCallback } from './types';

/**
 * Wraps a method callback to ensure that it can only be called by the contract itself.
 * @param handler - The method callback to wrap.
 * @returns A new method callback that throws an error if the call is not from the contract itself.
 */
export function selfCallWrapper(handler: MethodCallback): MethodCallback {
  return async (context: Context) => {
    if (!isSelfCall(context)) {
      throw new Error('Only contract itself can call it');
    }
    return handler(context);
  };
}
