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

Support extracting token deposit info from txs #481

Merged
merged 4 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions packages/web3/src/codec/unlock-script-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,5 @@ export const unlockScriptCodec = new EnumCodec<UnlockScript>('unlock script', {
P2SH: p2shCodec,
SameAsPrevious: sameAsPreviousCodec
})

export const encodedSameAsPrevious = unlockScriptCodec.encode({ kind: 'SameAsPrevious', value: 'SameAsPrevious' })
113 changes: 81 additions & 32 deletions packages/web3/src/exchange/exchange.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ import {
getALPHDepositInfo,
validateExchangeAddress,
isALPHTransferTx,
isTokenTransferTx,
getTokenDepositInfo
getDepositInfo,
isTransferTx
} from './exchange'
import { NodeProvider } from '../api'
import { binToHex } from '../utils'

describe('exchange', function () {
it('should get address from unlock script', () => {
Expand Down Expand Up @@ -139,7 +138,6 @@ describe('exchange', function () {

it('should validate deposit ALPH transaction', () => {
expect(isALPHTransferTx(txTemplate)).toEqual(true)
expect(isTokenTransferTx(txTemplate)).toEqual(false)
expect(getSenderAddress(txTemplate)).toEqual(fromAddress)
expect(getALPHDepositInfo(txTemplate)).toEqual([{ targetAddress: exchangeAddress, depositAmount: 10n }])

Expand Down Expand Up @@ -207,7 +205,7 @@ describe('exchange', function () {
])
})

it('should validate deposit token transaction', () => {
it('should validate deposit transaction', () => {
const tokenId0 = '25469eb0d0d0a55deea832924547b7b166c70a3554fe321e81886d3c18f19d64'
const tokenOutputTemplate = { ...outputTemplate, tokens: [{ id: tokenId0, amount: '10' }] }
const unsignedTokenTxTemplate = {
Expand All @@ -216,14 +214,15 @@ describe('exchange', function () {
}
const tokenTxTemplate = { ...txTemplate, unsigned: unsignedTokenTxTemplate }
expect(isALPHTransferTx(tokenTxTemplate)).toEqual(false)
expect(isTokenTransferTx(tokenTxTemplate)).toEqual(true)
expect(isTransferTx(tokenTxTemplate)).toEqual(true)
expect(isTransferTx(txTemplate)).toEqual(true)
expect(getSenderAddress(tokenTxTemplate)).toEqual(fromAddress)

const tx0: Transaction = { ...tokenTxTemplate, unsigned: { ...unsignedTokenTxTemplate, scriptOpt: '00112233' } }
const tx1: Transaction = { ...tokenTxTemplate, contractInputs: [outputRef] }
const tx2: Transaction = { ...tokenTxTemplate, generatedOutputs: [{ ...outputTemplate, type: 'AssetOutput' }] }
const tx3: Transaction = { ...tokenTxTemplate, unsigned: { ...unsignedTokenTxTemplate, inputs: [] } }
;[txTemplate, tx0, tx1, tx2, tx3].forEach((tx) => expect(isTokenTransferTx(tx)).toEqual(false))
;[tx0, tx1, tx2, tx3].forEach((tx) => expect(isTransferTx(tx)).toEqual(false))

const multipleTargetAddressOutputTx: Transaction = {
...tokenTxTemplate,
Expand All @@ -232,13 +231,16 @@ describe('exchange', function () {
fixedOutputs: [...unsignedTokenTxTemplate.fixedOutputs, { ...tokenOutputTemplate, address: exchangeAddress }]
}
}
expect(getTokenDepositInfo(multipleTargetAddressOutputTx)).toEqual([
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
}
])
expect(getDepositInfo(multipleTargetAddressOutputTx)).toEqual({
alph: [{ targetAddress: exchangeAddress, depositAmount: 20n }],
tokens: [
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
}
]
})

const sweepTx: Transaction = {
...tokenTxTemplate,
Expand All @@ -247,13 +249,16 @@ describe('exchange', function () {
fixedOutputs: [unsignedTokenTxTemplate.fixedOutputs[2], { ...tokenOutputTemplate, address: exchangeAddress }]
}
}
expect(getTokenDepositInfo(sweepTx)).toEqual([
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
}
])
expect(getDepositInfo(sweepTx)).toEqual({
alph: [{ targetAddress: exchangeAddress, depositAmount: 20n }],
tokens: [
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
}
]
})

const tokenId1 = '3de370f893cb1383c828c0eb22c89aceb13fa56ddced1848db27ce7fa419c80c'
const multipleTokenTx: Transaction = {
Expand All @@ -268,17 +273,61 @@ describe('exchange', function () {
]
}
}
expect(getTokenDepositInfo(multipleTokenTx)).toEqual([
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
},
{
tokenId: tokenId1,
targetAddress: exchangeAddress,
depositAmount: 20n
expect(getDepositInfo(multipleTokenTx)).toEqual({
alph: [{ targetAddress: exchangeAddress, depositAmount: 40n }],
tokens: [
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
},
{
tokenId: tokenId1,
targetAddress: exchangeAddress,
depositAmount: 20n
}
]
})

const newAddress = '1GKWggDapVjTdU2vyna3YjVgdpnwHkKzx8FHA9gU7uoeY'
const depositAlphAndTokenTx: Transaction = {
...tokenTxTemplate,
unsigned: {
...unsignedTokenTxTemplate,
fixedOutputs: [
...unsignedTokenTxTemplate.fixedOutputs,
{ ...outputTemplate, address: exchangeAddress },
{ ...outputTemplate, address: newAddress },
{ ...tokenOutputTemplate, tokens: [{ id: tokenId1, amount: '10' }], address: exchangeAddress },
{ ...tokenOutputTemplate, tokens: [{ id: tokenId0, amount: '10' }], address: exchangeAddress },
{ ...tokenOutputTemplate, tokens: [{ id: tokenId1, amount: '10' }], address: exchangeAddress }
]
}
])
}

expect(getDepositInfo(depositAlphAndTokenTx)).toEqual({
alph: [
{
targetAddress: exchangeAddress,
depositAmount: 50n
},
{
targetAddress: newAddress,
depositAmount: 10n
}
],
tokens: [
{
tokenId: tokenId0,
targetAddress: exchangeAddress,
depositAmount: 20n
},
{
tokenId: tokenId1,
targetAddress: exchangeAddress,
depositAmount: 20n
}
]
})
})
})
64 changes: 36 additions & 28 deletions packages/web3/src/exchange/exchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { AddressType, addressFromPublicKey, addressFromScript } from '../address
import { base58ToBytes, binToHex, HexString, hexToBinUnsafe, isHexString } from '../utils'
import { Transaction } from '../api/api-alephium'
import { Address } from '../signer'
import { P2SH, unlockScriptCodec } from '../codec/unlock-script-codec'
import { encodedSameAsPrevious, P2SH, unlockScriptCodec } from '../codec/unlock-script-codec'
import { scriptCodec } from '../codec/script-codec'
import { TraceableError } from '../error'

Expand All @@ -40,7 +40,12 @@ export function isALPHTransferTx(tx: Transaction): boolean {
return isTransferTx(tx) && checkALPHOutput(tx)
}

export function getALPHDepositInfo(tx: Transaction): { targetAddress: Address; depositAmount: bigint }[] {
export interface BaseDepositInfo {
targetAddress: Address
depositAmount: bigint
}

export function getALPHDepositInfo(tx: Transaction): BaseDepositInfo[] {
if (!isALPHTransferTx(tx)) return []

const inputAddresses = getInputAddresses(tx)
Expand All @@ -62,7 +67,7 @@ function getInputAddresses(tx: Transaction): Address[] {
const inputAddresses: Address[] = []
for (const input of tx.unsigned.inputs) {
try {
if (input.unlockScript === '03') continue // SameAsPrevious
if (input.unlockScript === binToHex(encodedSameAsPrevious)) continue
const address = getAddressFromUnlockScript(input.unlockScript)
if (!inputAddresses.includes(address)) {
inputAddresses.push(address)
Expand All @@ -74,36 +79,44 @@ function getInputAddresses(tx: Transaction): Address[] {
return inputAddresses
}

export function isTokenTransferTx(tx: Transaction): boolean {
return isTransferTx(tx) && checkTokenOutput(tx)
export interface TokenDepositInfo extends BaseDepositInfo {
tokenId: HexString
}

export function getTokenDepositInfo(tx: Transaction): {
tokenId: HexString
targetAddress: Address
depositAmount: bigint
}[] {
if (!isTokenTransferTx(tx)) return []
export interface DepositInfo {
alph: BaseDepositInfo[]
tokens: TokenDepositInfo[]
}

export function getDepositInfo(tx: Transaction): DepositInfo {
if (!isTransferTx) return { alph: [], tokens: [] }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be isTransferTx(tx)


const inputAddresses = getInputAddresses(tx)
const result = new Map<HexString, Map<Address, bigint>>()
const alphDepositInfos = new Map<Address, bigint>()
const tokenDepositInfos = new Map<HexString, Map<Address, bigint>>()
tx.unsigned.fixedOutputs.forEach((o) => {
if (!inputAddresses.includes(o.address) && o.tokens.length > 0) {
if (!inputAddresses.includes(o.address)) {
const alphAmount = alphDepositInfos.get(o.address) ?? 0n
alphDepositInfos.set(o.address, alphAmount + BigInt(o.attoAlphAmount))

o.tokens.forEach((token) => {
const depositPerToken = result.get(token.id) ?? new Map<Address, bigint>()
const depositPerToken = tokenDepositInfos.get(token.id) ?? new Map<Address, bigint>()
const currentAmount = depositPerToken.get(o.address) ?? 0n
depositPerToken.set(o.address, currentAmount + BigInt(token.amount))
result.set(token.id, depositPerToken)
tokenDepositInfos.set(token.id, depositPerToken)
})
}
})
return Array.from(result.entries()).flatMap(([tokenId, depositPerToken]) => {
return Array.from(depositPerToken.entries()).map(([targetAddress, depositAmount]) => ({
tokenId,
targetAddress,
depositAmount
}))
})
return {
alph: Array.from(alphDepositInfos.entries()).map(([key, value]) => ({ targetAddress: key, depositAmount: value })),
tokens: Array.from(tokenDepositInfos.entries()).flatMap(([tokenId, depositPerToken]) => {
return Array.from(depositPerToken.entries()).map(([targetAddress, depositAmount]) => ({
tokenId,
targetAddress,
depositAmount
}))
})
}
}

// we assume that the tx is a simple transfer tx, i.e. isALPHTransferTx(tx) || isTokenTransferTx(tx)
Expand Down Expand Up @@ -154,12 +167,7 @@ function checkALPHOutput(tx: Transaction): boolean {
return outputs.every((o) => o.tokens.length === 0)
}

function checkTokenOutput(tx: Transaction): boolean {
const outputs = tx.unsigned.fixedOutputs
return outputs.some((o) => o.tokens.length > 0)
}

function isTransferTx(tx: Transaction): boolean {
export function isTransferTx(tx: Transaction): boolean {
if (
tx.contractInputs.length !== 0 ||
tx.generatedOutputs.length !== 0 ||
Expand Down
6 changes: 4 additions & 2 deletions packages/web3/src/exchange/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export {
getSenderAddress,
isALPHTransferTx,
getALPHDepositInfo,
isTokenTransferTx,
getTokenDepositInfo
BaseDepositInfo,
TokenDepositInfo,
DepositInfo,
getDepositInfo
} from './exchange'
Loading