@taqueria/plugin-contract-types 0.3.0 → 0.4.0-rc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/type-utils.ts CHANGED
@@ -1,35 +1,33 @@
1
1
  import { ContractAbstraction, ContractMethod, ContractMethodObject, ContractProvider, Wallet } from '@taquito/taquito';
2
2
 
3
- type BaseContractType = { methods: unknown, methodsObject: unknown, storage: unknown };
3
+ type BaseContractType = { methods: unknown; methodsObject: unknown; storage: unknown };
4
4
 
5
5
  type ContractMethodsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
6
- [M in keyof TContract['methods']]:
7
- TContract['methods'][M] extends (...args: infer A) => unknown
8
- ? (...args: A) => ContractMethod<T>
9
- : never
6
+ [M in keyof TContract['methods']]: TContract['methods'][M] extends (...args: infer A) => unknown
7
+ ? (...args: A) => ContractMethod<T>
8
+ : never;
10
9
  };
11
10
  type ContractMethodsObjectsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
12
- [M in keyof TContract['methodsObject']]:
13
- TContract['methodsObject'][M] extends (...args: infer A) => unknown
14
- ? (...args: A) => ContractMethodObject<T>
15
- : never
11
+ [M in keyof TContract['methodsObject']]: TContract['methodsObject'][M] extends (...args: infer A) => unknown
12
+ ? (...args: A) => ContractMethodObject<T>
13
+ : never;
16
14
  };
17
15
  type ContractStorageOf<TContract extends BaseContractType> = TContract['storage'];
18
16
 
19
- export type ContractAbstractionFromContractType<TContract extends BaseContractType> =
20
- ContractAbstraction<ContractProvider,
21
- ContractMethodsOf<ContractProvider, TContract>,
22
- ContractMethodsObjectsOf<ContractProvider, TContract>,
23
- {},
24
- {},
25
- ContractStorageOf<TContract>
26
- >;
17
+ export type ContractAbstractionFromContractType<TContract extends BaseContractType> = ContractAbstraction<
18
+ ContractProvider,
19
+ ContractMethodsOf<ContractProvider, TContract>,
20
+ ContractMethodsObjectsOf<ContractProvider, TContract>,
21
+ {},
22
+ {},
23
+ ContractStorageOf<TContract>
24
+ >;
27
25
 
