Icon LinkInstantiating a script

Similar to contracts and predicates, once you've written a script in Sway and compiled it with forc build (read here for more on how to work with Sway), you'll get the script binary. Using the binary, you can instantiate a script as shown in the code snippet below:

import { Script, AbiCoder, arrayify } from 'fuels';
const scriptBin = readFileSync(join(__dirname, './path/to/script-binary.bin'));
 
type MyStruct = {
	arg_one: boolean;
	arg_two: BigNumberish;
};
 
describe('Script', () => {
	let scriptRequest: ScriptRequest<MyStruct, MyStruct>;
	beforeAll(() => {
const abiCoder = new AbiCoder();
scriptRequest = new ScriptRequest(
	scriptBin,
	(myStruct: MyStruct) => {
	const encoded = abiCoder.encode(jsonAbiFragmentMock[0].inputs, [myStruct]);
	return arrayify(encoded);
	},
	(scriptResult) => {
	if (scriptResult.returnReceipt.type === ReceiptType.Revert) {
	  throw new Error('Reverted');
	}
	if (scriptResult.returnReceipt.type !== ReceiptType.ReturnData) {
	  throw new Error('fail');
	}
	const decoded = abiCoder.decode(
	  jsonAbiFragmentMock[0].outputs,
	  scriptResult.returnReceipt.data
	);
	return (decoded as any)[0];
	}
);
	});

In the next section, we show how to call a script.