Skip to content

Commit

Permalink
feat(plugins): add Babel Fees plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
capt-nemo429 committed Dec 14, 2022
1 parent 0253b2a commit 3a2e23a
Show file tree
Hide file tree
Showing 20 changed files with 986 additions and 3 deletions.
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ export default {
testEnvironment: "node",
maxWorkers: 1, // this limit is being used to circumvent this issue https://github.com/facebook/jest/issues/11617
preset: "ts-jest",
roots: ["./packages"]
roots: ["./packages", "./plugins"]
};
1 change: 0 additions & 1 deletion packages/common/src/constants.ts

This file was deleted.

1 change: 0 additions & 1 deletion packages/common/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from "./utils";
export * from "./types";
export * from "./constants";
21 changes: 21 additions & 0 deletions plugins/babel-fees/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 capt-nemo429

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.
3 changes: 3 additions & 0 deletions plugins/babel-fees/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @fleet-sdk/babel-fees-plugin [![License](https://badgen.net/github/license/fleet-sdk/fleet/)](https://github.com/fleet-sdk/fleet/blob/master/LICENSE) [![npm](https://badgen.net/npm/v/@fleet-sdk/babel-fees-plugin)](https://www.npmjs.com/package/@fleet-sdk/babel-fees-plugin)

Babel Fees utilities and plugin for Fleet SDK.
20 changes: 20 additions & 0 deletions plugins/babel-fees/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default {
collectCoverageFrom: ["./src/**/*.ts", "!./src/**/I[A-Z]*.ts", "!./src/**/index.ts"],
coveragePathIgnorePatterns: ["/node_modules/", "./src/tests", "./src/types"],
coverageDirectory: "./coverage",
coverageProvider: "v8",
coverageReporters: ["text", "json"],
collectCoverage: false,
testEnvironment: "node",
coverageThreshold: {
global: {
statements: "100",
lines: "100",
branches: "100",
functions: "100"
}
},
maxWorkers: 1, // this limit is being used to circumvent this issue https://github.com/facebook/jest/issues/11617
preset: "ts-jest",
roots: ["./src"]
};
57 changes: 57 additions & 0 deletions plugins/babel-fees/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@fleet-sdk/babel-fees-plugin",
"version": "0.1.0-alpha.14",
"description": "Babel Fees plugin for Fleet SDK.",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"typings": "dist/esm/index.d.ts",
"sideEffects": false,
"repository": {
"type": "git",
"url": "https://github.com/fleet-sdk/fleet.git",
"directory": "plugins/babel-fees-plugin"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"keywords": [
"ergo",
"blockchain",
"babel fees"
],
"dependencies": {
"@fleet-sdk/core": "workspace:^",
"@fleet-sdk/common": "workspace:^"
},
"scripts": {
"build": "run-p build:*",
"build:cjs": "tsc -p tsconfig.json",
"build:esm": "tsc -p tsconfig.esm.json",
"fix": "run-s fix:*",
"fix:prettier": "prettier src/**/*.ts --write",
"fix:lint": "eslint src --ext .ts --fix",
"test": "run-s build test:*",
"test:lint": "eslint src --ext .ts",
"test:prettier": "prettier src/**/*.ts --list-different",
"test:unit": "jest",
"watch:build": "tsc -p tsconfig.json -w",
"watch:test": "jest --watch",
"cov:html": "jest --coverage --coverageReporters=html ; open-cli coverage/index.html",
"cov:json": "jest --coverage --coverageReporters=json",
"cov:check": "jest --coverage --coverageReporters=text"
},
"engines": {
"node": ">=10"
},
"files": [
"src",
"dist",
"!**/*.spec.*",
"!**/*.json",
"!tests",
"CHANGELOG.md",
"LICENSE",
"README.md"
]
}
6 changes: 6 additions & 0 deletions plugins/babel-fees/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const BABEL_FEE_CONTRACT_TEMPLATE_HASH =
"4e83fa68ef3ed9794bbab5d8799998a9e09fb10a0afe8d1bf928936dfd11c465";

export const BABEL_ERGOTREE_PREFIX = "100604000e20";
export const BABEL_ERGOTREE_SUFFIX =
"0400040005000500d803d601e30004d602e4c6a70408d603e4c6a7050595e67201d804d604b2a5e4720100d605b2db63087204730000d606db6308a7d60799c1a7c17204d1968302019683050193c27204c2a7938c720501730193e4c672040408720293e4c672040505720393e4c67204060ec5a796830201929c998c7205029591b1720673028cb272067303000273047203720792720773057202";
2 changes: 2 additions & 0 deletions plugins/babel-fees/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./plugins";
export * from "./utils";
102 changes: 102 additions & 0 deletions plugins/babel-fees/src/plugins.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { ensureBigInt, first } from "@fleet-sdk/common";
import { SByte, SColl, SConstant, SParse, TransactionBuilder } from "@fleet-sdk/core";
import { BabelSwapPlugin } from "./plugins";
import { babelBoxesMock } from "./tests/babelBoxesMock";
import { regularBoxesMock } from "./tests/regularBoxesMock";
import { getTokenPrice, isValidBabelBox, isValidBabelContract } from "./utils";

describe("Babel Swap Plugin", () => {
const height = 895586;
const changeAddress = "9hY16vzHmmfyVBwKeFGHvb2bMFsG94A1u7To1QWtUokACyFVENQ";

it("Should add babel input and output", () => {
const babelBox = first(babelBoxesMock);
const payingTokenAmount = 5n;

const tx = new TransactionBuilder(height)
.from(regularBoxesMock)
.extend(
BabelSwapPlugin(babelBox, {
tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04",
amount: payingTokenAmount
})
)
.payMinFee()
.sendChangeTo(changeAddress)
.build("EIP-12");

const input = tx.inputs.find((box) => isValidBabelBox(box));
if (!input || !input.extension[0]) {
fail();
}

const outputIndex = SParse<number>(input.extension[0]);
const output = tx.outputs[outputIndex];
expect(isValidBabelContract(output.ergoTree)).toBeTruthy();
expect(output.ergoTree).toBe(input.ergoTree);
expect(output.additionalRegisters.R4).toBe(input.additionalRegisters.R4);
expect(output.additionalRegisters.R5).toBe(input.additionalRegisters.R5);
expect(output.additionalRegisters.R6).toBe(SConstant(SColl(SByte, input.boxId)));

const swappedNanoErgs = getTokenPrice(input) * payingTokenAmount;
expect(ensureBigInt(input.value)).toBe(BigInt(output.value) + swappedNanoErgs);
expect(first(input.assets)).toEqual({
tokenId: first(output.assets).tokenId,
amount: (ensureBigInt(first(output.assets).amount) - payingTokenAmount).toString()
});
});

it("Should fail if invalid babel box is added", () => {
const nonBabelBox = regularBoxesMock[1];

expect(() => {
new TransactionBuilder(height)
.from(regularBoxesMock[0])
.extend(
BabelSwapPlugin(nonBabelBox, {
tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04",
amount: 1n
})
)
.payMinFee()
.sendChangeTo(changeAddress)
.build("EIP-12");
}).toThrow();
});

it("Should fail if valid babel box is added but incompatible tokenId", () => {
const babelBox = first(babelBoxesMock);

expect(() => {
new TransactionBuilder(height)
.from(regularBoxesMock)
.extend(
BabelSwapPlugin(babelBox, {
tokenId: "0cd8c9f416e5b1ca9f986a7f10a84191dfb85941619e49e53c0dc30ebf83324b",
amount: 10n
})
)
.payMinFee()
.sendChangeTo(changeAddress)
.build("EIP-12");
}).toThrow();
});

it("Should fail if the box does not have enough ERG to swap for the tokens", () => {
const babelBox = first(babelBoxesMock);

expect(() => {
new TransactionBuilder(height)
.from(regularBoxesMock)
.extend(
BabelSwapPlugin(babelBox, {
tokenId: "03faf2cb329f2e90d6d23b58d91bbb6c046aa143261cc21f52fbe2824bfcbf04",
amount: "10000000"
})
)
.payMinFee()
.sendChangeTo(changeAddress)
.build("EIP-12");
}).toThrow();
});
});
55 changes: 55 additions & 0 deletions plugins/babel-fees/src/plugins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { ensureBigInt } from "@fleet-sdk/common";
import {
Amount,
Box,
ErgoUnsignedInput,
FleetPlugin,
OutputBuilder,
SAFE_MIN_BOX_VALUE,
SByte,
SColl,
SConstant,
SInt,
TokenAmount
} from "@fleet-sdk/core";
import { getTokenPrice, isBabelContractForTokenId, isValidBabelBox } from "./utils";

export function BabelSwapPlugin(babelBox: Box<Amount>, token: TokenAmount<Amount>): FleetPlugin {
return ({ addInputs, addOutputs }) => {
if (!isValidBabelBox(babelBox)) {
throw new Error("Invalid Babel Box.");
}

if (!isBabelContractForTokenId(babelBox.ergoTree, token.tokenId)) {
throw new Error(
`The Babel Box '${babelBox.boxId}' is not compatible with Token ID '${token.tokenId}'.`
);
}

const input = new ErgoUnsignedInput(babelBox);
const changeAmount = input.value - ensureBigInt(token.amount) * getTokenPrice(babelBox);

if (changeAmount < SAFE_MIN_BOX_VALUE) {
throw new Error(
"The selected Babel Box does not have enough ERG to swap for the selected amount of tokens."
);
}

const outputsLength = addOutputs(
new OutputBuilder(changeAmount, input.ergoTree)
.addTokens(input.assets)
.addTokens(token)
.setAdditionalRegisters({
R4: input.additionalRegisters.R4,
R5: input.additionalRegisters.R5,
R6: SConstant(SColl(SByte, input.boxId))
})
);

addInputs(
input.setContextVars({
0: SConstant(SInt(outputsLength - 1))
})
);
};
}
Loading

0 comments on commit 3a2e23a

Please sign in to comment.