Skip to content

Instantly share code, notes, and snippets.

@alexzofa
Last active September 17, 2021 23:09
Show Gist options
  • Save alexzofa/737980d712f31e8640e9ae7e602a8709 to your computer and use it in GitHub Desktop.
Save alexzofa/737980d712f31e8640e9ae7e602a8709 to your computer and use it in GitHub Desktop.
sample code to use bundle for uploading 0-n.png in the ./assets folder to Arweave
import Arweave from "arweave";
import {
bundleAndSignData,
createData,
ArweaveSigner,
DataItem,
} from "arbundles";
import { JWKInterface } from "arweave/node/lib/wallet";
import fs from "fs";
const assetFolder = "./assets";
const startId = 1;
const numOfAssets = 5;
const imageTxRecord = ".arweave_image_tx_ids";
async function main() {
const wallet = readJWK(process.env.ARWEAVE_WALLET!);
const arSigner = new ArweaveSigner(wallet)
const arweave = Arweave.init({
host: "arweave.dev",
port: 443,
protocol: "https",
timeout: 60000,
logging: false,
});
let imageDataItems = [];
console.log("start bundling");
for (let seq = startId; seq < startId + numOfAssets; seq++) {
let filepath = `${assetFolder}/${seq}.png`;
let data = fs.readFileSync(filepath);
const item = createData(data, arSigner, {
tags: [{ name: "Content-Type", value: "image/png" }],
});
item.sign(arSigner);
imageDataItems.push(item);
}
console.log("data items created");
const ids = await generateAndUploadBundle(arweave, imageDataItems, wallet, 2);
// save image tx id, to be used in metadata image uri
fs.writeFileSync(imageTxRecord, ids.toString());
console.log(`bundle uploaded & individual ids saved to ${imageTxRecord}`);
}
async function generateAndUploadBundle(
arweave: Arweave,
items: DataItem[],
wallet: JWKInterface,
priorityMultiplier: number
): Promise<string[]> {
const bundle = await bundleAndSignData(items, arSigner);
let ids = bundle.getIds();
const tx = await bundle.toTransaction(arweave, wallet);
// hike price to jump the queue
let price = +tx.reward;
price *= priorityMultiplier;
tx.reward = price.toString();
await arweave.transactions.sign(tx, wallet);
console.log("tx id:", tx.id);
let uploader = await arweave.transactions.getUploader(tx);
while (!uploader.isComplete) {
await uploader.uploadChunk();
console.log(
`${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`
);
}
return ids;
}
function readJWK(jwkpath: string): JWKInterface {
const data = require(jwkpath);
let jwk: JWKInterface = {
kty: data.kty,
e: data.e,
n: data.n,
d: data.d,
p: data.p,
q: data.q,
dp: data.dp,
dq: data.dq,
qi: data.qi,
};
return jwk;
}
main()
.catch((err) => {
console.error(err);
process.exit(-1);
})
.then(() => process.exit());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment