@0xobelisk/sui-cli 1.2.0-pre.21 → 1.2.0-pre.24

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.
@@ -1,250 +1,250 @@
1
- import { Transaction, UpgradePolicy } from '@0xobelisk/sui-client';
2
- import { execSync } from 'child_process';
3
- import chalk from 'chalk';
4
- import { UpgradeError } from './errors';
5
- import {
6
- getOldPackageId,
7
- getVersion,
8
- getUpgradeCap,
9
- saveContractData,
10
- getOnchainSchemas,
11
- switchEnv,
12
- getSchemaId,
13
- getDubheSchemaId,
14
- initializeDubhe
15
- } from './utils';
16
- import * as fs from 'fs';
17
- import * as path from 'path';
18
- import { DubheConfig } from '@0xobelisk/sui-common';
19
-
20
- type Migration = {
21
- schemaName: string;
22
- fields: string;
23
- };
24
-
25
- function updateMigrateMethod(projectPath: string, migrations: Migration[]): void {
26
- let filePath = `${projectPath}/sources/codegen/core/schema.move`;
27
- const fileContent = fs.readFileSync(filePath, 'utf-8');
28
- const migrateMethodRegex = new RegExp(
29
- `public fun migrate\\(_schema: &mut Schema, _ctx: &mut TxContext\\) {[^}]*}`
30
- );
31
- const newMigrateMethod = `
32
- public fun migrate(_schema: &mut Schema, _ctx: &mut TxContext) {
33
- ${migrations
34
- .map((migration) => {
35
- let storage_type = '';
36
- if (migration.fields.includes('StorageValue')) {
37
- storage_type = `storage_value::new(b"${migration.schemaName}", _ctx)`;
38
- } else if (migration.fields.includes('StorageMap')) {
39
- storage_type = `storage_map::new(b"${migration.schemaName}", _ctx)`;
40
- } else if (migration.fields.includes('StorageDoubleMap')) {
41
- storage_type = `storage_double_map::new(b"${migration.schemaName}", _ctx)`;
42
- }
43
- return `storage::add_field<${migration.fields}>(&mut _schema.id, b"${migration.schemaName}", ${storage_type});`;
44
- })
45
- .join('')}
46
- }
47
- `;
48
-
49
- const updatedContent = fileContent.replace(migrateMethodRegex, newMigrateMethod);
50
- fs.writeFileSync(filePath, updatedContent, 'utf-8');
51
- }
52
-
53
- function replaceEnvField(
54
- filePath: string,
55
- networkType: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
56
- field: 'original-published-id' | 'latest-published-id' | 'published-version',
57
- newValue: string
58
- ): string {
59
- const envFilePath = path.resolve(filePath);
60
- const envContent = fs.readFileSync(envFilePath, 'utf-8');
61
- const envLines = envContent.split('\n');
62
-
63
- const networkSectionIndex = envLines.findIndex((line) => line.trim() === `[env.${networkType}]`);
64
- if (networkSectionIndex === -1) {
65
- console.log(`Network type [env.${networkType}] not found in the file.`);
66
- return '';
67
- }
68
-
69
- let fieldIndex = -1;
70
- let previousValue: string = '';
71
- for (let i = networkSectionIndex + 1; i < envLines.length; i++) {
72
- const line = envLines[i].trim();
73
- if (line.startsWith('[')) break; // End of the current network section
74
-
75
- if (line.startsWith(field)) {
76
- fieldIndex = i;
77
- previousValue = line.split('=')[1].trim().replace(/"/g, '');
78
- break;
79
- }
80
- }
81
-
82
- if (fieldIndex !== -1) {
83
- envLines[fieldIndex] = `${field} = "${newValue}"`;
84
- const newEnvContent = envLines.join('\n');
85
- fs.writeFileSync(envFilePath, newEnvContent, 'utf-8');
86
- } else {
87
- console.log(`${field} not found for [env.${networkType}].`);
88
- }
89
-
90
- return previousValue;
91
- }
92
- export async function upgradeHandler(
93
- config: DubheConfig,
94
- name: string,
95
- network: 'mainnet' | 'testnet' | 'devnet' | 'localnet'
96
- ) {
97
- await switchEnv(network);
98
-
99
- const path = process.cwd();
100
- const projectPath = `${path}/src/${name}`;
101
-
102
- const dubhe = initializeDubhe({
103
- network
104
- });
105
-
106
- let oldVersion = Number(await getVersion(projectPath, network));
107
- let oldPackageId = await getOldPackageId(projectPath, network);
108
- let upgradeCap = await getUpgradeCap(projectPath, network);
109
- let schemaId = await getSchemaId(projectPath, network);
110
-
111
- const original_published_id = replaceEnvField(
112
- `${projectPath}/Move.lock`,
113
- network,
114
- 'original-published-id',
115
- '0x0000000000000000000000000000000000000000000000000000000000000000'
116
- );
117
-
118
- let pendingMigration: Migration[] = [];
119
- let schemas = await getOnchainSchemas(projectPath, network);
120
- Object.entries(config.schemas).forEach(([key, value]) => {
121
- if (!schemas.hasOwnProperty(key)) {
122
- pendingMigration.push({ schemaName: key, fields: value });
123
- }
124
- });
125
- updateMigrateMethod(projectPath, pendingMigration);
126
-
127
- try {
128
- let modules: any, dependencies: any, digest: any;
129
- try {
130
- const {
131
- modules: extractedModules,
132
- dependencies: extractedDependencies,
133
- digest: extractedDigest
134
- } = JSON.parse(
135
- execSync(`sui move build --dump-bytecode-as-base64 --path ${path}/src/${name}`, {
136
- encoding: 'utf-8'
137
- })
138
- );
139
-
140
- modules = extractedModules;
141
- dependencies = extractedDependencies;
142
- digest = extractedDigest;
143
- } catch (error: any) {
144
- throw new UpgradeError(error.stdout);
145
- }
146
-
147
- console.log('\nšŸš€ Starting Upgrade Process...');
148
- console.log('šŸ“‹ OldPackageId:', oldPackageId);
149
- console.log('šŸ“‹ UpgradeCap Object Id:', upgradeCap);
150
- console.log('šŸ“‹ OldVersion:', oldVersion);
151
-
152
- const tx = new Transaction();
153
- const ticket = tx.moveCall({
154
- target: '0x2::package::authorize_upgrade',
155
- arguments: [
156
- tx.object(upgradeCap),
157
- tx.pure.u8(UpgradePolicy.COMPATIBLE),
158
- tx.pure.vector('u8', digest)
159
- ]
160
- });
161
-
162
- const receipt = tx.upgrade({
163
- modules,
164
- dependencies,
165
- package: oldPackageId,
166
- ticket
167
- });
168
-
169
- tx.moveCall({
170
- target: '0x2::package::commit_upgrade',
171
- arguments: [tx.object(upgradeCap), receipt]
172
- });
173
-
174
- const result = await dubhe.signAndSendTxn({
175
- tx,
176
- onSuccess: (result) => {
177
- console.log(chalk.green(`Upgrade Transaction Digest: ${result.digest}`));
178
- },
179
- onError: (error) => {
180
- console.log(chalk.red('Upgrade Transaction failed!'));
181
- console.error(error);
182
- }
183
- });
184
-
185
- let newPackageId = '';
186
- result.objectChanges!.map((object) => {
187
- if (object.type === 'published') {
188
- console.log(chalk.blue(`${name} new PackageId: ${object.packageId}`));
189
- console.log(chalk.blue(`${name} new Version: ${oldVersion + 1}`));
190
- newPackageId = object.packageId;
191
- }
192
- });
193
-
194
- replaceEnvField(
195
- `${projectPath}/Move.lock`,
196
- network,
197
- 'original-published-id',
198
- original_published_id
199
- );
200
- replaceEnvField(`${projectPath}/Move.lock`, network, 'latest-published-id', newPackageId);
201
- replaceEnvField(`${projectPath}/Move.lock`, network, 'published-version', oldVersion + 1 + '');
202
-
203
- saveContractData(
204
- name,
205
- network,
206
- newPackageId,
207
- schemaId,
208
- upgradeCap,
209
- oldVersion + 1,
210
- config.schemas
211
- );
212
-
213
- console.log(`\nšŸš€ Starting Migration Process...`);
214
- pendingMigration.forEach((migration) => {
215
- console.log('šŸ“‹ Added Fields:', JSON.stringify(migration, null, 2));
216
- });
217
- await new Promise((resolve) => setTimeout(resolve, 5000));
218
-
219
- const migrateTx = new Transaction();
220
- const newVersion = oldVersion + 1;
221
- let args = [];
222
- if (name !== 'dubhe') {
223
- let dubheSchemaId = await getDubheSchemaId(network);
224
- args.push(migrateTx.object(dubheSchemaId));
225
- }
226
- args.push(migrateTx.object(schemaId));
227
- args.push(migrateTx.pure.address(newPackageId));
228
- args.push(migrateTx.pure.u32(newVersion));
229
- migrateTx.moveCall({
230
- target: `${newPackageId}::${name}_migrate::migrate_to_v${newVersion}`,
231
- arguments: args
232
- });
233
-
234
- await dubhe.signAndSendTxn({
235
- tx: migrateTx,
236
- onSuccess: (result) => {
237
- console.log(chalk.green(`Migration Transaction Digest: ${result.digest}`));
238
- },
239
- onError: (error) => {
240
- console.log(
241
- chalk.red('Migration Transaction failed!, Please execute the migration manually.')
242
- );
243
- console.error(error);
244
- }
245
- });
246
- } catch (error: any) {
247
- console.log(chalk.red('upgrade handler execution failed!'));
248
- console.error(error.message);
249
- }
250
- }
1
+ // import { Transaction, UpgradePolicy } from '@0xobelisk/sui-client';
2
+ // import { execSync } from 'child_process';
3
+ // import chalk from 'chalk';
4
+ // import { UpgradeError } from './errors';
5
+ // import {
6
+ // getOldPackageId,
7
+ // getVersion,
8
+ // getUpgradeCap,
9
+ // saveContractData,
10
+ // getOnchainSchemas,
11
+ // switchEnv,
12
+ // getSchemaId,
13
+ // getDubheSchemaId,
14
+ // initializeDubhe
15
+ // } from './utils';
16
+ // import * as fs from 'fs';
17
+ // import * as path from 'path';
18
+ // import { DubheConfig } from '@0xobelisk/sui-common';
19
+
20
+ // type Migration = {
21
+ // schemaName: string;
22
+ // fields: string;
23
+ // };
24
+
25
+ // function updateMigrateMethod(projectPath: string, migrations: Migration[]): void {
26
+ // let filePath = `${projectPath}/sources/codegen/core/schema.move`;
27
+ // const fileContent = fs.readFileSync(filePath, 'utf-8');
28
+ // const migrateMethodRegex = new RegExp(
29
+ // `public fun migrate\\(_schema: &mut Schema, _ctx: &mut TxContext\\) {[^}]*}`
30
+ // );
31
+ // const newMigrateMethod = `
32
+ // public fun migrate(_schema: &mut Schema, _ctx: &mut TxContext) {
33
+ // ${migrations
34
+ // .map((migration) => {
35
+ // let storage_type = '';
36
+ // if (migration.fields.includes('StorageValue')) {
37
+ // storage_type = `storage_value::new(b"${migration.schemaName}", _ctx)`;
38
+ // } else if (migration.fields.includes('StorageMap')) {
39
+ // storage_type = `storage_map::new(b"${migration.schemaName}", _ctx)`;
40
+ // } else if (migration.fields.includes('StorageDoubleMap')) {
41
+ // storage_type = `storage_double_map::new(b"${migration.schemaName}", _ctx)`;
42
+ // }
43
+ // return `storage::add_field<${migration.fields}>(&mut _schema.id, b"${migration.schemaName}", ${storage_type});`;
44
+ // })
45
+ // .join('')}
46
+ // }
47
+ // `;
48
+
49
+ // const updatedContent = fileContent.replace(migrateMethodRegex, newMigrateMethod);
50
+ // fs.writeFileSync(filePath, updatedContent, 'utf-8');
51
+ // }
52
+
53
+ // function replaceEnvField(
54
+ // filePath: string,
55
+ // networkType: 'mainnet' | 'testnet' | 'devnet' | 'localnet',
56
+ // field: 'original-published-id' | 'latest-published-id' | 'published-version',
57
+ // newValue: string
58
+ // ): string {
59
+ // const envFilePath = path.resolve(filePath);
60
+ // const envContent = fs.readFileSync(envFilePath, 'utf-8');
61
+ // const envLines = envContent.split('\n');
62
+
63
+ // const networkSectionIndex = envLines.findIndex((line) => line.trim() === `[env.${networkType}]`);
64
+ // if (networkSectionIndex === -1) {
65
+ // console.log(`Network type [env.${networkType}] not found in the file.`);
66
+ // return '';
67
+ // }
68
+
69
+ // let fieldIndex = -1;
70
+ // let previousValue: string = '';
71
+ // for (let i = networkSectionIndex + 1; i < envLines.length; i++) {
72
+ // const line = envLines[i].trim();
73
+ // if (line.startsWith('[')) break; // End of the current network section
74
+
75
+ // if (line.startsWith(field)) {
76
+ // fieldIndex = i;
77
+ // previousValue = line.split('=')[1].trim().replace(/"/g, '');
78
+ // break;
79
+ // }
80
+ // }
81
+
82
+ // if (fieldIndex !== -1) {
83
+ // envLines[fieldIndex] = `${field} = "${newValue}"`;
84
+ // const newEnvContent = envLines.join('\n');
85
+ // fs.writeFileSync(envFilePath, newEnvContent, 'utf-8');
86
+ // } else {
87
+ // console.log(`${field} not found for [env.${networkType}].`);
88
+ // }
89
+
90
+ // return previousValue;
91
+ // }
92
+ // export async function upgradeHandler(
93
+ // config: DubheConfig,
94
+ // name: string,
95
+ // network: 'mainnet' | 'testnet' | 'devnet' | 'localnet'
96
+ // ) {
97
+ // await switchEnv(network);
98
+
99
+ // const path = process.cwd();
100
+ // const projectPath = `${path}/src/${name}`;
101
+
102
+ // const dubhe = initializeDubhe({
103
+ // network
104
+ // });
105
+
106
+ // let oldVersion = Number(await getVersion(projectPath, network));
107
+ // let oldPackageId = await getOldPackageId(projectPath, network);
108
+ // let upgradeCap = await getUpgradeCap(projectPath, network);
109
+ // let schemaId = await getSchemaId(projectPath, network);
110
+
111
+ // const original_published_id = replaceEnvField(
112
+ // `${projectPath}/Move.lock`,
113
+ // network,
114
+ // 'original-published-id',
115
+ // '0x0000000000000000000000000000000000000000000000000000000000000000'
116
+ // );
117
+
118
+ // let pendingMigration: Migration[] = [];
119
+ // let schemas = await getOnchainSchemas(projectPath, network);
120
+ // Object.entries(config.schemas).forEach(([key, value]) => {
121
+ // if (!schemas.hasOwnProperty(key)) {
122
+ // pendingMigration.push({ schemaName: key, fields: value });
123
+ // }
124
+ // });
125
+ // updateMigrateMethod(projectPath, pendingMigration);
126
+
127
+ // try {
128
+ // let modules: any, dependencies: any, digest: any;
129
+ // try {
130
+ // const {
131
+ // modules: extractedModules,
132
+ // dependencies: extractedDependencies,
133
+ // digest: extractedDigest
134
+ // } = JSON.parse(
135
+ // execSync(`sui move build --dump-bytecode-as-base64 --path ${path}/src/${name}`, {
136
+ // encoding: 'utf-8'
137
+ // })
138
+ // );
139
+
140
+ // modules = extractedModules;
141
+ // dependencies = extractedDependencies;
142
+ // digest = extractedDigest;
143
+ // } catch (error: any) {
144
+ // throw new UpgradeError(error.stdout);
145
+ // }
146
+
147
+ // console.log('\nšŸš€ Starting Upgrade Process...');
148
+ // console.log('šŸ“‹ OldPackageId:', oldPackageId);
149
+ // console.log('šŸ“‹ UpgradeCap Object Id:', upgradeCap);
150
+ // console.log('šŸ“‹ OldVersion:', oldVersion);
151
+
152
+ // const tx = new Transaction();
153
+ // const ticket = tx.moveCall({
154
+ // target: '0x2::package::authorize_upgrade',
155
+ // arguments: [
156
+ // tx.object(upgradeCap),
157
+ // tx.pure.u8(UpgradePolicy.COMPATIBLE),
158
+ // tx.pure.vector('u8', digest)
159
+ // ]
160
+ // });
161
+
162
+ // const receipt = tx.upgrade({
163
+ // modules,
164
+ // dependencies,
165
+ // package: oldPackageId,
166
+ // ticket
167
+ // });
168
+
169
+ // tx.moveCall({
170
+ // target: '0x2::package::commit_upgrade',
171
+ // arguments: [tx.object(upgradeCap), receipt]
172
+ // });
173
+
174
+ // const result = await dubhe.signAndSendTxn({
175
+ // tx,
176
+ // onSuccess: (result) => {
177
+ // console.log(chalk.green(`Upgrade Transaction Digest: ${result.digest}`));
178
+ // },
179
+ // onError: (error) => {
180
+ // console.log(chalk.red('Upgrade Transaction failed!'));
181
+ // console.error(error);
182
+ // }
183
+ // });
184
+
185
+ // let newPackageId = '';
186
+ // result.objectChanges!.map((object) => {
187
+ // if (object.type === 'published') {
188
+ // console.log(chalk.blue(`${name} new PackageId: ${object.packageId}`));
189
+ // console.log(chalk.blue(`${name} new Version: ${oldVersion + 1}`));
190
+ // newPackageId = object.packageId;
191
+ // }
192
+ // });
193
+
194
+ // replaceEnvField(
195
+ // `${projectPath}/Move.lock`,
196
+ // network,
197
+ // 'original-published-id',
198
+ // original_published_id
199
+ // );
200
+ // replaceEnvField(`${projectPath}/Move.lock`, network, 'latest-published-id', newPackageId);
201
+ // replaceEnvField(`${projectPath}/Move.lock`, network, 'published-version', oldVersion + 1 + '');
202
+
203
+ // saveContractData(
204
+ // name,
205
+ // network,
206
+ // newPackageId,
207
+ // schemaId,
208
+ // upgradeCap,
209
+ // oldVersion + 1,
210
+ // config.schemas
211
+ // );
212
+
213
+ // console.log(`\nšŸš€ Starting Migration Process...`);
214
+ // pendingMigration.forEach((migration) => {
215
+ // console.log('šŸ“‹ Added Fields:', JSON.stringify(migration, null, 2));
216
+ // });
217
+ // await new Promise((resolve) => setTimeout(resolve, 5000));
218
+
219
+ // const migrateTx = new Transaction();
220
+ // const newVersion = oldVersion + 1;
221
+ // let args = [];
222
+ // if (name !== 'dubhe') {
223
+ // let dubheSchemaId = await getDubheSchemaId(network);
224
+ // args.push(migrateTx.object(dubheSchemaId));
225
+ // }
226
+ // args.push(migrateTx.object(schemaId));
227
+ // args.push(migrateTx.pure.address(newPackageId));
228
+ // args.push(migrateTx.pure.u32(newVersion));
229
+ // migrateTx.moveCall({
230
+ // target: `${newPackageId}::${name}_migrate::migrate_to_v${newVersion}`,
231
+ // arguments: args
232
+ // });
233
+
234
+ // await dubhe.signAndSendTxn({
235
+ // tx: migrateTx,
236
+ // onSuccess: (result) => {
237
+ // console.log(chalk.green(`Migration Transaction Digest: ${result.digest}`));
238
+ // },
239
+ // onError: (error) => {
240
+ // console.log(
241
+ // chalk.red('Migration Transaction failed!, Please execute the migration manually.')
242
+ // );
243
+ // console.error(error);
244
+ // }
245
+ // });
246
+ // } catch (error: any) {
247
+ // console.log(chalk.red('upgrade handler execution failed!'));
248
+ // console.error(error.message);
249
+ // }
250
+ // }