Skip to content

Commit

Permalink
feat: Add codemods and Migration recipe for Ethers migration from v5.…
Browse files Browse the repository at this point in the history
…x to v6.x (#1290)

* feat: Add codemods for Ethers migration from v5.x to v6.x

* Migration Recipe Added

* Updated readme of migration recipe
  • Loading branch information
Yugal41735 authored Sep 20, 2024
1 parent 91fedfc commit 1e4022d
Show file tree
Hide file tree
Showing 131 changed files with 2,590 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/.codemodrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"$schema": "https://codemod-utils.s3.us-west-1.amazonaws.com/configuration_schema.json",
"name": "ethers/Big-Numbers",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": [
"ethers.js"
]
}
}
2 changes: 2 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
9 changes: 9 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 yugal41735

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 changes: 27 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
This codemod migrates **BigNumber** in v5 to **BigInt** in v6 in **ethers.js** library.
It also changes the syntax for addition, and checking equality according to v6.

## Example

### Before

```ts
// Using BigNumber in v5
value = BigNumber.from('1000');
// Adding two values in v5
sum = value1.add(value2);
// Checking equality in v5
isEqual = value1.eq(value2);
```

### After

```ts
// Using BigInt in v6
value = BigInt('1000');
// Addition, keep in mind, both values must be a BigInt
sum = value1 + value2;
// Checking equality
isEqual = value1 == value2;
```

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Using BigNumber in v5
value = BigNumber.from('1000');
// Adding two values in v5
sum = value1.add(value2);
// Checking equality in v5
isEqual = value1.eq(value2);
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Using BigInt in v6
value = BigInt('1000');
// Addition, keep in mind, both values must be a BigInt
sum = value1 + value2;
// Checking Equality
isEqual = value1 == value2;
13 changes: 13 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/cdmd_dist/index.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*! @license
The MIT License (MIT)
Copyright (c) 2024 yugal41735
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"default",{enumerable:true,get:function(){return transform}});function transform(file,api){const j=api.jscodeshift;const root=j(file.source);let dirtyFlag=false;root.find(j.CallExpression,{callee:{object:{name:"BigNumber"},property:{name:"from"}}}).forEach(path=>{if(j.Literal.check(path.node.arguments[0])){path.replace(j.callExpression(j.identifier("BigInt"),[path.node.arguments[0]]));dirtyFlag=true}});root.find(j.CallExpression,{callee:{property:{name:"add"}}}).forEach(path=>{const{object}=path.node.callee;const args=path.node.arguments;if(args&&args.length===1){path.replace(j.binaryExpression("+",object,args[0]));dirtyFlag=true}});root.find(j.CallExpression,{callee:{property:{name:"eq"}}}).forEach(path=>{const{object}=path.node.callee;const args=path.node.arguments;if(args&&args.length===1){path.replace(j.binaryExpression("==",object,args[0]));dirtyFlag=true}});return dirtyFlag?root.toSource():undefined}
23 changes: 23 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "ethers-big-numbers",
"license": "MIT",
"devDependencies": {
"@types/node": "20.9.0",
"typescript": "^5.2.2",
"vitest": "^1.0.1",
"@codemod.com/codemod-utils": "*",
"jscodeshift": "^0.15.1",
"@types/jscodeshift": "^0.11.10"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch"
},
"files": [
"README.md",
".codemodrc.json",
"/dist/index.cjs"
],
"type": "module",
"author": "yugal41735"
}
48 changes: 48 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export default function transform(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
let dirtyFlag = false;

// Transform BigNumber.from('1000') to BigInt('1000')
root.find(j.CallExpression, {
callee: {
object: { name: 'BigNumber' },
property: { name: 'from' }
}
}).forEach(path => {
if (j.Literal.check(path.node.arguments[0])) {
path.replace(j.callExpression(j.identifier('BigInt'), [path.node.arguments[0]]));
dirtyFlag = true;
}
});

// Transform value1.add(value2) to value1 + value2
root.find(j.CallExpression, {
callee: {
property: { name: 'add' }
}
}).forEach(path => {
const { object } = path.node.callee;
const args = path.node.arguments;
if (args && args.length === 1) {
path.replace(j.binaryExpression('+', object, args[0]));
dirtyFlag = true;
}
});

// Transform value1.eq(value2) to value1 == value2
root.find(j.CallExpression, {
callee: {
property: { name: 'eq' }
}
}).forEach(path => {
const { object } = path.node.callee;
const args = path.node.arguments;
if (args && args.length === 1) {
path.replace(j.binaryExpression('==', object, args[0]));
dirtyFlag = true;
}
});

return dirtyFlag ? root.toSource() : undefined;
}
40 changes: 40 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/test/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, it } from 'vitest';
import jscodeshift, { type API } from 'jscodeshift';
import transform from '../src/index.js';
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