28
- export type WalletContractAbstractionFromContractType<TContract extends BaseContractType> =
29
- ContractAbstraction<Wallet,
30
- ContractMethodsOf<Wallet, TContract>,
31
- ContractMethodsObjectsOf<Wallet, TContract>,
32
- {},
33
- {},
34
- ContractStorageOf<TContract>
35
- >;
26
+ export type WalletContractAbstractionFromContractType<TContract extends BaseContractType> = ContractAbstraction<
27
+ Wallet,
28
+ ContractMethodsOf<Wallet, TContract>,
29
+ ContractMethodsObjectsOf<Wallet, TContract>,
30
+ {},
31
+ {},
32
+ ContractStorageOf<TContract>
33
+ >;
package/tasks.ts CHANGED
@@ -1,60 +1,56 @@
1
- import { SanitizedArgs, PluginResponse, Failure, LikeAPromise } from "@taqueria/node-sdk/types";
2
- import glob from 'fast-glob'
3
- import { join } from 'path'
4
- import { generateContractTypesProcessContractFiles } from "./src/cli-process";
5
-
6
- type PluginOpts = {
7
- // TODO: Document these
8
- typescriptDir: string,
9
- typeAliasMode?: 'local' | 'file' | 'library' | 'simple',
10
- };
11
- type Opts = SanitizedArgs & Record<string, unknown>;
12
-
13
- const getContractAbspath = (contractFilename: string, parsedArgs: Opts) =>
14
- join(parsedArgs.artifactsDir, /\.tz$/.test(contractFilename) ? contractFilename : `${contractFilename}.tz`)
15
-
16
-
17
- const generateContractTypes = (parsedArgs: Opts & PluginOpts) => async (contractFilename: string) : Promise<string> => {
18
- const contractAbspath = getContractAbspath(contractFilename, parsedArgs);
19
- await generateContractTypesProcessContractFiles({
20
- inputTzContractDirectory: parsedArgs.artifactsDir,
21
- inputFiles: [contractAbspath],
22
- outputTypescriptDirectory: parsedArgs.typescriptDir,
23
- format: 'tz',
24
- typeAliasMode: parsedArgs.typeAliasMode ?? 'file',
25
- });
26
-
27
- return `${contractFilename}: Types generated`;
1
+ import { LikeAPromise, PluginResponse, RequestArgs, TaqError } from '@taqueria/node-sdk/types';
2
+ import glob from 'fast-glob';
3
+ import { join } from 'path';
4
+ import { generateContractTypesProcessContractFiles } from './src/cli-process';
5
+ interface Opts extends RequestArgs.ProxyRequestArgs {
6
+ // TODO: Document these
7
+ typescriptDir?: string;
8
+ typeAliasMode?: 'local' | 'file' | 'library' | 'simple';
9
+ contract?: string;
28
10
  }
29
11
 
30
- const generateContractTypesAll = async (parsedArgs: Opts & PluginOpts) : Promise<string[]> => {
31
- const files = await glob("**/*.tz", {cwd: parsedArgs.artifactsDir});
32
- return await Promise.all(files.map(generateContractTypes(parsedArgs)));
33
- }
34
-
35
- export const generateTypes = <T>(parsedArgs: Opts): LikeAPromise<PluginResponse, Failure<T>> => {
36
- debugger
37
- parsedArgs.typescriptDir = parsedArgs.typescriptDir || 'types';
12
+ const getContractAbspath = (contractFilename: string, parsedArgs: Opts) =>
13
+ join(parsedArgs.config.artifactsDir, /\.tz$/.test(contractFilename) ? contractFilename : `${contractFilename}.tz`);
14
+
15
+ const generateContractTypes = (parsedArgs: Opts) =>
16
+ async (contractFilename: string): Promise<string> => {
17
+ const contractAbspath = getContractAbspath(contractFilename, parsedArgs);
18
+ await generateContractTypesProcessContractFiles({
19
+ inputTzContractDirectory: parsedArgs.config.artifactsDir,
20
+ inputFiles: [contractAbspath],
21
+ outputTypescriptDirectory: parsedArgs.typescriptDir || 'types',
22
+ format: 'tz',
23
+ typeAliasMode: parsedArgs.typeAliasMode ?? 'file',
24
+ });
25
+
26
+ return `${contractFilename}: Types generated`;
27
+ };
28
+
29
+ const generateContractTypesAll = async (parsedArgs: Opts): Promise<string[]> => {
30
+ const files = await glob('**/*.tz', { cwd: parsedArgs.config.artifactsDir });
31
+ return await Promise.all(files.map(generateContractTypes(parsedArgs)));
32
+ };
38
33
 
39
- console.log('generateTypes', {
40
- typescriptDir: parsedArgs.typescriptDir
41
- });
34
+ export const generateTypes = (parsedArgs: Opts): LikeAPromise<PluginResponse, TaqError.t> => {
35
+ parsedArgs.typescriptDir = parsedArgs.typescriptDir || 'types';
42
36
 
43
- const argsTyped = parsedArgs as Opts & PluginOpts;
37
+ console.log('generateTypes', {
38
+ typescriptDir: parsedArgs.typescriptDir,
39
+ });
44
40
 
45
- const p = argsTyped.contract
46
- ? generateContractTypes(argsTyped) (argsTyped.contract as string)
47
- : generateContractTypesAll(argsTyped)
41
+ const p = parsedArgs.contract
42
+ ? generateContractTypes(parsedArgs)(parsedArgs.contract)
43
+ : generateContractTypesAll(parsedArgs);
48
44
 
49
- return p.then(data => {
50
- console.log(
51
- (Array.isArray(data))
52
- ? data.join("\n")
53
- : data
54
- )
55
- })
56
- }
45
+ return p.then(data => {
46
+ console.log(
47
+ (Array.isArray(data))
48
+ ? data.join('\n')
49
+ : data,
50
+ );
51
+ });
52
+ };
57
53
 
58
54
  export const tasks = {
59
- generateTypes,
60
- }
55
+ generateTypes,
56
+ };
@@ -1,69 +1,79 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import path from 'path';
3
3
  import { promisify } from 'util';
4
- import { generateContractTypesFromMichelsonCode } from '../src/generator/process';
5
4
  import { normalizeContractName } from '../src/generator/contract-name';
6
- import { TypeAliasData } from '../src/generator/typescript-output';
7
-
5
+ import { generateContractTypesFromMichelsonCode } from '../src/generator/process';
6
+ import { TypeAliasData, TypeUtilsData } from '../src/generator/typescript-output';
8
7
 
9
8
  const readFileText = async (filePath: string): Promise<string> => {
10
- return fs.readFile(filePath, { encoding: 'utf8' });
9
+ return fs.readFile(filePath, { encoding: 'utf8' });
11
10
  };
12
11
 
13
12
  describe('Generate Example Contracts', () => {
13
+ const typeAliasDataLibrary: TypeAliasData = { mode: 'library', importPath: '@taquito/contract-type-generator' };
14
+ const typeAliasDataSimple: TypeAliasData = { mode: 'simple' };
14
15
 
15
- const typeAliasDataLibrary: TypeAliasData = { mode: 'library', importPath: '@taquito/contract-type-generator' };
16
- const typeAliasDataSimple: TypeAliasData = { mode: 'simple' };
17
-
18
- const exampleDir = path.resolve(__dirname, `../example`);
19
-
20
- const testContractTypeGeneration = async (contractFileName: string, format: 'tz' | 'json', mode: 'library' | 'simple') => {
21
- const contractRaw = await readFileText(`${exampleDir}/contracts/${contractFileName}.${format}`);
22
- const expectedTypeFileContent = await readFileText(`${exampleDir}/types${mode === 'simple' ? '-simple' : ''}/${contractFileName}.types.ts`);
23
- const expectedCodeFileContent = await readFileText(`${exampleDir}/types${mode === 'simple' ? '-simple' : ''}/${contractFileName}.code.ts`);
24
- const contractName = normalizeContractName(contractFileName);
25
- const typeAliasData = mode === 'library' ? typeAliasDataLibrary : typeAliasDataSimple;
26
- const { typescriptCodeOutput: { typesFileContent: actualTypesFileContent, contractCodeFileContent: actualCodeFileContent } } = generateContractTypesFromMichelsonCode(contractRaw, contractName, format, typeAliasData);
27
- expect(actualTypesFileContent.trim()).toEqual(expectedTypeFileContent.trim());
28
- expect(actualCodeFileContent.trim()).toEqual(expectedCodeFileContent.trim());
29
- };
30
-
31
- it('Generate Types 01 - tz library', async () => {
32
- await testContractTypeGeneration('example-contract-1', 'tz', 'library');
33
- });
34
- it('Generate Types 01 - tz simple', async () => {
35
- await testContractTypeGeneration('example-contract-1', 'tz', 'simple');
36
- });
37
- it('Generate Types 02 - tz library', async () => {
38
- await testContractTypeGeneration('example-contract-2', 'tz', 'library');
39
- });
40
- it('Generate Types 02 - tz simple', async () => {
41
- await testContractTypeGeneration('example-contract-2', 'tz', 'simple');
42
- });
16
+ const exampleDir = path.resolve(__dirname, `../example`);
43
17
 
44
- it('Generate Types 03 - json library', async () => {
45
- await testContractTypeGeneration('example-contract-3', 'json', 'library');
46
- });
18
+ const testContractTypeGeneration = async (
19
+ contractFileName: string,
20
+ format: 'tz' | 'json',
21
+ mode: 'library' | 'simple',
22
+ ) => {
23
+ const contractRaw = await readFileText(`${exampleDir}/contracts/${contractFileName}.${format}`);
24
+ const expectedTypeFileContent = await readFileText(
25
+ `${exampleDir}/types${mode === 'simple' ? '-simple' : ''}/${contractFileName}.types.ts`,
26
+ );
27
+ const expectedCodeFileContent = await readFileText(
28
+ `${exampleDir}/types${mode === 'simple' ? '-simple' : ''}/${contractFileName}.code.ts`,
29
+ );
30
+ const contractName = normalizeContractName(contractFileName);
31
+ const typeAliasData = mode === 'library' ? typeAliasDataLibrary : typeAliasDataSimple;
32
+ const typeUtilsData: TypeUtilsData = { importPath: `./type-utils` };
33
+ const {
34
+ typescriptCodeOutput: {
35
+ typesFileContent: actualTypesFileContent,
36
+ contractCodeFileContent: actualCodeFileContent,
37
+ },
38
+ } = generateContractTypesFromMichelsonCode(contractRaw, contractName, format, typeAliasData, typeUtilsData);
39
+ expect(actualTypesFileContent.trim()).toEqual(expectedTypeFileContent.trim());
40
+ expect(actualCodeFileContent.trim()).toEqual(expectedCodeFileContent.trim());
41
+ };
47
42
 
48
- it('Generate Types 04 - newer protocol', async () => {
49
- await testContractTypeGeneration('example-contract-4', 'tz', 'library');
50
- });
51
- it('Generate Types 04 - tz simple', async () => {
52
- await testContractTypeGeneration('example-contract-4', 'tz', 'simple');
53
- });
43
+ it('Generate Types 01 - tz library', async () => {
44
+ await testContractTypeGeneration('example-contract-1', 'tz', 'library');
45
+ });
46
+ it('Generate Types 01 - tz simple', async () => {
47
+ await testContractTypeGeneration('example-contract-1', 'tz', 'simple');
48
+ });
49
+ it('Generate Types 02 - tz library', async () => {
50
+ await testContractTypeGeneration('example-contract-2', 'tz', 'library');
51
+ });
52
+ it('Generate Types 02 - tz simple', async () => {
53
+ await testContractTypeGeneration('example-contract-2', 'tz', 'simple');
54
+ });
54
55
 
55
- // it(`Generate Types - All`, async () => {
56
- // const allExampleContracts = (await fs.readdir(`${exampleDir}/contracts/`)).filter(f=>f.endsWith('.tz') || f.endsWith('.json'));
56
+ it('Generate Types 03 - json library', async () => {
57
+ await testContractTypeGeneration('example-contract-3', 'json', 'library');
58
+ });
57
59
 
58
- // for(const f of allExampleContracts){
59
- // const fRelative = f.replace(exampleDir,'');
60
- // const m = fRelative.match(/^(.*)\.(tz|json)$/);
61
- // if(!m){ return; }
62
- // const [_,filename, ext] = m;
60
+ it('Generate Types 04 - newer protocol', async () => {
61
+ await testContractTypeGeneration('example-contract-4', 'tz', 'library');
62
+ });
63
+ it('Generate Types 04 - tz simple', async () => {
64
+ await testContractTypeGeneration('example-contract-4', 'tz', 'simple');
65
+ });
63
66
 
64
- // await testContractTypeGeneration(filename, ext as 'tz'|'json', 'simple');
65
- // }
66
- // });
67
+ // it(`Generate Types - All`, async () => {
68
+ // const allExampleContracts = (await fs.readdir(`${exampleDir}/contracts/`)).filter(f=>f.endsWith('.tz') || f.endsWith('.json'));
67
69
 
70
+ // for(const f of allExampleContracts){
71
+ // const fRelative = f.replace(exampleDir,'');
72
+ // const m = fRelative.match(/^(.*)\.(tz|json)$/);
73
+ // if(!m){ return; }
74
+ // const [_,filename, ext] = m;
68
75
 
76
+ // await testContractTypeGeneration(filename, ext as 'tz'|'json', 'simple');
77
+ // }
78
+ // });
69
79
  });
