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

implement rpc calculate_dao_maximum_withdraw in sdk #578

Merged
merged 8 commits into from
Mar 2, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
31 changes: 30 additions & 1 deletion packages/ckb-sdk-core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference types="../types/global" />

import RPC from '@nervosnetwork/ckb-sdk-rpc'
import { ParameterRequiredException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import { ParameterRequiredException, HexStringWithout0xException } from '@nervosnetwork/ckb-sdk-utils/lib/exceptions'
import * as utils from '@nervosnetwork/ckb-sdk-utils'

import generateRawTransaction from './generateRawTransaction'
Expand Down Expand Up @@ -420,6 +420,35 @@ class CKB {
}
}

public calculateDaoMaximumWithdraw = async (
outPoint: CKBComponents.OutPoint,
withdrawBlockHash: string
): Promise<string> => {
const depositTx = await this.rpc.getTransaction(outPoint.txHash)
if (depositTx.txStatus.status !== 'committed') throw new Error('Transaction is not committed yet')
const depositCell = depositTx.transaction.outputs[+outPoint.index]
const depositBlockHash = depositTx.txStatus.blockHash
const depositHeader = await this.rpc.getHeader(depositBlockHash)
const depositAr = this.#extracDaoData(depositHeader.dao).ar
const withDrawHeader = await this.rpc.getHeader(withdrawBlockHash)
const withdrawAr = this.#extracDaoData(withDrawHeader.dao).ar
return utils.calculateMaximumWithdraw(depositCell, depositAr, withdrawAr);
}

#extracDaoData = (dao: CKBComponents.DAO) => {
if (!dao.startsWith('0x')) {
throw new HexStringWithout0xException(dao)
}
const value = dao.replace('0x', '');
const toBigEndian = utils.toBigEndian;
return {
c: toBigEndian(`0x${value.slice(0, 8)}`),
ar: toBigEndian(`0x${value.slice(16, 32)}`),
s: toBigEndian(`0x${value.slice(32, 48)}`),
u: toBigEndian(`0x${value.slice(48, 64)}`)
}
}

#secp256k1DepsShouldBeReady = () => {
if (!this.config.secp256k1Dep) {
throw new ParameterRequiredException('Secp256k1 dep')
Expand Down
16 changes: 15 additions & 1 deletion packages/ckb-sdk-utils/src/convertors/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assertToBeHexStringOrBigint } from '../validators'
import { assertToBeHexStringOrBigint, assertToBeHexString } from '../validators'
import { HexStringWithout0xException } from '../exceptions'

/**
Expand Down Expand Up @@ -61,6 +61,19 @@ export const hexToBytes = (rawhex: string | number | bigint) => {
return new Uint8Array(bytes)
}

/**
* Converts a hex string in little endian into big endian
*
* @memberof convertors
* @param {string} le16 The hex string to convert
* @returns {string} Returns a big endian
*/
export const toBigEndian = (leHex: string) => {
assertToBeHexString(leHex)
const bytes = hexToBytes(leHex);
return `0x${bytes.reduceRight((pre, cur) => pre + cur.toString(16), '')}`
}

export const bytesToHex = (bytes: Uint8Array): string =>
`0x${[...bytes].map(b => b.toString(16).padStart(2, '0')).join('')}`

Expand All @@ -70,4 +83,5 @@ export default {
toUint64Le,
hexToBytes,
bytesToHex,
toBigEndian
}
28 changes: 27 additions & 1 deletion packages/ckb-sdk-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { hexToBytes } from './convertors'
import { pubkeyToAddress, AddressOptions } from './address'
import { ParameterRequiredException } from './exceptions'
import crypto from './crypto'
import { serializeScript } from './serialization/script'
import { serializeOutput, serializeScript } from './serialization';
import { serializeRawTransaction, serializeTransaction, serializeWitnessArgs } from './serialization/transaction'
import { PERSONAL } from './const'

Expand Down Expand Up @@ -44,3 +44,29 @@ export const privateKeyToPublicKey = (privateKey: string) => {

export const privateKeyToAddress = (privateKey: string, options: AddressOptions) =>
pubkeyToAddress(privateKeyToPublicKey(privateKey), options)

export const calculateMaximumWithdraw = (
depositCell: CKBComponents.CellOutput,
depositAr: string,
withdrawAr: string
) => {
const depositCellSerialized = serializeOutput(depositCell).slice(2).length / 2;
console.log(depositCellSerialized);
yanguoyu marked this conversation as resolved.
Show resolved Hide resolved
const occupiedCapacity = JSBI.asUintN(
64,
JSBI.multiply(JSBI.BigInt(100000000), JSBI.BigInt(depositCellSerialized))
);
return JSBI.add(
JSBI.divide(
JSBI.multiply(
JSBI.subtract(
JSBI.asUintN(64, JSBI.BigInt(depositCell.capacity)),
occupiedCapacity
),
JSBI.asUintN(64, JSBI.BigInt(withdrawAr))
),
JSBI.asUintN(64, JSBI.BigInt(depositAr))
),
occupiedCapacity
).toString()
}