Skip to content

Commit

Permalink
CR: update
Browse files Browse the repository at this point in the history
  • Loading branch information
banklesss committed Oct 14, 2024
1 parent 62319a9 commit 713e411
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ describe('cip30ExtensionMaker', () => {
})

it('should support getBalance', async () => {
console.log('test-1')
const cip30 = cip30ExtensionMaker(mocks.wallet, mocks.walletMeta)
console.log('test2', cip30)
const result = await cip30.getBalance()
console.log('test3')
expect(result).toBeDefined()
console.log('test4')
expect(await (await result.coin()).toStr()).toBe('2282543724')
})

Expand Down
153 changes: 63 additions & 90 deletions apps/wallet-mobile/src/yoroi-wallets/cardano/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,27 @@ import {BaseAsset, RawUtxo} from '../types/other'
import {DefaultAsset} from '../types/tokens'
import {YoroiEntry} from '../types/yoroi'
import {Amounts} from '../utils/utils'
import {CardanoMobile} from '../wallets'
import {toAssetNameHex, toPolicyId} from './api/utils'
import {withMinAmounts} from './getMinAmounts'
import {MultiToken} from './MultiToken'
import {CardanoTypes} from './types'
import {wrappedCsl} from './wrappedCsl'
import {wrappedCsl as getCSL, wrappedCsl} from './wrappedCsl'

export const deriveRewardAddressHex = async (
accountPubKeyHex: string,
chainId: number,
role: number,
index: number,
): Promise<string> => {
const {csl, release} = wrappedCsl()

try {
const accountPubKeyPtr = await csl.Bip32PublicKey.fromBytes(Buffer.from(accountPubKeyHex, 'hex'))
const stakingKey = await (await (await accountPubKeyPtr.derive(role)).derive(index)).toRawKey()
const credential = await csl.Credential.fromKeyhash(await stakingKey.hash())
const rewardAddr = await csl.RewardAddress.new(chainId, credential)
const rewardAddrAsAddr = await rewardAddr.toAddress()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = Buffer.from((await rewardAddrAsAddr.toBytes()) as any, 'hex').toString('hex')
return result
} finally {
release()
}
const accountPubKeyPtr = await CardanoMobile.Bip32PublicKey.fromBytes(Buffer.from(accountPubKeyHex, 'hex'))
const stakingKey = await (await (await accountPubKeyPtr.derive(role)).derive(index)).toRawKey()
const credential = await CardanoMobile.Credential.fromKeyhash(await stakingKey.hash())
const rewardAddr = await CardanoMobile.RewardAddress.new(chainId, credential)
const rewardAddrAsAddr = await rewardAddr.toAddress()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = Buffer.from((await rewardAddrAsAddr.toBytes()) as any, 'hex').toString('hex')
return result
}

export const deriveRewardAddressFromAddress = async (address: string, chainId: number): Promise<string> => {
Expand Down Expand Up @@ -65,46 +60,34 @@ export const identifierToCardanoAsset = async (
policyId: CardanoTypes.ScriptHash
name: CardanoTypes.AssetName
}> => {
const {csl, release} = wrappedCsl()

try {
const policyId = toPolicyId(tokenId)
const assetNameHex = toAssetNameHex(tokenId)
const policyId = toPolicyId(tokenId)
const assetNameHex = toAssetNameHex(tokenId)

return {
policyId: await csl.ScriptHash.fromBytes(Buffer.from(policyId, 'hex')),
name: await csl.AssetName.new(Buffer.from(assetNameHex, 'hex')),
}
} finally {
release()
return {
policyId: await CardanoMobile.ScriptHash.fromBytes(Buffer.from(policyId, 'hex')),
name: await CardanoMobile.AssetName.new(Buffer.from(assetNameHex, 'hex')),
}
}

export const cardanoValueFromRemoteFormat = async (utxo: RawUtxo) => {
const {csl, release} = wrappedCsl()

try {
const value = await csl.Value.new(await csl.BigNum.fromStr(utxo.amount))
if (utxo.assets.length === 0) return value
const assets = await csl.MultiAsset.new()

for (const remoteAsset of utxo.assets) {
const {policyId, name} = await identifierToCardanoAsset(remoteAsset.assetId)
let policyContent = await assets.get(policyId)
policyContent = policyContent?.hasValue() ? policyContent : await csl.Assets.new()
await policyContent.insert(name, await csl.BigNum.fromStr(remoteAsset.amount))
// recall: we always have to insert since WASM returns copies of objects
await assets.insert(policyId, policyContent)
}

if ((await assets.len()) > 0) {
await value.setMultiasset(assets)
}
const value = await CardanoMobile.Value.new(await CardanoMobile.BigNum.fromStr(utxo.amount))
if (utxo.assets.length === 0) return value
const assets = await CardanoMobile.MultiAsset.new()

for (const remoteAsset of utxo.assets) {
const {policyId, name} = await identifierToCardanoAsset(remoteAsset.assetId)
let policyContent = await assets.get(policyId)
policyContent = policyContent?.hasValue() ? policyContent : await CardanoMobile.Assets.new()
await policyContent.insert(name, await CardanoMobile.BigNum.fromStr(remoteAsset.amount))
// recall: we always have to insert since WASM returns copies of objects
await assets.insert(policyId, policyContent)
}

return value
} finally {
release()
if ((await assets.len()) > 0) {
await value.setMultiasset(assets)
}

return value
}
// matches RawUtxo and a tx input/output
type RemoteValue = {
Expand Down Expand Up @@ -188,52 +171,40 @@ export const isTokenInfo = (token: Balance.TokenInfo | DefaultAsset): token is B
}

export const generateCIP30UtxoCbor = async (utxo: RawUtxo) => {
const {csl, release} = wrappedCsl()

try {
const txHash = await csl.TransactionHash.fromBytes(Buffer.from(utxo.tx_hash, 'hex'))
if (!txHash) throw new Error('Invalid tx hash')
const txHash = await CardanoMobile.TransactionHash.fromBytes(Buffer.from(utxo.tx_hash, 'hex'))
if (!txHash) throw new Error('Invalid tx hash')

const index = utxo.tx_index
const input = await csl.TransactionInput.new(txHash, index)
const address = await csl.Address.fromBech32(utxo.receiver)
if (!address) throw new Error('Invalid address')
const index = utxo.tx_index
const input = await CardanoMobile.TransactionInput.new(txHash, index)
const address = await CardanoMobile.Address.fromBech32(utxo.receiver)
if (!address) throw new Error('Invalid address')

const amount = await csl.BigNum.fromStr(utxo.amount)
if (!amount) throw new Error('Invalid amount')
const amount = await CardanoMobile.BigNum.fromStr(utxo.amount)
if (!amount) throw new Error('Invalid amount')

const collateral = await csl.Value.new(amount)
const output = await csl.TransactionOutput.new(address, collateral)
const transactionUnspentOutput = await csl.TransactionUnspentOutput.new(input, output)
const collateral = await CardanoMobile.Value.new(amount)
const output = await CardanoMobile.TransactionOutput.new(address, collateral)
const transactionUnspentOutput = await CardanoMobile.TransactionUnspentOutput.new(input, output)

return transactionUnspentOutput.toHex()
} finally {
release()
}
return transactionUnspentOutput.toHex()
}

export const createRawTxSigningKey = async (rootKey: string, derivationPath: number[]) => {
const {csl, release} = wrappedCsl()

try {
if (derivationPath.length !== 5) throw new Error('Invalid derivation path')
const masterKey = await csl.Bip32PrivateKey.fromBytes(Buffer.from(rootKey, 'hex'))
const accountPrivateKey = await masterKey
.derive(derivationPath[0])
.then((key) => key.derive(derivationPath[1]))
.then((key) => key.derive(derivationPath[2]))
.then((key) => key.derive(derivationPath[3]))
.then((key) => key.derive(derivationPath[4]))

const rawKey = await accountPrivateKey.toRawKey()
const bech32 = await rawKey.toBech32()

const pkey = await csl.PrivateKey.fromBech32(bech32)
if (!pkey) throw new Error('Invalid private key')
return pkey
} finally {
release()
}
if (derivationPath.length !== 5) throw new Error('Invalid derivation path')
const masterKey = await CardanoMobile.Bip32PrivateKey.fromBytes(Buffer.from(rootKey, 'hex'))
const accountPrivateKey = await masterKey
.derive(derivationPath[0])
.then((key) => key.derive(derivationPath[1]))
.then((key) => key.derive(derivationPath[2]))
.then((key) => key.derive(derivationPath[3]))
.then((key) => key.derive(derivationPath[4]))

const rawKey = await accountPrivateKey.toRawKey()
const bech32 = await rawKey.toBech32()

const pkey = await CardanoMobile.PrivateKey.fromBech32(bech32)
if (!pkey) throw new Error('Invalid private key')
return pkey
}

export const copyFromCSL = async <T extends {toHex: () => Promise<string>}>(
Expand All @@ -259,8 +230,7 @@ export const getTransactionUnspentOutput = async ({
bytes: Uint8Array
index: number
}) => {
const {csl, release} = wrappedCsl()

const {csl, release} = getCSL()
try {
const tx = await csl.Transaction.fromBytes(bytes)
const body = await tx.body()
Expand All @@ -271,7 +241,10 @@ export const getTransactionUnspentOutput = async ({
const value = await originalOutput.amount()
const receiver = await originalOutput.address()
const output = await csl.TransactionOutput.new(receiver, value)
return copyFromCSL(csl.TransactionUnspentOutput, await csl.TransactionUnspentOutput.new(input, output))
return copyFromCSL(
CardanoMobile.TransactionUnspentOutput,
await CardanoMobile.TransactionUnspentOutput.new(input, output),
)
} finally {
release()
}
Expand Down

0 comments on commit 713e411

Please sign in to comment.