const buildApi = (parser: string | undefined): API => ({
j: parser ? jscodeshift.withParser(parser) : jscodeshift,
jscodeshift: parser ? jscodeshift.withParser(parser) : jscodeshift,
stats: () => {
console.error(
'The stats function was called, which is not supported on purpose',
);
},
report: () => {
console.error(
'The report function was called, which is not supported on purpose',
);
},
});

describe('ethereumjs/1/big-number-to-big-int-and-operator-transformations', () => {
it('test #1', async () => {
const INPUT = await readFile(join(__dirname, '..', '__testfixtures__/fixture1.input.ts'), 'utf-8');
const OUTPUT = await readFile(join(__dirname, '..', '__testfixtures__/fixture1.output.ts'), 'utf-8');

const actualOutput = transform({
path: 'index.js',
source: INPUT,
},
buildApi('tsx'), {}
);

assert.deepEqual(
actualOutput?.replace(/W/gm, ''),
OUTPUT.replace(/W/gm, ''),
);
});
});
38 changes: 38 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"compilerOptions": {
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"lib": [
"ESNext",
"DOM"
],
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"jsx": "react-jsx",
"useDefineForClassFields": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
"strict": true,
"strictNullChecks": true,
"incremental": true,
"noUncheckedIndexedAccess": true,
"noPropertyAccessFromIndexSignature": false,
"allowJs": true
},
"include": [
"./src/**/*.ts",
"./src/**/*.js",
"./test/**/*.ts",
"./test/**/*.js"
],
"exclude": ["node_modules", "./dist/**/*"],
"ts-node": {
"transpileOnly": true
}
}
7 changes: 7 additions & 0 deletions packages/codemods/ethers/v6/big-numbers/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { configDefaults, defineConfig } from 'vitest/config';

export default defineConfig({
test: {
include: [...configDefaults.include, '**/test/*.ts'],
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "https://codemod-utils.s3.us-west-1.amazonaws.com/configuration_schema.json",
"name": "Ethers/6/Contracts/Ambiguous-Methods",
"version": "1.0.0",
"engine": "jscodeshift",
"private": false,
"arguments": [],
"meta": {
"tags": [
"ethers.js",
"Migration"
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 yugal41735

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70 changes: 70 additions & 0 deletions packages/codemods/ethers/v6/contracts-ambiguous-methods/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
In v5, in the case of an ambiguous method, it was necessary to look up a method by its canonical normalized signature. In v6 the signature does not need to be normalized and the Typed API provides a cleaner way to access the desired method.

In v5, duplicate definitions also injected warnings into the console, since there was no way to detect them at run-time.

## Example

### Before

```ts
abi = [
"function foo(address bar)",
"function foo(uint160 bar)",
]
contract = new Contract(address, abi, provider)

// In v5 it was necessary to specify the fully-qualified normalized
// signature to access the desired method. For example:
contract["foo(address)"](addr)

// These would fail, since there signature is not normalized:
contract["foo(address )"](addr)
contract["foo(address addr)"](addr)

// This would fail, since the method is ambiguous:
contract.foo(addr)
```

### After

```ts
abi = [
"function foo(address bar)",
"function foo(uint160 bar)",
]
contract = new Contract(address, abi, provider)

// Any of these work fine:
contract["foo(address)"](addr)
contract["foo(address )"](addr)
contract["foo(address addr)"](addr)

// This still fails, since there is no way to know which
// method was intended
contract.foo(addr)

// However, the Typed API makes things a bit easier, since it
// allows providing typing information to the Contract:
contract.foo(Typed.address(addr))
```

Transformation done using this codemod

### Before

```ts
abi = ['function foo(address bar)', 'function foo(uint160 bar)'];
contract = new Contract(address, abi, provider);

contract.foo(addr);
```

### After

```ts
abi = ['function foo(address bar)', 'function foo(uint160 bar)'];
contract = new Contract(address, abi, provider);

contract.foo(Typed.address(addr));
```

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
abi = ['function foo(address bar)', 'function foo(uint160 bar)'];
contract = new Contract(address, abi, provider);

contract.foo(addr);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
abi = ['function foo(address bar)', 'function foo(uint160 bar)'];
contract = new Contract(address, abi, provider);

contract.foo(Typed.address(addr));
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*! @license
The MIT License (MIT)
Copyright (c) 2024 yugal41735
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"default",{enumerable:true,get:function(){return transform}});function transform(file,api){const j=api.jscodeshift;const root=j(file.source);let dirtyFlag=false;root.find(j.CallExpression).forEach(path=>{const{callee,arguments:args}=path.node;if(j.MemberExpression.check(callee)&&j.Identifier.check(callee.object)&&callee.object.name==="contract"&&j.Identifier.check(callee.property)&&callee.property.name==="foo"){if(args.length>0){path.node.arguments[0]=j.callExpression(j.memberExpression(j.identifier("Typed"),j.identifier("address")),[args[0]]);dirtyFlag=true}}});return dirtyFlag?root.toSource():undefined}
Loading

0 comments on commit 1e4022d

Please sign in to comment.