Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: purge hardcoded snippets on 'using typegen' page #1403

Merged
merged 23 commits into from
Dec 14, 2023
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
cf36fa3
docs: purge hardcoded snippets on 'using typegen' page
Dhaiwat10 Nov 3, 2023
b2401e7
Update .gitignore
Dhaiwat10 Nov 3, 2023
92cccc9
delete typegen files
Dhaiwat10 Nov 3, 2023
eb7aab3
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 3, 2023
c8688cb
fix formatting
Dhaiwat10 Nov 4, 2023
1e09eb8
update ignore files
Dhaiwat10 Nov 5, 2023
ff1a803
refactor package.json
Dhaiwat10 Nov 5, 2023
2bea851
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 5, 2023
dec658a
fix author
Dhaiwat10 Nov 7, 2023
582d990
fix author
Dhaiwat10 Nov 7, 2023
717f4fb
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 7, 2023
f5881e7
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 7, 2023
b19874f
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 23, 2023
1ba44ca
update predicate test
Dhaiwat10 Nov 23, 2023
f876e94
fix failing predicate test
Dhaiwat10 Nov 30, 2023
e48d575
Merge branch 'master' into dp/hardcoded-snippets-typegen
Dhaiwat10 Nov 30, 2023
50061dc
Merge branch 'master' into dp/hardcoded-snippets-typegen
danielbate Dec 8, 2023
d6da86e
Fix merge conflict
Dhaiwat10 Dec 12, 2023
4b9667c
Fix authors
Dhaiwat10 Dec 12, 2023
5362f2f
Merge branch 'rc/salamander' into dp/hardcoded-snippets-typegen
Dhaiwat10 Dec 13, 2023
06211d4
add gasLimit
Dhaiwat10 Dec 14, 2023
cdcb3d2
Merge branch 'rc/salamander' into dp/hardcoded-snippets-typegen
Dhaiwat10 Dec 14, 2023
83c46a5
update gas limit
Dhaiwat10 Dec 14, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/odd-kids-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
4 changes: 3 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -4,7 +4,9 @@ dist/
out/

apps/demo-fuels/src/sway-programs-api
apps/demo-typegen/src/generated-types
apps/demo-typegen/src/contract-types
apps/demo-typegen/src/script-types
apps/demo-typegen/src/predicate-types
apps/demo-nextjs
apps/demo-react-cra
apps/demo-react-vite
4 changes: 3 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -8,7 +8,9 @@ apps/demo-fuels/src/sway-programs-api
apps/demo-nextjs
apps/demo-react-cra
apps/demo-react-vite
apps/demo-typegen/src/generated-types
apps/demo-typegen/src/contract-types
apps/demo-typegen/src/script-types
apps/demo-typegen/src/predicate-types
apps/docs/.vitepress/cache/

packages/fuels/test/fixtures/project
4 changes: 3 additions & 1 deletion apps/demo-typegen/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
node_modules
src/generated-types
src/contract-types
src/predicate-types
src/script-types

# Forc
**/out/debug/**
10 changes: 8 additions & 2 deletions apps/demo-typegen/package.json
Original file line number Diff line number Diff line change
@@ -5,8 +5,14 @@
"author": "Fuel Labs <[email protected]> (https://fuel.network/)",
"scripts": {
"pretest": "run-s build:forc build:types",
"build:forc": "pnpm fuels-forc build -p contract",
"build:types": "pnpm fuels typegen -i contract/out/debug/demo-contract-abi.json -o src/generated-types"
"build:forc": "run-p forc:*",
"forc:contract": "pnpm fuels-forc build -p contract",
"forc:script": "pnpm fuels-forc build -p script",
"forc:predicate": "pnpm fuels-forc build -p predicate",
"build:types": "run-p types:*",
"types:contract": "pnpm fuels typegen -i contract/out/debug/demo-contract-abi.json -o src/contract-types",
"types:script": "pnpm fuels typegen -i script/out/debug/script-abi.json -o src/script-types --script",
"types:predicate": "pnpm fuels typegen -i predicate/out/debug/predicate-abi.json -o src/predicate-types --predicate"
},
"license": "Apache-2.0",
"dependencies": {
2 changes: 2 additions & 0 deletions apps/demo-typegen/predicate/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
target
7 changes: 7 additions & 0 deletions apps/demo-typegen/predicate/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
license = "Apache-2.0"
name = "predicate"

[dependencies]
5 changes: 5 additions & 0 deletions apps/demo-typegen/predicate/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
predicate;

fn main() -> bool {
true
}
2 changes: 2 additions & 0 deletions apps/demo-typegen/script/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
target
7 changes: 7 additions & 0 deletions apps/demo-typegen/script/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
license = "Apache-2.0"
name = "script"

[dependencies]
5 changes: 5 additions & 0 deletions apps/demo-typegen/script/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
script;

fn main() -> u8 {
10
}
102 changes: 97 additions & 5 deletions apps/demo-typegen/src/demo.test.ts
Original file line number Diff line number Diff line change
@@ -2,24 +2,52 @@
import { safeExec } from '@fuel-ts/errors/test-utils';
import { generateTestWallet } from '@fuel-ts/wallet/test-utils';
import type { BN } from 'fuels';
import { ContractFactory, Provider, toHex, BaseAssetId, Wallet, FUEL_NETWORK_URL } from 'fuels';

import { DemoContractAbi__factory } from './generated-types';
import bytecode from './generated-types/DemoContractAbi.hex';
import {
ContractFactory,
Provider,
toHex,
BaseAssetId,
Wallet,
FUEL_NETWORK_URL,
Address,
} from 'fuels';

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

import { DemoContractAbi__factory } from './contract-types';
import bytecode from './contract-types/DemoContractAbi.hex';
import { PredicateAbi__factory } from './predicate-types';
import { ScriptAbi__factory } from './script-types';

let gasPrice: BN;
describe('ExampleContract', () => {
beforeAll(async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
({ minGasPrice: gasPrice } = provider.getGasConfig());
});
it('with imported storage slots', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[500_000, BaseAssetId]]);

// #region typegen-demo-contract-storage-slots
// #context import storageSlots from './contract/out/debug/demo-contract-storage_slots.json';

const contract = await DemoContractAbi__factory.deployContract(bytecode, wallet, {
storageSlots,
gasPrice,
});
// #endregion typegen-demo-contract-storage-slots

expect(contract.id).toBeTruthy();
});
it('should return the input', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[500_000, BaseAssetId]]);

// Deploy
const factory = new ContractFactory(bytecode, DemoContractAbi__factory.abi, wallet);
const contract = await factory.deployContract({ gasPrice });
const contractId = contract.id;

// Call
const { value } = await contract.functions
@@ -31,20 +59,29 @@ describe('ExampleContract', () => {
expect(value.toHex()).toEqual(toHex(1337));

// You can also make a call using the factory
const contractInstance = DemoContractAbi__factory.connect(contract.id, wallet);
// #region typegen-demo-contract-factory-connect
// #context import { DemoContractAbi__factory } from './types';

const contractInstance = DemoContractAbi__factory.connect(contractId, wallet);
const { value: v2 } = await contractInstance.functions
.return_input(1337)
.txParams({ gasPrice, gasLimit: 10_000 })
.call();
// #endregion typegen-demo-contract-factory-connect
expect(v2.toHex()).toBe(toHex(1337));
});

it('deployContract method', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[500_000, BaseAssetId]]);

// #region typegen-demo-contract-factory-deploy
// #context import { DemoContractAbi__factory } from './types';
// #context import bytecode from './types/DemoContractAbi.hex';

// Deploy
const contract = await DemoContractAbi__factory.deployContract(bytecode, wallet, { gasPrice });
// #endregion typegen-demo-contract-factory-deploy

// Call
const { value } = await contract.functions
@@ -89,3 +126,58 @@ it('should throw when dry running via contract factory with wallet with no resou

expect((<Error>error).message).toMatch('not enough coins to fit the target');
});

test('Example script', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[500_000, BaseAssetId]]);

// TODO: investigate why do we need to specify the gasLimit here. If we don't specify it, the call fails saying `FuelError: Gas limit '0' is lower than the required: '19'.`

// #region typegen-demo-script
// #context import { ScriptAbi__factory } from './types';

const script = ScriptAbi__factory.createInstance(wallet);
const { value } = await script.functions
.main()
.txParams({
gasPrice: provider.getGasConfig().minGasPrice,
gasLimit: 10_000,
})
.call();
// #endregion typegen-demo-script
// @ts-expect-error TODO: investitage - typegen is expecting value to be a number but the value being returned is the string '0xa'
expect(value.toNumber()).toBe(10);
});

test('Example predicate', async () => {
// #region typegen-demo-predicate
// #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 predicate = PredicateAbi__factory.createInstance(provider);

const tx = await wallet.transfer(predicate.address, 100_000, BaseAssetId, {
gasPrice: provider.getGasConfig().minGasPrice,
gasLimit: 50,
});
await tx.wait();

const initialPredicateBalance = await predicate.getBalance();

// Then we are transferring some coins from the predicate to a random address (receiver)
const tx2 = await predicate.transfer(receiver.address, 50_000, BaseAssetId, {
gasPrice: provider.getGasConfig().minGasPrice,
gasLimit: 50,
});
await tx2.wait();

expect((await receiver.getBalance()).toNumber()).toEqual(50_000);
expect((await predicate.getBalance()).toNumber()).toBeLessThan(
initialPredicateBalance.toNumber()
);
// #endregion typegen-demo-predicate
});
81 changes: 6 additions & 75 deletions apps/docs/src/guide/abi-typegen/using-generated-types.md
Original file line number Diff line number Diff line change
@@ -10,49 +10,19 @@ pnpm fuels typegen -i ./abis/*-abi.json -o ./types

We can use these files like so:

<!-- TODO: stop using hard-coded snippets -->

```ts
import { Wallet } from "fuels";
import { MyContract__factory } from "./types";

const contractId = "0x...";
const wallet = Wallet.fromAddress("...");
const contract = MyContract__factory.connect(contractId, wallet);

// All contract methods are available under functions with the correct types
const { transactionId, value } = await contract.functions.my_fn(1).call();

console.log(transactionId, value);
```
<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-factory-connect{ts:line-numbers}

## Contract

Let's use the Contract class to deploy a contract:

```ts
import { Wallet } from "fuels";
import { MyContract__factory } from "./types";
import bytecode from "./types/MyContract.hex.ts";

const wallet = Wallet.fromAddress("...");

const contract = await MyContract__factory.deployContract(bytecode, wallet);

console.log(contract.id);
```
<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-factory-deploy{ts:line-numbers}

### Autoloading of Storage Slots

Typegen tries to resolve, auto-load, and embed the [Storage Slots](../contracts//storage-slots.md) for your Contract within the `MyContract__factory` class. Still, you can override it alongside other options from [`DeployContractOptions`](https://github.com/FuelLabs/fuels-ts/blob/a64b67b9fb2d7f764ab9151a21d2266bf2df3643/packages/contract/src/contract-factory.ts#L19-L24), when calling the `deployContract` method:

```ts
import storageSlots from "../contract/out/debug/storage-slots.json";

const contract = await MyContract__factory.deployContract(bytecode, wallet, {
storageSlots,
});
```
<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-contract-storage-slots{ts:line-numbers}

## Script

@@ -64,58 +34,19 @@ pnpm fuels typegen -i ./abis/*-abi.json -o ./types --script

We can use these files like so:

<!-- TODO: stop using hard-coded snippets -->

```ts
import { Wallet } from "fuels";
import { MyScript__factory } from "./types";

const wallet = Wallet.fromAddress("...");
const script = ScriptAbi__factory.createInstance(wallet);

const { value, logs } = await script.functions.main(1).call();

console.log({ value, logs });
```
<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-script{ts:line-numbers}

## Predicate

Consider the following predicate:

<<< @/../../../packages/fuel-gauge/test/fixtures/forc-projects/predicate-main-args-struct/src/main.sw#Predicate-main-args{ts:line-numbers}

Now, after generating types via:
After generating types via:

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

We can use these files like so:

<!-- TODO: stop using hard-coded snippets -->

```ts
import { Wallet } from "fuels";
import { MyPredicate__factory } from "./types";

const wallet = Wallet.fromAddress("...");
const predicate = MyPredicate__factory.createInstance();

await predicate
.setData({
has_account: true,
total_complete: 100,
})
.transfer(wallet.address, <amount>);

const walletBalance = await wallet.getBalance();
const predicateBalance = await predicate.getBalance();

console.log({
walletBalance,
predicateBalance,
});
```
<<< @/../../demo-typegen/src/demo.test.ts#typegen-demo-predicate{ts:line-numbers}

See also:

4 changes: 3 additions & 1 deletion nodemon.config.json
Original file line number Diff line number Diff line change
@@ -11,6 +11,8 @@
"**/Forc.lock",
"**/getBuiltinVersions.ts",
"**/out/debug/**",
"apps/demo-typegen/src/generated-types/**"
"apps/demo-typegen/src/contract-types/**",
"apps/demo-typegen/src/predicate-types/**",
"apps/demo-typegen/src/script-types/**"
]
}