Skip to content

使用生成的类型

通过以下方式生成类型:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types

我们可以像这样使用这些文件:

ts
// #context import { DemoContractAbi__factory } from './types';

const contractInstance = DemoContractAbi__factory.connect(contractId, wallet);
const { value: v2 } = await contractInstance.functions.return_input(1337).call();

合约

让我们使用 Contract 类部署合约:

ts
// #context import { DemoContractAbi__factory } from './types';
// #context import bytecode from './types/DemoContractAbi.hex';

// Deploy
const contract = await DemoContractAbi__factory.deployContract(bytecode, wallet);

存储槽的自动加载

Typegen 会尝试解析、自动加载并嵌入您合约的存储槽MyContract__factory 类中。但是,您可以在调用 deployContract 方法时覆盖它,以及其他 DeployContractOptions 中的选项:

ts
// #context import storageSlots from './contract/out/debug/demo-contract-storage_slots.json';

const contract = await DemoContractAbi__factory.deployContract(bytecode, wallet, {
  storageSlots,
});

脚本

通过以下方式生成类型:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --script

我们可以像这样使用这些文件:

ts
// #context import { ScriptAbi__factory } from './types';

const script = ScriptAbi__factory.createInstance(wallet);
const { value } = await script.functions.main().call();

谓词

通过以下方式生成类型:

console
pnpm fuels typegen -i ./abis/*-abi.json -o ./types --predicate

我们可以像这样使用这些文件:

ts
// #context import type { PredicateAbiInputs } from './types';
// #context import { PredicateAbi__factory } from './types';

// In this exchange, we are first transferring some coins to the predicate
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[500_000, baseAssetId]]);
const receiver = Wallet.fromAddress(Address.fromRandom(), provider);

const predicateData: PredicateAbiInputs = [];
const predicate = PredicateAbi__factory.createInstance(provider, predicateData);

const tx = await wallet.transfer(predicate.address, 150_000, baseAssetId);
const { isStatusSuccess } = await tx.wait();

// Then we are transferring some coins from the predicate to a random address (receiver)
const tx2 = await predicate.transfer(receiver.address, 50_000, baseAssetId);
await tx2.wait();

expect((await receiver.getBalance()).toNumber()).toEqual(50_000);
expect(isStatusSuccess).toBeTruthy();

另请参阅: