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

feat: new infra for code snippets #2651

Draft
wants to merge 101 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 84 commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
28c0b1c
Starting new code-snippets app
arboleya Jul 2, 2024
48bbcba
Porting getting-started snippets
arboleya Jul 2, 2024
5b4f678
Ignoring new app in changesets
arboleya Jul 2, 2024
a45a02a
Adding changeset
arboleya Jul 2, 2024
b382460
Ignoring wrapped snippets files (generated)
arboleya Jul 2, 2024
a83e65c
Ignore test files trying to import files that haven’t been built yet
arboleya Jul 2, 2024
41c2943
Merge branch 'master' into aa/feat/infra-for-new-snippets
Torres-ssf Jul 3, 2024
596242c
Merge branch 'master' into aa/feat/infra-for-new-snippets
Torres-ssf Jul 3, 2024
89bd596
Using real code/file rather than code-string
arboleya Jul 4, 2024
89348f9
Adding example using `launchTestNode` and `LOCAL_NETWORK_URL` overrides
arboleya Jul 4, 2024
0b790b7
Skipping until forc workspace has at least one member
arboleya Jul 4, 2024
125aaad
Renaming variable
arboleya Jul 4, 2024
3406527
Fixing regex
arboleya Jul 4, 2024
01f8558
Ignoring lint issues individually
arboleya Jul 4, 2024
b63c163
Removing from browser group
arboleya Jul 4, 2024
36dbe16
Lintfix
arboleya Jul 4, 2024
663d9ce
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Jul 4, 2024
9134334
Restoring console after snippet
arboleya Jul 4, 2024
168f124
Keeping wrapper free from weird hacks
arboleya Jul 4, 2024
3dd1e3f
Adding mock utility
arboleya Jul 4, 2024
6ed91e2
Using mocking utility
arboleya Jul 4, 2024
939f9d6
Validating if `nertworkUrl` was properly mocked
arboleya Jul 4, 2024
571e85c
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Jul 4, 2024
f795f00
Mock provider instead?
arboleya Jul 4, 2024
5732d8c
Mocking only for localhost
arboleya Jul 4, 2024
020022f
Adjusting snippets
arboleya Jul 4, 2024
1388057
Wrapping snippet in a try/catch
arboleya Jul 5, 2024
48f1176
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Jul 15, 2024
98b02e1
Adding blank spaces
arboleya Jul 15, 2024
ea01d46
Removing mocking utility
arboleya Jul 15, 2024
2cacdb2
Adding pass-through options for `console.log` calls
arboleya Jul 15, 2024
86205c4
Adding new slot for injecting test node launcher into wrapped snippet
arboleya Jul 15, 2024
a6545af
Injecting node launcher for snippets using `LOCAL_NETWORK_URL`
arboleya Jul 15, 2024
fd9a886
Trim snippets
arboleya Jul 15, 2024
8295f4f
Cleanup snippets tests
arboleya Jul 15, 2024
70dde7c
Stop ignoring test for `docs-snippets2`
arboleya Jul 15, 2024
45b576b
Re-adding `docs-snippets2` tests to knip ignore list
arboleya Jul 15, 2024
802356a
Using internal builds
arboleya Jul 19, 2024
74f7cef
Fixing ignore rule
arboleya Jul 19, 2024
8c0be15
Adding basic counter Sway project
arboleya Jul 19, 2024
6af5a6a
Improving scripts
arboleya Jul 19, 2024
143d8be
Adding sample env file
arboleya Jul 19, 2024
5a47c48
Standardizing snippets and tests
arboleya Jul 19, 2024
c68ea14
Validate env constants existence
arboleya Jul 20, 2024
7a65623
Drafting new snippet
arboleya Jul 20, 2024
f2f4133
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Jul 20, 2024
c32a6e9
Adjusting script command
arboleya Jul 20, 2024
0d81092
Removing unnecessary wallet
arboleya Jul 20, 2024
65d6e80
Extacting launcher into another file
arboleya Jul 20, 2024
7ddc250
New API draft
arboleya Jul 20, 2024
28cce95
Syncing env and launcher template
arboleya Jul 20, 2024
47b19bd
Better docs
arboleya Jul 20, 2024
f0287c2
Adding new sway script
arboleya Jul 20, 2024
4ac46af
Removing API draft
arboleya Jul 20, 2024
e0c319e
Fixing file location
arboleya Jul 20, 2024
c647814
Add script to workspace
arboleya Jul 20, 2024
1ebc19d
Improve snippet
arboleya Jul 20, 2024
9c93682
Using new snippets
arboleya Jul 20, 2024
739d78e
Add new API draft
arboleya Jul 20, 2024
3808175
Matching extra blankspace
arboleya Jul 20, 2024
a91820f
Ignoring env file
arboleya Jul 20, 2024
7b8bbbb
Adding region marks
arboleya Jul 20, 2024
847c412
Avoid repetition
arboleya Jul 20, 2024
3f756e9
Trim env consts
arboleya Jul 20, 2024
16abcb4
Cleanup
arboleya Jul 20, 2024
094355b
Playing around new API
arboleya Jul 20, 2024
a5d3d08
Tidying up
arboleya Jul 20, 2024
501d913
Ignoring experimental file
arboleya Jul 20, 2024
71f0c01
Ignoring generated files in eslint
arboleya Jul 20, 2024
ae8fc47
Adjusting wallets count
arboleya Jul 20, 2024
4379cff
Moving chunk around
arboleya Jul 20, 2024
b4f2164
Adjusting ignore rule
arboleya Jul 20, 2024
8bf6293
Improving imports manipulation
arboleya Jul 20, 2024
9590341
Adding comments
arboleya Jul 20, 2024
4be8d63
Adjusting template markers
arboleya Jul 20, 2024
88a04b4
Tyop
arboleya Jul 20, 2024
57289fd
Update draft
arboleya Jul 20, 2024
71847b0
Update title
arboleya Jul 20, 2024
2f02691
Adjust deployment usage
arboleya Jul 20, 2024
a7fd7e7
Updating example
arboleya Jul 22, 2024
7f8c273
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Jul 22, 2024
247898c
Removing temp draft
arboleya Jul 22, 2024
dfe8eb9
Removing temp draft section
arboleya Jul 22, 2024
e73a076
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 1, 2024
e03c3db
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 11, 2024
aa09fbd
Updating broken test
arboleya Aug 11, 2024
0268ef3
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 13, 2024
5cb05ae
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 13, 2024
afa36c7
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 30, 2024
6e05237
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Aug 31, 2024
739ccef
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Sep 5, 2024
dd4d3f8
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Sep 6, 2024
3c36528
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Sep 7, 2024
5d85686
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Sep 10, 2024
9647ccf
Using `NETWORK_URL` across the board
arboleya Sep 10, 2024
85c8cbd
Reword comment
arboleya Sep 10, 2024
1fcdf29
Adding scripts dir to tsconfig
arboleya Sep 10, 2024
3b463d0
Starting with more wallets
arboleya Sep 10, 2024
405b4fd
Merge branch 'master' into aa/feat/infra-for-new-snippets
arboleya Sep 13, 2024
9532319
Automatically generating tests for code snippets
arboleya Sep 13, 2024
00234d6
Forcing assertion failures to throw
arboleya Sep 13, 2024
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
1 change: 1 addition & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"demo-node-esm",
"demo-typegen",
"@fuel-ts/docs-snippets",
"@fuel-ts/docs-snippets2",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we prefix the docs-snippets with @fuel-ts/? I thought we only did this for packages?

"template-nextjs",
"create-fuels-counter-guide",
"demo-wallet-sdk-react"
Expand Down
4 changes: 4 additions & 0 deletions .changeset/lemon-cars-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

feat: new infra for code snippets
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ apps/demo-nextjs
apps/demo-react-cra
apps/demo-react-vite
apps/create-fuels-counter-guide
apps/docs-snippets2/src/typegend
apps/docs-snippets2/src/**/*.wrapped.ts

packages/fuels/test/fixtures/project
packages/account/src/providers/__generated__
Expand Down
1 change: 1 addition & 0 deletions .knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"/apps/docs/*",
"/packages/abi-typegen/test/**",
"templates/**",
"/apps/docs-snippets2/**/*.test.ts",
"apps/create-fuels-counter-guide/**"
],
"ignoreDependencies": [
Expand Down
6 changes: 6 additions & 0 deletions apps/docs-snippets2/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
extends: ['../../.eslintrc.js'],
rules: {
'no-console': 'off',
},
};
2 changes: 2 additions & 0 deletions apps/docs-snippets2/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
src/typegend
*.wrapped.ts
9 changes: 9 additions & 0 deletions apps/docs-snippets2/fuels.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createConfig } from 'fuels';

export default createConfig({
workspace: './sway',
output: './src/typegend',
forcBuildFlags: ['--release'],
forcPath: 'fuels-forc',
fuelCorePath: 'fuels-core',
});
22 changes: 22 additions & 0 deletions apps/docs-snippets2/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "@fuel-ts/docs-snippets2",
"version": "0.67.0",
"description": "",
"private": true,
"scripts": {
"build": "run-s wrap:snippets build:forc",
"build:forc": "pnpm fuels build",
"wrap:snippets": "tsx scripts/wrap-snippets.ts",
"pretest": "pnpm build",
"test": "cd ../.. && pnpm run test:filter apps/docs-snippets2"
},
"dependencies": {
"fuels": "workspace:*"
},
"devDependencies": {
"glob": "^10.2.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
16 changes: 16 additions & 0 deletions apps/docs-snippets2/scripts/launcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { launchTestNode } from 'fuels/test-utils';

using node = await launchTestNode({ walletsConfig: { count: 3 } });

export const LOCAL_NETWORK_URL = node.provider.url;

const [w0, w2, w3] = node.wallets;

export const WALLET_ADDRESS = w0.address;
export const WALLET_PVT_KEY = w0.privateKey;

export const WALLET_ADDRESS_2 = w2.address;
export const WALLET_PVT_KEY_2 = w2.privateKey;

export const WALLET_ADDRESS_3 = w3.address;
export const WALLET_PVT_KEY_3 = w3.privateKey;
88 changes: 88 additions & 0 deletions apps/docs-snippets2/scripts/wrap-snippets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { readFileSync, writeFileSync } from 'fs';
import { globSync } from 'glob';
import { join } from 'path';

const wrapperFnFilepath = join(__dirname, 'wrapper-fn.ts');
const wrapperFnContents = readFileSync(wrapperFnFilepath, 'utf-8');

/**
* Wrap snippet for testing
* @param filepath - Snippet filepath
*/
export const wrapSnippet = (filepath: string) => {
const snippetContents = readFileSync(filepath, 'utf8');

/*
Filter all imports from file.
*/
const importsReg = /^[\s\S]+from.+['"];/gm;
let imports = snippetContents.match(importsReg)?.toString() ?? '';
const snippetsNoImports = imports.length ? snippetContents.split(imports)[1] : snippetContents;

/*
Removes .env file import
*/
const envImportReg = /import.+\{.+([\s\S]+).+\}.+from.+'\.\.\/env';/gm;
if (envImportReg.test(imports)) {
const allImports = imports.match(envImportReg)?.[0];
const envImport = `import ${allImports?.split('import ').pop()}`;
imports = imports.replace(envImport, '');
}

/*
Inject node launcher & friends
*/
let nodeLauncher = '';
const localNetworkReg = /,?\s+LOCAL_NETWORK_URL(\s*,)?/;
if (localNetworkReg.test(imports)) {
/*
Removes `LOCAL_NETWORK_URL` from `fuels` import members
*/
imports = imports.replace(localNetworkReg, '$1');

/*
Adds launchNode import
*/
imports += `\nimport { launchTestNode } from 'fuels/test-utils'`;

/*
Injects launched node and env constants
*/
nodeLauncher = readFileSync(join(__dirname, 'launcher.ts'), 'utf-8')
.replace(/import.*$/gm, '') // ignore file imports
.replace(/export /g, '') // remove export keywords
.trim() // zip
.replace(/\n/g, '\n '); // indent chunk
}

/*
Format indentation
*/
const indented = snippetsNoImports.replace(/^/gm, ' ').trim();
const formatted = wrapperFnContents
.replace('// %SNIPPET%', indented)
.replace('// %NODE_LAUNCHER%', nodeLauncher);

/*
Write wrapped snippet to disk
*/
const wrappedPath = filepath.replace('.ts', '.wrapped.ts');
const wrappedSnippet = [imports, '\n', formatted].join('');

writeFileSync(wrappedPath, wrappedSnippet);
};

/*
Wrap all snippets inside `src` dir
*/
const dir = 'src/**';
const src = `${dir}/*.ts`;
const ignore = [
`src/typegend/**`,
`src/env.ts`,
`src/transactions/new-api.ts`,
`${dir}/*.test.ts`,
`${dir}/*.wrapped.ts`,
];

globSync(src, { ignore }).forEach(wrapSnippet);
36 changes: 36 additions & 0 deletions apps/docs-snippets2/scripts/wrapper-fn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

// eslint-disable-next-line @typescript-eslint/require-await
export const main = async (passLogsThrough: boolean = false): Promise<any | any[]> => {
const logs: any[] = [];
const bkpConsole = console;

// eslint-disable-next-line no-global-assign
console = {
...console,
log: (...args: any[]) => {
if (passLogsThrough) {
bkpConsole.log.apply(null, args);
}
logs.push(args);
},
};

// TEST NODE LAUNCHER ———>>>
// %NODE_LAUNCHER%
// <<<——— TEST NODE LAUNCHER

try {
// SNIPPET ———>>>
// %SNIPPET%
// <<<——— SNIPPET
} catch (error) {
console.error(error);
return { error };
}

// eslint-disable-next-line no-global-assign
console = bkpConsole;

return logs;
};
8 changes: 8 additions & 0 deletions apps/docs-snippets2/src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const WALLET_ADDRESS = '<overriden-by-wrapper>';
export const WALLET_PVT_KEY = '<overriden-by-wrapper>';

export const WALLET_ADDRESS_2 = '<overriden-by-wrapper>';
export const WALLET_PVT_KEY_2 = '<overriden-by-wrapper>';

export const WALLET_ADDRESS_3 = '<overriden-by-wrapper>';
export const WALLET_PVT_KEY_3 = '<overriden-by-wrapper>';
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { main } from './connecting-to-localnode.wrapped';

/**
* @group node
*/
test('it works', async () => {
const [[{ balances }]] = await main();
expect(balances).toBeInstanceOf(Array);
});
12 changes: 12 additions & 0 deletions apps/docs-snippets2/src/introduction/connecting-to-localnode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// #region main
nedsalk marked this conversation as resolved.
Show resolved Hide resolved
import { Provider, Wallet, LOCAL_NETWORK_URL } from 'fuels';

const ADDRESS = '0x767caf5b08eba21c561078a4d5be09bbd7f16b9eca22699a61f1edd9e456126f';

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromAddress(ADDRESS, provider);

const { balances } = await wallet.getBalances();

console.log({ balances });
// #endregion main
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { main } from './connecting-to-testnet.wrapped';

/**
* @group node
*/
test('it works', async () => {
const [[{ balances }]] = await main();
expect(balances).toBeInstanceOf(Array);
});
12 changes: 12 additions & 0 deletions apps/docs-snippets2/src/introduction/connecting-to-testnet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// #region main
import { Provider, Wallet, TESTNET_NETWORK_URL } from 'fuels';

const ADDRESS = '0x767caf5b08eba21c561078a4d5be09bbd7f16b9eca22699a61f1edd9e456126f';

const provider = await Provider.create(TESTNET_NETWORK_URL);
const wallet = Wallet.fromAddress(ADDRESS, provider);

const { balances } = await wallet.getBalances();

console.log({ balances });
// #endregion main
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { main } from './transaction-parameters.wrapped';

/**
* @group node
*/
test('it works', async () => {
const [[{ isStatusSuccess }]] = await main();
expect(isStatusSuccess).toBeTruthy();
});
61 changes: 61 additions & 0 deletions apps/docs-snippets2/src/transactions/transaction-parameters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// #region full
import type { TxParams } from 'fuels';
import { bn, LOCAL_NETWORK_URL, Provider, ScriptTransactionRequest, Wallet } from 'fuels';

import { WALLET_PVT_KEY } from '../env';
import { CounterAbi__factory } from '../typegend';
import counterBytecode from '../typegend/contracts/CounterAbi.hex';
import { ScriptSumAbi__factory } from '../typegend/scripts';

const { storageSlots } = CounterAbi__factory;

const provider = await Provider.create(LOCAL_NETWORK_URL);
const wallet = Wallet.fromPrivateKey(WALLET_PVT_KEY, provider);

const deploy = await CounterAbi__factory.deployContract(counterBytecode, wallet, {
storageSlots,
});

const { contract } = await deploy.waitForResult();

// #region transaction-parameters-6
const txParams: TxParams = {
// #region transaction-parameters-1
gasLimit: bn(69242),
// #endregion transaction-parameters-1
// #region transaction-parameters-2
maxFee: bn(69242),
// #endregion transaction-parameters-2
// #region transaction-parameters-3
tip: bn(100),
// #endregion transaction-parameters-3
// #region transaction-parameters-4
maturity: 1,
// #endregion transaction-parameters-4
// #region transaction-parameters-5
witnessLimit: bn(5000),
// #endregion transaction-parameters-5
};
// #endregion transaction-parameters-6

// #region transaction-parameters-7
const transactionRequest = new ScriptTransactionRequest({
script: ScriptSumAbi__factory.bin,
gasLimit: 100,
});
// #endregion transaction-parameters-7

// #region transaction-parameters-8
const { waitForResult } = await contract.functions
.increment_count(15) //
.txParams(txParams)
.call();

const {
value,
transactionResult: { isStatusSuccess },
} = await waitForResult();

console.log({ value, isStatusSuccess, transactionRequest });
// #endregion transaction-parameters-8
// #endregion full
2 changes: 2 additions & 0 deletions apps/docs-snippets2/sway/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
target
2 changes: 2 additions & 0 deletions apps/docs-snippets2/sway/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[workspace]
members = ["counter", "script-sum"]
7 changes: 7 additions & 0 deletions apps/docs-snippets2/sway/counter/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 = "counter"

[dependencies]
27 changes: 27 additions & 0 deletions apps/docs-snippets2/sway/counter/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
contract;

abi Counter {
#[storage(read)]
fn get_count() -> u64;

#[storage(write, read)]
fn increment_count(amount: u64) -> u64;
}

storage {
counter: u64 = 0,
}

impl Counter for Contract {
#[storage(read)]
fn get_count() -> u64 {
storage.counter.read()
}

#[storage(write, read)]
fn increment_count(amount: u64) -> u64 {
let current = storage.counter.read();
storage.counter.write(current + amount);
storage.counter.read()
}
}
7 changes: 7 additions & 0 deletions apps/docs-snippets2/sway/script-sum/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-sum"

[dependencies]
Loading
Loading