Created
March 9, 2024 15:56
-
-
Save ZigBalthazar/97c7f5412dab59a23b6863169b21ced1 to your computer and use it in GitHub Desktop.
implementatiton of UTXO in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type UTXO = { | |
id: string; | |
amount: number; | |
}; | |
type Wallet = { | |
address: string; | |
utxos: UTXO[]; | |
}; | |
let state: Map<string, Wallet> = new Map(); | |
state.set("Alice", { | |
address: "Alice", | |
utxos: [ | |
{ id: generateId(), amount: 100 }, | |
{ id: generateId(), amount: 20 }, | |
], | |
}); | |
state.set("Bob", { | |
address: "Bob", | |
utxos: [ | |
{ id: generateId(), amount: 17 }, | |
{ id: generateId(), amount: 80 }, | |
], | |
}); | |
function generateId(): string { | |
return Math.random().toString(36).substring(2, 10); | |
} | |
function getWallet(address: string): Wallet | undefined { | |
return state.get(address); | |
} | |
function addUTXO(wallet: Wallet, amount: number): void { | |
wallet.utxos.push({ id: generateId(), amount }); | |
} | |
function removeUTXO(wallet: Wallet, utxoId: string): void { | |
wallet.utxos = wallet.utxos.filter(utxo => utxo.id !== utxoId); | |
} | |
function transfer(sender: string, receiver: string, amount: number): void { | |
const senderWallet = getWallet(sender); | |
const receiverWallet = getWallet(receiver); | |
if (!senderWallet || !receiverWallet) { | |
throw new Error("Sender or receiver does not exist."); | |
} | |
const totalAmount = senderWallet.utxos.reduce((sum, utxo) => sum + utxo.amount, 0); | |
if (totalAmount < amount) { | |
throw new Error("Insufficient funds."); | |
} | |
let sum = 0; | |
const selectedUTXOs: UTXO[] = []; | |
for (const utxo of senderWallet.utxos) { | |
if (sum >= amount) break; | |
selectedUTXOs.push(utxo); | |
sum += utxo.amount; | |
} | |
const remainingAmount = sum - amount; | |
if (remainingAmount > 0) { | |
addUTXO(senderWallet, remainingAmount); | |
} | |
for (const utxo of selectedUTXOs) { | |
removeUTXO(senderWallet, utxo.id); | |
} | |
addUTXO(receiverWallet, amount); | |
} | |
transfer("Alice", "Bob", 110); | |
console.log(state.get("Alice")); | |
console.log(state.get("Bob")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment