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
Show file tree
Hide file tree
Changes from 8 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
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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
Expand Up @@ -5,8 +5,14 @@
"author": "Fuel Labs <contact@fuel.sh> (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": {
Expand Down
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 = ["Dhaiwat Pandya"]
Dhaiwat10 marked this conversation as resolved.
Show resolved Hide resolved
entry = "main.sw"
license = "Apache-2.0"
name = "predicate"

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

fn main(input: u8) -> bool {
let answer: u8 = 10;

input == answer
}
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 = ["Dhaiwat Pandya"]
Dhaiwat10 marked this conversation as resolved.
Show resolved Hide resolved
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
}
77 changes: 74 additions & 3 deletions apps/demo-typegen/src/demo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,42 @@
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 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.return_input(1337).txParams({ gasPrice }).call();
Expand All @@ -28,20 +48,29 @@
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 })
.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.return_input(1337).txParams({ gasPrice }).call();
Expand Down Expand Up @@ -79,3 +108,45 @@

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]]);

// #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,
})
.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 () => {

Check failure on line 131 in apps/demo-typegen/src/demo.test.ts

View workflow job for this annotation

GitHub Actions / Tests annotations (🧪 jest-coverage-report-action)

Example predicate

Error: not enough coins to fit the target: {"response":{"data":null,"errors":[{"message":"not enough coins to fit the target","locations":[{"line":2,"column":3}],"path":["coinsToSpend"]}],"status":200,"headers":{}},"request":{"query":"query getCoinsToSpend($owner: Address!, $queryPerAsset: [SpendQueryElementInput!]!, $excludedIds: ExcludeInput) {\n coinsToSpend(\n owner: $owner\n queryPerAsset: $queryPerAsset\n excludedIds: $excludedIds\n ) {\n ...coinFragment\n ...messageCoinFragment\n }\n}\n\nfragment coinFragment on Coin {\n __typename\n utxoId\n owner\n amount\n assetId\n maturity\n blockCreated\n txCreatedIdx\n}\n\nfragment messageCoinFragment on MessageCoin {\n __typename\n sender\n recipient\n nonce\n amount\n assetId\n daHeight\n}","variables":{"owner":"0x8b0cb3a1f0649630113189eeaea44c9a5ea9cc6e0962ce0545a519db056c920e","queryPerAsset":[{"assetId":"0x0000000000000000000000000000000000000000000000000000000000000000","amount":"158696"}],"excludedIds":{"messages":[],"utxos":[]}}}} at /home/runner/work/fuels-ts/fuels-ts/node_modules/.pnpm/graphql-request@5.0.0_graphql@16.6.0/node_modules/graphql-request/src/index.ts:497:11 at step (/home/runner/work/fuels-ts/fuels-ts/node_modules/.pnpm/graphql-request@5.0.0_graphql@16.6.0/node_modules/graphql-request/dist/index.js:63:23) at Object.next (/home/runner/work/fuels-ts/fuels-ts/node_modules/.pnpm/graphql-request@5.0.0_graphql@16.6.0/node_modules/graphql-request/dist/index.js:44:53) at fulfilled (/home/runner/work/fuels-ts/fuels-ts/node_modules/.pnpm/graphql-request@5.0.0_graphql@16.6.0/node_modules/graphql-request/dist/index.js:35:58) at processTicksAndRejections (node:internal/process/task_queues:95:5)
// #region typegen-demo-predicate
// #context import { PredicateAbi__factory } from './types';
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet1 = await generateTestWallet(provider, [[500_000, BaseAssetId]]);
const wallet2 = await generateTestWallet(provider, [[500_000, BaseAssetId]]);

const predicate = PredicateAbi__factory.createInstance(provider);

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

const tx2 = await predicate.setData(10).transfer(wallet2.address, 50_000, BaseAssetId, {
gasPrice: provider.getGasConfig().minGasPrice,
});
await tx2.wait();

expect((await wallet2.getBalance()).toNumber()).toEqual(550_000);
// #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
Expand Up @@ -10,49 +10,19 @@ yarn exec fuels typegen -i ./abis/*-abi.json -o ./types

We can use these files like so:

<!-- TODO: stop using hardcoded 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

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

We can use these files like so:

<!-- TODO: stop using hardcoded 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/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
yarn exec fuels typegen -i ./abis/*-abi.json -o ./types --predicate
```

We can use these files like so:

<!-- TODO: stop using hardcoded 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:

Expand Down
4 changes: 3 additions & 1 deletion nodemon.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,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/**"
]
}
Loading