package/tsconfig.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
- "compilerOptions": {
3
- "target": "ES6",
4
- "module": "CommonJS",
5
- "declaration": true,
6
- "allowSyntheticDefaultImports": true,
7
- "esModuleInterop": true,
8
- "forceConsistentCasingInFileNames": true,
9
- "strict": true,
10
- "skipLibCheck": true,
11
- "outDir": "lib",
12
- }
13
- }
2
+ "compilerOptions": {
3
+ "target": "ES2021",
4
+ "module": "CommonJS",
5
+ "declaration": true,
6
+ "allowSyntheticDefaultImports": true,
7
+ "esModuleInterop": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "strict": true,
10
+ "skipLibCheck": true,
11
+ "outDir": "lib"
12
+ }
13
+ }
package/Readme.md DELETED
@@ -1,212 +0,0 @@
1
- This plugin will generate typescript types for a contract.
2
-
3
- In the simple case, it reads the `artifacts` folder for any `*.tz` Michelson files and will generate a types file with the matching filename for each.
4
-
5
- ## Requirements
6
-
7
- This is using a unmerged taquito PR:
8
-
9
- - https://github.com/ecadlabs/taquito/pull/1343
10
- - `npm i @taquito/taquito@11.1.0-6bfb6c08--1343 --registry https://npm.preview.tezostaquito.io/`
11
-
12
- ## Examples
13
-
14
- ### Example Usage (based on an nft auction contract from open minter sdk)
15
-
16
- ```ts
17
- export const exampleContractMethods1 = async () => {
18
-
19
- const Tezos = new TezosToolkit(`https://YOUR_PREFERRED_RPC_URL`)
20
-
21
- const contract = await Tezos.contract.at<TestContract>(`tz123`);
22
-
23
- contract.methods.bid(tas.nat(0));
24
- contract.methods.configure(
25
- /*opening_price:*/ tas.mutez(10),
26
- /*min_raise_percent:*/ tas.nat(10),
27
- /*min_raise:*/ tas.mutez(10),
28
- /*round_time:*/ tas.nat(10),
29
- /*extend_time:*/ tas.nat(10),
30
- /*asset:*/ [{
31
- fa2_address: tas.address(`tz123`),
32
- fa2_batch: [{
33
- amount: tas.nat(100),
34
- token_id: tas.nat(`100000000000000`),
35
- }],
36
- }],
37
- /*start_time:*/ tas.timestamp(new Date()),
38
- /*end_time:*/ tas.timestamp(`2020-01-01`),
39
- );
40
-
41
- // methodsObject
42
- contract.methodsObject.bid(tas.nat(0));
43
- contract.methodsObject.configure({
44
- asset: [{
45
- fa2_address: tas.address(`tz123`),
46
- fa2_batch: [{
47
- amount: tas.nat(100),
48
- token_id: tas.nat(`100000000000000`),
49
- }],
50
- }],
51
- start_time: tas.timestamp(new Date()),
52
- end_time: tas.timestamp(`2020-01-01`),
53
- extend_time: tas.nat(10),
54
- min_raise: tas.mutez(10),
55
- min_raise_percent: tas.nat(10),
56
- opening_price: tas.mutez(10),
57
- round_time: tas.nat(10),
58
- });
59
-
60
- };
61
- ```
62
-
63
-
64
- ### Example typegen task
65
-
66
- ```console
67
- $ taqueria typegen --typescriptDir ./types
68
- generateTypes
69
- {
70
- "typescriptDir": "./types"
71
- }
72
- Generating Types: /home/rick/projects/crypto/taqueria/example/artifacts => /home/rick/projects/crypto/taqueria/example/types
73
- Contracts Found:
74
- - /home/rick/projects/crypto/taqueria/example/artifacts/example-contract-1.tz
75
- Processing /example-contract-1.tz...example-contract-1.tz: Types generated
76
- ```
77
-
78
-
79
- ### Example type output
80
-
81
- ```ts
82
- type Storage = {
83
- pauseable_admin?: {
84
- admin: address;
85
- paused: boolean;
86
- pending_admin?: address;
87
- };
88
- current_id: nat;
89
- max_auction_time: nat;
90
- max_config_to_start_time: nat;
91
- auctions: BigMap<nat, {
92
- seller: address;
93
- current_bid: mutez;
94
- start_time: timestamp;
95
- last_bid_time: timestamp;
96
- round_time: int;
97
- extend_time: int;
98
- asset: Array<{
99
- fa2_address: address;
100
- fa2_batch: Array<{
101
- token_id: nat;
102
- amount: nat;
103
- }>;
104
- }>;
105
- min_raise_percent: nat;
106
- min_raise: mutez;
107
- end_time: timestamp;
108
- highest_bidder: address;
109
- }>;
110
- };
111
-
112
- type Methods = {
113
- confirm_admin: () => Promise<void>;
114
- pause: (param: boolean) => Promise<void>;
115
- set_admin: (param: address) => Promise<void>;
116
- bid: (param: nat) => Promise<void>;
117
- cancel: (param: nat) => Promise<void>;
118
- configure: (
119
- opening_price: mutez,
120
- min_raise_percent: nat,
121
- min_raise: mutez,
122
- round_time: nat,
123
- extend_time: nat,
124
- asset: Array<{
125
- fa2_address: address;
126
- fa2_batch: Array<{
127
- token_id: nat;
128
- amount: nat;
129
- }>;
130
- }>,
131
- start_time: timestamp,
132
- end_time: timestamp,
133
- ) => Promise<void>;
134
- resolve: (param: nat) => Promise<void>;
135
- };
136
- ```
137
-
138
-
139
- ## Taquito library changes
140
-
141
- See [example-usage.ts](example/example-usage.ts) for full example
142
-
143
- ### Before
144
-
145
- Using taquito with the generated contract types:
146
-
147
- The at method can be called providing a type with a utility method that can be provided:
148
- ```ts
149
- const contract = await Tezos.contract.at(`tz123`, contractAbstractionComposer<TestContractType>());
150
-
151
- // methods can now use typed parameters
152
- // methodsObject will be able to use type parameters
153
- ```
154
-
155
- This can work the same with a wallet
156
- ```ts
157
- const contract = await Tezos.wallet.at(`tz123`, walletAbstractionComposer<TestContractType>());
158
- ```
159
-
160
- Alternatively, this can be done with a cast:
161
- ```ts
162
- const contract = await Tezos.contract.at(`tz123`) as ContractProviderFromContractType<TestContractType>;
163
- ```
164
-
165
-
166
- The originate contract does not have any way to provide a type, so this requires a cast:
167
- ```ts
168
- const originationResult = await Tezos.contract.originate({...});
169
- const contract = await originationResult.contract(5) as ContractProviderFromContractType<TestContractType2>;
170
- ```
171
-
172
-
173
- For accessing storage, there is no way to pass the type through the contract class,
174
- so it requires providing the type again:
175
- ```ts
176
- const contract = await Tezos.contract.at(`tz123`) as ContractProviderFromContractType<TestContractType>;
177
- const storage = await contract.storage<StorageFromContractType<TestContractType>>();
178
- ```
179
-
180
-
181
- ### After
182
-
183
- Extending ContractAbstraction with additional generic types:
184
-
185
- The at method can be called with the contract type provided:
186
- ```ts
187
- const contract = await Tezos.contract.at<TestContract>(`tz123`);
188
-
189
- // methods can now use typed parameters
190
- // methodsObject will be able to use type parameters
191
- // storage will be able to use type parameters
192
-
193
- ```
194
-
195
- This can work the same with a wallet
196
- ```ts
197
- const contract = await Tezos.wallet.at<TestWalletContract>(`tz123`);
198
- ```
199
-
200
- The originate contract now accepts a type:
201
- ```ts
202
- const originationResult = await Tezos.contract.originate({...});
203
- const contract = await originationResult.contract<TestContract2>(5);
204
- ```
205
-
206
-
207
- The contract type now also provides the default storage type:
208
- ```ts
209
- const contract = await Tezos.contract.at<TestContract>(`tz123`);
210
- const storage = await contract.storage();
211
- ```
212
-